In practical: book.xml
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>
start element:abc
, end element:abc
.start element: bookstore
start element: book with an attribute category equal to cooking
start element: title with an attribute lang equal to en
Text node, with data equal to Everyday Italian
....
end element: title
.....
end element: book
end element: bookstore
If you didn't want to use async/await inside your method, but still "decorate" it so as to be able to use the await keyword from outside, TaskCompletionSource.cs:
public static Task<T> RunAsync<T>(Func<T> function)
{
if (function == null) throw new ArgumentNullException(“function”);
var tcs = new TaskCompletionSource<T>();
ThreadPool.QueueUserWorkItem(_ =>
{
try
{
T result = function();
tcs.SetResult(result);
}
catch(Exception exc) { tcs.SetException(exc); }
});
return tcs.Task;
}
To support such a paradigm with Tasks, we need a way to retain the Task façade and the ability to refer to an arbitrary asynchronous operation as a Task, but to control the lifetime of that Task according to the rules of the underlying infrastructure that’s providing the asynchrony, and to do so in a manner that doesn’t cost significantly. This is the purpose of TaskCompletionSource.
I saw it's also used in the .NET source, e.g. WebClient.cs:
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task<string> UploadStringTaskAsync(Uri address, string method, string data)
{
// Create the task to be returned
var tcs = new TaskCompletionSource<string>(address);
// Setup the callback event handler
UploadStringCompletedEventHandler handler = null;
handler = (sender, e) => HandleCompletion(tcs, e, (args) => args.Result, handler, (webClient, completion) => webClient.UploadStringCompleted -= completion);
this.UploadStringCompleted += handler;
// Start the async operation.
try { this.UploadStringAsync(address, method, data, tcs); }
catch
{
this.UploadStringCompleted -= handler;
throw;
}
// Return the task that represents the async operation
return tcs.Task;
}
Finally, I also found the following useful:
I get asked this question all the time. The implication is that there must be some thread somewhere that’s blocking on the I/O call to the external resource. So, asynchronous code frees up the request thread, but only at the expense of another thread elsewhere in the system, right? No, not at all.
To understand why asynchronous requests scale, I’ll trace a (simplified) example of an asynchronous I/O call. Let’s say a request needs to write to a file. The request thread calls the asynchronous write method. WriteAsync is implemented by the Base Class Library (BCL), and uses completion ports for its asynchronous I/O. So, the WriteAsync call is passed down to the OS as an asynchronous file write. The OS then communicates with the driver stack, passing along the data to write in an I/O request packet (IRP).
This is where things get interesting: If a device driver can’t handle an IRP immediately, it must handle it asynchronously. So, the driver tells the disk to start writing and returns a “pending” response to the OS. The OS passes that “pending” response to the BCL, and the BCL returns an incomplete task to the request-handling code. The request-handling code awaits the task, which returns an incomplete task from that method and so on. Finally, the request-handling code ends up returning an incomplete task to ASP.NET, and the request thread is freed to return to the thread pool.
Introduction to Async/Await on ASP.NET
If the target is to improve scalability (rather than responsiveness), it all relies on the existence of an external I/O that provides the opportunity to do that.
If you want to be employed professionally as a game developer you need to know C/C++. End of story!
The m000493
method seems to perform some kind of XOR encryption. This means that the same method can be used for both encrypting and decrypting the text. All you have to do is reverse m0001cd
:
string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));
string result = m000493(p0, "_p0lizei.");
// result == "gaia^unplugged^Ta..."
with return m0001cd(builder3.ToString());
changed to return builder3.ToString();
.
In SQL Management Studio you can:
Right click on the result set grid, select 'Save Result As...' and save in.
On a tool bar toggle 'Result to Text' button. This will prompt for file name on each query run.
If you need to automate it, use bcp tool.
At a minimum, change this:
function BlockID() {
var IDs = new Array();
images['s'] = "Images/Block_01.png";
images['g'] = "Images/Block_02.png";
images['C'] = "Images/Block_03.png";
images['d'] = "Images/Block_04.png";
return IDs;
}
To this:
function BlockID() {
var IDs = new Object();
IDs['s'] = "Images/Block_01.png";
IDs['g'] = "Images/Block_02.png";
IDs['C'] = "Images/Block_03.png";
IDs['d'] = "Images/Block_04.png";
return IDs;
}
There are a couple fixes to point out. First, images
is not defined in your original function, so assigning property values to it will throw an error. We correct that by changing images
to IDs
. Second, you want to return an Object
, not an Array
. An object can be assigned property values akin to an associative array or hash -- an array cannot. So we change the declaration of var IDs = new Array();
to var IDs = new Object();
.
After those changes your code will run fine, but it can be simplified further. You can use shorthand notation (i.e., object literal property value shorthand) to create the object and return it immediately:
function BlockID() {
return {
"s":"Images/Block_01.png"
,"g":"Images/Block_02.png"
,"C":"Images/Block_03.png"
,"d":"Images/Block_04.png"
};
}
I would put the code in the viewWillAppear delegate on each view being shown:
Like this where you need to hide it:
- (void)viewWillAppear:(BOOL)animated
{
[yourObject hideBar];
}
Like this where you need to show it:
- (void)viewWillAppear:(BOOL)animated
{
[yourObject showBar];
}
if(is_array($arr) && count($arr) > 1)
Just to be sure that $arr is indeed an array.
sizeof
is an alias of count
, I prefer to use count because:
Hit F4 and you'll get what you are looking for.
Add this to your plugins array in webpack.config.js
new webpack.ProvidePlugin({
'window.jQuery': 'jquery',
'window.$': 'jquery',
})
then require jquery normally
require('jquery');
If pain persists getting other scripts to see it, try explicitly placing it in the global context via (in the entry js)
window.$ = jQuery;
You use this code in your button click event
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
In the first step, it will work fine as the value of a
will be 1 and that of b
will be 2 but as 2+1 will be returned and in the next step the value of b
will be the return value from step 1 i.e 3
and so b.x
will be undefined...and undefined + anyNumber will be NaN and that is why you are getting that result.
arr.reduce(function(a,b){return a + b.x},0);
With Java 8, you can use a reference method.
You could add compare
method to your Book
class
class Book {
public static int compare(Book a, Book b)
{
return a.name.compareTo(b.name);
}
}
And then you could do this :
Arrays.sort(books , Book::compare);
Here is the full example:
class Book {
String name;
String author;
public Book(String name, String author) {
this.name = name;
this.author = author;
}
public static int compareBooks(Book a , Book b)
{
return a.name.compareTo(b.name);
}
@Override
public String toString() {
return "name : " + name + "\t" + "author : " + author;
}
public static void main(String[] args) {
Book[] books = {
new Book("Book 3" , "Author 1"),
new Book("Book 2" , "Author 2"),
new Book("Book 1" , "Author 3"),
new Book("Book 4" , "Author 4")
};
Arrays.sort(books , Book::compareBooks);
Arrays.asList(books).forEach(System.out::println);
}
}
I tested the performance difference between x*x*...
vs pow(x,i)
for small i
using this code:
#include <cstdlib>
#include <cmath>
#include <boost/date_time/posix_time/posix_time.hpp>
inline boost::posix_time::ptime now()
{
return boost::posix_time::microsec_clock::local_time();
}
#define TEST(num, expression) \
double test##num(double b, long loops) \
{ \
double x = 0.0; \
\
boost::posix_time::ptime startTime = now(); \
for (long i=0; i<loops; ++i) \
{ \
x += expression; \
x += expression; \
x += expression; \
x += expression; \
x += expression; \
x += expression; \
x += expression; \
x += expression; \
x += expression; \
x += expression; \
} \
boost::posix_time::time_duration elapsed = now() - startTime; \
\
std::cout << elapsed << " "; \
\
return x; \
}
TEST(1, b)
TEST(2, b*b)
TEST(3, b*b*b)
TEST(4, b*b*b*b)
TEST(5, b*b*b*b*b)
template <int exponent>
double testpow(double base, long loops)
{
double x = 0.0;
boost::posix_time::ptime startTime = now();
for (long i=0; i<loops; ++i)
{
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
}
boost::posix_time::time_duration elapsed = now() - startTime;
std::cout << elapsed << " ";
return x;
}
int main()
{
using std::cout;
long loops = 100000000l;
double x = 0.0;
cout << "1 ";
x += testpow<1>(rand(), loops);
x += test1(rand(), loops);
cout << "\n2 ";
x += testpow<2>(rand(), loops);
x += test2(rand(), loops);
cout << "\n3 ";
x += testpow<3>(rand(), loops);
x += test3(rand(), loops);
cout << "\n4 ";
x += testpow<4>(rand(), loops);
x += test4(rand(), loops);
cout << "\n5 ";
x += testpow<5>(rand(), loops);
x += test5(rand(), loops);
cout << "\n" << x << "\n";
}
Results are:
1 00:00:01.126008 00:00:01.128338
2 00:00:01.125832 00:00:01.127227
3 00:00:01.125563 00:00:01.126590
4 00:00:01.126289 00:00:01.126086
5 00:00:01.126570 00:00:01.125930
2.45829e+54
Note that I accumulate the result of every pow calculation to make sure the compiler doesn't optimize it away.
If I use the std::pow(double, double)
version, and loops = 1000000l
, I get:
1 00:00:00.011339 00:00:00.011262
2 00:00:00.011259 00:00:00.011254
3 00:00:00.975658 00:00:00.011254
4 00:00:00.976427 00:00:00.011254
5 00:00:00.973029 00:00:00.011254
2.45829e+52
This is on an Intel Core Duo running Ubuntu 9.10 64bit. Compiled using gcc 4.4.1 with -o2 optimization.
So in C, yes x*x*x
will be faster than pow(x, 3)
, because there is no pow(double, int)
overload. In C++, it will be the roughly same. (Assuming the methodology in my testing is correct.)
This is in response to the comment made by An Markm:
Even if a using namespace std
directive was issued, if the second parameter to pow
is an int
, then the std::pow(double, int)
overload from <cmath>
will be called instead of ::pow(double, double)
from <math.h>
.
This test code confirms that behavior:
#include <iostream>
namespace foo
{
double bar(double x, int i)
{
std::cout << "foo::bar\n";
return x*i;
}
}
double bar(double x, double y)
{
std::cout << "::bar\n";
return x*y;
}
using namespace foo;
int main()
{
double a = bar(1.2, 3); // Prints "foo::bar"
std::cout << a << "\n";
return 0;
}
PROCESSOR_ARCHITECTURE=x86
Will appear on Win32, and
PROCESSOR_ARCHITECTURE=AMD64
will appear for Win64.
If you are perversely running the 32-bit cmd.exe
process then Windows presents two environment variables:
PROCESSOR_ARCHITECTURE=x86
PROCESSOR_ARCHITEW6432=AMD64
There is a straight forward clean solution available. Use the wholeTextFiles() method. This will take a directory and forms a key value pair. The returned RDD will be a pair RDD. Find below the description from Spark docs:
SparkContext.wholeTextFiles lets you read a directory containing multiple small text files, and returns each of them as (filename, content) pairs. This is in contrast with textFile, which would return one record per line in each file
.xlsx
loads 4 times longer than .xlsb
and saves 2 times longer and has 1.5 times a bigger file. I tested this on a generated worksheet with 10'000 rows * 1'000 columns = 10'000'000 (10^7) cells of simple chained =…+1
formulas:
?--------------------------------?
¦ ¦ .xlsx ¦ .xlsb ¦
¦--------------+--------+--------¦
¦ loading time ¦ 165s ¦ 43s ¦
+--------------+--------+--------¦
¦ saving time ¦ 115s ¦ 61s ¦
+--------------+--------+--------¦
¦ file size ¦ 91 MB ¦ 65 MB ¦
?--------------------------------?
(Hardware: Core2Duo 2.3 GHz, 4 GB RAM, 5.400 rpm SATA II HD; Windows 7, under somewhat heavy load from other processes.)
Beside this, there should be no differences. More precisely,
both formats support exactly the same feature set
cites this blog post from 2006-08-29. So maybe the info that .xlsb
does not support Ribbon code is newer than the upper citation, but I figure that forum source of yours is just wrong. When cracking open the binary file, it seems to condensedly mimic the OOXML file structure 1-to-1: Blog article from 2006-08-07
Please use the below mysql query.
SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
FROM information_schema.columns
WHERE table_schema = '<DATABASE NAME>'
AND table_name = '<TABLE NAME>'
AND COLUMN_NAME = '<COLOMN NAME>'
Swing + SwingX + Miglayout is my combination of choice. Miglayout is so much simpler than Swings perceived 200 different layout managers and much more powerful. Also, it provides you with the ability to "debug" your layouts, which is especially handy when creating complex layouts.
I needed to add this functionality to a project I was working on recently and adding jQuery Mobile just to solve this problem seemed like overkill, so I came up with a solution and put it on github: bcSwipe (Bootstrap Carousel Swipe).
It's a lightweight jQuery plugin (~600 bytes minified vs jQuery Mobile touch events at 8kb), and it's been tested on Android and iOS.
This is how you use it:
$('.carousel').bcSwipe({ threshold: 50 });
A really simple explanation that I found useful: the nosniff response header is a way to keep a website more secure.
From Security Researcher, Scott Helme, here:
It prevents Google Chrome and Internet Explorer from trying to mime-sniff the content-type of a response away from the one being declared by the server.
Well there are a bunch of different utilities for this, e.g. Apache Commons Lang String Utils
but in the end, it has to loop over the string to count the occurrences one way or another.
Note also that the countMatches
method above has the following signature so will work for substrings as well.
public static int countMatches(String str, String sub)
The source for this is (from here):
public static int countMatches(String str, String sub) {
if (isEmpty(str) || isEmpty(sub)) {
return 0;
}
int count = 0;
int idx = 0;
while ((idx = str.indexOf(sub, idx)) != -1) {
count++;
idx += sub.length();
}
return count;
}
I was curious if they were iterating over the string or using Regex.
numpy.linspace()
gives you a one-dimensional NumPy array. For example:
>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
Therefore:
for index,point in my_array
cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:
>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])
Now you can do this:
>>> for x, y in two_d:
print(x, y)
1 2
4 5
If you want a %
symbol in search_criteria
to be treated as a literal character rather than as a wildcard, escape it to [%]
... where name like '%' + replace(search_criteria, '%', '[%]') + '%'
As BalausC mentioned in a comment, you are probably looking for CSS (Cascading Style Sheets) not HTML attributes.
To position an element, a <table>
in your case you want to use either padding or margins.
the difference between margins and paddings can be seen as the "box model":
Image from HTML Dog article on margins and padding http://www.htmldog.com/guides/cssbeginner/margins/.
I highly recommend the article above if you need to learn how to use CSS.
To move the table down and right I would use margins like so:
table{
margin:25px 0 0 25px;
}
This is in shorthand so the margins are as follows:
margin: top right bottom left;
Double check if you have set and initial value for int and decimal values to be printed.
This sample is printing an empty line
declare @Number INT
print 'The number is : ' + CONVERT(VARCHAR, @Number)
And this sample is printing -> The number is : 1
declare @Number INT = 1
print 'The number is : ' + CONVERT(VARCHAR, @Number)
If you want to keep it simple, use fixdockergid
on your Dockerfile.
It is very simple to do, open your PowerShell and write the following command if you have number of ps1 files. here you have to change the path with your path.
PS C:\Users> Get-ChildItem -Path "D:\downlod" -Recurse | Unblock-File
Visual Studio 2013 now supports setup projects. Microsoft have shipped a Visual Studio extension to produce setup projects.
When you are trying to prevent XSS, it's important to think of the context. As an example how and what to escape is very different if you are ouputting data inside a variable in a javascript snippet as opposed to outputting data in an HTML tag or an HTML attribute.
I have an example of this here: http://erlend.oftedal.no/blog/?blogid=91
Also checkout the OWASP XSS Prevention Cheat Sheet: http://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet
So the short answer is, make sure you escape output like suggested by Tendayi Mawushe, but take special care when you are outputting data in HTML attributes or javascript.
The BCP Utility can also be used in the form of a .bat file, but be cautious of escape sequences (ie quotes "" must be used in conjunction with ) and the appropriate tags.
.bat Example:
C:
bcp "\"YOUR_SERVER\".dbo.Proc" queryout C:\FilePath.txt -T -c -q
-- Add PAUSE here if you'd like to see the completed batch
-q MUST be used in the presence of quotations within the query itself.
BCP can also run Stored Procedures if necessary. Again, be cautious: Temporary Tables must be created prior to execution or else you should consider using Table Variables.
Basically, you check if an object is an instance of a specific class. You normally use it, when you have a reference or parameter to an object that is of a super class or interface type and need to know whether the actual object has some other type (normally more concrete).
Example:
public void doSomething(Number param) {
if( param instanceof Double) {
System.out.println("param is a Double");
}
else if( param instanceof Integer) {
System.out.println("param is an Integer");
}
if( param instanceof Comparable) {
//subclasses of Number like Double etc. implement Comparable
//other subclasses might not -> you could pass Number instances that don't implement that interface
System.out.println("param is comparable");
}
}
Note that if you have to use that operator very often it is generally a hint that your design has some flaws. So in a well designed application you should have to use that operator as little as possible (of course there are exceptions to that general rule).
I should this On Windows, environment variable expansion is %BUILD_NUMBER%
Based on the given answers and information in the question, this is the code you should use:
public static boolean doesURLExist(URL url) throws IOException
{
// We want to check the current URL
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// We don't need to get data
httpURLConnection.setRequestMethod("HEAD");
// Some websites don't like programmatic access so pretend to be a browser
httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
int responseCode = httpURLConnection.getResponseCode();
// We only accept response code 200
return responseCode == HttpURLConnection.HTTP_OK;
}
Of course tested and working.
Its all depend on your client data access-layer. Many ORM frameworks rely on explicitly querying the SCOPE_IDENTITY during the insert operation.
If you are in complete control over the data access layer then is arguably better to return SCOPE_IDENTITY() as an output parameter. Wrapping the return in a result set adds unnecessary meta data overhead to describe the result set, and complicates the code to process the requests result.
If you prefer a result set return, then again is arguable better to use the OUTPUT clause:
INSERT INTO MyTable (col1, col2, col3)
OUTPUT INSERTED.id, col1, col2, col3
VALUES (@col1, @col2, @col3);
This way you can get the entire inserted row back, including default and computed columns, and you get a result set containing one row for each row inserted, this working correctly with set oriented batch inserts.
Overall, I can't see a single case when returning SCOPE_IDENTITY()
as a result set would be a good practice.
Use the return
keyword.
From MSDN:
The return statement terminates execution of the method in which it appears and returns control to the calling method. It can also return the value of the optional expression. If the method is of the type void, the return statement can be omitted.
So in your case, the usage would be:
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
{
return; //exit this event
}
}
I think the difference between the two boils down to access. Environment variables are accessible by any process and Java system properties are only accessible by the process they are added to.
Also as Bohemian stated, env variables are set in the OS (however they 'can' be set through Java) and system properties are passed as command line options or set via setProperty()
.
$("#ddlMultiselect").val('').trigger("change");
for multi-select drop-down, it will clear displayed text.
Of course there is. Check out mysql_query
, and mysql_fetch_row
if you use MySQL.
Example from PHP manual:
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
When you go and write you shell script always put first line as #!/usr/bin/env bash . This shell doesn't omit or manipulate escape sequences. ex echo "This is first \n line" prints This is first \n line.
If any of you looking for Bootstrap-4. Here it is
<div class="row no-gutters">
<div class="col-10">
<img class="img-fluid" src="/resources/img1.jpg" alt="">
</div>
</div>
UPDATE:
This has been fixed in jQuery 3.x.If you have no possibility to upgrade to any version above 3.0, you could use following snippet BUT be aware that now you will lose sync behaviour of script loading in the targeted content.
You could fix it, setting explicitly async option of xhr request to true
:
$.ajaxPrefilter(function( options, original_Options, jqXHR ) {
options.async = true;
});
As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.
Because no one actually created an answer with using .on()
instead of bind()
i decided to create one.
$('div#dialog').on('dialogclose', function(event) {
//custom logic fired after dialog is closed.
});
Use this code:
@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
@Html.HiddenFor(m => m.EmploymentType[i].Text)
@Html.CheckBoxFor(m => m.EmploymentType[i].Checked, new { id = "YourId" })
}
Here is a CSV action result I wrote that takes a DataTable and converts it into CSV. You can return this from your view and it will prompt the user to download the file. You should be able to convert this easily into a List compatible form or even just put your list into a DataTable.
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
namespace Detectent.Analyze.ActionResults
{
public class CSVResult : ActionResult
{
/// <summary>
/// Converts the columns and rows from a data table into an Microsoft Excel compatible CSV file.
/// </summary>
/// <param name="dataTable"></param>
/// <param name="fileName">The full file name including the extension.</param>
public CSVResult(DataTable dataTable, string fileName)
{
Table = dataTable;
FileName = fileName;
}
public string FileName { get; protected set; }
public DataTable Table { get; protected set; }
public override void ExecuteResult(ControllerContext context)
{
StringBuilder csv = new StringBuilder(10 * Table.Rows.Count * Table.Columns.Count);
for (int c = 0; c < Table.Columns.Count; c++)
{
if (c > 0)
csv.Append(",");
DataColumn dc = Table.Columns[c];
string columnTitleCleaned = CleanCSVString(dc.ColumnName);
csv.Append(columnTitleCleaned);
}
csv.Append(Environment.NewLine);
foreach (DataRow dr in Table.Rows)
{
StringBuilder csvRow = new StringBuilder();
for(int c = 0; c < Table.Columns.Count; c++)
{
if(c != 0)
csvRow.Append(",");
object columnValue = dr[c];
if (columnValue == null)
csvRow.Append("");
else
{
string columnStringValue = columnValue.ToString();
string cleanedColumnValue = CleanCSVString(columnStringValue);
if (columnValue.GetType() == typeof(string) && !columnStringValue.Contains(","))
{
cleanedColumnValue = "=" + cleanedColumnValue; // Prevents a number stored in a string from being shown as 8888E+24 in Excel. Example use is the AccountNum field in CI that looks like a number but is really a string.
}
csvRow.Append(cleanedColumnValue);
}
}
csv.AppendLine(csvRow.ToString());
}
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = "text/csv";
response.AppendHeader("Content-Disposition", "attachment;filename=" + this.FileName);
response.Write(csv.ToString());
}
protected string CleanCSVString(string input)
{
string output = "\"" + input.Replace("\"", "\"\"").Replace("\r\n", " ").Replace("\r", " ").Replace("\n", "") + "\"";
return output;
}
}
}
jcomeau@intrepid:~$ mystring="one two three four five"
jcomeau@intrepid:~$ echo "string length: ${#mystring}"
string length: 23
link Couting characters, words, lenght of the words and total lenght in a sentence
import { Component, ElementRef, ViewChild} from '@angular/core';
@Component({
selector: 'my-app',
template:
`
<input #inputEl value="hithere">
`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
@ViewChild('inputEl') inputEl:ElementRef;
ngAfterViewInit() {
console.log(this.inputEl);
}
}
#inputEl
on the <input>
tag.ngAfterViewInit
lifecycle hook.Note:
If you want to manipulate the DOM elements use the Renderer2 API instead of accessing the elements directly. Permitting direct access to the DOM can make your application more vulnerable to XSS attacks
jQuery to check for checked? Really?
if(!this.checked) {
Don't use a bazooka to do a razor's job.
If you are like me, then you might have started with a Class Library, and then switched this to a Console Application. If so, change this...
namespace ClassLibrary1
{
public class Class1
{
}
}
To this...
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
}
}
}
For changing the color
.slick-prev:before {
color: some-color!important;
}
.slick-next:before {
color: some-color!important;
}
Hi We sort of had the same problem if I understand you well. So check what pysftp version you're using. If it's the latest one which is 0.2.9 downgrade to 0.2.8. Check this out. https://github.com/Yenthe666/auto_backup/issues/47
NODE_ENV
is an environment variable made popular by the express web server framework. When a node application is run, it can check the value of the environment variable and do different things based on the value. NODE_ENV
specifically is used (by convention) to state whether a particular environment is a production or a development environment. A common use-case is running additional debugging or logging code if running in a development environment.
You can use the following code to access the environment variable yourself so that you can perform your own checks and logic:
var environment = process.env.NODE_ENV
Assume production if you don't recognise the value:
var isDevelopment = environment === 'development'
if (isDevelopment) {
setUpMoreVerboseLogging()
}
You can alternatively using express' app.get('env')
function, but note that this is NOT RECOMMENDED as it defaults to "development"
, which may result in development code being accidentally run in a production environment - it's much safer if your app throws an error if this important value is not set (or if preferred, defaults to production logic as above).
Be aware that if you haven't explicitly set NODE_ENV
for your environment, it will be undefined
if you access it from process.env
, there is no default.
How to actually set the environment variable varies from operating system to operating system, and also depends on your user setup.
If you want to set the environment variable as a one-off, you can do so from the command line:
export NODE_ENV=production
$env:NODE_ENV = 'production'
In the long term, you should persist this so that it isn't unset if you reboot - rather than list all the possible methods to do this, I'll let you search how to do that yourself!
Convention has dictated that there are two 'main' values you should use for NODE_ENV
, either production
or development
, all lowercase. There's nothing to stop you from using other values, (test
, for example, if you wish to use some different logic when running automated tests), but be aware that if you are using third-party modules, they may explicitly compare with 'production'
or 'development'
to determine what to do, so there may be side effects that aren't immediately obvious.
Finally, note that it's a really bad idea to try to set NODE_ENV
from within a node application itself - if you do, it will only be applied to the process from which it was set, so things probably won't work like you'd expect them to. Don't do it - you'll regret it.
Syntax errors is not checked easily in external servers, just runtime errors.
What I do? Just like you, I use
ini_set('display_errors', 'On');
error_reporting(E_ALL);
However, before run I check syntax errors in a PHP file using an online PHP syntax checker.
The best, IMHO is PHP Code Checker
I copy all the source code, paste inside the main box and click the Analyze
button.
It is not the most practical method, but the 2 procedures are complementary and it solves the problem completely
It turns out this is either a poorly documented, intentionally misleading, or undocumented interaction between the "controls" param and the "modestbranding" param. There is no way to remove YouTube's logo from an embedded YouTube video, at least while the video controls are exposed. All you get to do is choose how and when you want the logo to appear. Here are the details:
If controls = 1 and modestbranding = 1, then the YouTube logo is bigger, is on the video still image as a grayscale watermark in the lower right, and shows when the play controls are exposed as a big gray scale watermark in the lower right. example:
<iframe width="560" height="315" src="https://www.youtube.com/embed/Z6ytvzNlmRo?rel=0&controls=1&&showinfo=0&modestbranding=1" frameborder="0"></iframe>
If controls = 1 and modestbranding = 0 (our change here), then the YouTube logo is smaller, is not on the video still image as a grayscale watermark in the lower right, and shows only when the controls are exposed as a white icon in the lower right. example:
<iframe width="560" height="315" src="https://www.youtube.com/embed/Z6ytvzNlmRo?rel=0&controls=1&&showinfo=0&modestbranding=0" frameborder="0"></iframe>
If controls = 0, then the modestbranding param is ignored and the YouTube logo is bigger, is on the video still image as a grayscale watermark in the lower right, the watermark appears on hover of a playing video, and the watermark appears in the lower right of any paused video. example:
<iframe width="560" height="315" src="https://www.youtube.com/embed/Z6ytvzNlmRo?rel=0&controls=0&&showinfo=0&modestbranding=1" frameborder="0"></iframe>
The integer input would mean that it can only take positive numbers, 0 and negative numbers too. This is how I have been able to achieve this using Javascript keypress.
<input type="number" (keypress)="keypress($event, $event.target.value)" >
keypress(evt, value){
if (evt.charCode >= 48 && evt.charCode <= 57 || (value=="" && evt.charCode == 45))
{
return true;
}
return false;
}
The given code won't allow user to enter alphabets nor decimal on runtime, just positive and negative integer values.
As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).
On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.
You can check awesome material design components for AngularJS:
https://material.angularjs.org
jQuery has very helpful function called serialize.
Demo: http://jsfiddle.net/55xnJ/2/
//Just type:
$("#preview_form").serialize();
//to get result:
single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1
Use this in your my.ini
under
[mysqldump]
user=root
password=anything
A height of 100% for is, presumably, the height of your browser's inner window, because that is the height of its parent, the page. An auto
height will be the minimum height of necessary to contain .
debug_backtrace()[1]['function'];
You can use it like this:
echo 'The calling function: ' . debug_backtrace()[1]['function'];
Note that this is only compatible with versions of PHP released within the last year. But it's a good idea to keep your PHP up to date anyway for security reasons.
Code :
var now = new Date();
var time = now.getTime();
time += 3600 * 1000;
now.setTime(time);
document.cookie =
'username=' + value +
'; expires=' + now.toUTCString() +
'; path=/';
Mongo's in-built export is working fine, unless you want to any data manipulation like format date, covert data types etc.
Following command works as charm.
mongoexport -h localhost -d databse -c collection --type=csv
--fields erpNum,orderId,time,status
-q '{"time":{"$gt":1438275600000}, "status":{"$ne" :"Cancelled"}}'
--out report.csv
Here is a Android variant, but same principle can be used in plain Java too.
private static final String TAG = YourClass.class.getSimpleName();
private static final String TAG = YourClass.class.getName();
Newer versions of vim allow a :set numberwidth=x
value, which sets the width of the line number display. I don't really use folding etc, so I wouldn't know about that though. Drawing a thin vertical line is beyond the abilities of a console application though. GVim may allow this (I don't use it, so can't comment there).
One more solution:
function firstOrNull(array, expr) {
for (var i = 0; i < array.length; i++) {
if (expr(array[i]))
return array[i];
}
return null;
}
Using: firstOrNull([{ a: 1, b: 2 }, { a: 3, b: 3 }], function(item) { return item.a === 3; });
This function don't executes for each element from the array (it's valuable for large arrays)
This is how you can do it. This code assumes the existance of a buffered image called 'image' (like your comment says)
// The required drawing location
int drawLocationX = 300;
int drawLocationY = 300;
// Rotation information
double rotationRequired = Math.toRadians (45);
double locationX = image.getWidth() / 2;
double locationY = image.getHeight() / 2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
// Drawing the rotated image at the required drawing locations
g2d.drawImage(op.filter(image, null), drawLocationX, drawLocationY, null);
The CSS tag 'margin' is actually a shorthand for the four separate margin values, top/left/bottom/right. Use css('marginTop')
, etc. - note they will have 'px' on the end if you have specified them that way.
Use parseInt()
around the result to turn it in to the number value.
NB. As noted by Omaty, the order of the shorthand 'margin' tag is:
top right bottom left
- the above list was not written in a way intended to be the list order, just a list of that specified in the tag.
In Python, the name of the class refers to the class instance. Consider:
class A: pass
class B: pass
class C: pass
lst = [A, B, C]
# instantiate second class
b_instance = lst[1]()
print b_instance
You can insert object items to an array as this
let obj = {_x000D_
'1st': {_x000D_
name: 'stackoverflow'_x000D_
},_x000D_
'2nd': {_x000D_
name: 'stackexchange'_x000D_
}_x000D_
};_x000D_
_x000D_
let wholeArray = Object.keys(obj).map(key => obj[key]);_x000D_
_x000D_
console.log(wholeArray);
_x000D_
If all you need is to show custom pages which have some fancy error messages for your site when DEBUG = False
, then add two templates named 404.html and 500.html in your templates directory and it will automatically pick up this custom pages when a 404 or 500 is raised.
$? is the result (exit code) of the last executed command.
Let Spring 3 injection take care of this.
Thanks to tsunade21 the easiest way is:
@RequestMapping(method = RequestMethod.GET)
public ModelAndView anyMethodNameGoesHere(Principal principal) {
final String loggedInUserName = principal.getName();
}
If you wish to inject pure function, instead of text, you can use this method:
function inject(){_x000D_
document.body.style.backgroundColor = 'blue';_x000D_
}_x000D_
_x000D_
// this includes the function as text and the barentheses make it run itself._x000D_
var actualCode = "("+inject+")()"; _x000D_
_x000D_
document.documentElement.setAttribute('onreset', actualCode);_x000D_
document.documentElement.dispatchEvent(new CustomEvent('reset'));_x000D_
document.documentElement.removeAttribute('onreset');
_x000D_
And you can pass parameters (unfortunatelly no objects and arrays can be stringifyed) to the functions. Add it into the baretheses, like so:
function inject(color){_x000D_
document.body.style.backgroundColor = color;_x000D_
}_x000D_
_x000D_
// this includes the function as text and the barentheses make it run itself._x000D_
var color = 'yellow';_x000D_
var actualCode = "("+inject+")("+color+")";
_x000D_
You can concatenate the array values with implode and a separator of | and then use preg_match to search for the value.
Here is the solution I came up with ...
$emails = array('@gmail', '@hotmail', '@outlook', '@live', '@msn', '@yahoo', '@ymail', '@aol');
$emails = implode('|', $emails);
if(!preg_match("/$emails/i", $email)){
// do something
}
Just wanted to throw in my 2 cents:
public static class HttpClientExt
{
public static Uri AddQueryParams(this Uri uri, string query)
{
var ub = new UriBuilder(uri);
ub.Query = string.IsNullOrEmpty(uri.Query) ? query : string.Join("&", uri.Query.Substring(1), query);
return ub.Uri;
}
public static Uri AddQueryParams(this Uri uri, IEnumerable<string> query)
{
return uri.AddQueryParams(string.Join("&", query));
}
public static Uri AddQueryParams(this Uri uri, string key, string value)
{
return uri.AddQueryParams(string.Join("=", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value)));
}
public static Uri AddQueryParams(this Uri uri, params KeyValuePair<string,string>[] kvps)
{
return uri.AddQueryParams(kvps.Select(kvp => string.Join("=", HttpUtility.UrlEncode(kvp.Key), HttpUtility.UrlEncode(kvp.Value))));
}
public static Uri AddQueryParams(this Uri uri, IDictionary<string, string> kvps)
{
return uri.AddQueryParams(kvps.Select(kvp => string.Join("=", HttpUtility.UrlEncode(kvp.Key), HttpUtility.UrlEncode(kvp.Value))));
}
public static Uri AddQueryParams(this Uri uri, NameValueCollection nvc)
{
return uri.AddQueryParams(nvc.AllKeys.SelectMany(nvc.GetValues, (key, value) => string.Join("=", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value))));
}
}
The docs say that uri.Query
will start with a ?
if it's non-empty and you should trim it off if you're going to modify it.
Note that HttpUtility.UrlEncode
is found in System.Web
.
Usage:
var uri = new Uri("https://api.del.icio.us/v1/posts/suggest").AddQueryParam("url","http://stackoverflow.com")
Boosting your maven-compiler-plugin to 3.8.0 seems to be necessary but not sufficient. If you're still having problems, you should also make sure your JAVA_HOME environment variable is set to Java 10 (or 11) if you're running from the command line. (The error message you get won't tell you this.) Or if you're running from an IDE, you need to make sure it is set to run maven with your current JDK.
I created a working demo that shows how to use the Google Maps API Directions Service in Javascript through a
DirectionsService
object to send and receive direction requestsDirectionsRenderer
object to render the returned route on the mapfunction initMap() {_x000D_
var pointA = new google.maps.LatLng(51.7519, -1.2578),_x000D_
pointB = new google.maps.LatLng(50.8429, -0.1313),_x000D_
myOptions = {_x000D_
zoom: 7,_x000D_
center: pointA_x000D_
},_x000D_
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),_x000D_
// Instantiate a directions service._x000D_
directionsService = new google.maps.DirectionsService,_x000D_
directionsDisplay = new google.maps.DirectionsRenderer({_x000D_
map: map_x000D_
}),_x000D_
markerA = new google.maps.Marker({_x000D_
position: pointA,_x000D_
title: "point A",_x000D_
label: "A",_x000D_
map: map_x000D_
}),_x000D_
markerB = new google.maps.Marker({_x000D_
position: pointB,_x000D_
title: "point B",_x000D_
label: "B",_x000D_
map: map_x000D_
});_x000D_
_x000D_
// get route from A to B_x000D_
calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB);_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB) {_x000D_
directionsService.route({_x000D_
origin: pointA,_x000D_
destination: pointB,_x000D_
travelMode: google.maps.TravelMode.DRIVING_x000D_
}, function(response, status) {_x000D_
if (status == google.maps.DirectionsStatus.OK) {_x000D_
directionsDisplay.setDirections(response);_x000D_
} else {_x000D_
window.alert('Directions request failed due to ' + status);_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
initMap();
_x000D_
html,_x000D_
body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
#map-canvas {_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
}
_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>_x000D_
_x000D_
<div id="map-canvas"></div>
_x000D_
Also on Jsfiddle: http://jsfiddle.net/user2314737/u9no8te4/
You can use the Web Services using an API_KEY issuing a request like this:
https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&key=API_KEY
An API_KEY can be obtained in the Google Developer Console with a quota of 2,500 free requests/day.
A request can return JSON or XML results that can be used to draw a path on a map.
Official documentation for Web Services using the Google Maps Directions API are here
$("#select_id").find("option:selected").text();
It is helpful if your control is on Server side. In .NET it looks like:
$('#<%= dropdownID.ClientID %>').find("option:selected").text();
If you are importing or you have an array (of type string) in your code and you have to convert it into arraylist (offcourse string) then use of collections is better. like this:
String array1[] = getIntent().getExtras().getStringArray("key1"); or String array1[] = ... then
List allEds = new ArrayList(); Collections.addAll(allEds, array1);
You are using an inline table value function. Therefore you must use Select * From function. If you want to use select function() you must use a scalar function.
https://msdn.microsoft.com/fr-fr/library/ms186755%28v=sql.120%29.aspx
Single line looping,
declare -a listOfNames=('db_a' 'db_b' 'db_c')
for databaseName in ${listOfNames[@]}; do echo $databaseName; done;
you will get an output like this,
db_a
db_b
db_c
I have built a performance framework that manipulates and graphs millions of datasets, and even then, the javascript calculation latency was on order of tens of milliseconds. Unless you're worried about going over the array size limit, I don't think you have much to worry about.
Use the following:
echo (text here) >> (name here).txt
Ex. echo my name is jeff >> test.txt
test.txt
my name is jeff
You can use it in a script too.
According to docs :
Foo mock = mock(Foo.class, CALLS_REAL_METHODS);
// this calls the real implementation of Foo.getSomething()
value = mock.getSomething();
when(mock.getSomething()).thenReturn(fakeValue);
// now fakeValue is returned
value = mock.getSomething();
Just use the event-handler. Something like this should work:
$('.js-my-element').bind('contextmenu', function(e) {
e.preventDefault();
alert('The eventhandler will make sure, that the contextmenu dosn't appear.');
});
Start phpMyAdmin and access wp_users from your wordpress instance. Edit record and select user_pass function to match MD5. Write the string that will be your new password in VALUE. Click, GO. Go to your wordpress website and enter your new password. Back to phpMyAdmin you will see that WP changed the HASH to something like $P$B... enjoy!
You can use this
var fs = require('fs');
var myCss = {
style : fs.readFileSync('./style.css','utf8');
};
app.get('/', function(req, res){
res.render('index.ejs', {
title: 'My Site',
myCss: myCss
});
});
put this on template
<%- myCss.style %>
just build style.css
<style>
body {
background-color: #D8D8D8;
color: #444;
}
</style>
I try this for some custom css. It works for me
This may sound Evil™ and I haven't tested it, but how about initializing all values in an array at allocation to '\0'
and then using strlen()
? This would give you your so-called real value since it would stop counting at the first '\0'
it encounters.
Well, now that I think about it though, please don't Ever™ do this. Unless, you want to land in a pile of dirty memory.
Also, for the allocated memory or the total memory you may use the following functions if your environment provides them:
It means, essentially, what it says; that 'this is important, ignore subsequent rules, and any usual specificity issues, apply this rule!'
In normal use a rule defined in an external stylesheet is overruled by a style defined in the head
of the document, which, in turn, is overruled by an in-line style within the element itself (assuming equal specificity of the selectors). Defining a rule with the !important
'attribute' (?) discards the normal concerns as regards the 'later' rule overriding the 'earlier' ones.
Also, ordinarily, a more specific rule will override a less-specific rule. So:
a {
/* css */
}
Is normally overruled by:
body div #elementID ul li a {
/* css */
}
As the latter selector is more specific (and it doesn't, normally, matter where the more-specific selector is found (in the head
or the external stylesheet) it will still override the less-specific selector (in-line style attributes will always override the 'more-', or the 'less-', specific selector as it's always more specific.
If, however, you add !important
to the less-specific selector's CSS declaration, it will have priority.
Using !important
has its purposes (though I struggle to think of them), but it's much like using a nuclear explosion to stop the foxes killing your chickens; yes, the foxes will be killed, but so will the chickens. And the neighbourhood.
It also makes debugging your CSS a nightmare (from personal, empirical, experience).
use the JavaScript Date()
object. There are a number of ways to get the time, date, timestamps, etc from the object. (Reference)
function myFunction() {
var d = new Date();
var timeStamp = d.getTime(); // Number of ms since Jan 1, 1970
// OR:
var currentTime = d.toLocaleTimeString(); // "12:35 PM", for instance
}
Try a custom propTypes :
const childrenPropTypeLogic = (props, propName, componentName) => {
const prop = props[propName];
return React.Children
.toArray(prop)
.find(child => child.type !== 'div') && new Error(`${componentName} only accepts "div" elements`);
};
static propTypes = {
children : childrenPropTypeLogic
}
const {Component, PropTypes} = React;_x000D_
_x000D_
const childrenPropTypeLogic = (props, propName, componentName) => {_x000D_
var error;_x000D_
var prop = props[propName];_x000D_
_x000D_
React.Children.forEach(prop, function (child) {_x000D_
if (child.type !== 'div') {_x000D_
error = new Error(_x000D_
'`' + componentName + '` only accepts children of type `div`.'_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
return error;_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
class ContainerComponent extends Component {_x000D_
static propTypes = {_x000D_
children: childrenPropTypeLogic,_x000D_
}_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<div>_x000D_
{this.props.children}_x000D_
</div>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
class App extends Component {_x000D_
render(){_x000D_
return (_x000D_
<ContainerComponent>_x000D_
<div>1</div>_x000D_
<div>2</div>_x000D_
</ContainerComponent>_x000D_
)_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App /> , document.querySelector('section'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<section />
_x000D_
Use <location>
configuration tag, and <allow users="?"/>
to allow anonymous only or <allow users="*"/>
for all:
<configuration>
<location path="Path/To/Public/Folder">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
</configuration>
Register your handler with signal.signal
like this:
#!/usr/bin/env python
import signal
import sys
def signal_handler(sig, frame):
print('You pressed Ctrl+C!')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()
Code adapted from here.
More documentation on signal
can be found here.
try this html code
<md-input #myInput placeholder="Item name..." [(ngModel)]="name"></md-input>
<div *ngFor="let item of filteredItems | search: name">
{{item.name}}
</div>
use search pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'search'
})
export class SearchPipe implements PipeTransform {
transform(value: any, args?: any): any {
if(!value)return null;
if(!args)return value;
args = args.toLowerCase();
return value.filter(function(item){
return JSON.stringify(item).toLowerCase().includes(args);
});
}
}
You need a permission for this
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
and method:
public boolean saveImageOnExternalData(String filePath, byte[] fileData) {
boolean isFileSaved = false;
try {
File f = new File(filePath);
if (f.exists())
f.delete();
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
fos.write(fileData);
fos.flush();
fos.close();
isFileSaved = true;
// File Saved
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOException");
e.printStackTrace();
}
return isFileSaved;
// File Not Saved
}
You can follow one of the below approaches:
1) Basic, single type :
//One type
public static <T> void fill(List <T> list, T val) {
for(int i=0; i<list.size(); i++){
list.set(i, val);
}
}
2) Multiple Types :
// multiple types as parameters
public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) {
return val1+" "+val2;
}
3) Below will raise compiler error as 'T3 is not in the listing of generic types that are used in function declaration part.
//Raised compilation error
public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) {
return 0;
}
Correct : Compiles fine
public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) {
return 0;
}
Sample Class Code :
package generics.basics;
import java.util.ArrayList;
import java.util.List;
public class GenericMethods {
/*
Declare the generic type parameter T in this method.
After the qualifiers public and static, you put <T> and
then followed it by return type, method name, and its parameters.
Observe : type of val is 'T' and not '<T>'
* */
//One type
public static <T> void fill(List <T> list, T val) {
for(int i=0; i<list.size(); i++){
list.set(i, val);
}
}
// multiple types as parameters
public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) {
return val1+" "+val2;
}
/*// Q: To audience -> will this compile ?
*
* public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) {
return 0;
}*/
public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) {
return null;
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
System.out.println(list.toString());
fill(list, 100);
System.out.println(list.toString());
List<String> Strlist = new ArrayList<>();
Strlist.add("Chirag");
Strlist.add("Nayak");
System.out.println(Strlist.toString());
fill(Strlist, "GOOD BOY");
System.out.println(Strlist.toString());
System.out.println(multipleTypeArgument("Chirag", 100));
System.out.println(multipleTypeArgument(100,"Nayak"));
}
}
// class definition ends
Sample Output:
[10, 20]
[100, 100]
[Chirag, Nayak]
[GOOD BOY, GOOD BOY]
Chirag 100
100 Nayak
The specific method used to set environment variables will vary by CI service, build approach, platform and tools you're using.
If you're using Buddybuild for CI to build an app and manage environment variables, and you need access to config from JS, create a env.js.example
with keys (with empty string values) for check-in to source control, and use Buddybuild to produce an env.js
file at build time in the post-clone
step, hiding the file contents from the build logs, like so:
#!/usr/bin/env bash
ENVJS_FILE="$BUDDYBUILD_WORKSPACE/env.js"
# Echo what's happening to the build logs
echo Creating environment config file
# Create `env.js` file in project root
touch $ENVJS_FILE
# Write environment config to file, hiding from build logs
tee $ENVJS_FILE > /dev/null <<EOF
module.exports = {
AUTH0_CLIENT_ID: '$AUTH0_CLIENT_ID',
AUTH0_DOMAIN: '$AUTH0_DOMAIN'
}
EOF
Tip: Don't forget to add env.js
to .gitignore
so config and secrets aren't checked into source control accidentally during development.
You can then manage how the file gets written using the Buddybuild variables like BUDDYBUILD_VARIANTS
, for instance, to gain greater control over how your config is produced at build time.
I know this post is really old but I worked on a package that does this called flask_optional_routes. The code is located at: https://github.com/sudouser2010/flask_optional_routes.
from flask import Flask
from flask_optional_routes import OptionalRoutes
app = Flask(__name__)
optional = OptionalRoutes(app)
@optional.routes('/<user_id>/<user_name>?/')
def foobar(user_id, user_name=None):
return 'it worked!'
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000)
Just for the fun of it:
CURDATE() = DATE(NOW())
Or
NOW() = CONCAT(CURDATE(), ' ', CURTIME())
I prefer visual presentation:
+------------------------------------------------------------------------------+
¦ Property ¦ HashMap ¦ TreeMap ¦ LinkedHashMap ¦
¦--------------+---------------------+-------------------+---------------------¦
¦ Iteration ¦ no guarantee order ¦ sorted according ¦ ¦
¦ Order ¦ will remain constant¦ to the natural ¦ insertion-order ¦
¦ ¦ over time ¦ ordering ¦ ¦
¦--------------+---------------------+-------------------+---------------------¦
¦ Get/put ¦ ¦ ¦ ¦
¦ remove ¦ O(1) ¦ O(log(n)) ¦ O(1) ¦
¦ containsKey ¦ ¦ ¦ ¦
¦--------------+---------------------+-------------------+---------------------¦
¦ ¦ ¦ NavigableMap ¦ ¦
¦ Interfaces ¦ Map ¦ Map ¦ Map ¦
¦ ¦ ¦ SortedMap ¦ ¦
¦--------------+---------------------+-------------------+---------------------¦
¦ ¦ ¦ ¦ ¦
¦ Null ¦ allowed ¦ only values ¦ allowed ¦
¦ values/keys ¦ ¦ ¦ ¦
¦--------------+---------------------------------------------------------------¦
¦ ¦ Fail-fast behavior of an iterator cannot be guaranteed ¦
¦ Fail-fast ¦ impossible to make any hard guarantees in the presence of ¦
¦ behavior ¦ unsynchronized concurrent modification ¦
¦--------------+---------------------------------------------------------------¦
¦ ¦ ¦ ¦ ¦
¦Implementation¦ buckets ¦ Red-Black Tree ¦ double-linked ¦
¦ ¦ ¦ ¦ buckets ¦
¦--------------+---------------------------------------------------------------¦
¦ Is ¦ ¦
¦ synchronized ¦ implementation is not synchronized ¦
+------------------------------------------------------------------------------+
I ran into this issue with my desktop application ('Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine). I did not have the option to build as a 32 bit app. Hoping this would help others in the same situation.
I did the following and the issue went away:
Installed the 64 bit version of Microsoft Access Database Engine 2010 Redistributable, as suggested by neo
Changed my provider to Microsoft.ACE.OLEDB.12.0
Try this
-moz-box-shadow:0 5px 5px rgba(182, 182, 182, 0.75);
-webkit-box-shadow: 0 5px 5px rgba(182, 182, 182, 0.75);
box-shadow: 0 5px 5px rgba(182, 182, 182, 0.75);
You can see it in http://jsfiddle.net/wJ7qp/
I've used $(textarea).val/html/text(any_str_var)
all worked for me.
If you want to be sure that your variable as a string is added to the textarea, you can always concat like so:
$(textarea).val(unknown_var + '')
.val() method is definitely used on textarea - see: https://api.jquery.com/val/
.html() can be used to get or set the contents of any element - see: https://api.jquery.com/html/#html2
.text() is the same as .html except this can be used to set XML content: see - https://api.jquery.com/text/#text-text
You can also read more about how each act upon special characters with each of those links.
You could also use JDBC to achieve this. Let's create a sample csv file.
write.table(x=mtcars, file="mtcars.csv", sep=",", row.names=F, col.names=T) # create example csv file
Download and save the the CSV JDBC driver from this link: http://sourceforge.net/projects/csvjdbc/files/latest/download
> library(RJDBC)
> path.to.jdbc.driver <- "jdbc//csvjdbc-1.0-18.jar"
> drv <- JDBC("org.relique.jdbc.csv.CsvDriver", path.to.jdbc.driver)
> conn <- dbConnect(drv, sprintf("jdbc:relique:csv:%s", getwd()))
> head(dbGetQuery(conn, "select * from mtcars"), 3)
mpg cyl disp hp drat wt qsec vs am gear carb
1 21 6 160 110 3.9 2.62 16.46 0 1 4 4
2 21 6 160 110 3.9 2.875 17.02 0 1 4 4
3 22.8 4 108 93 3.85 2.32 18.61 1 1 4 1
> head(dbGetQuery(conn, "select mpg, gear from mtcars"), 3)
MPG GEAR
1 21 4
2 21 4
3 22.8 4
delete
is used for one single pointer and delete[]
is used for deleting an array through a pointer.
This might help you to understand better.
I'm currently managing a MySQL database on Amazon's cloud infrastructure that has grown to 160 GB. Query performance is fine. What has become a nightmare is backups, restores, adding slaves, or anything else that deals with the whole dataset, or even DDL on large tables. Getting a clean import of a dump file has become problematic. In order to make the process stable enough to automate, various choices needed to be made to prioritize stability over performance. If we ever had to recover from a disaster using a SQL backup, we'd be down for days.
Horizontally scaling SQL is also pretty painful, and in most cases leads to using it in ways you probably did not intend when you chose to put your data in SQL in the first place. Shards, read slaves, multi-master, et al, they are all really shitty solutions that add complexity to everything you ever do with the DB, and not one of them solves the problem; only mitigates it in some ways. I would strongly suggest looking at moving some of your data out of MySQL (or really any SQL) when you start approaching a dataset of a size where these types of things become an issue.
Update: a few years later, and our dataset has grown to about 800 GiB. In addition, we have a single table which is 200+ GiB and a few others in the 50-100 GiB range. Everything I said before holds. It still performs just fine, but the problems of running full dataset operations have become worse.
Building on the examples above I thought I'd throw in a way of transparently binding a controller variable to a service variable.
In the example below changes to the Controller $scope.count
variable will automatically be reflected in the Service count
variable.
In production we're actually using the this binding to update an id on a service which then asynchronously fetches data and updates its service vars. Further binding that means that controllers automagically get updated when the service updates itself.
The code below can be seen working at http://jsfiddle.net/xuUHS/163/
View:
<div ng-controller="ServiceCtrl">
<p> This is my countService variable : {{count}}</p>
<input type="number" ng-model="count">
<p> This is my updated after click variable : {{countS}}</p>
<button ng-click="clickC()" >Controller ++ </button>
<button ng-click="chkC()" >Check Controller Count</button>
</br>
<button ng-click="clickS()" >Service ++ </button>
<button ng-click="chkS()" >Check Service Count</button>
</div>
Service/Controller:
var app = angular.module('myApp', []);
app.service('testService', function(){
var count = 10;
function incrementCount() {
count++;
return count;
};
function getCount() { return count; }
return {
get count() { return count },
set count(val) {
count = val;
},
getCount: getCount,
incrementCount: incrementCount
}
});
function ServiceCtrl($scope, testService)
{
Object.defineProperty($scope, 'count', {
get: function() { return testService.count; },
set: function(val) { testService.count = val; },
});
$scope.clickC = function () {
$scope.count++;
};
$scope.chkC = function () {
alert($scope.count);
};
$scope.clickS = function () {
++testService.count;
};
$scope.chkS = function () {
alert(testService.count);
};
}
As complementary answer I would like to offer an alternative. I'm using git-ftp and it works fine.
https://github.com/git-ftp/git-ftp
Easy to use, only type:
git ftp push
and git will automatically upload project files.
Regards
I ran into a similar situation today - deploying an app to a mac os x server, and receiving the 'getaddrinfo' message when I tried to access an external api. It turns out that the error occurs when the ssh session that originally launched the app is no longer active. That's why everything works perfectly if you ssh into your server and run commands manually (or launch the server manually) - as long as you keep your ssh session alive, this error won't occur.
Whether this is a bug or a quirk in OS X, I'm not sure. Here's the page that led me to the solution - http://lists.apple.com/archives/unix-porting/2010/Jul/msg00001.html
All I had to do was update my capistrano task to launch the app using 'nohup'. So changing
run "cd #{current_path} && RAILS_ENV=production unicorn_rails -c config/unicorn.rb -D"
to
run "cd #{current_path} && RAILS_ENV=production nohup unicorn_rails -c config/unicorn.rb -D"
did the trick for me.
Hope this helps somebody - it was quite a pain to figure out!
WebConfigurationManager.ConnectionStrings["YourConnectionString"].ProviderName;
To display the Alt text of missing images, we have to add a style like this. I think, there is no need to add extra javascript for this.
.Your_Image_Class_Name {
font-size: 14px;
}
It's work for me. Enjoy!!!!
i know this is an old post, but wanted to share how i solved the same problem.
My image was inheriting a float:left from a parent class. By setting float:none I was able to make margin:0 auto and display: block work properly. Hope it may help someone in the future.
Solution that will work for multiple scopes and multiple variables within those scopes
This service was based off of Anton's answer, but is more extensible and will work across multiple scopes and allows the selection of multiple scope variables in the same scope. It uses the route path to index each scope, and then the scope variable names to index one level deeper.
Create service with this code:
angular.module('restoreScope', []).factory('restoreScope', ['$rootScope', '$route', function ($rootScope, $route) {
var getOrRegisterScopeVariable = function (scope, name, defaultValue, storedScope) {
if (storedScope[name] == null) {
storedScope[name] = defaultValue;
}
scope[name] = storedScope[name];
}
var service = {
GetOrRegisterScopeVariables: function (names, defaultValues) {
var scope = $route.current.locals.$scope;
var storedBaseScope = angular.fromJson(sessionStorage.restoreScope);
if (storedBaseScope == null) {
storedBaseScope = {};
}
// stored scope is indexed by route name
var storedScope = storedBaseScope[$route.current.$$route.originalPath];
if (storedScope == null) {
storedScope = {};
}
if (typeof names === "string") {
getOrRegisterScopeVariable(scope, names, defaultValues, storedScope);
} else if (Array.isArray(names)) {
angular.forEach(names, function (name, i) {
getOrRegisterScopeVariable(scope, name, defaultValues[i], storedScope);
});
} else {
console.error("First argument to GetOrRegisterScopeVariables is not a string or array");
}
// save stored scope back off
storedBaseScope[$route.current.$$route.originalPath] = storedScope;
sessionStorage.restoreScope = angular.toJson(storedBaseScope);
},
SaveState: function () {
// get current scope
var scope = $route.current.locals.$scope;
var storedBaseScope = angular.fromJson(sessionStorage.restoreScope);
// save off scope based on registered indexes
angular.forEach(storedBaseScope[$route.current.$$route.originalPath], function (item, i) {
storedBaseScope[$route.current.$$route.originalPath][i] = scope[i];
});
sessionStorage.restoreScope = angular.toJson(storedBaseScope);
}
}
$rootScope.$on("savestate", service.SaveState);
return service;
}]);
Add this code to your run function in your app module:
$rootScope.$on('$locationChangeStart', function (event, next, current) {
$rootScope.$broadcast('savestate');
});
window.onbeforeunload = function (event) {
$rootScope.$broadcast('savestate');
};
Inject the restoreScope service into your controller (example below):
function My1Ctrl($scope, restoreScope) {
restoreScope.GetOrRegisterScopeVariables([
// scope variable name(s)
'user',
'anotherUser'
],[
// default value(s)
{ name: 'user name', email: '[email protected]' },
{ name: 'another user name', email: '[email protected]' }
]);
}
The above example will initialize $scope.user to the stored value, otherwise will default to the provided value and save that off. If the page is closed, refreshed, or the route is changed, the current values of all registered scope variables will be saved off, and will be restored the next time the route/page is visited.
Delete Multiple checkbox using PHP Code
<input type="checkbox" name="chkbox[] value=".$row[0]."/>
<input type="submit" name="delete" value="delete"/>
<?php
if(isset($_POST['delete']))
{
$cnt=array();
$cnt=count($_POST['chkbox']);
for($i=0;$i<$cnt;$i++)
{
$del_id=$_POST['chkbox'][$i];
$query="delete from $tablename where Id=".$del_id;
mysql_query($query);
}
}
You can simply use:
mvn --settings YourOwnSettings.xml clean install
or
mvn -s YourOwnSettings.xml clean install
With the help of the given links I was able to solve the problem myself. The correct way is to get the resource ID with
getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
"raw", getPackageName());
To get it as a InputStream
InputStream ins = getResources().openRawResource(
getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
"raw", getPackageName()));
RAND(CHECKSUM(NEWID()))
The above will generate a (pseudo-) random number between 0 and 1, exclusive. If used in a select, because the seed value changes for each row, it will generate a new random number for each row (it is not guaranteed to generate a unique number per row however).
Example when combined with an upper limit of 10 (produces numbers 1 - 10):
CAST(RAND(CHECKSUM(NEWID())) * 10 as INT) + 1
Transact-SQL Documentation:
You shouldn't use both ngRoute
and UI-router
. Here's a sample code for UI-router:
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
_x000D_
$stateProvider_x000D_
.state('state1', {_x000D_
url: "/state1",_x000D_
templateUrl: "partials/state1.html",_x000D_
controller: 'YourCtrl'_x000D_
})_x000D_
_x000D_
.state('state2', {_x000D_
url: "/state2",_x000D_
templateUrl: "partials/state2.html",_x000D_
controller: 'YourOtherCtrl'_x000D_
});_x000D_
$urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?
You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router
What about sending a SIGSTOP to itself?
This should pause the process until SIGCONT is received. Which is in your case: never.
kill -STOP "$$";
# grace time for signal delivery
sleep 60;
I search a way to map a many-to-many association table with extra column(s) with hibernate in xml files configuration.
Assuming with have two table 'a' & 'c' with a many to many association with a column named 'extra'. Cause I didn't find any complete example, here is my code. Hope it will help :).
First here is the Java objects.
public class A implements Serializable{
protected int id;
// put some others fields if needed ...
private Set<AC> ac = new HashSet<AC>();
public A(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Set<AC> getAC() {
return ac;
}
public void setAC(Set<AC> ac) {
this.ac = ac;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
final int prime = 97;
int result = 1;
result = prime * result + id;
return result;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof A))
return false;
final A other = (A) obj;
if (id != other.getId())
return false;
return true;
}
}
public class C implements Serializable{
protected int id;
// put some others fields if needed ...
public C(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
final int prime = 98;
int result = 1;
result = prime * result + id;
return result;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof C))
return false;
final C other = (C) obj;
if (id != other.getId())
return false;
return true;
}
}
Now, we have to create the association table. The first step is to create an object representing a complex primary key (a.id, c.id).
public class ACId implements Serializable{
private A a;
private C c;
public ACId() {
super();
}
public A getA() {
return a;
}
public void setA(A a) {
this.a = a;
}
public C getC() {
return c;
}
public void setC(C c) {
this.c = c;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((a == null) ? 0 : a.hashCode());
result = prime * result
+ ((c == null) ? 0 : c.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ACId other = (ACId) obj;
if (a == null) {
if (other.a != null)
return false;
} else if (!a.equals(other.a))
return false;
if (c == null) {
if (other.c != null)
return false;
} else if (!c.equals(other.c))
return false;
return true;
}
}
Now let's create the association object itself.
public class AC implements java.io.Serializable{
private ACId id = new ACId();
private String extra;
public AC(){
}
public ACId getId() {
return id;
}
public void setId(ACId id) {
this.id = id;
}
public A getA(){
return getId().getA();
}
public C getC(){
return getId().getC();
}
public void setC(C C){
getId().setC(C);
}
public void setA(A A){
getId().setA(A);
}
public String getExtra() {
return extra;
}
public void setExtra(String extra) {
this.extra = extra;
}
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
AC that = (AC) o;
if (getId() != null ? !getId().equals(that.getId())
: that.getId() != null)
return false;
return true;
}
public int hashCode() {
return (getId() != null ? getId().hashCode() : 0);
}
}
At this point, it's time to map all our classes with hibernate xml configuration.
A.hbm.xml and C.hxml.xml (quiete the same).
<class name="A" table="a">
<id name="id" column="id_a" unsaved-value="0">
<generator class="identity">
<param name="sequence">a_id_seq</param>
</generator>
</id>
<!-- here you should map all others table columns -->
<!-- <property name="otherprop" column="otherprop" type="string" access="field" /> -->
<set name="ac" table="a_c" lazy="true" access="field" fetch="select" cascade="all">
<key>
<column name="id_a" not-null="true" />
</key>
<one-to-many class="AC" />
</set>
</class>
<class name="C" table="c">
<id name="id" column="id_c" unsaved-value="0">
<generator class="identity">
<param name="sequence">c_id_seq</param>
</generator>
</id>
</class>
And then association mapping file, a_c.hbm.xml.
<class name="AC" table="a_c">
<composite-id name="id" class="ACId">
<key-many-to-one name="a" class="A" column="id_a" />
<key-many-to-one name="c" class="C" column="id_c" />
</composite-id>
<property name="extra" type="string" column="extra" />
</class>
Here is the code sample to test.
A = ADao.get(1);
C = CDao.get(1);
if(A != null && C != null){
boolean exists = false;
// just check if it's updated or not
for(AC a : a.getAC()){
if(a.getC().equals(c)){
// update field
a.setExtra("extra updated");
exists = true;
break;
}
}
// add
if(!exists){
ACId idAC = new ACId();
idAC.setA(a);
idAC.setC(c);
AC AC = new AC();
AC.setId(idAC);
AC.setExtra("extra added");
a.getAC().add(AC);
}
ADao.save(A);
}
According to the Javascript standard, String.replace
isn't supposed to modify the string itself. It just returns the modified string. You can refer to the Mozilla Developer Network documentation for more info.
You can always just set the string to the modified value:
variableABC = variableABC.replace('B', 'D')
Edit: The code given above is to only replace the first occurrence.
To replace all occurrences, you could do:
variableABC = variableABC.replace(/B/g, "D");
To replace all occurrences and ignore casing
variableABC = variableABC.replace(/B/gi, "D");
You should include bootstrap-datepicker.js
after bootstrap.js
and you should bind the datepicker
to your control.
$(function(){
$('.datepicker').datepicker({
format: 'mm-dd-yyyy'
});
});
Since you don't need to actually edit the file:
I would like to give you also the idea to disable an <option>
with a given defined value (not innerhtml
). I recommend to it with jQuery
to get the simplest way. See my sample below.
HTML
Status:
<div id="option">
<select class="status">
<option value="hand" selected>Hand</option>
<option value="simple">Typed</option>
<option value="printed">Printed</option>
</select>
</div>
Javascript
The idea here is how to disable Printed
option when current Status
is Hand
var status = $('#option').find('.status');//to get current the selected value
var op = status.find('option');//to get the elements for disable attribute
(status.val() == 'hand')? op[2].disabled = true: op[2].disabled = false;
You may see how it works here:
Error:Execution failed for task com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException:
finished with non-zero exit value 1
One reason for this error to occure is that the file path to a resource file is to long:
Error: File path too long on Windows, keep below 240 characters
Fix: Move your project folder closer to the root of your disk
Don't:// folder/folder/folder/folder/very_long_folder_name/MyProject...
Do://folder/short_name/MyProject
Another reason could be duplicated resources or name spaces
Example:
<style name="MyButton" parent="android:Widget.Button">
<item name="android:textColor">@color/accent_color</item>
<item name="android:textColor">#000000</item>
</style>
And make sure all file names and extensions are in lowercase
Wrong
myimage.PNG
myImage.png
Correct
my_image.png
Make sure to Clean/Rebuild project
(delete the 'build' folder)
Perl implementation of @Jean-Paul's algorithm.
#!/usr/bin/perl
use strict;
use Data::Dumper;
sub mean {
my $data = shift;
my $sum = 0;
my $mean_val = 0;
for my $item (@$data) {
$sum += $item;
}
$mean_val = $sum / (scalar @$data) if @$data;
return $mean_val;
}
sub variance {
my $data = shift;
my $variance_val = 0;
my $mean_val = mean($data);
my $sum = 0;
for my $item (@$data) {
$sum += ($item - $mean_val)**2;
}
$variance_val = $sum / (scalar @$data) if @$data;
return $variance_val;
}
sub std {
my $data = shift;
my $variance_val = variance($data);
return sqrt($variance_val);
}
# @param y - The input vector to analyze
# @parameter lag - The lag of the moving window
# @parameter threshold - The z-score at which the algorithm signals
# @parameter influence - The influence (between 0 and 1) of new signals on the mean and standard deviation
sub thresholding_algo {
my ($y, $lag, $threshold, $influence) = @_;
my @signals = (0) x @$y;
my @filteredY = @$y;
my @avgFilter = (0) x @$y;
my @stdFilter = (0) x @$y;
$avgFilter[$lag - 1] = mean([@$y[0..$lag-1]]);
$stdFilter[$lag - 1] = std([@$y[0..$lag-1]]);
for (my $i=$lag; $i <= @$y - 1; $i++) {
if (abs($y->[$i] - $avgFilter[$i-1]) > $threshold * $stdFilter[$i-1]) {
if ($y->[$i] > $avgFilter[$i-1]) {
$signals[$i] = 1;
} else {
$signals[$i] = -1;
}
$filteredY[$i] = $influence * $y->[$i] + (1 - $influence) * $filteredY[$i-1];
$avgFilter[$i] = mean([@filteredY[($i-$lag)..($i-1)]]);
$stdFilter[$i] = std([@filteredY[($i-$lag)..($i-1)]]);
}
else {
$signals[$i] = 0;
$filteredY[$i] = $y->[$i];
$avgFilter[$i] = mean([@filteredY[($i-$lag)..($i-1)]]);
$stdFilter[$i] = std([@filteredY[($i-$lag)..($i-1)]]);
}
}
return {
signals => \@signals,
avgFilter => \@avgFilter,
stdFilter => \@stdFilter
};
}
my $y = [1,1,1.1,1,0.9,1,1,1.1,1,0.9,1,1.1,1,1,0.9,1,1,1.1,1,1,1,1,1.1,0.9,1,1.1,1,1,0.9,
1,1.1,1,1,1.1,1,0.8,0.9,1,1.2,0.9,1,1,1.1,1.2,1,1.5,1,3,2,5,3,2,1,1,1,0.9,1,1,3,
2.6,4,3,3.2,2,1,1,0.8,4,4,2,2.5,1,1,1];
my $lag = 30;
my $threshold = 5;
my $influence = 0;
my $result = thresholding_algo($y, $lag, $threshold, $influence);
print Dumper $result;
function yourfunctionName() {
var yourFileName = $("#yourinputfieldis").val();
var yourFileExtension = yourFileName .replace(/^.*\./, '');
switch (yourFileExtension ) {
case 'pdf':
case 'jpg':
case 'doc':
$("#formId").submit();// your condition what you want to do
break;
default:
alert('your File extension is wrong.');
this.value = '';
}
}
I'm really not sure what you're doing to get that error, it looks like you're trying to run cx_Freeze on its own, without arguments. So here is a short step-by-step guide on how to do it in windows (Your screenshot looks rather like the windows command line, so I'm assuming that's your platform)
Write your setup.py file. Your script above looks correct so it should work, assuming that your script exists.
Open the command line (Start
-> Run
-> "cmd"
)
Go to the location of your setup.py file and run python setup.py build
Notes:
There may be a problem with the name of your script. "Main.py" contains upper case letters, which might cause confusion since windows' file names are not case sensitive, but python is. My approach is to always use lower case for scripts to avoid any conflicts.
Make sure that python is on your PATH (read http://docs.python.org/using/windows.html)1
Make sure are are looking at the new cx_Freeze documentation. Google often seems to bring up the old docs.
In the default installation, call a page that doesn't exist and you get an error with the version at the end:
Object not found!
The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.
If you think this is a server error, please contact the webmaster.
Error 404
localhost
10/03/08 14:41:45
Apache/2.2.8 (Win32) DAV/2 mod_ssl/2.2.8 OpenSSL/0.9.8g mod_autoindex_color PHP/5.2.5
Url.Action("Evil", model)
will generate a get query string but your ajax method is post and it will throw error status of 500(Internal Server Error). – Fereydoon Barikzehy Feb 14 at 9:51
Just Add "JsonRequestBehavior.AllowGet" on your Json object.
The issue seems to be that you are adding the deffered.promise
when deffered
is itself the promise you should be adding:
Try changing to promises.push(deffered);
so you don't add the unwrapped promise to the array.
UploadService.uploadQuestion = function(questions){
var promises = [];
for(var i = 0 ; i < questions.length ; i++){
var deffered = $q.defer();
var question = questions[i];
$http({
url : 'upload/question',
method: 'POST',
data : question
}).
success(function(data){
deffered.resolve(data);
}).
error(function(error){
deffered.reject();
});
promises.push(deffered);
}
return $q.all(promises);
}
You have to use value attribute
to get its value
<input type="text" name="FirstName" value="First Name" />
try -
var text = $('#DynamicValueAssignedHere').find('input[name="FirstName"]').val();
OP wanted two specific maps, but if you'd like to have a dynamic number of maps on one page (for instance a list of retailer locations) you need to go another route. The standard implementation of Google maps API defines the map as a global variable, this won't work with a dynamic number of maps. Here's my code to solve this without global variables:
function mapAddress(mapElement, address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var mapOptions = {
zoom: 14,
center: results[0].geometry.location,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById(mapElement), mapOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
Just pass the ID and address of each map to the function to plot the map and mark the address.
dataGridView1.Sort(dataGridView1.Columns[0],ListSortDirection.Ascending);
Yes, O3 is buggier. I'm a compiler developer and I've identified clear and obvious gcc bugs caused by O3 generating buggy SIMD assembly instructions when building my own software. From what I've seen, most production software ships with O2 which means O3 will get less attention wrt testing and bug fixes.
Think of it this way: O3 adds more transformations on top of O2, which adds more transformations on top of O1. Statistically speaking, more transformations means more bugs. That's true for any compiler.
This is an interesting and insightful discussion with so many experts contributing. I feel this post should be looped back from within the Android development main website, because it does revolve around one of the core designs of the Android OS.
I would also like to add my two cents here.
So far I have been impressed with Android's way of handling lifecycle events, bringing the concept of a web-like experience to native apps.
Having said that I still believe that there should be a Quit button. Why? ... not for me or Ted or any of the tech gurus here, but for the sole purpose of meeting an end user demand.
Though I am not a big fan of Windows, but long back they introduced a concept that most end users are used to (an X button) ... "I want to quit running a widget when 'I' want to".
That does not mean someone (OS, developer?) will take care of that at its/his/her own discretion... it simply means "where is my Red X button that I am used to". My action should be analogous to 'end a call on pressing of a button', 'turn off the device by pressing a button', and so on and so forth ... it's a perception. It brings a satisfaction per se that my action indeed achieve its purpose.
Even though a developer can spoof this behavior using suggestions given here, the perception still remains i.e. an application should completely cease to function (now), by an independent, trusted and neutral source (OS) on demand from the end user.
I did this before using the MSXML library and then using the XMLHttpRequest object, see here.
You can pass the authorised keys in to your container using a shared folder and set permissions using a docker file like this:
FROM ubuntu:16.04
RUN apt-get install -y openssh-server
RUN mkdir /var/run/sshd
EXPOSE 22
RUN cp /root/auth/id_rsa.pub /root/.ssh/authorized_keys
RUN rm -f /root/auth
RUN chmod 700 /root/.ssh
RUN chmod 400 /root/.ssh/authorized_keys
RUN chown root. /root/.ssh/authorized_keys
CMD /usr/sbin/sshd -D
And your docker run contains something like the following to share an auth directory on the host (holding the authorised_keys) with the container then open up the ssh port which will be accessable through port 7001 on the host.
-d -v /home/thatsme/dockerfiles/auth:/root/auth -–publish=127.0.0.1:7001:22
You may want to look at https://github.com/jpetazzo/nsenter which appears to be another way to open a shell on a container and execute commands within a container.
This should do it:
ALTER TABLE test MODIFY locationExpert VARCHAR(120)
While TheBrent's answer is true in general, it does not answer the question of how to do it in the official bootstrap way. The markup for bootstrap is simple:
<ul class="inline">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
The Rope container may be worth if have to insert/delete string into the random place of destination string or for a long char sequences. Here is an example from SGI's implementation:
crope r(1000000, 'x'); // crope is rope<char>. wrope is rope<wchar_t>
// Builds a rope containing a million 'x's.
// Takes much less than a MB, since the
// different pieces are shared.
crope r2 = r + "abc" + r; // concatenation; takes on the order of 100s
// of machine instructions; fast
crope r3 = r2.substr(1000000, 3); // yields "abc"; fast.
crope r4 = r2.substr(1000000, 1000000); // also fast.
reverse(r2.mutable_begin(), r2.mutable_end());
// correct, but slow; may take a
// minute or more.
Remember that each Add
will check the capacity of the collection and resize it whenever necessary (slower). With AddRange
, the collection will be set the capacity and then added the items (faster). This extension method will be extremely slow, but will work.
I know this is an older question, but for reference, a really simple way for formatting dates without any data annotations or any other settings is as follows:
@Html.TextBoxFor(m => m.StartDate, new { @Value = Model.StartDate.ToString("dd-MMM-yyyy") })
The above format can of course be changed to whatever.
As with many tasks in ggplot, the general strategy is to put what you'd like to add to the plot into a data frame in a way such that the variables match up with the variables and aesthetics in your plot. So for example, you'd create a new data frame like this:
dfTab <- as.data.frame(table(df))
colnames(dfTab)[1] <- "x"
dfTab$lab <- as.character(100 * dfTab$Freq / sum(dfTab$Freq))
So that the x
variable matches the corresponding variable in df
, and so on. Then you simply include it using geom_text
:
ggplot(df) + geom_bar(aes(x,fill=x)) +
geom_text(data=dfTab,aes(x=x,y=Freq,label=lab),vjust=0) +
opts(axis.text.x=theme_blank(),axis.ticks=theme_blank(),
axis.title.x=theme_blank(),legend.title=theme_blank(),
axis.title.y=theme_blank())
This example will plot just the percentages, but you can paste
together the counts as well via something like this:
dfTab$lab <- paste(dfTab$Freq,paste("(",dfTab$lab,"%)",sep=""),sep=" ")
Note that in the current version of ggplot2, opts
is deprecated, so we would use theme
and element_blank
now.
* {
margin: 0;
}
html, body {
height: 90%;
}
.content {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto ;
}
just try
<img :src="require(`${imgPreUrl}img/logo.png`)">
_x000D_
I tried what Disco S2 suggested, it was close but this is what ended up working for me. This was called after completing an action inside another tab.
for (UINavigationController *controller in self.tabBarController.viewControllers)
{
if ([controller isKindOfClass:[MyViewController class]])
{
[self.tabBarController setSelectedViewController:controller];
break;
}
}
The problem you're having is that the event-handlers are being bound before the elements are present in the DOM, if you wrap the jQuery inside of a $(document).ready()
then it should work perfectly well:
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").show("slow");
});
});
An alternative is to place the <script></script>
at the foot of the page, so it's encountered after the DOM has been loaded and ready.
To make the div
hide again, once the #music
element is clicked, simply use toggle()
:
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").toggle();
});
});
And for fading:
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").fadeToggle();
});
});
This is more of a continuation of jglouie's response.
If you are using openssl to convert the PKCS#12 certificate to public/private PEM keys, there is no need to rename the file. Assuming the file is called cert.pfx, the following three commands will create a public pem key and an encrypted private pem key:
openssl pkcs12 -in cert.pfx -out cert.pem -nodes -nokeys
openssl pkcs12 -in cert.pfx -out cert_key.pem -nodes -nocerts
openssl rsa -in cert_key.pem -out cert_key.pem -des3
The first two commands may prompt for an import password. This will be a password that was provided with the PKCS#12 file.
The third command will let you specify the encryption passphrase for the certificate. This is what you will enter when using the certificate.
<script type="text/javascript">
function AlertFilesize(){
if(window.ActiveXObject){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.getElementById('fileInput').value;
var thefile = fso.getFile(filepath);
var sizeinbytes = thefile.size;
}else{
var sizeinbytes = document.getElementById('fileInput').files[0].size;
}
var fSExt = new Array('Bytes', 'KB', 'MB', 'GB');
fSize = sizeinbytes; i=0;while(fSize>900){fSize/=1024;i++;}
alert((Math.round(fSize*100)/100)+' '+fSExt[i]);
}
</script>
<input id="fileInput" type="file" onchange="AlertFilesize();" />
Work on IE and FF
You can use these tools:
Sample code to change an image into a byte array
public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using (var ms = new MemoryStream())
{
imageIn.Save(ms,imageIn.RawFormat);
return ms.ToArray();
}
}
C# Image to Byte Array and Byte Array to Image Converter Class
You can do it like:
val df = sqlContext.emptyDataFrame
if( df.eq(sqlContext.emptyDataFrame) )
println("empty df ")
else
println("normal df")
You can do something just like this.
IF EXISTS ( SELECT * FROM TableName WHERE Column=colval)
BEGIN
select
select name ,Id from TableName WHERE Column=colval
END
ELSE
SELECT 'test' as name,0 as Id
If you offer cbind
a set of arguments all of whom are vectors, you will get not a dataframe, but rather a matrix, in this case an all character matrix. They have different features. You can get a dataframe if some of your arguments remain dataframes, Try:
merger <- cbind(Date =as.character(Date),
weather1[ , c("High", "Low", "Avg..High", "Avg.Low")] ,
ScnMov =sale$Scanned.Movement[a] )
you can use the UNION ALL
keyword for this.
Here is the MSDN doc to do it in T-SQL http://msdn.microsoft.com/en-us/library/ms180026.aspx
UNION ALL - combines the result set
UNION- Does something like a Set Union and doesnt output duplicate values
For the difference with an example: http://sql-plsql.blogspot.in/2010/05/difference-between-union-union-all.html
Have you tried os.mkdir?
You might also try this little code snippet:
mypath = ...
if not os.path.isdir(mypath):
os.makedirs(mypath)
makedirs creates multiple levels of directories, if needed.
Named exports:
Let's say you create a file called utils.js
, with utility functions that you want to make available for other modules (e.g. a React component). Then you would make each function a named export:
export function add(x, y) {
return x + y
}
export function mutiply(x, y) {
return x * y
}
Assuming that utils.js is located in the same directory as your React component, you can use its exports like this:
import { add, multiply } from './utils.js';
...
add(2, 3) // Can be called wherever in your component, and would return 5.
Or if you prefer, place the entire module's contents under a common namespace:
import * as utils from './utils.js';
...
utils.multiply(2,3)
Default exports:
If you on the other hand have a module that only does one thing (could be a React class, a normal function, a constant, or anything else) and want to make that thing available to others, you can use a default export. Let's say we have a file log.js
, with only one function that logs out whatever argument it's called with:
export default function log(message) {
console.log(message);
}
This can now be used like this:
import log from './log.js';
...
log('test') // Would print 'test' in the console.
You don't have to call it log
when you import it, you could actually call it whatever you want:
import logToConsole from './log.js';
...
logToConsole('test') // Would also print 'test' in the console.
Combined:
A module can have both a default export (max 1), and named exports (imported either one by one, or using *
with an alias). React actually has this, consider:
import React, { Component, PropTypes } from 'react';
You need:
public int sumAll(int...numbers){
int result = 0;
for(int i = 0 ; i < numbers.length; i++) {
result += numbers[i];
}
return result;
}
Then call the method and give it as many int values as you need:
int result = sumAll(1,4,6,3,5,393,4,5);//.....
System.out.println(result);
git reset
does know five "modes": soft, mixed, hard, merge and keep. I will start with the first three, since these are the modes you'll usually encounter. After that you'll find a nice little a bonus, so stay tuned.
When using git reset --soft HEAD~1
you will remove the last commit from the current branch, but the file changes will stay in your working tree. Also the changes will stay on your index, so following with a git commit
will create a commit with the exact same changes as the commit you "removed" before.
This is the default mode and quite similar to soft. When "removing" a commit with git reset HEAD~1
you will still keep the changes in your working tree but not on the index; so if you want to "redo" the commit, you will have to add the changes (git add
) before commiting.
When using git reset --hard HEAD~1
you will lose all uncommited changes in addition to the changes introduced in the last commit. The changes won't stay in your working tree so doing a git status
command will tell you that you don't have any changes in your repository.
Tread carefully with this one. If you accidentally remove uncommited changes which were never tracked by git
(speak: committed or at least added to the index), you have no way of getting them back using git
.
git reset --keep HEAD~1
is an interesting and useful one. It only resets the files which are different between the current HEAD
and the given commit. It aborts the reset if one or more of these files has uncommited changes. It basically acts as a safer version of hard
.
You can read more about that in the git reset documentation.
Note
When doing git reset
to remove a commit the commit isn't really lost, there just is no reference pointing to it or any of it's children. You can still recover a commit which was "deleted" with git reset
by finding it's SHA-1 key, for example with a command such as git reflog
.
This is the code I'm using to embed images into HTML mail and PDF documents.
<?php
$logo_path = 'http://localhost/img/logo.jpg';
$type = pathinfo($logo_path, PATHINFO_EXTENSION);
$image_contents = file_get_contents($logo_path);
$image64 = 'data:image/' . $type . ';base64,' . base64_encode($image_contents);
echo '<img src="' . $image64 .'" />';
?>
Since Java 8, there are some standard options to do this in JDK:
Collection<E> in = ...
Object[] mapped = in.stream().map(e -> doMap(e)).toArray();
// or
List<E> mapped = in.stream().map(e -> doMap(e)).collect(Collectors.toList());
See java.util.Collection.stream()
and java.util.stream.Collectors.toList()
.
How exact do you need it to be? td.days / 365.25
will get you pretty close, if you're worried about leap years.
Much like jdsumsion's answer you can also stash your current work but then use a difftool like meld to pull selected changes from the stash. That way you can even edit the hunks manually very easy, which is a bit of a pain when in git add -p
:
$ git stash -u
$ git difftool -d -t meld stash
$ git commit -a -m "some message"
$ git stash pop
Using the stash method gives you the opportunity to test, if your code still works, before you commit it.
If anyone came to this question looking for ways to add multiple parameters at the same time (my case), you can use .params
with a MultivalueMap instead of adding each .param
:
LinkedMultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>()
requestParams.add("id", "1");
requestParams.add("name", "john");
requestParams.add("age", "30");
mockMvc.perform(get("my/endpoint").params(requestParams)).andExpect(status().isOk())
To print the last column of a line just use $(NF):
awk '{print $(NF)}'
git pull
prints Already up-to-date
solution:
you might be created a repository/project in remote(server) and added some file there, Then again created a Folder in your local and initialised git git init
- this is the mistake, you should not create git init
in local, instead clone the project to your local using git clone
then pull
My implementation
import $ from 'jquery';
$(document).ready(() => {
$('#whatDescribesYouSelectInput').on('change', (e) => {
if (e.target.value === 'Other') {
$('#whatDescribesYouOtherInput').attr('type', 'text');
$('#specifyLabel').show();
} else {
$('#whatDescribesYouOtherInput').attr('type', 'hidden');
$('#specifyLabel').hide();
}
});
});
Old question but worth adding an answer if using .NET Core 3.0 or later. JSON serialization/deserialization is built into the framework (System.Text.Json), so you don't have to use third party libraries any more. Here's an example based off the top answer given by @Icarus
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var json = "[{\"Name\":\"John Smith\", \"Age\":35}, {\"Name\":\"Pablo Perez\", \"Age\":34}]";
// use the built in Json deserializer to convert the string to a list of Person objects
var people = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(json);
foreach (var person in people)
{
Console.WriteLine(person.Name + " is " + person.Age + " years old.");
}
}
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
}
}
Should be as simple as:
git reset --hard 56e05f
That'll get you back to that specific point in time.
You may use event handler serverclick as below
//cmdAction is the id of HTML button as below
<body>
<form id="form1" runat="server">
<button type="submit" id="cmdAction" text="Button1" runat="server">
Button1
</button>
</form>
</body>
//cs code
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
cmdAction.ServerClick += new EventHandler(submit_click);
}
protected void submit_click(object sender, EventArgs e)
{
Response.Write("HTML Server Button Control");
}
}
I recently needed to do this as well... here's how I got to it:
$_product->getMediaGalleryImages()->getItemByColumnValue('label', 'LABEL_NAME')->getUrl();
Hope that helps you!
For windows users ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
I had the same issue, and this trick works for me
Hope this helps..
public interface IService {
String BASE_URL = "https://api.demo.com/";
@GET("Login") //i.e https://api.demo.com/Search?
Call<Products> getUserDetails(@Query("email") String emailID, @Query("password") String password)
}
It will be called this way. Considering you did the rest of the code already.
Call<Results> call = service.getUserDetails("[email protected]", "Password@123");
For example when a query is returned, it will look like this.
https://api.demo.com/[email protected]&password=Password@123
After facing so many troubles, here is the solution that I found.
open that file in any text editor and find your missing file ItemGroup.
<ItemGroup>
<None Include="..." />
</ItemGroup>
remove that ItemGroup and open once again your project and build
I think you misunderstand Unicode and its relationship to Perl. No matter which way you store data, Unicode, ISO-8859-1, or many other things, your program has to know how to interpret the bytes it gets as input (decoding) and how to represent the information it wants to output (encoding). Get that interpretation wrong and you garble the data. There isn't some magic default setup inside your program that's going to tell the stuff outside your program how to act.
You think it's hard, most likely, because you are used to everything being ASCII. Everything you should have been thinking about was simply ignored by the programming language and all of the things it had to interact with. If everything used nothing but UTF-8 and you had no choice, then UTF-8 would be just as easy. But not everything does use UTF-8. For instance, you don't want your input handle to think that it's getting UTF-8 octets unless it actually is, and you don't want your output handles to be UTF-8 if the thing reading from them can't handle UTF-8. Perl has no way to know those things. That's why you are the programmer.
I don't think Unicode in Perl 5 is too complicated. I think it's scary and people avoid it. There's a difference. To that end, I've put Unicode in Learning Perl, 6th Edition, and there's a lot of Unicode stuff in Effective Perl Programming. You have to spend the time to learn and understand Unicode and how it works. You're not going to be able to use it effectively otherwise.
This is a sample program for calculating sum of integers for variable arguments and array on integers. Hope this helps.
var CalculateSum = function(){
calculateSumService.apply( null, arguments );
}
var calculateSumService = function(){
var sum = 0;
if( arguments.length === 1){
var args = arguments[0];
for(var i = 0;i<args.length; i++){
sum += args[i];
}
}else{
for(var i = 0;i<arguments.length; i++){
sum += arguments[i];
}
}
alert(sum);
}
//Sample method call
// CalculateSum(10,20,30);
// CalculateSum([10,20,30,40,50]);
// CalculateSum(10,20);
It's case by case. We want to minimize the "total cost of ownership" of the software over its lifespan. Stating "using namespace std" has some costs, but not using it also has a cost in legibility.
People correctly point out that when using it, when the standard library introduces new symbols and definitions, your code ceases to compile, and you may be forced to rename variables. And yet this is probably good long-term, since future maintainers will be momentarily confused or distracted if you're using a keyword for some surprising purpose.
You don't want to have a template called vector, say, which isn't the vector known by everyone else. And the number of new definitions thus introduced in the C++ library is small enough it may simply not come up. There is a cost to having to do this kind of change, but the cost is not high and is offset by the clarity gained by not using std
symbol names for other purposes.
Given the number of classes, variables, and functions, stating std::
on every one might fluff up your code by 50% and make it harder to get your head around. An algorithm or step in a method that could be taken in on one screenful of code now requires scrolling back and forth to follow. This is a real cost. Arguably it may not be a high cost, but people who deny it even exists are inexperienced, dogmatic, or simply wrong.
I'd offer the following rules:
std
is different from all other libraries. It is the one library everyone basically needs to know, and in my view is best thought of as part of the language. Generally speaking there is an excellent case for using namespace std
even if there isn't for other libraries.
Never force the decision onto the author of a compilation unit (a .cpp file) by putting this using
in a header. Always defer the decision to the compilation unit author. Even in a project that has decided to use using namespace std
everywhere may fine a few modules that are best handled as exceptions to that rule.
Even though the namespace feature lets you have many modules with symbols defined the same, it's going to be confusing to do so. Keep the names different to the extent possible. Even if not using the namespace feature, if you have a class named foo
and std
introduces a class named foo
, it's probably better long-run to rename your class anyway.
An alternative to using namespaces is to manually namespace symbols by prefixing them. I have two libraries I've used for decades, both starting as C libraries, actually, where every symbol is prefixed with "AK" or "SCWin". Generally speaking, this is like avoiding the "using" construct, but you don't write the twin colons. AK::foo()
is instead AKFoo()
. It makes code 5-10% denser and less verbose, and the only downside is that you'll be in big trouble if you have to use two such libraries that have the same prefixing. Note the X Window libraries are excellent in this regard, except they forgot to do so with a few #defines: TRUE and FALSE should have been XTRUE and XFALSE, and this set up a namespace clash with Sybase or Oracle that likewise used TRUE and FALSE with different values! (ASCII 0 and 1 in the case of the database!) One special advantage of this is that it applies seemlessly to preprocessor definitions, whereas the C++ using
/namespace
system doesn't handle them. A nice benefit of this is that it gives an organic slope from being part of a project to eventually being a library. In a large application of mine, all window classes are prefixed Win
, all signal-processing modules Mod, and so on. There's little chance of any of these being reused so there's no practical benefit to making each group into a library, but it makes obvious in a few seconds how the project breaks into sub-projects.
It was setting the DNS that did the trick for me. If you are using the Eclipse or Netbeans plugins, you can set it through Default Emulator options, or Emulator Options respectively. You can also use set it from the command line if you start your emulator from CLI. In all cases, the option is "-dns-server x.x.x.x,x.x.x.x" without the quotes. There is no option in the ADB gui to permanently associate the option with your virtual device.
Order of magnitude: zero.
In other words, you won't see your throughput cut in half, or anything like it, when you add TLS. Answers to the "duplicate" question focus heavily on application performance, and how that compares to SSL overhead. This question specifically excludes application processing, and seeks to compare non-SSL to SSL only. While it makes sense to take a global view of performance when optimizing, that is not what this question is asking.
The main overhead of SSL is the handshake. That's where the expensive asymmetric cryptography happens. After negotiation, relatively efficient symmetric ciphers are used. That's why it can be very helpful to enable SSL sessions for your HTTPS service, where many connections are made. For a long-lived connection, this "end-effect" isn't as significant, and sessions aren't as useful.
Here's an interesting anecdote. When Google switched Gmail to use HTTPS, no additional resources were required; no network hardware, no new hosts. It only increased CPU load by about 1%.
I'm adding this for posterity; There's an easier way that doesn't involve writing more JS. Using the amazing firebug addon for firefox,
override onReceivedSslError and remove
super.onReceivedSslError(view, handler, error)
And to solve Google security:
setDomStorageEnabled(true);
Full code is:
webView.enableJavaScript();
webView.getSettings().setDomStorageEnabled(true); // Add this
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.setWebViewClient(new WebViewClient(){
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
// DO NOT CALL SUPER METHOD
super.onReceivedSslError(view, handler, error);
}
});
Fortunately, jQuery selectors allow you much more freedom:
$("div a").click( function(event)
{
var clicked = $(this); // jQuery wrapper for clicked element
// ... click-specific code goes here ...
});
...will attach the specified callback to each <a>
contained in a <div>
.
Two solutions for this error:
1. add this permission in your androidManifest.xml of your Android project
<uses-permission android:name="android.permission.INTERNET"/>
2. Turn on the Internet Connection of your device first.
I also got the same error in my SQL Code, This solution works for me,
Check the data in Primary Table May be you are entering a column value which is not present in the primary key column.
Disable time zone.
Use challenge.datetime_start.replace(tzinfo=None);
You can also use replace(tzinfo=None)
for other datetime.
if challenge.datetime_start.replace(tzinfo=None) <= datetime.now().replace(tzinfo=None) <= challenge.datetime_end.replace(tzinfo=None):
A bit late for probable answer, might help new people. In case you have multiple instances of database:
mongoimport --host <host_name>:<host_port> --db <database_name> --collection <collection_name> --file <path_to_dump_file> -u <my_user> -p <my_pass>
Assuming credentials needed, otherwise remove this option.
To complete answers in case of editing default value :
In your rails console :
rails g migration MigrationName
In the migration :
def change
change_column :tables, :field_name, :field_type, default: value
end
Will look like :
def change
change_column :members, :approved, :boolean, default: true
end
I was trying to do the exact same thing, open a text file (a CSV for Pandas actually). Don't want to make a copy of it, just want to open it. The form-WTF has a nice file browser, but then it opens the file and makes a temporary file, which it presents as a memory stream. With a little work under the hood,
form = UploadForm()
if form.validate_on_submit():
filename = secure_filename(form.fileContents.data.filename)
filestream = form.fileContents.data
filestream.seek(0)
ef = pd.read_csv( filestream )
sr = pd.DataFrame(ef)
return render_template('dataframe.html',tables=[sr.to_html(justify='center, classes='table table-bordered table-hover')],titles = [filename], form=form)
I had same problem and finally I understood that my node version is old. For example, you can install the current active LTS node version in Ubuntu by the following steps:
sudo apt-get update
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
sudo apt-get install nodejs -y
Installation instructions for more versions and systems can be found in the following link:
https://github.com/nodesource/distributions/blob/master/README.md
In my case (using IntelliJ) File
- Invalidate Caches / Restart...
did the trick.
==
be used on enum
?Yes: enums have tight instance controls that allows you to use ==
to compare instances. Here's the guarantee provided by the language specification (emphasis by me):
JLS 8.9 Enums
An enum type has no instances other than those defined by its enum constants.
It is a compile-time error to attempt to explicitly instantiate an enum type. The
final clone
method inEnum
ensures thatenum
constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of anenum
type exist beyond those defined by theenum
constants.Because there is only one instance of each
enum
constant, it is permissible to use the==
operator in place of theequals
method when comparing two object references if it is known that at least one of them refers to anenum
constant. (Theequals
method inEnum
is afinal
method that merely invokessuper.equals
on its argument and returns the result, thus performing an identity comparison.)
This guarantee is strong enough that Josh Bloch recommends, that if you insist on using the singleton pattern, the best way to implement it is to use a single-element enum
(see: Effective Java 2nd Edition, Item 3: Enforce the singleton property with a private constructor or an enum type; also Thread safety in Singleton)
==
and equals
?As a reminder, it needs to be said that generally, ==
is NOT a viable alternative to equals
. When it is, however (such as with enum
), there are two important differences to consider:
==
never throws NullPointerException
enum Color { BLACK, WHITE };
Color nothing = null;
if (nothing == Color.BLACK); // runs fine
if (nothing.equals(Color.BLACK)); // throws NullPointerException
==
is subject to type compatibility check at compile timeenum Color { BLACK, WHITE };
enum Chiral { LEFT, RIGHT };
if (Color.BLACK.equals(Chiral.LEFT)); // compiles fine
if (Color.BLACK == Chiral.LEFT); // DOESN'T COMPILE!!! Incompatible types!
==
be used when applicable?Bloch specifically mentions that immutable classes that have proper control over their instances can guarantee to their clients that ==
is usable. enum
is specifically mentioned to exemplify.
Item 1: Consider static factory methods instead of constructors
[...] it allows an immutable class to make the guarantee that no two equal instances exist:
a.equals(b)
if and only ifa==b
. If a class makes this guarantee, then its clients can use the==
operator instead of theequals(Object)
method, which may result in improved performance. Enum types provide this guarantee.
To summarize, the arguments for using ==
on enum
are:
The count function is meant to be used on
A stdClass is neither of these. The easier/quickest way to accomplish what you're after is
$count = count(get_object_vars($some_std_class_object));
This uses PHP's get_object_vars function, which will return the properties of an object as an array. You can then use this array with PHP's count function.
Are you perhaps using java.sql.Date
? While that has millisecond granularity as a Java class (it is a subclass of java.util.Date
, bad design decision), it will be interpreted by the JDBC driver as a date without a time component. You have to use java.sql.Timestamp
instead.
As it often happens, this question is confusing as hell. People are coming here having two different tasks in mind:
That's two absolutely different tasks that have nothing in common and cannot be solved by the same function. Ironically, for neither of them the actual PDOStatement::rowCount()
function has to be used.
Let's see why
Before using PDO I just simply used
mysql_num_rows()
.
Means you already did it wrong. Using mysql_num_rows()
or rowCount()
to count the number of rows in the table is a real disaster in terms of consuming the server resources. A database has to read all the rows from the disk, consume the memory on the database server, then send all this heap of data to PHP, consuming PHP process' memory as well, burdening your server with absolute no reason.
Besides, selecting rows only to count them simply makes no sense. A count(*)
query has to be run instead. The database will count the records out of the index, without reading the actual rows and then only one row returned.
For this purpose the code suggested in the accepted answer is fair, save for the fact it won't be an "extra" query but the only query to run.
The second use case is not as disastrous as rather pointless: in case you need to know whether your query returned any data, you always have the data itself!
Say, if you are selecting only one row. All right, you can use the fetched row as a flag:
$stmt->execute();
$row = $stmt->fetch();
if (!$row) { // here! as simple as that
echo 'No data found';
}
In case you need to get many rows, then you can use fetchAll()
.
fetchAll()
is something I won't want as I may sometimes be dealing with large datasets
Yes of course, for the first use case it would be twice as bad. But as we learned already, just don't select the rows only to count them, neither with rowCount()
nor fetchAll()
.
But in case you are going to actually use the rows selected, there is nothing wrong in using fetchAll()
. Remember that in a web application you should never select a huge amount of rows. Only rows that will be actually used on a web page should be selected, hence you've got to use LIMIT
, WHERE
or a similar clause in your SQL. And for such a moderate amount of data it's all right to use fetchAll()
. And again, just use this function's result in the condition:
$stmt->execute();
$data = $stmt->fetchAll();
if (!$data) { // again, no rowCount() is needed!
echo 'No data found';
}
And of course it will be absolute madness to run an extra query only to tell whether your other query returned any rows, as it suggested in the two top answers.
In such a rare case when you need to select a real huge amount of rows (in a console application for example), you have to use an unbuffered query, in order to reduce the amount of memory used. But this is the actual case when rowCount()
won't be available, thus there is no use for this function as well.
Hence, that's the only use case when you may possibly need to run an extra query, in case you'd need to know a close estimate for the number of rows selected.
You can actually do what Chris Chalmers does in his answer, but you must make sure that HAML doesn't parse the JavaScript. This approach is actually useful when you need to use a different type than text/javascript
, which is was I needed to do for MathJax
.
You can use the plain
filter to keep HAML from parsing the script and throwing an illegal nesting error:
%script{type: "text/x-mathjax-config"}
:plain
MathJax.Hub.Config({
tex2jax: {
inlineMath: [["$","$"],["\\(","\\)"]]
}
});
CONVERT(VARCHAR,GETDATE(),120)