Here's how Stoyan Stefanov does it in his JavaScript Patterns book which I found to be very good (it also shows how he does comments that allows for auto-generated API documentation, and how to add a method to a custom object's prototype):
/**
* My JavaScript application
*
* @module myapp
*/
/** @namespace Namespace for MYAPP classes and functions. */
var MYAPP = MYAPP || {};
/**
* A maths utility
* @namespace MYAPP
* @class math_stuff
*/
MYAPP.math_stuff = {
/**
* Sums two numbers
*
* @method sum
* @param {Number} a First number
* @param {Number} b Second number
* @return {Number} Sum of the inputs
*/
sum: function (a, b) {
return a + b;
},
/**
* Multiplies two numbers
*
* @method multi
* @param {Number} a First number
* @param {Number} b Second number
* @return {Number} The inputs multiplied
*/
multi: function (a, b) {
return a * b;
}
};
/**
* Constructs Person objects
* @class Person
* @constructor
* @namespace MYAPP
* @param {String} First name
* @param {String} Last name
*/
MYAPP.Person = function (first, last) {
/**
* First name of the Person
* @property first_name
* @type String
*/
this.first_name = first;
/**
* Last name of the Person
* @property last_name
* @type String
*/
this.last_name = last;
};
/**
* Return Person's full name
*
* @method getName
* @return {String} First name + last name
*/
MYAPP.Person.prototype.getName = function () {
return this.first_name + ' ' + this.last_name;
};
There is a simple solution, which is the HTML5 input
event. It's supported in current versions of all major browsers for <input type="text">
elements and there's a simple workaround for IE < 9. See the following answers for more details:
Example (except IE < 9: see links above for workaround):
$("#your_id").on("input", function() {
alert("Change to " + this.value);
});
Don't like any of those solutions.
this is how i do it:
$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='"
. sqlEsc($somename) . "' ;";
then i use my own sqlEsc function:
function sqlEsc($val)
{
global $mysqli;
return mysqli_real_escape_string($mysqli, $val);
}
If you use homebrew cask, you can do
brew cask install android-sdk
mkdir ~/Library/Android/sdk/tools
ln -s /usr/local/bin/ ~/Library/Android/sdk/tools/bin
flutter doctor --android-licenses
mysql 5.4 provides a native split function:
SPLIT_STR(<column>, '<delimiter>', <index>)
System.IO.Path.GetTempPath()
The path specified by the TMP
environment variable.
The path specified by the TEMP
environment variable.
The path specified by the USERPROFILE
environment variable.
The Windows directory.
Run php --ini
in your terminal, you'll get all details about ini files
[root@tamilan src]# php --ini
Configuration File (php.ini) Path: /etc
Loaded Configuration File: /etc/php.ini
Scan for additional .ini files in: /etc/php.d
Additional .ini files parsed: /etc/php.d/apc.ini,
/etc/php.d/bcmath.ini,
/etc/php.d/curl.ini,
/etc/php.d/dba.ini,
/etc/php.d/dom.ini,
/etc/php.d/fileinfo.ini,
/etc/php.d/gd.ini,
/etc/php.d/imap.ini,
/etc/php.d/json.ini,
/etc/php.d/mbstring.ini,
/etc/php.d/memcache.ini,
/etc/php.d/mysql.ini,
/etc/php.d/mysqli.ini,
/etc/php.d/pdo.ini,
/etc/php.d/pdo_mysql.ini,
/etc/php.d/pdo_sqlite.ini,
/etc/php.d/phar.ini,
/etc/php.d/posix.ini,
/etc/php.d/sqlite3.ini,
/etc/php.d/ssh2.ini,
/etc/php.d/sysvmsg.ini,
/etc/php.d/sysvsem.ini,
/etc/php.d/sysvshm.ini,
/etc/php.d/wddx.ini,
/etc/php.d/xmlreader.ini,
/etc/php.d/xmlwriter.ini,
/etc/php.d/xsl.ini,
/etc/php.d/zip.ini
For more, use helping command php --help
It'll display all the possible options.
Here's an extension method using @Kolman's answer. It's marginally easier to remember to use Path() than GetLeftPart. You might want to rename Path to GetPath, at least until they add extension properties to C#.
Usage:
Uri uri = new Uri("http://www.somewhere.com?param1=foo¶m2=bar");
string path = uri.Path();
The class:
using System;
namespace YourProject.Extensions
{
public static class UriExtensions
{
public static string Path(this Uri uri)
{
if (uri == null)
{
throw new ArgumentNullException("uri");
}
return uri.GetLeftPart(UriPartial.Path);
}
}
}
AttributeError("'str' object has no attribute 'read'",)
This means exactly what it says: something tried to find a .read
attribute on the object that you gave it, and you gave it an object of type str
(i.e., you gave it a string).
The error occurred here:
json.load (jsonofabitch)['data']['children']
Well, you aren't looking for read
anywhere, so it must happen in the json.load
function that you called (as indicated by the full traceback). That is because json.load
is trying to .read
the thing that you gave it, but you gave it jsonofabitch
, which currently names a string (which you created by calling .read
on the response
).
Solution: don't call .read
yourself; the function will do this, and is expecting you to give it the response
directly so that it can do so.
You could also have figured this out by reading the built-in Python documentation for the function (try help(json.load)
, or for the entire module (try help(json)
), or by checking the documentation for those functions on http://docs.python.org .
You're most likely looking at using a flash/silverlight/activeX control. The <input type="file" />
control doesn't handle that.
If you don't mind the user selecting a file as a means to getting its directory, you may be able to bind to that control's change
event then strip the filename portion and save the path somewhere--but that's about as good as it gets.
Keep in mind that webpages are designed to interact with servers. Nothing about providing a local directory to a remote server is "typical" (a server can't access it so why ask for it?); however files are a means to selectively passing information.
you may try the TO_CHAR function to convert the result
e.g.
SELECT TO_CHAR(92, '99.99') AS RES FROM DUAL
SELECT TO_CHAR(92.258, '99.99') AS RES FROM DUAL
Hope it helps
You can also do like this if you're only interested in extracting the "user_id":
String userId =
given().
contentType("application/json").
body(requestBody).
when().
post("/admin").
then().
statusCode(200).
extract().
path("user_id");
In its simplest form it looks like this:
String userId = get("/person").path("person.userId");
If you want to post parameter in okhttp as body content which can be encrypted string with content-type as "application/x-www-form-urlencoded" you can first use URLEncoder to encode the data and then use :
final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("application/x-www-form-urlencoded");
okhttp3.Request request = new okhttp3.Request.Builder()
.url(urlOfServer)
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, yourBodyDataToPostOnserver))
.build();
you can add header according to your requirement.
Oh Raphael has moved on significantly since June. There is a new charting library that can work with it and these are very eye catching. Raphael also supports full SVG path syntax and is incorporating really advanced path methods. Come see 1.2.8+ at my site (Shameless plug) and then bounce over to the Dmitry's site from there. http://www.irunmywebsite.com/raphael/raphaelsource.html
Try this. It uses the split
function which is a core part of javascript, nothing to do with jQuery.
var parts = html.split(":-"),
i, l
;
for (i = 0, l = parts.length; i < l; i += 2) {
$("#" + parts[i]).text(parts[i + 1]);
}
Just write <a href="#"></a>
.
If that's what you want, you don't need a server-side control.
For what should be completely obvious reasons, ordinary Apps are not allowed to create arbitrary windows on top of the lock screen. What do you think I could do if I created a window on your lockscreen that could perfectly imitate the real lockscreen so you couldn't tell the difference?
The technical reason for your error is the use of the TYPE_KEYGUARD_DIALOG
flag - it requires android.permission.INTERNAL_SYSTEM_WINDOW
which is a signature-level permission. This means that only Apps signed with the same certificate as the creator of the permission can use it.
The creator of android.permission.INTERNAL_SYSTEM_WINDOW
is the Android system itself, so unless your App is part of the OS, you don't stand a chance.
There are well defined and well documented ways of notifying the user of information from the lockscreen. You can create customised notifications which show on the lockscreen and the user can interact with them.
Typing cd
will take you back to your home directory.
Whereas typing cd ..
will move you up only one directory (the direct parent of the current directory).
string is an alias for String in the .NET Framework.
Where "String" is in fact System.String.
I would say that they are interchangeable and there is no difference when and where you should use one or the other.
It would be better to be consistent with which one you did use though.
For what it's worth, I use string
to declare types - variables, properties, return values and parameters. This is consistent with the use of other system types - int, bool, var
etc (although Int32
and Boolean
are also correct).
I use String when using the static methods on the String class, like String.Split()
or String.IsNullOrEmpty()
. I feel that this makes more sense because the methods belong to a class, and it is consistent with how I use other static methods.
Personally I would go with:
DataTable tbl = Gridview1.DataSource as DataTable;
This would allow you to test for null as this results in either DataTable object or null. Casting it as a DataTable using (DataTable)Gridview1.DataSource would cause a crashing error in case the DataSource is actually a DataSet or even some kind of collection.
Supporting Documentation: MSDN Documentation on "as"
I also came across this problem. In my case, I didn't know the type of the IEnumerable. So the answers given above wont work. However, I solved it like this:
public static DataTable CreateDataTable(IEnumerable source)
{
var table = new DataTable();
int index = 0;
var properties = new List<PropertyInfo>();
foreach (var obj in source)
{
if (index == 0)
{
foreach (var property in obj.GetType().GetProperties())
{
if (Nullable.GetUnderlyingType(property.PropertyType) != null)
{
continue;
}
properties.Add(property);
table.Columns.Add(new DataColumn(property.Name, property.PropertyType));
}
}
object[] values = new object[properties.Count];
for (int i = 0; i < properties.Count; i++)
{
values[i] = properties[i].GetValue(obj);
}
table.Rows.Add(values);
index++;
}
return table;
}
Keep in mind that using this method, requires at least one item in the IEnumerable. If that's not the case, the DataTable wont create any columns.
I have follow Wellington Lorindo posting. And My problem was solved.
Steps 1. run in terminal
ps ax | grep mysql
Result was
11200 ? Ssl 0:01 /usr/sbin/mysqld
11514 pts/0 S+ 0:00 grep mysql
Steps 2. Again type this
sudo service mysql start
And problem solved.
Thanks Wellington Lorindo
It's the remainder operator and is used to get the remainder after integer division. Lots of languages have it. For example:
10 % 3 // = 1 ; because 3 * 3 gets you 9, and 10 - 9 is 1.
Apparently it is not the same as the modulo operator entirely.
This fixed my issue:
Go to terminal shell and type mongo
.
Then type use db_name
.
Then type:
db.createUser(
{
user: "mongodb",
pwd: "dogmeatsubparflavour1337",
roles: [ { role: "dbOwner", db: "db_name" } ]
}
)
Also try: db.getUsers()
Quick sample:
const MongoClient = require('mongodb').MongoClient;
// MongoDB Connection Info
const url = 'mongodb://mongodb:[email protected]:27017/?authMechanism=DEFAULT&authSource=db_name';
// Additional options: https://docs.mongodb.com/manual/reference/connection-string/#connection-string-options
// Use Connect Method to connect to the Server
MongoClient.connect(url)
.then((db) => {
console.log(db);
console.log('Casually connected correctly to server.');
// Be careful with db.close() when working asynchronously
db.close();
})
.catch((error) => {
console.log(error);
});
Use this library: https://github.com/lukas-krecan/JsonUnit
Pom:
<dependency>
<groupId>net.javacrumbs.json-unit</groupId>
<artifactId>json-unit-assertj</artifactId>
<version>2.24.0</version>
<scope>test</scope>
</dependency>
IGNORING_ARRAY_ORDER - ignores order in arrays
assertThatJson("{\"test\":[1,2,3]}")
.when(Option.IGNORING_ARRAY_ORDER)
.isEqualTo("{\"test\": [3,2,1]}");
I've discovered in Excel 2007, if the results are a Table from an embedded query, the ss.000 does not work. I can paste the query results (from SQL Server Management Studio), and format the time just fine. But when I embed the query as a Data Connection in Excel, the format always gives .000 as the milliseconds.
size param increases the hits displayed from from the default(10) to 500.
http://localhost:9200/[indexName]/_search?pretty=true&size=500&q=*:*
Change the from step by step to get all the data.
http://localhost:9200/[indexName]/_search?size=500&from=0
https://www.w3schools.com/bootstrap/bootstrap_ref_js_modal.asp
Note: For <a>
elements, omit data-target, and use href="#modalID"
instead.
To enable CORS, 1.Go to App_Start folder. 2.add the namespace 'using System.Web.Http.Cors'; 3.Open the WebApiConfig.cs file and type the following in a static method.
config.EnableCors(new EnableCorsAttribute("https://localhost:44328",headers:"*", methods:"*"));
_x000D_
This is a simple answer, this will allow you to clear the screen for example. There are two examples below, with eval and exec, that will print 0 at the top after cleaning (if you're using Windows, change clear
to cls
, Linux and Mac users leave as is for example) or just execute it, respectively.
eval("os.system(\"clear\")")
exec("os.system(\"clear\")")
With recent browsers you can use the HTML5 download attribute as well:
<a download="quot.pdf" href="../doc/quot.pdf">Click here to Download quotation</a>
It is supported by most of the recent browsers except MSIE11. You can use a polyfill, something like this (note that this is for data uri only, but it is a good start):
(function (){
addEvent(window, "load", function (){
if (isInternetExplorer())
polyfillDataUriDownload();
});
function polyfillDataUriDownload(){
var links = document.querySelectorAll('a[download], area[download]');
for (var index = 0, length = links.length; index<length; ++index) {
(function (link){
var dataUri = link.getAttribute("href");
var fileName = link.getAttribute("download");
if (dataUri.slice(0,5) != "data:")
throw new Error("The XHR part is not implemented here.");
addEvent(link, "click", function (event){
cancelEvent(event);
try {
var dataBlob = dataUriToBlob(dataUri);
forceBlobDownload(dataBlob, fileName);
} catch (e) {
alert(e)
}
});
})(links[index]);
}
}
function forceBlobDownload(dataBlob, fileName){
window.navigator.msSaveBlob(dataBlob, fileName);
}
function dataUriToBlob(dataUri) {
if (!(/base64/).test(dataUri))
throw new Error("Supports only base64 encoding.");
var parts = dataUri.split(/[:;,]/),
type = parts[1],
binData = atob(parts.pop()),
mx = binData.length,
uiArr = new Uint8Array(mx);
for(var i = 0; i<mx; ++i)
uiArr[i] = binData.charCodeAt(i);
return new Blob([uiArr], {type: type});
}
function addEvent(subject, type, listener){
if (window.addEventListener)
subject.addEventListener(type, listener, false);
else if (window.attachEvent)
subject.attachEvent("on" + type, listener);
}
function cancelEvent(event){
if (event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
}
function isInternetExplorer(){
return /*@cc_on!@*/false || !!document.documentMode;
}
})();
There is no extra advantage for each of them. It totally depends on your scenario. Code below shows their difference.
Before inserts your html here
<div id="mainTabsDiv">
Prepend inserts your html here
<div id="homeTabDiv">
<span>
Home
</span>
</div>
<div id="aboutUsTabDiv">
<span>
About Us
</span>
</div>
<div id="contactUsTabDiv">
<span>
Contact Us
</span>
</div>
Append inserts your html here
</div>
After inserts your html here
So lets say you have Activity AB that controls Frag A and Fragment B. Inside Fragment A you need an interface that Activity AB can implement. In the sample android code, they have:
private Callbacks mCallbacks = sDummyCallbacks;
/*A callback interface that all activities containing this fragment must implement. This mechanism allows activities to be notified of item selections. */
public interface Callbacks {
/*Callback for when an item has been selected. */
public void onItemSelected(String id);
}
/*A dummy implementation of the {@link Callbacks} interface that does nothing. Used only when this fragment is not attached to an activity. */
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public void onItemSelected(String id) {
}
};
The Callback interface is put inside one of your Fragments (let’s say Fragment A). I think the purpose of this Callbacks interface is like a nested class inside Frag A which any Activity can implement. So if Fragment A was a TV, the CallBacks is the TV Remote (interface) that allows Fragment A to be used by Activity AB. I may be wrong about the detail because I'm a noob but I did get my program to work perfectly on all screen sizes and this is what I used.
So inside Fragment A, we have: (I took this from Android’s Sample programs)
@Override
public void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id);
//mCallbacks.onItemSelected( PUT YOUR SHIT HERE. int, String, etc.);
//mCallbacks.onItemSelected (Object);
}
And inside Activity AB we override the onItemSelected method:
public class AB extends FragmentActivity implements ItemListFragment.Callbacks {
//...
@Override
//public void onItemSelected (CATCH YOUR SHIT HERE) {
//public void onItemSelected (Object obj) {
public void onItemSelected(String id) {
//Pass Data to Fragment B. For example:
Bundle arguments = new Bundle();
arguments.putString(“FragmentB_package”, id);
FragmentB fragment = new FragmentB();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction().replace(R.id.item_detail_container, fragment).commit();
}
So inside Activity AB, you basically throwing everything into a Bundle and passing it to B. If u are not sure how to use a Bundle, look the class up.
I am basically going by the sample code that Android provided. The one with the DummyContent stuff. When you make a new Android Application Package, it's the one titled MasterDetailFlow.
This is how you get the last record and update a field in Access DB.
UPDATE compalints
SET tkt = addzone &'-'& customer_code &'-'& sn where sn in (select max(sn) from compalints )
Would something like this work for you?
SELECT * FROM FB WHERE Dte >= DATE(NOW() - INTERVAL 2 MONTH);
I think you need a body for the getAppContext()
method:
public static Context getAppContext()
return MyApplication.context;
The fundamental issue with your code is that you mix two APIs. Unfortunately online resources are not great at pointing this out, but there are two semaphore APIs on UNIX-like systems:
Looking at the code above you used semget() from the System V API and tried to post through sem_post() which comes from the POSIX API. It is not possible to mix them.
To decide which semaphore API you want you don't have so many great resources. The simple best is the "Unix Network Programming" by Stevens. The section that you probably interested in is in Vol #2.
These two APIs are surprisingly different. Both support the textbook style semaphores but there are a few good and bad points in the System V API worth mentioning:
$('#editPOIForm').each(function(){
this.reset();
});
where editPOIForm
is the id
attribute of your form.
I had this issue happen for me as well...the issue was the packer wasn't running it seemed probably because my default shell was zsh. react-native tires to open a new terminal window and run .../node_modules/react-native/packager/launchPackager.command
but this didn't run. Manually running that (and keeping it running) fixed this for me.
You need to check that the myString
object is null
:
if (myString != null) {
doSomething
}
you may use
ImageSourceConverter class
to get what you want
img1.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("/Assets/check.png");
Even you don't need to measure the length of string. A ! operator can solve everything for you. Remember always: !(empty string) = true !(some string) = false
So you could write:
<input ng-model="somefield">
<span ng-show="!somefield">Sorry, the field is empty!</span>
<span ng-hide="!somefield">Thanks. Successfully validated!</span>
Working solution without access token as of October-14-2018:
Search for the username:
https://www.instagram.com/web/search/topsearch/?query=<username>
Example:
https://www.instagram.com/web/search/topsearch/?query=therock
This is a search query. Find the exact matched entry in the reply and get user ID from the entry.
If you are add more than argument ya dropdownlist in Asp.Net MVC. When you Edit record or pass value in view bag.
Use this it will be work:-
@Html.DropDownList("CurrencyID",null,String.Empty, new { @class = "form-control-mandatory" })
s = 'hi how are you'
l = list(map(lambda x: x,s.split()))
print(l)
Output: ['hi', 'how', 'are', 'you']
As you've noticed, you have no selectivity to your update statement so it is updating your entire table. If you want to update specific rows (ie where the IDs match) you probably want to do a coordinated subquery.
However, since you are using Oracle, it might be easier to create a materialized view for your query table and let Oracle's transaction mechanism handle the details. MVs work exactly like a table for querying semantics, are quite easy to set up, and allow you to specify the refresh interval.
I was having the same problem, finally figured out what to do:
#include <stdio.h>
#include <conio.h>
int main ()
{
int x;
float check;
reprocess:
printf ("enter a integer number:");
scanf ("%f", &check);
x=check;
if (x==check)
printf("\nYour number is %d", x);
else
{
printf("\nThis is not an integer number, please insert an integer!\n\n");
goto reprocess;
}
_getch();
return 0;
}
Try this on Windows by replacing YOURENV
:
{
...
"scripts": {
"help": "set NODE_ENV=YOURENV && tagove help",
"start": "set NODE_ENV=YOURENV && tagove start"
}
...
}
If anyone still cares on how to do this without JavaScript, let me complete Josh answer:
How to display the text of the filename:
The easiest way is to set both elements to a position:relative, give the label a higher z-index and give the input file negative margin until the label text is where you want it to be. Do not use display:none on the input!
input[type="file"] {
position:relative;
z-index:1;
margin-left:-90px;
}
.custom-file-upload {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
position:relative;
z-index:2;
background:white;
}
The absolute easiest way to stream a file into browser using ASP.NET MVC is this:
public ActionResult DownloadFile() {
return File(@"c:\path\to\somefile.pdf", "application/pdf", "Your Filename.pdf");
}
This is easier than the method suggested by @azarc3 since you don't even need to read the bytes.
Credit goes to: http://prideparrot.com/blog/archive/2012/8/uploading_and_returning_files#how_to_return_a_file_as_response
** Edit **
Apparently my 'answer' is the same as the OP's question. But I am not facing the problem he is having. Probably this was an issue with older version of ASP.NET MVC?
Since the fill() method (mentioned in the accepted answer) without arguments throw an error, I would suggest something like this (works for me, Angular 7.0.4, Typescript 3.1.6)
<div class="month" *ngFor="let item of items">
...
</div>
In component code:
this.items = Array.from({length: 10}, (v, k) => k + 1);
After many struggles and to achive a general, flexible and more readable solution, in my case I ended up saving the ORs results into ENV variables and doing the ANDs of those variables.
# RESULT_ONE = A OR B
RewriteRule ^ - [E=RESULT_ONE:False]
RewriteCond ...A... [OR]
RewriteCond ...B...
RewriteRule ^ - [E=RESULT_ONE:True]
# RESULT_TWO = C OR D
RewriteRule ^ - [E=RESULT_TWO:False]
RewriteCond ...C... [OR]
RewriteCond ...D...
RewriteRule ^ - [E=RESULT_TWO:True]
# if ( RESULT_ONE AND RESULT_TWO ) then ( RewriteRule ...something... )
RewriteCond %{ENV:RESULT_ONE} =True
RewriteCond %{ENV:RESULT_TWO} =True
RewriteRule ...something...
Requirements:
Even after double quotes, I had this problem for a few days.
Replaced Pipe Delimiter with Comma, then things worked fine.
I solved the problem by adding the following dependency
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>2.2</version>
</dependency>
Together with
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
As Kris mentions, you can use the $resource
service to interact with the server, but I get the impression you are beginning your journey with Angular - I was there last week - so I recommend to start experimenting directly with the $http
service. In this case you can call its get
method.
If you have the following JSON
[{ "text":"learn angular", "done":true },
{ "text":"build an angular app", "done":false},
{ "text":"something", "done":false },
{ "text":"another todo", "done":true }]
You can load it like this
var App = angular.module('App', []);
App.controller('TodoCtrl', function($scope, $http) {
$http.get('todos.json')
.then(function(res){
$scope.todos = res.data;
});
});
The get
method returns a promise object which
first argument is a success callback and the second an error
callback.
When you add $http
as a parameter of a function Angular does it magic
and injects the $http
resource into your controller.
I've put some examples here
This should do what you want:
sed 's/two.*/BLAH/'
$ echo " one two three five
> four two five five six
> six one two seven four" | sed 's/two.*/BLAH/'
one BLAH
four BLAH
six one BLAH
The $
is unnecessary because the .*
will finish at the end of the line anyways, and the g
at the end is unnecessary because your first match will be the first two
to the end of the line.
If you're trying to read XML generated from a URL without file_get_contents()
then you'll probably want to have a look at cURL
I recommend using https://github.com/aleksaan/diskusage utility which I wrote. Very simple and helpful. And very fast.
Just type in a command shell
diskusage.exe -path 'd:/go; d:/Books'
and get list of folders arranged by size
1.| DIR: d:/go | SIZE: 325.72 Mb | DEPTH: 1 2.| DIR: d:/Books | SIZE: 14.01 Mb | DEPTH: 1
This example was executed at 272ms on HDD.
You can increase depth of subfolders to analyze, for example:
diskusage.exe -path 'd:/go; d:/Books' -depth 2
and get sizes not only for selected folders but also for its subfolders
1.| DIR: d:/go | SIZE: 325.72 Mb | DEPTH: 1 2.| DIR: d:/go/pkg | SIZE: 212.88 Mb | DEPTH: 2 3.| DIR: d:/go/src | SIZE: 62.57 Mb | DEPTH: 2 4.| DIR: d:/go/bin | SIZE: 30.44 Mb | DEPTH: 2 5.| DIR: d:/Books/Chess | SIZE: 14.01 Mb | DEPTH: 2 6.| DIR: d:/Books | SIZE: 14.01 Mb | DEPTH: 1 7.| DIR: d:/go/api | SIZE: 6.41 Mb | DEPTH: 2 8.| DIR: d:/go/test | SIZE: 5.11 Mb | DEPTH: 2 9.| DIR: d:/go/doc | SIZE: 4.00 Mb | DEPTH: 2 10.| DIR: d:/go/misc | SIZE: 3.82 Mb | DEPTH: 2 11.| DIR: d:/go/lib | SIZE: 358.25 Kb | DEPTH: 2
*** 3.5Tb on the server has been scanned for 3m12s**
You are having this problem because you are attempting to console log app.address() before the connection has been made. You just have to be sure to console log after the connection is made, i.e. in a callback or after an event signaling that the connection has been made.
Fortunately, the 'listening' event is emitted by the server after the connection is made so just do this:
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
app.get('/', function(req, res) {
res.send("Hello World!");
});
server.listen(3000, 'localhost');
server.on('listening', function() {
console.log('Express server started on port %s at %s', server.address().port, server.address().address);
});
This works just fine in nodejs v0.6+ and Express v3.0+.
with jQuery:
$("#playerSource").attr("src", "new_src");
var audio = $("#player");
audio[0].pause();
audio[0].load();//suspends and restores all audio element
if (isAutoplay)
audio[0].play();
To add attachment, don't forget to add.
MailcapCommandMap mc = (MailcapCommandMap) CommandMap
.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
Use snprintf()
from stdlib.h
. Worked for me.
double num = 123412341234.123456789;
char output[50];
snprintf(output, 50, "%f", num);
printf("%s", output);
The following code does what is required
function doTest() {
SpreadsheetApp.getActiveSheet().getRange('F2').setValue('Hello');
}
See the first answer to Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++
Then just loop over all the elements in cout << M.at<double>(0,0);
rather than just 0,0
Or better still with the C++ interface:
cv::Mat M;
cout << "M = " << endl << " " << M << endl << endl;
You'll normally be returning JSON either because:
A) You are building part / all of your application as a Single Page Application (SPA) and you need your client-side JavaScript to be able to pull in additional data without fully reloading the page.
or
B) You are building an API that third parties will be consuming and you have decided to use JSON to serialize your data.
Or, possibly, you are eating your own dogfood and doing both
In both cases render :json => some_data
will JSON-ify the provided data. The :callback
key in the second example needs a bit more explaining (see below), but it is another variation on the same idea (returning data in a way that JavaScript can easily handle.)
:callback
?JSONP (the second example) is a way of getting around the Same Origin Policy that is part of every browser's built-in security. If you have your API at api.yoursite.com
and you will be serving your application off of services.yoursite.com
your JavaScript will not (by default) be able to make XMLHttpRequest
(XHR - aka ajax) requests from services
to api
. The way people have been sneaking around that limitation (before the Cross-Origin Resource Sharing spec was finalized) is by sending the JSON data over from the server as if it was JavaScript instead of JSON). Thus, rather than sending back:
{"name": "John", "age": 45}
the server instead would send back:
valueOfCallbackHere({"name": "John", "age": 45})
Thus, a client-side JS application could create a script
tag pointing at api.yoursite.com/your/endpoint?name=John
and have the valueOfCallbackHere
function (which would have to be defined in the client-side JS) called with the data from this other origin.)
use appcmd to export one or all the sites out then reimport into the new server. It could be iis7.0 or 7.5 When you export out using appcmd, the passwords are decrypted, then reimport and they will reencrypt.
You can use @@trancount
in MSSQL
From the documentation:
Returns the number of BEGIN TRANSACTION statements that have occurred on the current connection.
.live() was deprecated and has now been removed from jQuery 1.9 You should use .on()
UPDATE:
New link for the icons image size by apple.
https://developer.apple.com/ios/human-interface-guidelines/graphics/image-size-and-resolution/
Yes it's True here it is Apple provide Official documentation regarding icon's or image size
you have to set images for iPhone6 and iPhone6+
For iPhone 6:
750 x 1334 (@2x) for portrait
1334 x 750 (@2x) for landscape
For iPhone 6 Plus:
1242 x 2208 (@3x) for portrait
2208 x 1242 (@3x) for landscape
For more info regarding Images and it's resolution this is best ever helpful post
For setting images size for controls you can set 1x @2x and @3x like following:
I tried different solutions, such as using a text editor to insert a new line and get the End Of Line character as recommended in the top answer above. None of these worked, unfortunately.
The solution that did finally work for me was very simple: I copy-pasted the content of a CSV file into a new blank CSV file, saved it, and the problem was gone.
size()
is a method specified in java.util.Collection
, which is then inherited by every data structure in the standard library. length
is a field on any array (arrays are objects, you just don't see the class normally), and length()
is a method on java.lang.String
, which is just a thin wrapper on a char[]
anyway.
Perhaps by design, Strings are immutable, and all of the top-level Collection subclasses are mutable. So where you see "length" you know that's constant, and where you see "size" it isn't.
Give this a try
$indo=$_GET['id'];
$result = mysql_query("SELECT * FROM student WHERE IDNO='$indo'");
I think this works..
For example if you want to repeat a word called "HELP" for 1000 times the following is the best way.
word = ['HELP']
repeat = 1000 * word
Then you will get the list of 1000 words and make that into a data frame if you want by using following command
word_data =pd.DataFrame(repeat)
word_data.columns = ['list_of_words'] #To change the column name
private void SortGridGenerico< T >(
ref List< T > lista
, SortDirection sort
, string propriedadeAOrdenar)
{
if (!string.IsNullOrEmpty(propriedadeAOrdenar)
&& lista != null
&& lista.Count > 0)
{
Type t = lista[0].GetType();
if (sort == SortDirection.Ascending)
{
lista = lista.OrderBy(
a => t.InvokeMember(
propriedadeAOrdenar
, System.Reflection.BindingFlags.GetProperty
, null
, a
, null
)
).ToList();
}
else
{
lista = lista.OrderByDescending(
a => t.InvokeMember(
propriedadeAOrdenar
, System.Reflection.BindingFlags.GetProperty
, null
, a
, null
)
).ToList();
}
}
}
Having just gone round the internet to read up on this and the options in Spring I'd second Luke's answer, use BCrypt (it's mentioned in the source code at Spring).
The best resource I found to explain why to hash/salt and why use BCrypt is a good choice is here: Salted Password Hashing - Doing it Right.
In case you do not want to remove or uninstall the credentials manager: see https://serverfault.com/questions/544156/git-clone-fail-instead-of-prompting-for-credentials/1054253#answer-1054253 for the solution that worked for me.
Explanations, etc. in that page (linked to prevent duplicate content in the same website family).
TL;DR: this now sits on top of my automated bash
scripts:
# https://serverfault.com/questions/544156/git-clone-fail-instead-of-prompting-for-credentials
export GIT_TERMINAL_PROMPT=0
# next env var doesn't help...
export GIT_SSH_COMMAND='ssh -oBatchMode=yes'
# these should shut up git asking, but only partly: the X-windows-like dialog doesn't pop up no more, but ...
export GIT_ASKPASS=echo
export SSH_ASKPASS=echo
# We needed to find *THIS* to shut up the bloody git-for-windows credential manager:
# https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows#answer-45513654
export GCM_INTERACTIVE=never
The final nail in the coffin of that credentials manager was the unique bit (GCM_INTERACTIVE
) in Martin Ba's answer above: How do I disable Git Credential Manager for Windows?
Here is another method, much simple, lets say your dataframe name is daat
and column name is YEARMONTH
daat.YEARMONTH.value_counts()
Your collection class could have a method that returns a collection (a sublist) based on criteria passed in to define the filter. Build a new collection with the foreach loop and pass it out.
Or, have the method and loop modify the existing collection by setting a "filtered" or "active" flag (property). This one could work but could also cause poblems in multithreaded code. If other objects deped on the contents of the collection this is either good or bad depending of how you use the data.
As of PHP 5.5, PHP has simple, secure functions for hashing and verifying passwords, password_hash() and password_verify()
$password = 'anna';
$hash = password_hash($password, PASSWORD_DEFAULT);
$expensiveHash = password_hash($password, PASSWORD_DEFAULT, array('cost' => 20));
password_verify('anna', $hash); //Returns true
password_verify('anna', $expensiveHash); //Also returns true
password_verify('elsa', $hash); //Returns false
When password_hash()
is used, it generates a random salt and includes it in the outputted hash (along with the the cost and algorithm used.) password_verify()
then reads that hash and determines the salt and encryption method used, and verifies it against the provided plaintext password.
Providing the PASSWORD_DEFAULT
instructs PHP to use the default hashing algorithm of the installed version of PHP. Exactly which algorithm that means is intended to change over time in future versions, so that it will always be one of the strongest available algorithms.
Increasing cost (which defaults to 10) makes the hash harder to brute-force but also means generating hashes and verifying passwords against them will be more work for your server's CPU.
Note that even though the default hashing algorithm may change, old hashes will continue to verify just fine because the algorithm used is stored in the hash and password_verify()
picks up on it.
Identified this solution while reading this thread. Figured id post this for the next guy possibly.
When dealing with Laravel migration file from a package, I Ran into this issue.
My old value was
$table->increments('id');
My new
$table->integer('id')->autoIncrement();
Any !important can be overridden by another !important, the normal CSS precedence rules still apply.
Example:
#an-element{
background: #F00 !important;
}
#an-element{
background: #0F0 !important; //Makes #an-element green
}
Then you could add a style attribute (using JavaScript/jQuery) to override the CSS
$(function () {
$("#an-element").attr('style', 'background: #00F !important;');
//Makes #an-element blue
});
See the result here
Just keep it simple :)
grep + echo should suffice:
grep -qxF 'include "/configs/projectname.conf"' foo.bar || echo 'include "/configs/projectname.conf"' >> foo.bar
-q
be quiet-x
match the whole line-F
pattern is a plain stringEdit: incorporated @cerin and @thijs-wouters suggestions.
I even run the command prompt as Administrator but it didn't work for me with the below error.
'keytool' is not recognized as an internal or external command,
operable program or batch file.
If the path to the keytool is not in your System paths then you will need to use the full path to use the keytool, which is
C:\Program Files\Java\jre<version>\bin
So, the command should be like
"C:\Program Files\Java\jre<version>\bin\keytool.exe" -importcert -alias certificateFileAlias -file CertificateFileName.cer -keystore cacerts
that worked for me.
Check out the Arrays.fill methods.
int[] array = new int[4];
Arrays.fill(array, 0);
Study up on multidimensional arrays. This question might help.
It is not a good idea to return iterators. Iterators become invalid when modifications to the vector (inversion\deletion ) happens. Also, the iterator is a local object created on stack and hence returning the address of the same is not at all safe. I'd suggest you to work with myObject rather than vector iterators.
EDIT: If the object is lightweight then its better you return the object itself. Otheriwise return pointers to myObject stored in the vector.
Current for 2016 link is https://msdn.microsoft.com/en-us/library/mt204009.aspx
SQL Server Data Tools in Visual Studio 2015 is a modern development tool that you can download for free to build SQL Server relational databases, Azure SQL databases, Integration Services packages, Analysis Services data models, and Reporting Services reports. With SSDT, you can design and deploy any SQL Server content type with the same ease as you would develop an application in Visual Studio. This release supports SQL Server 2016 through SQL Server 2005, and provides the design environment for adding features that are new in SQL Server 2016.
Note that you don't need to have Visual Studio pre-installed. SSDT will install required components of VS, if it is not installed on your machine.
This release supports SQL Server 2016 through SQL Server 2005, and provides the design environment for adding features that are new in SQL Server 2016
Previously included in SQL Server standalone Business Intelligence Studio is not available any more and in last years replaced by SQL Server Data Tools (SSDT) for Visual Studio. See answer http://sqlmag.com/sql-server-2014/q-where-business-intelligence-development-studio-bids-sql-server-2014
Take a look at this MSDN reference. In the notes it states that the numbers are rounded to the number of decimal places requested.
If instead you use "{0:R}" it will produce what's referred to as a "round-trip" value, take a look at this MSDN reference for more info, here's my code and the output:
double d = 10 * 0.69;
Console.WriteLine(" {0:R}", d);
Console.WriteLine("+ {0:F20}", 6.9 - d);
Console.WriteLine("= {0:F20}", 6.9);
output
6.8999999999999995
+ 0.00000000000000088818
= 6.90000000000000000000
While the w32tm /resync
in theory does the job, it only does so under certain conditions. When "down to the millisecond" matters, however, I found that Windows wouldn't actually make the adjustment; as if "oh, I'm off by 2.5 seconds, close enough bro, nothing to see or do here".
In order to truly force the resync (Windows 7):
w32tm /resync
watch -n 0.1 date
on a Linux machine on the network that I had SSH'd over into)--- Rapid Method ---
net start w32time
(Time Service must be running)time 8
(where 8 may be replaced by any 'hour' value, presumably 0-23)w32tm /resync
I see this is old but... I dont know if you are looking for code to generate the numbers/options every time its loaded or not. But I use an excel or open office calc page and place use the auto numbering all the time. It may look like this...
| <option>
| 1 | </option>
|
Then I highlight the cells in the row and drag them down until there are 100 or the number that I need. I now have code snippets that I just refer back to.
The other solutions here didn't work for me so I had to use:
if(!$(event.target).is('#foo'))
{
// hide menu
}
In htop
, you can simply search with
/process-name
I know this is a pretty old thread, but to keep things up to date and more relevant, you can use the more accurate performance.now()
functionality to get finer grain timing in javascript.
window.performance = window.performance || {};
performance.now = (function() {
return performance.now ||
performance.mozNow ||
performance.msNow ||
performance.oNow ||
performance.webkitNow ||
Date.now /*none found - fallback to browser default */
})();
You guessed right, HTTP Headers are not part of the URL.
And when you type a URL in the browser the request will be issued with standard headers. Anyway REST Apis are not meant to be consumed by typing the endpoint in the address bar of a browser.
The most common scenario is that your server consumes a third party REST Api.
To do so your server-side code forges a proper GET (/PUT/POST/DELETE) request pointing to a given endpoint (URL) setting (when needed, like your case) some headers and finally (maybe) sending some data (as typically occurrs in a POST request for example).
The code to forge the request, send it and finally get the response back depends on your server side language.
If you want to test a REST Api you may use curl
tool from the command line.
curl
makes a request and outputs the response to stdout (unless otherwise instructed).
In your case the test request would be issued like this:
$curl -H "Accept: application/json" 'http://localhost:8080/otp/routers/default/plan?fromPlace=52.5895,13.2836&toPlace=52.5461,13.3588&date=2017/04/04&time=12:00:00'
The H
or --header
directive sets a header and its value.
You can install any current version of Anaconda. You can then make a conda environment with your particular needs from the documentation
conda create -n tensorflowproject python=3.5 tensorflow ipython
This command has a specific version for python and when this tensorflowproject environment gets updated it will upgrade to Python 3.5999999999 but never go to 3.6 . Then you switch to your environment using either
source activate tensorflowproject
for linux/mac or
activate tensorflowproject
on windows
This blog post is a great little cheat-sheet to keep handy when trying to format strings to a variety of formats.
link to trojan removed
Edit
The link was removed because Google temporarily warned that the site (or related site) may have been spreading malicious software. It is now off the list an no longer reported as problematic. Google "SteveX String Formatting" you'll find the search result and you can visit it at your discretion.
Contents of table cell, variable height, could be more than 60px;
<div style="position: absolute; bottom: 0px;">
Notice
</div>
You can also use MongoDB's geospatial indexing feature to select the documents 'nearest' to a random number.
First, enable geospatial indexing on a collection:
db.docs.ensureIndex( { random_point: '2d' } )
To create a bunch of documents with random points on the X-axis:
for ( i = 0; i < 10; ++i ) {
db.docs.insert( { key: i, random_point: [Math.random(), 0] } );
}
Then you can get a random document from the collection like this:
db.docs.findOne( { random_point : { $near : [Math.random(), 0] } } )
Or you can retrieve several document nearest to a random point:
db.docs.find( { random_point : { $near : [Math.random(), 0] } } ).limit( 4 )
This requires only one query and no null checks, plus the code is clean, simple and flexible. You could even use the Y-axis of the geopoint to add a second randomness dimension to your query.
Date.valid = function(str){
var d = new Date(str);
return (Object.prototype.toString.call(d) === "[object Date]" && !isNaN(d.getTime()));
}
https://gist.github.com/dustinpoissant/b83750d8671f10c414b346b16e290ecf
setTimeout
is a kind of Thread, it holds a operation for a given time and execute.
setTimeout(function,time_in_mills);
in here the first argument should be a function type; as an example if you want to print your name after 3 seconds, your code should be something like below.
setTimeout(function(){console.log('your name')},3000);
Key point to remember is, what ever you want to do by using the setTimeout
method, do it inside a function. If you want to call some other method by parsing some parameters, your code should look like below:
setTimeout(function(){yourOtherMethod(parameter);},3000);
Calling axvline in a loop, as others have suggested, works, but can be inconvenient because
Instead you can use the following convenience functions which create all the lines as a single plot object:
import matplotlib.pyplot as plt
import numpy as np
def axhlines(ys, ax=None, lims=None, **plot_kwargs):
"""
Draw horizontal lines across plot
:param ys: A scalar, list, or 1D array of vertical offsets
:param ax: The axis (or none to use gca)
:param lims: Optionally the (xmin, xmax) of the lines
:param plot_kwargs: Keyword arguments to be passed to plot
:return: The plot object corresponding to the lines.
"""
if ax is None:
ax = plt.gca()
ys = np.array((ys, ) if np.isscalar(ys) else ys, copy=False)
if lims is None:
lims = ax.get_xlim()
y_points = np.repeat(ys[:, None], repeats=3, axis=1).flatten()
x_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(ys), axis=0).flatten()
plot = ax.plot(x_points, y_points, scalex = False, **plot_kwargs)
return plot
def axvlines(xs, ax=None, lims=None, **plot_kwargs):
"""
Draw vertical lines on plot
:param xs: A scalar, list, or 1D array of horizontal offsets
:param ax: The axis (or none to use gca)
:param lims: Optionally the (ymin, ymax) of the lines
:param plot_kwargs: Keyword arguments to be passed to plot
:return: The plot object corresponding to the lines.
"""
if ax is None:
ax = plt.gca()
xs = np.array((xs, ) if np.isscalar(xs) else xs, copy=False)
if lims is None:
lims = ax.get_ylim()
x_points = np.repeat(xs[:, None], repeats=3, axis=1).flatten()
y_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(xs), axis=0).flatten()
plot = ax.plot(x_points, y_points, scaley = False, **plot_kwargs)
return plot
NB: Should you want the year to be based on some reference date, the code below calculates the dates for the between
statement:
declare @referenceTime datetime = getutcdate()
select *
from myTable
where SomeDate
between dateadd(year, year(@referenceTime) - 1900, '01-01-1900') --1st Jan this year (midnight)
and dateadd(millisecond, -3, dateadd(year, year(@referenceTime) - 1900, '01-01-1901')) --31st Dec end of this year (just before midnight of the new year)
Similarly, if you're using a year value, swapping year(@referenceDate)
for your reference year's value will work
declare @referenceYear int = 2010
select *
from myTable
where SomeDate
between dateadd(year,@referenceYear - 1900, '01-01-1900') --1st Jan this year (midnight)
and dateadd(millisecond, -3, dateadd(year,@referenceYear - 1900, '01-01-1901')) --31st Dec end of this year (just before midnight of the new year)
As a newbie in React world, I came across a similar issues where I could not edit
the textarea and struggled
with binding. It's worth knowing about controlled
and uncontrolled
elements when it comes to react.
The value of the following uncontrolled textarea
cannot be changed because of value
<textarea type="text" value="some value"
onChange={(event) => this.handleOnChange(event)}></textarea>
The value of the following uncontrolled textarea
can be changed because of use of defaultValue
or no value attribute
<textarea type="text" defaultValue="sample"
onChange={(event) => this.handleOnChange(event)}></textarea>
<textarea type="text"
onChange={(event) => this.handleOnChange(event)}></textarea>
The value of the following controlled textarea
can be changed because of how
value is mapped to a state as well as the onChange
event listener
<textarea value={this.state.textareaValue}
onChange={(event) => this.handleOnChange(event)}></textarea>
Here is my solution using different syntax. I prefer the auto-bind
than manual binding however, if I were to not use {(event) => this.onXXXX(event)}
then that would cause the content of textarea
to be not editable OR the event.preventDefault()
does not work as expected. Still a lot to learn I suppose.
class Editor extends React.Component {
constructor(props) {
super(props)
this.state = {
textareaValue: ''
}
}
handleOnChange(event) {
this.setState({
textareaValue: event.target.value
})
}
handleOnSubmit(event) {
event.preventDefault();
this.setState({
textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
})
}
render() {
return <div>
<form onSubmit={(event) => this.handleOnSubmit(event)}>
<textarea rows={10} cols={30} value={this.state.textareaValue}
onChange={(event) => this.handleOnChange(event)}></textarea>
<br/>
<input type="submit" value="Save"/>
</form>
</div>
}
}
ReactDOM.render(<Editor />, document.getElementById("content"));
The versions of libraries are
"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4"
If you want to load/process/display images I suggest you use an image processing framework. Using Marvin, for instance, you can do that easily with just a few lines of source code.
Source code:
public class Example extends JFrame{
MarvinImagePlugin prewitt = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.edge.prewitt");
MarvinImagePlugin errorDiffusion = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.halftone.errorDiffusion");
MarvinImagePlugin emboss = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.color.emboss");
public Example(){
super("Example");
// Layout
setLayout(new GridLayout(2,2));
// Load images
MarvinImage img1 = MarvinImageIO.loadImage("./res/car.jpg");
MarvinImage img2 = new MarvinImage(img1.getWidth(), img1.getHeight());
MarvinImage img3 = new MarvinImage(img1.getWidth(), img1.getHeight());
MarvinImage img4 = new MarvinImage(img1.getWidth(), img1.getHeight());
// Image Processing plug-ins
errorDiffusion.process(img1, img2);
prewitt.process(img1, img3);
emboss.process(img1, img4);
// Set panels
addPanel(img1);
addPanel(img2);
addPanel(img3);
addPanel(img4);
setSize(560,380);
setVisible(true);
}
public void addPanel(MarvinImage image){
MarvinImagePanel imagePanel = new MarvinImagePanel();
imagePanel.setImage(image);
add(imagePanel);
}
public static void main(String[] args) {
new Example().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output:
The easiest way to do this is by using the built in MaskFormatter in the javax.swing.text library.
You can do something like this :
import javax.swing.text.MaskFormatter;
String phoneMask= "###-###-####";
String phoneNumber= "123423452345";
MaskFormatter maskFormatter= new MaskFormatter(phoneMask);
maskFormatter.setValueContainsLiteralCharacters(false);
maskFormatter.valueToString(phoneNumber) ;
Check if IIS Express is installed. If IIS Express is missing, Visual Studio might discard the setting <UseIISExpress>false</UseIISExpress>
and still look for the express.
What you'd probably want in a web application with Spring -
In addition, Spring is HUGE - so there are a lot of other things you might be interested in using in a web app such as Spring AOP or Spring Security. But the four things listed above describe the common components of Spring that are used in a web app.
Works fine for me, the code needed around the getResource() thing is as follows:
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> spinner, View v,
int arg2, long arg3) {
String selectedVal = getResources().getStringArray(R.array.compass_rate_values)[spinner.getSelectedItemPosition()];
//Do something with the value
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Just need to make sure (by yourself) the values in the two arrays are aligned properly!
a less-jquerish approach:
$('#mytable tr').each(function() {
if (!this.rowIndex) return; // skip first row
var customerId = this.cells[0].innerHTML;
});
this can obviously be changed to work with not-the-first cells.
This worked for me;
1- git init
2- git add .
3- git commit -m "Add all my files"
4- git remote add origin https://github.com/USER_NAME/FOLDER_NAME
5- git pull origin master --allow-unrelated-histories
6- git push origin master
Assuming that yourObject.toString() returns "true" or "false", you can try
boolean b = Boolean.valueOf(yourObject.toString())
Below solution will be useful when, you are having controllers (both parent and directive (isolated)) in 'controller As' format
someone might find this useful,
directive :
var directive = {
link: link,
restrict: 'E',
replace: true,
scope: {
clearFilters: '='
},
templateUrl: "/temp.html",
bindToController: true,
controller: ProjectCustomAttributesController,
controllerAs: 'vmd'
};
return directive;
function link(scope, element, attrs) {
scope.vmd.clearFilters = scope.vmd.SetFitlersToDefaultValue;
}
}
directive Controller :
function DirectiveController($location, dbConnection, uiUtility) {
vmd.SetFitlersToDefaultValue = SetFitlersToDefaultValue;
function SetFitlersToDefaultValue() {
//your logic
}
}
html code :
<Test-directive clear-filters="vm.ClearFilters"></Test-directive>
<a class="pull-right" style="cursor: pointer" ng-click="vm.ClearFilters()"><u>Clear</u></a>
//this button is from parent controller which will call directive controller function
Well, I found a solution. It moves the mess, so that MVVM works.
First add this class:
public class ExtendedTreeView : TreeView
{
public ExtendedTreeView()
: base()
{
this.SelectedItemChanged += new RoutedPropertyChangedEventHandler<object>(___ICH);
}
void ___ICH(object sender, RoutedPropertyChangedEventArgs<object> e)
{
if (SelectedItem != null)
{
SetValue(SelectedItem_Property, SelectedItem);
}
}
public object SelectedItem_
{
get { return (object)GetValue(SelectedItem_Property); }
set { SetValue(SelectedItem_Property, value); }
}
public static readonly DependencyProperty SelectedItem_Property = DependencyProperty.Register("SelectedItem_", typeof(object), typeof(ExtendedTreeView), new UIPropertyMetadata(null));
}
and add this to your xaml:
<local:ExtendedTreeView ItemsSource="{Binding Items}" SelectedItem_="{Binding Item, Mode=TwoWay}">
.....
</local:ExtendedTreeView>
Microsoft has a tool called JLCA: Java Language Conversion Assistant. I can't tell if it is better though, as I have never compared the two.
answer = True
myvar = 'the answer is ' + str(answer) #since answer variable is in boolean format, therefore, we have to convert boolean into string format which can be easily done using this
print(myvar)
I just had a similar problem, the DISTINCT keyword works magic:
INSERT INTO Table2(Id, Name) SELECT DISTINCT Id, Name FROM Table1
update the 'name' attribute:
UPDATE test SET data=data||'{"name":"my-other-name"}' WHERE id = 1;
and if you wanted to remove for example the 'name' and 'tags' attributes:
UPDATE test SET data=data-'{"name","tags"}'::text[] WHERE id = 1;
You can't use CSS to disable Textbox. solution would be HTML Attribute.
disabled="disabled"
when(
fooDao.getBar(
any(Bazoo.class)
)
).thenReturn(myFoo);
or (to avoid null
s):
when(
fooDao.getBar(
(Bazoo)notNull()
)
).thenReturn(myFoo);
Don't forget to import matchers (many others are available):
For Mockito 2.1.0 and newer:
import static org.mockito.ArgumentMatchers.*;
For older versions:
import static org.mockito.Matchers.*;
from functools import partial as p
from operator import mul
map(p(mul,5),my_list)
is one way you could do it ... your teacher probably knows a much less complicated way that was probably covered in class
My advise is: try not to rely on dependencies when you can easily do it with few lines of codes
Here's what you're trying to achieve in 14 lines of code:
fs.isDir = function(dpath) {
try {
return fs.lstatSync(dpath).isDirectory();
} catch(e) {
return false;
}
};
fs.mkdirp = function(dirname) {
dirname = path.normalize(dirname).split(path.sep);
dirname.forEach((sdir,index)=>{
var pathInQuestion = dirname.slice(0,index+1).join(path.sep);
if((!fs.isDir(pathInQuestion)) && pathInQuestion) fs.mkdirSync(pathInQuestion);
});
};
Node-sass tries to download the binary for you platform when installing. Node 5 is supported by 3.8 https://github.com/sass/node-sass/releases/tag/v3.8.0 If your Jenkins can't download the prebuilt binary, then you need to follow the platform requirements on Node-gyp README (Python2, VS or MSBuild, ...) If possible I'd suggest updating your Node to at least 6 since 5 isn't supported by Node anymore. If you want to upgrade to 8, you'll need to update node-sass to 4.5.3
I guess I'm a little late (a lot late;-)) to this post, but I'd like to add Perst, an open source, object-oriented embedded database for Java &.NET. for your consideration. Perst is an open source / dual license embedded database for Java. The distribution is compatible with Google's Android platform, and also includes Perst Lite for Java ME. We've even built an Android benchmark and produced a whitepaper on the subject...you can take a look here: http://www.mcobject.com/index.cfm?fuseaction=download&pageid=581§ionid=133
All the best, Chris
Php has a super sexy function for this, just pass the array to it:
$json = json_encode($var);
$.ajax({
url:"Example.php",
type:"POST",
dataType : "json",
success:function(msg){
console.info(msg);
}
});
simples :)
<div class="overflow-auto p-3 mb-3 mb-md-0 mr-md-3 bg-light" style="max-width: 260px; max-height: 100px;">
<strong>Column 0 </strong><br>
<strong>Column 1</strong><br>
<strong>Column 2</strong><br>
<strong>Column 3</strong><br>
<strong>Column 4</strong><br>
<strong>Column 5</strong><br>
<strong>Column 6</strong><br>
<strong>Column 7</strong><br>
<strong>Column 8</strong><br>
<strong>Column 9</strong><br>
<strong>Column 10</strong><br>
<strong>Column 11</strong><br>
<strong>Column 12</strong><br>
<strong>Column 13</strong><br>
</div>
</div>
Install jQuery using NPM Jquery NPM
npm install jquery
Install the jQuery declaration file
npm install -D @types/jquery
Import jQuery inside .ts
import * as $ from 'jquery';
call inside class
export class JqueryComponent implements OnInit {
constructor() {
}
ngOnInit() {
$(window).click(function () {
alert('ok');
});
}
}
You need to map attributes to aesthetics (colours within the aes statement) to produce a legend.
cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h, fill = "BAR"),colour="#333333")+ #green
geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) + #red
geom_point(aes(y=b, colour="LINE1"),size=3) + #red
geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) +
geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) + #blue
geom_point(aes(y=c,colour="LINE2"),size=3) + #blue
geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) +
scale_colour_manual(name="Error Bars",values=cols) + scale_fill_manual(name="Bar",values=cols) +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
I understand where Roland is coming from, but since this is only 3 attributes, and complications arise from superimposing bars and error bars this may be reasonable to leave the data in wide format like it is. It could be slightly reduced in complexity by using geom_pointrange.
To change the background color for the error bars legend in the original, add + theme(legend.key = element_rect(fill = "white",colour = "white"))
to the plot specification. To merge different legends, you typically need to have a consistent mapping for all elements, but it is currently producing an artifact of a black background for me. I thought guide = guide_legend(fill = NULL,colour = NULL)
would set the background to null for the legend, but it did not. Perhaps worth another question.
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) + #red
geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) + #red
geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) +
geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) + #blue
geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) + #blue
geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) +
scale_colour_manual(name="Error Bars",values=cols, guide = guide_legend(fill = NULL,colour = NULL)) +
scale_fill_manual(name="Bar",values=cols, guide="none") +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
To get rid of the black background in the legend, you need to use the override.aes
argument to the guide_legend
. The purpose of this is to let you specify a particular aspect of the legend which may not be being assigned correctly.
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) + #red
geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) + #red
geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) +
geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) + #blue
geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) + #blue
geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) +
scale_colour_manual(name="Error Bars",values=cols,
guide = guide_legend(override.aes=aes(fill=NA))) +
scale_fill_manual(name="Bar",values=cols, guide="none") +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
Still using indirect. Say your A1 cell is your variable that will contain the name of the referenced sheet (Jan). If you go by:
=INDIRECT(CONCATENATE("'",A1," Item'", "!J3"))
Then you will have the 'Jan Item'!J3 value.
Use the following location where you can find all ~AutoRecover.~vs*.sql
(autorecovery files):
C:\Users\<YourUserName>\Documents\SQL Server Management Studio\Backup Files\Solution1
The filter name I mentioned in my web.xml doesn't exist. After correcting the typo it worked perfectly.
If you have trouble with caching ajax you can turn it off:
$.ajaxSetup({cache: false});
You probably want a dict instead of separate variables. For example
d = {}
for i in range(3):
d["group" + str(i)] = self.getGroup(selected, header+i)
If you insist on actually modifying local variables, you could use the locals
function:
for i in range(3):
locals()["group"+str(i)] = self.getGroup(selected, header+i)
On the other hand, if what you actually want is to modify instance variables of the class you're in, then you can use the setattr
function
for i in group(3):
setattr(self, "group"+str(i), self.getGroup(selected, header+i)
And of course, I'm assuming with all of these examples that you don't just want a list:
groups = [self.getGroup(i,header+i) for i in range(3)]
Try This:
$url = "http://www.google.com/search?q=".$strSearch."&hl=en&start=0&sa=N";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_URL, urlencode($url));
$response = curl_exec($ch);
curl_close($ch);
slide_in_down.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="@android:integer/config_longAnimTime"
android:fromYDelta="0%p"
android:toYDelta="100%p" />
</set>
slide_in_up.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="@android:integer/config_longAnimTime"
android:fromYDelta="100%p"
android:toYDelta="0%p" />
</set>
slide_out_down.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="@android:integer/config_longAnimTime"
android:fromYDelta="-100%"
android:toYDelta="0"
/>
</set>
slide_out_up.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="@android:integer/config_longAnimTime"
android:fromYDelta="0%p"
android:toYDelta="-100%p"
/>
</set>
direction = down
activity.getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.slide_out_down, R.anim.slide_in_down)
.replace(R.id.container, new CardFrontFragment())
.commit();
direction = up
activity.getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.slide_in_up, R.anim.slide_out_up)
.replace(R.id.container, new CardFrontFragment())
.commit();
Try Javascript .NET. It is hosted on GitHub It was originally hosted on CodePlex, here)
Project discussions: http://javascriptdotnet.codeplex.com/discussions
It implements Google V8. You can compile and run JavaScript directly from .NET code with it, and supply CLI objects to be used by the JavaScript code as well. It generates native code from JavaScript.
* {_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
html, body {_x000D_
height: 100%;_x000D_
}_x000D_
ul {_x000D_
height: 100%;_x000D_
}_x000D_
li {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
align-items:center;_x000D_
background: silver;_x000D_
width: 100%;_x000D_
height: 20%;_x000D_
}
_x000D_
<ul>_x000D_
<li>This is the text</li>_x000D_
</ul>
_x000D_
Without VBA...
If you can use a helper column, you can use the MATCH
function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match
To simply identify duplicates, use a helper column
Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:
=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")
Drag/copy this forumla down, and it should identify the duplicates.
To highlight cells, use conditional formatting:
With some tinkering, you can use this MATCH
function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.
Something like:
=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))
For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:
=B1="Duplicate"
This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.
The following implementation of a PriorityQueue
uses SortedSet
from the System library.
using System;
using System.Collections.Generic;
namespace CDiggins
{
interface IPriorityQueue<T, K> where K : IComparable<K>
{
bool Empty { get; }
void Enqueue(T x, K key);
void Dequeue();
T Top { get; }
}
class PriorityQueue<T, K> : IPriorityQueue<T, K> where K : IComparable<K>
{
SortedSet<Tuple<T, K>> set;
class Comparer : IComparer<Tuple<T, K>> {
public int Compare(Tuple<T, K> x, Tuple<T, K> y) {
return x.Item2.CompareTo(y.Item2);
}
}
PriorityQueue() { set = new SortedSet<Tuple<T, K>>(new Comparer()); }
public bool Empty { get { return set.Count == 0; } }
public void Enqueue(T x, K key) { set.Add(Tuple.Create(x, key)); }
public void Dequeue() { set.Remove(set.Max); }
public T Top { get { return set.Max.Item1; } }
}
}
Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
An int
is a 32-bit integer; a long
is a 64-bit integer. Which one to use depends on how large the numbers are that you expect to work with.
int
and long
are primitive types, while Integer
and Long
are objects. Primitive types are more efficient, but sometimes you need to use objects; for example, Java's collection classes can only work with objects, so if you need a list of integers you have to make it a List<Integer>
, for example (you can't use int
in a List
directly).
I was looking for the same thing when I came here, but the lack of a generic "upsert" function botherd me a bit so I thought you could just pass the update and insert sql as arguments on that function form the manual
that would look like this:
CREATE FUNCTION upsert (sql_update TEXT, sql_insert TEXT)
RETURNS VOID
LANGUAGE plpgsql
AS $$
BEGIN
LOOP
-- first try to update
EXECUTE sql_update;
-- check if the row is found
IF FOUND THEN
RETURN;
END IF;
-- not found so insert the row
BEGIN
EXECUTE sql_insert;
RETURN;
EXCEPTION WHEN unique_violation THEN
-- do nothing and loop
END;
END LOOP;
END;
$$;
and perhaps to do what you initially wanted to do, batch "upsert", you could use Tcl to split the sql_update and loop the individual updates, the preformance hit will be very small see http://archives.postgresql.org/pgsql-performance/2006-04/msg00557.php
the highest cost is executing the query from your code, on the database side the execution cost is much smaller
If you want to maintain the order in which you added the elements to the map, use LinkedHashMap
as opposed to just HashMap
.
Here is an approach that will allow you to get a value by its index in the map:
public Object getElementByIndex(LinkedHashMap map,int index){
return map.get( (map.keySet().toArray())[ index ] );
}
You can use :
window.history.pushState('obj', 'newtitle', newUrlWithQueryString)
using System.Net;
WebClient webClient = new WebClient();
webClient.DownloadFile("http://mysite.com/myfile.txt", @"c:\myfile.txt");
In my windows 10 Enterprise edition os this code works fine: (suppose for environment namely testenv)
conda env remove --name testenv
If your solution contains two projects interacting with each other and both using one same reference, And if version of respective reference is different in both projects; Then also such errors occurred. Keep updating all references to latest one.
I think this is very nice and short
<img src="imagenotfound.gif" alt="Image not found" onerror="this.src='imagefound.gif';" />
But, be careful. The user's browser will be stuck in an endless loop if the onerror image itself generates an error.
EDIT
To avoid endless loop, remove the onerror
from it at once.
<img src="imagenotfound.gif" alt="Image not found" onerror="this.onerror=null;this.src='imagefound.gif';" />
By calling this.onerror=null
it will remove the onerror then try to get the alternate image.
NEW I would like to add a jQuery way, if this can help anyone.
<script>
$(document).ready(function()
{
$(".backup_picture").on("error", function(){
$(this).attr('src', './images/nopicture.png');
});
});
</script>
<img class='backup_picture' src='./images/nonexistent_image_file.png' />
You simply need to add class='backup_picture' to any img tag that you want a backup picture to load if it tries to show a bad image.
I have achieved this by a http API node
request which returns required object from node object for HTML
page at client ,
for eg: API: localhost:3000/username
returns logged in user from cache by node App object .
node route file,
app.get('/username', function(req, res) {
res.json({ udata: req.session.user });
});
A link must have an href
target to be specified to enable it to be a usable display object.
Most browsers will not parse advanced JavaScript in the href
of an <a>
element, for example:
<a href="javascript:var el = document.getElementById('foo');">Get element</a>
Because the href
tag in most browsers does not allow whitespace or will convert whitespace to %20
(the HEX code for space), the JavaScript interpreter will run into multiple errors.
So if you want to use an <a>
element's href
to execute inline JavaScript, you must specify a valid value for href
first that isn't too complex (doesn't contain whitespace), and then provide the JavaScript in an event attribute tag like onClick
, onMouseOver
, onMouseOut
, etc.
The typical answer is to do something like this:
<a href="#" onclick="var el = document.getElementById('foo');">Get element</a>
This works fine but it makes the page scroll to the top because the #
in the href
tells the browser to do this.
Placing a #
in the <a>
element's href
specifies the root anchor, which is by default the top of the page, but you can specify a different location by specifying the name
attribute inside an <a>
element.
<a name="middleOfPage"></a>
You can then change your <a>
element's href
to jump to middleOfPage
and execute the JavaScript in the onClick
event:
<a href="#middleOfPage" onclick="var el = document.getElementById('foo');">Get element</a>
There will be many times where you do not want that link jumping around, so you can do two things:
<a href="#thisLinkName" name="thisLinkCame" onclick="var elem = document.getElementById('foo');">Get element</a>
Now it will go nowhere when clicked, but it could cause the page to re-centre itself from its current viewport.
The best way to use in-line javascript using an <a>
element's href
, but without having to do any of the above is JavaScript:void(0);
:
<a href="javascript:void(0);" onclick="var el = document.getElementById('foo');">Get element</a>
This tells the browser no to go anywhere, but instead execute the JavaScript:void(0);
function in the href
because it contains no whitespace, and will not be parsed as a URL. It will instead be run by the compiler.
void
is a keyword which, when supplied with a parameter of 0
returns undefined
, which does not use any more resources to handle a return value that would occur without specifying the 0
(it is more memory-management/performance friendly).
The next thing that happens is the onClick
gets executed. The page does not move, nothing happens display-wise.
I think the correct way to phrase your question is
Is there a way to get the timestamp by specifying the date in UTC?
, because timestamp is just a number which is absolute, not relative. The relative (or timezone aware) piece is the date.
I find pandas very convenient for timestamps, so:
import pandas as pd
dt1 = datetime(2008, 1, 1, 0, 0, 0, 0)
ts1 = pd.Timestamp(dt1, tz='utc').timestamp()
# make sure you get back dt1
datetime.utcfromtimestamp(ts1)
Here's a couple of suggestions:
Use date_range
for the index:
import datetime
import pandas as pd
import numpy as np
todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')
columns = ['A','B', 'C']
Note: we could create an empty DataFrame (with NaN
s) simply by writing:
df_ = pd.DataFrame(index=index, columns=columns)
df_ = df_.fillna(0) # with 0s rather than NaNs
To do these type of calculations for the data, use a numpy array:
data = np.array([np.arange(10)]*3).T
Hence we can create the DataFrame:
In [10]: df = pd.DataFrame(data, index=index, columns=columns)
In [11]: df
Out[11]:
A B C
2012-11-29 0 0 0
2012-11-30 1 1 1
2012-12-01 2 2 2
2012-12-02 3 3 3
2012-12-03 4 4 4
2012-12-04 5 5 5
2012-12-05 6 6 6
2012-12-06 7 7 7
2012-12-07 8 8 8
2012-12-08 9 9 9
No, not from code behind. A postback is a request initiated from a page on the client back to itself on the server using the Http POST method. On the server side you can request a redirect but the will be Http GET request.
@eOnOe has answered how we can change status bar tint through xml. But we can also change it dynamically in code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
View decor = getWindow().getDecorView();
if (shouldChangeStatusBarTintToDark) {
decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
} else {
// We want to change tint color to white again.
// You can also record the flags in advance so that you can turn UI back completely if
// you have set other flags before, such as translucent or full screen.
decor.setSystemUiVisibility(0);
}
}
The correct syntax is:
data: {status: status, name: name},
As specified here: http://api.jquery.com/jQuery.ajax/
So if that doesn't work, I would alert those variables to make sure they have values.
Very simple way to do this---
In your Activity--
TextView tv = (TextView) findViewById(R.id.site);
tv.setText(Html.fromHtml("<a href=http://www.stackoverflow.com> STACK OVERFLOW "));
tv.setMovementMethod(LinkMovementMethod.getInstance());
Then you will get just the Tag, not the whole link..
Hope it will help you...
In Angular 2 this is how we can set the default value for radio button:
HTML:
<label class="form-check-label">
<input type="radio" class="form-check-input" name="gender"
[(ngModel)]="gender" id="optionsRadios1" value="male">
Male
</label>
In the Component Class set the value of 'gender' variable equal to the value of radio button:
gender = 'male';
get_woocommerce_term_meta is depricated since Woo 3.6.0.
so change
$thumbnail_id = get_woocommerce_term_meta($value->term_id, 'thumbnail_id', true );
into: ($value->term_id should be woo category id)
get_term_meta($value->term_id, 'thumbnail_id', true)
see docs for details: https://docs.woocommerce.com/wc-apidocs/function-get_woocommerce_term_meta.html
My implementation:
def get_nested(data, *args):
if args and data:
element = args[0]
if element:
value = data.get(element)
return value if len(args) == 1 else get_nested(value, *args[1:])
Example usage:
>>> dct={"foo":{"bar":{"one":1, "two":2}, "misc":[1,2,3]}, "foo2":123}
>>> get_nested(dct, "foo", "bar", "one")
1
>>> get_nested(dct, "foo", "bar", "two")
2
>>> get_nested(dct, "foo", "misc")
[1, 2, 3]
>>> get_nested(dct, "foo", "missing")
>>>
There are no exceptions raised in case a key is missing, None value is returned in that case.
you can use indexOf for this
var a = 'how are you';
if (a.indexOf('are') > -1) {
return true;
} else {
return false;
}
Edit: This is an old answer that keeps getting up votes every once in a while so I thought I should clarify that in the above code, the if
clause is not required at all because the expression itself is a boolean. Here is a better version of it which you should use,
var a = 'how are you';
return a.indexOf('are') > -1;
Update in ECMAScript2016:
var a = 'how are you';
return a.includes('are'); //true
I'm not sure but:
If you call the delete method with a non transient object, this means first fetched the object from the DB. So it is normal to see a select statement. Perhaps in the end you see 2 select + 1 delete?
If you call the delete method with a transient object, then it is possible that you have a cascade="delete"
or something similar which requires to retrieve first the object so that "nested actions" can be performed if it is required.
Edit: Calling delete() with a transient instance means doing something like that:
MyEntity entity = new MyEntity();
entity.setId(1234);
session.delete(entity);
This will delete the row with id 1234, even if the object is a simple pojo not retrieved by Hibernate, not present in its session cache, not managed at all by Hibernate.
If you have an entity association Hibernate probably have to fetch the full entity so that it knows if the delete should be cascaded to associated entities.
On mac, press Command + R
or got to Database
-> Reverse Engineer
and keep selecting your requirements and continue
You can delimit your regexp with slashes instead of quotes and then a single backslash to escape the question mark. Try this:
var gent = /I like your Apartment. Could we schedule a viewing\?/g;
The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.
It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.
No, you can't. JavaScript is executed on the client side (browser), while the session data is stored on the server.
However, you can expose session variables for JavaScript in several ways:
In JSP you'd have something like:
<input type="hidden" name="pONumb" value="${sessionScope.pONumb} />
or:
<div id="product" data-prodnumber="${sessionScope.pONumb}" />
Then in JS:
// you can find a more efficient way to select the input you want
var inputs = document.getElementsByTagName("input"), len = inputs.length, i, pONumb;
for (i = 0; i < len; i++) {
if (inputs[i].name == "pONumb") {
pONumb = inputs[i].value;
break;
}
}
or:
var product = document.getElementById("product"), pONumb;
pONumb = product.getAttribute("data-prodnumber");
The inline example is the most straightforward, but if you then want to store your JavaScript code as an external resource (the recommended way) it won't be feasible.
<script>
var pONumb = ${sessionScope.pONumb};
[...]
</script>
I prefer this way, not using a cell but a range
Dim cell_to_test As Range, cells_changed As Range
Set cells_changed = Target(1, 1)
Set cell_to_test = Range( RANGE_OF_CELLS_TO_DETECT )
If Not Intersect(cells_changed, cell_to_test) Is Nothing Then
Macro
End If
h1 {
font-weight: bold;
color: #fff;
font-size: 32px;
}
h2 {
font-weight: bold;
color: #fff;
font-size: 24px;
}
Note that after color you can use a word (e.g. white
), a hex code (e.g. #fff
) or RGB (e.g. rgb(255,255,255)
) or RGBA (e.g. rgba(255,255,255,0.3)
).
I had a similar problem and solved it using ROW_NUMBER() in combination with the OVER keyword. The task was to retrospectively populate a new TicketNo (integer) field in a simple table based on the original CreatedDate, and grouped by ModuleId - so that ticket numbers started at 1 within each Module group and incremented by date. The table already had a TicketID primary key (a GUID).
Here's the SQL:
UPDATE Tickets SET TicketNo=T2.RowNo
FROM Tickets
INNER JOIN
(select TicketID, TicketNo,
ROW_NUMBER() OVER (PARTITION BY ModuleId ORDER BY DateCreated) AS RowNo from Tickets)
AS T2 ON T2.TicketID = Tickets.TicketID
Worked a treat!
The garbage collection is the main reason Java# CANNOT be used for real-time systems.
When will the GC happen?
How long will it take?
This is non-deterministic.
Option 1. Using boost library, you can declare the string as below
const boost::string_view helpText = "This is very long help text.\n"
"Also more text is here\n"
"And here\n"
// Pass help text here
setHelpText(helpText);
Option 2. If boost is not available in your project, you can use std::string_view() in modern C++.
One who has tried all other answers and had no luck the please check this check box, hope it'll help (did the trick for me xcode 6.0.1)
On Windows, part of the mystery appears to be where npm installs the Grunt.cmd file. While on my Linux box, I just had to run sudo npm install -g grunt-cli, on my Windows 8 work laptop, Grunt was placed in the '.npm-global' directory: %USER_HOME%\.npm-global and I had to add that to the Path.
So on Windows my steps were:
npm install -g grunt-cli
figure out where the heck grunt.cmd was (I guess for some it is in %USER_HOME%\App_Data\Roaming)
Added the location to my Path environment variable. Opened a new cmd prompt and the grunt command ran fine.
As you can see I only have java 1.7 installed (on a Ubuntu 14.04 machine).
update-java-alternatives -l
java-1.7.0-openjdk-amd64 1071 /usr/lib/jvm/java-1.7.0-openjdk-amd64
To install Java 8, I did,
sudo add-apt-repository ppa:openjdk-r/ppa
sudo apt-get update
sudo apt-get install openjdk-8-jdk
Afterwards, now I have java 7 and 8,
update-java-alternatives -l
java-1.7.0-openjdk-amd64 1071 /usr/lib/jvm/java-1.7.0-openjdk-amd64
java-1.8.0-openjdk-amd64 1069 /usr/lib/jvm/java-1.8.0-openjdk-amd64
BONUS ADDED (how to switch between different versions)
sudo update-alternatives --config java
There are 2 choices for the alternative java (providing /usr/bin/java). Selection Path Priority Status ------------------------------------------------------------ 0 /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java 1071 auto mode 1 /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java 1071 manual mode * 2 /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java 1069 manual mode Press enter to keep the current choice[*], or type selection number:
As you can see I'm running open jdk 8. To switch to to jdk 7, press 1
and hit the Enter key. Do the same for javac
as well with, sudo update-alternatives --config javac
.
Check versions to confirm the change: java -version
and javac -version
.
Is JavaScript object-oriented?
Answer : Yes
It has objects which can contain data and methods that act upon that data. Objects can contain other objects.
The two main ways of building up object systems are by inheritance (is-a) and by aggregation (has-a). JavaScript does both, but its dynamic nature allows it to excel at aggregation.
Some argue that JavaScript is not truly object oriented because it does not provide information hiding. That is, objects cannot have private variables and private methods: All members are public.
But it turns out that JavaScript objects can have private variables and private methods. (Click here now to find out how.) Of course, few understand this because JavaScript is the world's most misunderstood programming language.
Some argue that JavaScript is not truly object oriented because it does not provide inheritance. But it turns out that JavaScript supports not only classical inheritance, but other code reuse patterns as well.
It's not an official term. I guess it means knowledge of the Java language itself and the most important parts of the standard API (java.lang, java.io, java.utils packages, basically), as opposed to the multitude of specialzed APIs and frameworks (J2EE, JPA, JNDI, JSTL, ...) that are often required for Java jobs.
The reason that visible="false" does not work is because HTML is defined as a standard by a consortium group. The standard for the Table element does not have a visibility property defined.
You can see all the valid properties for a table by going to the standards web page for tables.
That page can be a bit hard to read, so here is a link to another page that makes it easier to read.
If you need the value before insert a row:
CREATE FUNCTION `getAutoincrementalNextVal`(`TableName` VARCHAR(50))
RETURNS BIGINT
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE Value BIGINT;
SELECT
AUTO_INCREMENT INTO Value
FROM
information_schema.tables
WHERE
table_name = TableName AND
table_schema = DATABASE();
RETURN Value;
END
You can use this in a insert:
INSERT INTO
document (Code, Title, Body)
VALUES (
sha1( concat (convert ( now() , char), ' ', getAutoincrementalNextval ('document') ) ),
'Title',
'Body'
);
Or, if you don't need else clause:
[ "$x" == "valid" ] && echo "x has the value 'valid'"
Try these if you use maven. I use maven for my project and when I do mvn clean install
and try to run a program it throws the exception. So, I clean the project and run it again and it works for me.
I use eclipse IDE.
For Class Not Found Exception when running Junit test, try running mvn clean test
once. It will compile all the test classes.
Step 1: Add the bean class into the dataFormat
list:
<dataFormats>
<json id="jack" library="Jackson" prettyPrint="true"
unmarshalTypeName="{ur bean class path}" />
</dataFormats>
Step 2: Marshal the bean prior to the client call:
<marchal id="marsh" ref="jack"/>
in Swift 4
in cellForRowAt indexPath:
cell.prescriptionButton.addTarget(self, action: Selector("onClicked:"), for: .touchUpInside)
function that run after user pressed button:
@objc func onClicked(sender: UIButton){
let tag = sender.tag
}
The -> is simply syntactic sugar for a pointer dereference,
As others have said:
pointer->method();
is a simple method of saying:
(*pointer).method();
For more pointer fun, check out Binky, and his magic wand of dereferencing:
If you are having a problem with the font working I have also had this in the past and the issue I found was down to the font-family: name. This had to match what font name was actually given.
The easiest way I found to find this out was to install the font and see what display name is given.
For example, I was using Gill Sans on one project, but the actual font was called Gill Sans MT. Spacing and capitlisation was also important to get right.
Hope that helps.
We can also use inplace
library(inplace)
x <- 1
x %+<-% 2
I wouldn't say that structs offer less functionality.
Sure, self is immutable except in a mutating function, but that's about it.
Inheritance works fine as long as you stick to the good old idea that every class should be either abstract or final.
Implement abstract classes as protocols and final classes as structs.
The nice thing about structs is that you can make your fields mutable without creating shared mutable state because copy on write takes care of that :)
That's why the properties / fields in the following example are all mutable, which I would not do in Java or C# or swift classes.
Example inheritance structure with a bit of dirty and straightforward usage at the bottom in the function named "example":
protocol EventVisitor
{
func visit(event: TimeEvent)
func visit(event: StatusEvent)
}
protocol Event
{
var ts: Int64 { get set }
func accept(visitor: EventVisitor)
}
struct TimeEvent : Event
{
var ts: Int64
var time: Int64
func accept(visitor: EventVisitor)
{
visitor.visit(self)
}
}
protocol StatusEventVisitor
{
func visit(event: StatusLostStatusEvent)
func visit(event: StatusChangedStatusEvent)
}
protocol StatusEvent : Event
{
var deviceId: Int64 { get set }
func accept(visitor: StatusEventVisitor)
}
struct StatusLostStatusEvent : StatusEvent
{
var ts: Int64
var deviceId: Int64
var reason: String
func accept(visitor: EventVisitor)
{
visitor.visit(self)
}
func accept(visitor: StatusEventVisitor)
{
visitor.visit(self)
}
}
struct StatusChangedStatusEvent : StatusEvent
{
var ts: Int64
var deviceId: Int64
var newStatus: UInt32
var oldStatus: UInt32
func accept(visitor: EventVisitor)
{
visitor.visit(self)
}
func accept(visitor: StatusEventVisitor)
{
visitor.visit(self)
}
}
func readEvent(fd: Int) -> Event
{
return TimeEvent(ts: 123, time: 56789)
}
func example()
{
class Visitor : EventVisitor
{
var status: UInt32 = 3;
func visit(event: TimeEvent)
{
print("A time event: \(event)")
}
func visit(event: StatusEvent)
{
print("A status event: \(event)")
if let change = event as? StatusChangedStatusEvent
{
status = change.newStatus
}
}
}
let visitor = Visitor()
readEvent(1).accept(visitor)
print("status: \(visitor.status)")
}
If you want distinct values from only two fields, plus return other fields with them, then the other fields must have some kind of aggregation on them (sum, min, max, etc.), and the two columns you want distinct must appear in the group by clause. Otherwise, it's just as Decker says.
You should declare the thread main as:
void* print_message(void*) // takes one parameter, unnamed if you aren't using it
You can probably use timers : http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx
Timers can provide you a precision up to 1 millisecond. Depending on the tick interval an event will be generated. Do your stuff inside the tick event.
Another way to do this is by using the bitstring
module:
>>> from bitstring import BitArray
>>> input_str = '0xff'
>>> c = BitArray(hex=input_str)
>>> c.bin
'0b11111111'
And if you need to strip the leading 0b
:
>>> c.bin[2:]
'11111111'
The bitstring
module isn't a requirement, as jcollado's answer shows, but it has lots of performant methods for turning input into bits and manipulating them. You might find this handy (or not), for example:
>>> c.uint
255
>>> c.invert()
>>> c.bin[2:]
'00000000'
etc.
Use ScriptEngine.eval(java.io.Reader)
to read the script
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// read script file
engine.eval(Files.newBufferedReader(Paths.get("C:/Scripts/Jsfunctions.js"), StandardCharsets.UTF_8));
Invocable inv = (Invocable) engine;
// call function from script file
inv.invokeFunction("yourFunction", "param");
C11 timespec_get
It returns up to nanoseconds, rounded to the resolution of the implementation.
It is already implemented in Ubuntu 15.10. API looks the same as the POSIX clock_gettime
.
#include <time.h>
struct timespec ts;
timespec_get(&ts, TIME_UTC);
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
More details here: https://stackoverflow.com/a/36095407/895245
More generic way in case qs
has more than one dictionaries:
[int(v) for lst in qs for k, v in lst.items()]
--
>>> qs = [{u'a': 15L, u'b': 9L, u'a': 16L}, {u'a': 20, u'b': 35}]
>>> result_list = [int(v) for lst in qs for k, v in lst.items()]
>>> result_list
[16, 9, 20, 35]
I find this quite tricky, but there is some information on it here at the MatPlotLib FAQ. It is rather cumbersome, and requires finding out about what space individual elements (ticklabels) take up...
Update:
The page states that the tight_layout()
function is the easiest way to go, which attempts to automatically correct spacing.
Otherwise, it shows ways to acquire the sizes of various elements (eg. labels) so you can then correct the spacings/positions of your axes elements. Here is an example from the above FAQ page, which determines the width of a very wide y-axis label, and adjusts the axis width accordingly:
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
ax.set_yticks((2,5,7))
labels = ax.set_yticklabels(('really, really, really', 'long', 'labels'))
def on_draw(event):
bboxes = []
for label in labels:
bbox = label.get_window_extent()
# the figure transform goes from relative coords->pixels and we
# want the inverse of that
bboxi = bbox.inverse_transformed(fig.transFigure)
bboxes.append(bboxi)
# this is the bbox that bounds all the bboxes, again in relative
# figure coords
bbox = mtransforms.Bbox.union(bboxes)
if fig.subplotpars.left < bbox.width:
# we need to move it over
fig.subplots_adjust(left=1.1*bbox.width) # pad a little
fig.canvas.draw()
return False
fig.canvas.mpl_connect('draw_event', on_draw)
plt.show()
From this document, this DTU percent is determined by this query:
SELECT end_time,
(SELECT Max(v)
FROM (VALUES (avg_cpu_percent), (avg_data_io_percent),
(avg_log_write_percent)) AS
value(v)) AS [avg_DTU_percent]
FROM sys.dm_db_resource_stats;
looks like the max of avg_cpu_percent
, avg_data_io_percent
and avg_log_write_percent
Reference:
This is validation of domain name in javascript:
<script>
function frmValidate() {
var val=document.frmDomin.name.value;
if (/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+$/.test(val)){
alert("Valid Domain Name");
return true;
} else {
alert("Enter Valid Domain Name");
val.name.focus();
return false;
}
}
</script>
This tells you all the details about your browser and the version of it.
<!DOCTYPE html>
<html>
<body>
<div id="example"></div>
<script>
txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
txt+= "<p>User-agent language: " + navigator.systemLanguage + "</p>";
document.getElementById("example").innerHTML=txt;
</script>
</body>
</html>
Using just awk you could do (I also shortened some of your piping):
strings -a libAddressDoctor5.so | awk '/EngineVersion/ { if(NR==2) { gsub("\"",""); print $2 } }'
I can't verify it for you because I don't know your exact input, but the following works:
echo "Blah EngineVersion=\"123\"" | awk '/EngineVersion/ { gsub("\"",""); print $2 }'
See also this question on removing single quotes.
First of all, whether a class has methods or what it's class structure is has nothing to do with mutability.
int
s and float
s are immutable. If I do
a = 1
a += 5
It points the name a
at a 1
somewhere in memory on the first line. On the second line, it looks up that 1
, adds 5
, gets 6
, then points a
at that 6
in memory -- it didn't change the 1
to a 6
in any way. The same logic applies to the following examples, using other immutable types:
b = 'some string'
b += 'some other string'
c = ('some', 'tuple')
c += ('some', 'other', 'tuple')
For mutable types, I can do thing that actallly change the value where it's stored in memory. With:
d = [1, 2, 3]
I've created a list of the locations of 1
, 2
, and 3
in memory. If I then do
e = d
I just point e
to the same list
d
points at. I can then do:
e += [4, 5]
And the list that both e
and d
points at will be updated to also have the locations of 4
and 5
in memory.
If I go back to an immutable type and do that with a tuple
:
f = (1, 2, 3)
g = f
g += (4, 5)
Then f
still only points to the original tuple
-- you've pointed g
at an entirely new tuple
.
Now, with your example of
class SortedKeyDict(dict):
def __new__(cls, val):
return dict.__new__(cls, val.clear())
Where you pass
d = (('zheng-cai', 67), ('hui-jun', 68),('xin-yi', 2))
(which is a tuple
of tuples
) as val
, you're getting an error because tuple
s don't have a .clear()
method -- you'd have to pass dict(d)
as val
for it to work, in which case you'll get an empty SortedKeyDict
as a result.