There is only three way to solve. paste in following code in this path application/config/autoload.php.
most of them I use this
require_once BASEPATH . '/helpers/url_helper.php';
this is good but some time, it fail
$autoload['helper'] = array('url');
I never use it but I know it work
$this->load->helper('url');
Here is my JSFiddle with corrected line breaks, or see it below.
$(document).ready(function() {
var MaxInputs = 2; //maximum extra input boxes allowed
var InputsWrapper = $("#InputsWrapper"); //Input boxes wrapper ID
var AddButton = $("#AddMoreFileBox"); //Add button ID
var x = InputsWrapper.length; //initlal text box count
var FieldCount=1; //to keep track of text box added
//on add input button click
$(AddButton).click(function (e) {
//max input box allowed
if(x <= MaxInputs) {
FieldCount++; //text box added ncrement
//add input box
$(InputsWrapper).append('<div><input type="text" name="mytext[]" id="field_'+ FieldCount +'"/> <a href="#" class="removeclass">Remove</a></div>');
x++; //text box increment
$("#AddMoreFileId").show();
$('AddMoreFileBox').html("Add field");
// Delete the "add"-link if there is 3 fields.
if(x == 3) {
$("#AddMoreFileId").hide();
$("#lineBreak").html("<br>");
}
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
if( x > 1 ) {
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
$("#AddMoreFileId").show();
$("#lineBreak").html("");
// Adds the "add" link again when a field is removed.
$('AddMoreFileBox').html("Add field");
}
return false;
})
});
var datos = $("#id_formulario").serialize();
$.ajax({
url: "url.php",
type: "POST",
dataType: "html",
data: datos,
success: function (prueba) {
alert("funciona!");
}//FIN SUCCES
});//FIN AJAX
I don't think there's any reason to add this function to JQuery's namespace. Why not just define the method by itself:
function showMessage(msg) {
alert(msg);
};
<input type="button" value="ahaha" onclick="showMessage('msg');" />
UPDATE: With a small change to how your method is defined I can get it to work:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script language="javascript">
// define the function within the global scope
$.fn.MessageBox = function(msg) {
alert(msg);
};
// or, if you want to encapsulate variables within the plugin
(function($) {
$.fn.MessageBoxScoped = function(msg) {
alert(msg);
};
})(jQuery); //<-- make sure you pass jQuery into the $ parameter
</script>
</head>
<body>
<div class="Title">Welcome!</div>
<input type="button" value="ahaha" id="test" onClick="$(this).MessageBox('msg');" />
</body>
</html>
I have the same issue and no case resolve me the problem. The only thing that works for me, it's put on the of the Site.master file, the next:
<script src="<%= ResolveUrl("~/Scripts/jquery-1.7.1.min.js") %>" type="text/javascript"></script>
<script src="<%= ResolveUrl("~/Scripts/bootstrap/js/bootstrap.min.js") %>" type="text/javascript"></script>
With src="<%= ResolveUrl("")... the load of jQuery in the Content Pages is correct.
You also should set border:none
to that css class.
If you want the entire row instead of just the id
, you can use df.nlargest
and pass in how many 'top' rows you want and you can also pass in for which column/columns you want it for.
df.nlargest(2,['A'])
will give you the rows corresponding to the top 2 values of A
.
use df.nsmallest
for min values.
The first way is easier to maintain. Each declaration is a single statement on a single line, so you can easily add, remove, and reorder the declarations.
With the second way, it is annoying to remove the first or last declaration because they start from the var
keyword and finish with the semicolon respectively. Every time you add a new declaration, you have to replace the semicolon in the last old line with a comma.
The problem is that since you are using ASP.NET controls with a runat
attribute, the ID of the control is not actually "test1". It's "test1" with a long string attached to it.
I got this issue when installing Bootstrap.
The following commands are what worked for me:
npm uninstall @angular-devkit/build-angular
npm install @angular-devkit/[email protected]
The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
index.php
<html>
<body>
<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
site2.php
<html>
<body>
Hello <?php echo $_POST["name"]; ?>!<br>
Your mail is <?php echo $_POST["mail"]; ?>.
</body>
</html>
output
Hello "name" !
Your email is "[email protected]" .
Thought I would mention this because it took a while for me to fix this issue and I couldn't find the answer anywhere on SO. The code I was working on worked for a co-worker but not for me (I was getting this same error). It worked for me in Chrome, but not in Edge.
I was able to get it working by clearing the cache in Edge.
This may not be the answer to this specific question, but I thought I would mention it in case it saves someone else a little time.
//Style
.trlink {
color:blue;
}
.trlink:hover {
color:red;
}
<tr class="trlink" onclick="function to navigate to a page goes here">
<td>linktext</td>
</tr>
Something along these lines perhaps? Though it does use JS, but that's only way to make a row (tr) clickable.
Unless you have a single cell with an anchor tag that fills the entire cell.
And then, you shouldn't be using a table anyhow.
You can also use it as a Helper class in your Projects.
"use strict";_x000D_
/**_x000D_
* @description Util file_x000D_
* @author Tarandeep Singh_x000D_
* @created 2016-08-09_x000D_
*/_x000D_
_x000D_
window.Sys = {};_x000D_
_x000D_
Sys = {_x000D_
isEmptyObject: function(val) {_x000D_
return this.isObject(val) && Object.keys(val).length;_x000D_
},_x000D_
/** This Returns Object Type */_x000D_
getType: function(val) {_x000D_
return Object.prototype.toString.call(val);_x000D_
},_x000D_
/** This Checks and Return if Object is Defined */_x000D_
isDefined: function(val) {_x000D_
return val !== void 0 || typeof val !== 'undefined';_x000D_
},_x000D_
/** Run a Map on an Array **/_x000D_
map: function(arr, fn) {_x000D_
var res = [],_x000D_
i = 0;_x000D_
for (; i < arr.length; ++i) {_x000D_
res.push(fn(arr[i], i));_x000D_
}_x000D_
arr = null;_x000D_
return res;_x000D_
},_x000D_
/** Checks and Return if the prop is Objects own Property */_x000D_
hasOwnProp: function(obj, val) {_x000D_
return Object.prototype.hasOwnProperty.call(obj, val);_x000D_
},_x000D_
/** Extend properties from extending Object to initial Object */_x000D_
extend: function(newObj, oldObj) {_x000D_
if (this.isDefined(newObj) && this.isDefined(oldObj)) {_x000D_
for (var prop in oldObj) {_x000D_
if (this.hasOwnProp(oldObj, prop)) {_x000D_
newObj[prop] = oldObj[prop];_x000D_
}_x000D_
}_x000D_
return newObj;_x000D_
} else {_x000D_
return newObj || oldObj || {};_x000D_
}_x000D_
}_x000D_
};_x000D_
_x000D_
// This Method will create Multiple functions in the Sys object that can be used to test type of_x000D_
['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Object', 'Array', 'Undefined']_x000D_
.forEach(_x000D_
function(name) {_x000D_
Sys['is' + name] = function(obj) {_x000D_
return toString.call(obj) == '[object ' + name + ']';_x000D_
};_x000D_
}_x000D_
);
_x000D_
<h1>Use the Helper JavaScript Methods..</h1>_x000D_
<code>use: if(Sys.isDefined(jQuery){console.log("O Yeah... !!");}</code>
_x000D_
"use strict";
/*** Helper Utils ***/
/**
* @description Util file :: From Vault
* @author Tarandeep Singh
* @created 2016-08-09
*/
var Sys = {};
Sys = {
isEmptyObject: function(val){
return this.isObject(val) && Object.keys(val).length;
},
/** This Returns Object Type */
getType: function(val){
return Object.prototype.toString.call(val);
},
/** This Checks and Return if Object is Defined */
isDefined: function(val){
return val !== void 0 || typeof val !== 'undefined';
},
/** Run a Map on an Array **/
map: function(arr,fn){
var res = [], i=0;
for( ; i<arr.length; ++i){
res.push(fn(arr[i], i));
}
arr = null;
return res;
},
/** Checks and Return if the prop is Objects own Property */
hasOwnProp: function(obj, val){
return Object.prototype.hasOwnProperty.call(obj, val);
},
/** Extend properties from extending Object to initial Object */
extend: function(newObj, oldObj){
if(this.isDefined(newObj) && this.isDefined(oldObj)){
for(var prop in oldObj){
if(this.hasOwnProp(oldObj, prop)){
newObj[prop] = oldObj[prop];
}
}
return newObj;
}else {
return newObj || oldObj || {};
}
}
};
/**
* This isn't Required but just makes WebStorm color Code Better :D
* */
Sys.isObject
= Sys.isArguments
= Sys.isFunction
= Sys.isString
= Sys.isArray
= Sys.isUndefined
= Sys.isDate
= Sys.isNumber
= Sys.isRegExp
= "";
/** This Method will create Multiple functions in the Sys object that can be used to test type of **/
['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Object', 'Array', 'Undefined']
.forEach(
function(name) {
Sys['is' + name] = function(obj) {
return toString.call(obj) == '[object ' + name + ']';
};
}
);
module.exports = Sys;
Currently in Use on a public git repo. Github Project
Now you can import this Sys code in a Sys.js file. then you can use this Sys object functions to find out the type of JavaScript Objects
you can also check is Object is Defined or type is Function or the Object is Empty... etc.
var m = function(){};
Sys.isObject({});
Sys.isFunction(m);
Sys.isString(m);
console.log(Sys.isDefined(jQuery));
Same from above, bit more detailed
Using .Net Core
Controller
public class TestController : Controller
{
private string connectionString;
public IDbConnection Connection
{
get { return new SqlConnection(connectionString); }
}
public TestController()
{
connectionString = @"Data Source=OCIUZWORKSPC;Initial Catalog=SocialStoriesDB;Integrated Security=True";
}
public JsonResult GetEventCategory(string q)
{
using (IDbConnection dbConnection = Connection)
{
var categories = dbConnection.Query<ResultTokenInput>("GetEventCategories", new { keyword = q },
commandType: CommandType.StoredProcedure).FirstOrDefault();
return Json(categories);
}
}
public class ResultTokenInput
{
public int ID { get; set; }
public string name { get; set; }
}
}
Stored Procedure ( parent child relation )
create PROCEDURE GetEventCategories
@keyword as nvarchar(100)
AS
BEGIN
WITH CTE(Id, Name, IdHierarchy,parentId) AS
(
SELECT
e.EventCategoryID as Id, cast(e.Title as varchar(max)) as Name,
cast(cast(e.EventCategoryID as char(5)) as varchar(max)) IdHierarchy,ParentID
FROM
EventCategory e where e.Title like '%'+@keyword+'%'
-- WHERE
-- parentid = @parentid
UNION ALL
SELECT
p.EventCategoryID as Id, cast(p.Title + '>>' + c.name as varchar(max)) as Name,
c.IdHierarchy + cast(p.EventCategoryID as char(5)),p.ParentID
FROM
EventCategory p
JOIN CTE c ON c.Id = p.parentid
where p.Title like '%'+@keyword+'%'
)
SELECT
*
FROM
CTE
ORDER BY
IdHierarchy
References in case
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using SocialStoriesCore.Data;
using Microsoft.EntityFrameworkCore;
using Dapper;
using System.Data;
using System.Data.SqlClient;
Like others have said, you need to provide the UniqueID of the control to the __doPostback() method.
__doPostBack('<%= btn.UniqueID %>', '');
On the server, the submitted form values are identified by the name attribute of the fields in the page.
The reason why UniqueID works is because UniqueID and name are in fact the same thing when the server control is rendered in HTML.
Here's an article that describes what is the UniqueID:
The UniqueID property is also used to provide value for the HTML "name" attribute of input fields (checkboxes, dropdown lists, and hidden fields). UniqueID also plays major role in postbacks. The UniqueID property of a server control, which supports postbacks, provides data for the __EVENTTARGET hidden field. The ASP.NET Runtime then uses the __EVENTTARGET field to find the control which triggered the postback and then calls its RaisePostBackEvent method.
src: https://www.telerik.com/blogs/the-difference-between-id-clientid-and-uniqueid
Check out the Zend_Db_Profiler. This allows you to log any SQL statement as it is prepared and executed. It works for UPDATE statements as well as SELECT queries.
I have wrote my own library on Python to expand variables being loaded from directories with a hierarchy like:
/root
|
+- /proj1
|
+- config.yaml
|
+- /proj2
|
+- config.yaml
|
... and so on ...
The key difference here is that the expansion must be applied only after all the config.yaml
files is loaded, where the variables from the next file can override the variables from the previous, so the pseudocode should look like this:
env = YamlEnv()
env.load('/root/proj1/config.yaml')
env.load('/root/proj1/proj2/config.yaml')
...
env.expand()
As an additional option the xonsh
script can export the resulting variables into environment variables (see the yaml_update_global_vars
function).
The scripts:
https://sourceforge.net/p/contools/contools/HEAD/tree/trunk/Scripts/Tools/cmdoplib.yaml.py https://sourceforge.net/p/contools/contools/HEAD/tree/trunk/Scripts/Tools/cmdoplib.yaml.xsh
Pros:
${MYUNDEFINEDVAR}
-> *$/{MYUNDEFINEDVAR}
)${env:MYVAR}
)\\
to /
in a path variable (${env:MYVAR:path}
)Cons:
${MYSCOPE.MYVAR}
is not implemented)Now try to run git commands on terminal.
It might ask you to do a two-step verification the first time, just follow the steps and you're done!
request.referer
is set by Rack and is set as follows:
def referer
@env['HTTP_REFERER'] || '/'
end
Just do a redirect_to request.referer
and it will always redirect to the true referring page, or the root_path ('/'). This is essential when passing tests that fail in cases of direct-nav to a particular page in which the controller throws a redirect_to :back
If you want to know only some basics inside the dll assembly e.g. Classes, method etc.,to load them dyanamically
you can make use of IL Disassembler tool provided by Microsoft.
Generally located at: "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin"
Check out http-tool
for firefox ..
https://addons.mozilla.org/en-US/firefox/addon/http-tool/
Aimed at web developers who need to debug HTTP requests and responses.
Can be extremely useful while developing REST based api.
Features:
* GET
* HEAD
* POST
* PUT
* DELETE
Add header(s) to request.
Add body content to request.
View header(s) in response.
View body content in response.
View status code of response.
View status text of response.
For J2EE you have a very comprehensive tutorial at: http://java.sun.com/javaee/5/docs/tutorial/doc/
If your install isn't already damaged, you can drop unwanted PostgreSQL servers ("clusters") using pg_dropcluster
. Use that in preference to a full purge and reinstall if you just want to restart with a fresh PostgreSQL instance.
$ pg_lsclusters
Ver Cluster Port Status Owner Data directory Log file
11 main 5432 online postgres /var/lib/postgresql/11/main /var/log/postgresql/postgresql-11-main.log
$ sudo systemctl stop postgresql@11-main
$ sudo pg_dropcluster --stop 11 main
$ sudo pg_createcluster --start 11 main
If you really need to do a full purge and reinstall, first make sure PostgreSQL isn't running. ps -C postgres
should show no results.
Now run:
apt-get --purge remove postgresql\*
to remove everything PostgreSQL from your system. Just purging the postgres
package isn't enough since it's just an empty meta-package.
Once all PostgreSQL packages have been removed, run:
rm -r /etc/postgresql/
rm -r /etc/postgresql-common/
rm -r /var/lib/postgresql/
userdel -r postgres
groupdel postgres
You should now be able to:
apt-get install postgresql
or for a complete install:
apt-get install postgresql-8.4 postgresql-contrib-8.4 postgresql-doc-8.4
writing this two line is more than enough for your work.
yourEditText.setKeyListener(null);
yourEditText.setEnabled(false);
I had angular-cli version 1.0.0-beta.28.3
, and the only thing that worked for me was deleting the angular-cli directly from the global node_modules folder:
cd /usr/local/bin/lib/node_modules
rm -rf angular-cli
After that ng version
output was, as expected:
command not found: ng
And I could install the latest angular-cli version:
npm install -g @angular/cli@latest
Hope it helps...
Generating strings from (for example) lowercase characters:
import random, string
def randomword(length):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(length))
Results:
>>> randomword(10)
'vxnxikmhdc'
>>> randomword(10)
'ytqhdohksy'
OS X
If you are using Vim in Mac OS X, unfortunately it comes with older version, and not complied with clipboard options. Luckily, Homebrew can easily solve this problem.
Install Vim:
brew install vim --with-lua --with-override-system-vi
Install the GUI version of Vim:
brew install macvim --with-lua --with-override-system-vi
Restart the terminal for it to take effect.
Append the following line to ~/.vimrc
set clipboard=unnamed
Now you can copy the line in Vim with yy
and paste it system-wide.
An alternative ist to use the short form of "concatenate" which is either "r_[...]" or "c_[...]" as shown in the example code beneath (see http://wiki.scipy.org/NumPy_for_Matlab_Users for additional information):
%pylab
vector_a = r_[0.:10.] #short form of "arange"
vector_b = array([1,1,1,1])
vector_c = r_[vector_a,vector_b]
print vector_a
print vector_b
print vector_c, '\n\n'
a = ones((3,4))*4
print a, '\n'
c = array([1,1,1])
b = c_[a,c]
print b, '\n\n'
a = ones((4,3))*4
print a, '\n'
c = array([[1,1,1]])
b = r_[a,c]
print b
print type(vector_b)
Which results in:
[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
[1 1 1 1]
[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 1. 1. 1. 1.]
[[ 4. 4. 4. 4.]
[ 4. 4. 4. 4.]
[ 4. 4. 4. 4.]]
[[ 4. 4. 4. 4. 1.]
[ 4. 4. 4. 4. 1.]
[ 4. 4. 4. 4. 1.]]
[[ 4. 4. 4.]
[ 4. 4. 4.]
[ 4. 4. 4.]
[ 4. 4. 4.]]
[[ 4. 4. 4.]
[ 4. 4. 4.]
[ 4. 4. 4.]
[ 4. 4. 4.]
[ 1. 1. 1.]]
The Content
table likely to have multiple duplicate Application
values that can't be mapped to Libraries
. Is it possible to drop the Application
column from the Libraries
Primary Key Index and add it as a Unique Key Index instead?
You often see the check for definedness so you don't have to deal with the warning for using an undef value (and in Perl 5.10 it tells you the offending variable):
Use of uninitialized value $name in ...
So, to get around this warning, people come up with all sorts of code, and that code starts to look like an important part of the solution rather than the bubble gum and duct tape that it is. Sometimes, it's better to show what you are doing by explicitly turning off the warning that you are trying to avoid:
{
no warnings 'uninitialized';
if( length $name ) {
...
}
}
In other cases, use some sort of null value instead of the data. With Perl 5.10's defined-or operator, you can give length
an explicit empty string (defined, and give back zero length) instead of the variable that will trigger the warning:
use 5.010;
if( length( $name // '' ) ) {
...
}
In Perl 5.12, it's a bit easier because length
on an undefined value also returns undefined. That might seem like a bit of silliness, but that pleases the mathematician I might have wanted to be. That doesn't issue a warning, which is the reason this question exists.
use 5.012;
use warnings;
my $name;
if( length $name ) { # no warning
...
}
Have you tried:
db.posts.find({"created_on": {"$gte": new Date(2012, 7, 14), "$lt": new Date(2012, 7, 15)}})
The problem you're going to run into is that dates are stored as timestamps in Mongo. So, to match a date you're asking it to match a timestamp. In your case I think you're trying to match a day (ie. from 00:00 to 23:59 on a specific date). If your dates are stored without times then you should be okay. Otherwise, try specifying your date as a range of time on the same day (ie. start=00:00, end=23:59) if gte doesn't work.
You could also use a StringVar
variable, even if it's not strictly necessary:
v = StringVar()
e = Entry(master, textvariable=v)
e.pack()
v.set("a default value")
s = v.get()
For more information, see this page on effbot.org.
$this->db->like()
This method enables you to generate LIKE clauses, useful for doing searches.
$this->db->like('title', 'match');
Produces: WHERE title
LIKE '%match%'
If you want to control where the wildcard (%) is placed, you can use an optional third argument. Your options are ‘before’, ‘after’, ‘none’ and ‘both’ (which is the default).
$this->db->like('title', 'match', 'before');
Produces: WHERE title
LIKE '%match'
$this->db->like('title', 'match', 'after');
Produces: WHERE title
LIKE 'match%'
$this->db->like('title', 'match', 'none');
Produces: WHERE title
LIKE 'match'
$this->db->like('title', 'match', 'both');
Produces: WHERE title
LIKE '%match%'
It's a linker error. ld
is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.
The error message tells you that none of the object files you're linking against contains a definition for avergecolumns
. The reason for that is that the function you've defined is called averagecolumns
(in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).
just give mother of div "class="col-lg-12""
<div class="form-group">
<div class="row">
<div class="col-xs-3">
<label for="class_type"><h2><span class=" label label-primary">Class Type</span></h2></label>
</div>
<div class="col-xs-2">
<select name="class_type" id="class_type" class=" form-control input-lg" style="width:200px" autocomplete="off">
<option >Economy</option>
<option >Premium Economy</option>
<option >Club World</option>
<option >First Class</option>
</select>
</div>
</div>
it will be
<div class="form-group">
<div class="col-lg-12">
<div class="row">
<div class="col-xs-3">
<label for="class_type"><h2><span class=" label label-primary">Class Type</span></h2></label>
</div>
<div class="col-xs-2">
<select name="class_type" id="class_type" class=" form-control input-lg" style="width:200px" autocomplete="off">
<option >Economy</option>
<option >Premium Economy</option>
<option >Club World</option>
<option >First Class</option>
</select>
</div>
</div>
</div>
A solution that keeps no traces of the "undo".
NOTE: don't do this if someone allready pulled your change (I would use this only on my personal repo)
do:
git reset <previous label or sha1>
this will re-checkout all the updates locally (so git status will list all updated files)
then you "do your work" and re-commit your changes (Note: this step is optional)
git commit -am "blabla"
At this moment your local tree differs from the remote
git push -f <remote-name> <branch-name>
will push and force remote to consider this push and remove the previous one (specifying remote-name and branch-name is not mandatory but is recommended to avoid updating all branches with update flag).
!! watch-out some tags may still be pointing removed commit !! how-to-delete-a-remote-tag
First go to Window -> Show View -> Error Logs in menu. It will display error logs if you have any. Then try to clean the project and build it again.
Regardless of whether its a script, a html file (for a frame, for example), css file, image, whatever, if you dont specify a server/domain the path of the html doc will be the default, so you could do, for example,
<script type=text/javascript src='/dir/jsfile.js'></script>
or
<script type=text/javascript src='../../scripts/jsfile.js'></script>
If you don't provide the server/domain, the path will be relative to either the path of the page or script of the main document's path
To set the disabled
property to true
or false
use
<button [disabled]="!nextLibAvailable" (click)="showNext('library')" class=" btn btn-info btn-xs" title="Next Lib"> {{libraries.name}}">
<i class="fa fa-chevron-right fa-fw"></i>
</button>
I know this is an old one, but I wanted to post a variation of the accepted answer that will work in IE without removing lines:
function multiLineHtmlEncode(value) {
var lines = value.split(/\r\n|\r|\n/);
for (var i = 0; i < lines.length; i++) {
lines[i] = htmlEncode(lines[i]);
}
return lines.join('\r\n');
}
function htmlEncode(value) {
return $('<div/>').text(value).html();
}
Don't hard code it: this is the sort of thing that can change. Many programs figure out what to bind to by reading in a config file, and doing whatever that says. This way, should your program sometime in the future need to bind to something that's not a public IP, it can do so.
Yes it is possible with the method:
- (void)setViewControllers:(NSArray *)viewControllers
direction:(UIPageViewControllerNavigationDirection)direction
animated:(BOOL)animated
completion:(void (^)(BOOL finished))completion;`
That is the same method used for setting up the first view controller on the page. Similar, you can use it to go to other pages.
Wonder why viewControllers
is an array, and not a single view controller?
That's because a page view controller could have a "spine" (like in iBooks), displaying 2 pages of content at a time. If you display 1 page of content at a time, then just pass in a 1-element array.
An example in Swift:
pageContainer.setViewControllers([displayThisViewController], direction: .Forward, animated: true, completion: nil)
In this case the file which you want to get is stored in the strpath variable:
string strPath = Server.MapPath(Request.ApplicationPath) + "/contents/member/" + strFileName;
You can use Phantombuster. Instagram has set some rate limit, so you will have to use either multiple accounts or wait for 15 minutes for the next run.
This is my implementation of the solution suggested by @mhm, where I discarded the use of jQuery.
The variable formId contains the id of the form and msg is an object with messages of my application.
This implementation tries to notify the user with the native HTML 5 error messages, if not possible then alert a generic form error message.
If there are no errors I submit the form.
let applyForm = document.getElementById(formId);
if (!applyForm.checkValidity()) {
if (applyForm.reportValidity) {
applyForm.reportValidity();
} else {
alert(msg.ieErrorForm);
}
} else {
applyForm.submit();
}
i tried my own implementation of itoa(), it seem's work in binary, octal, decimal and hex
#define INT_LEN (10)
#define HEX_LEN (8)
#define BIN_LEN (32)
#define OCT_LEN (11)
static char * my_itoa ( int value, char * str, int base )
{
int i,n =2,tmp;
char buf[BIN_LEN+1];
switch(base)
{
case 16:
for(i = 0;i<HEX_LEN;++i)
{
if(value/base>0)
{
n++;
}
}
snprintf(str, n, "%x" ,value);
break;
case 10:
for(i = 0;i<INT_LEN;++i)
{
if(value/base>0)
{
n++;
}
}
snprintf(str, n, "%d" ,value);
break;
case 8:
for(i = 0;i<OCT_LEN;++i)
{
if(value/base>0)
{
n++;
}
}
snprintf(str, n, "%o" ,value);
break;
case 2:
for(i = 0,tmp = value;i<BIN_LEN;++i)
{
if(tmp/base>0)
{
n++;
}
tmp/=base;
}
for(i = 1 ,tmp = value; i<n;++i)
{
if(tmp%2 != 0)
{
buf[n-i-1] ='1';
}
else
{
buf[n-i-1] ='0';
}
tmp/=base;
}
buf[n-1] = '\0';
strcpy(str,buf);
break;
default:
return NULL;
}
return str;
}
By using the array initializer list syntax, ie:
String myArray[] = { "one", "two", "three" };
The solution by PeterVR has the disadvantage that the additional color displays on top of the entire HTML block - meaning that it also shows up on top of div content, not just on top of the background image. This is fine if your div is empty, but if it is not using a linear gradient might be a better solution:
<div class="the-div">Red text</div>
<style type="text/css">
.the-div
{
background-image: url("the-image.png");
color: #f00;
margin: 10px;
width: 200px;
height: 80px;
}
.the-div:hover
{
background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
background-image: -moz-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
background-image: -o-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
background-image: -ms-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(0, 0, 0, 0.1)), to(rgba(0, 0, 0, 0.1))), url("the-image.png");
background-image: -webkit-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
}
</style>
See fiddle. Too bad that gradient specifications are currently a mess. See compatibility table, the code above should work in any browser with a noteworthy market share - with the exception of MSIE 9.0 and older.
Edit (March 2017): The state of the web got far less messy by now. So the linear-gradient
(supported by Firefox and Internet Explorer) and -webkit-linear-gradient
(supported by Chrome, Opera and Safari) lines are sufficient, additional prefixed versions are no longer necessary.
In my case this problem persisted when I created and saved the svg using Photoshop. What helped, was opening the file using Illustrator and exporting the svg afterwards.
@andrey answer in one line (tested in Swift 4.1):
extension UIResponder {
public var parentViewController: UIViewController? {
return next as? UIViewController ?? next?.parentViewController
}
}
usage:
let vc: UIViewController = view.parentViewController
Visible gallery changes visibility which is how you get the gallery over other view overlap. the Home sample app has some good examples of this technique.
Updated, Simple Solution
@media print {
body {
display: table;
table-layout: fixed;
padding-top: 2.5cm;
padding-bottom: 2.5cm;
height: auto;
}
}
Old Solution
Create section with each page, and use the below code to adjust margins, height and width.
If you are printing A4 size.
Then user
Size : 8.27in and 11.69 inches
@page Section1 {
size: 8.27in 11.69in;
margin: .5in .5in .5in .5in;
mso-header-margin: .5in;
mso-footer-margin: .5in;
mso-paper-source: 0;
}
div.Section1 {
page: Section1;
}
then create a div with all your content in it.
<div class="Section1">
type your content here...
</div>
An alternative to the accepted answer that fits in the first line:
#!/bin/bash -e
cd some_dir
./configure --some-flags
make
make install
function xText() {_x000D_
var x = $("#input").val();_x000D_
var x_length = x.length;_x000D_
var a = '';_x000D_
for (var i = 0; i < x_length; i++) {_x000D_
a += "x";_x000D_
}_x000D_
$("#output").val(a);_x000D_
}
_x000D_
.form-cus {width: 200px;margin: auto;position: relative;}_x000D_
.form-cus .putval, .form-cus .getval {width: 100%;box-sizing: border-box;}_x000D_
.form-cus .putval {position: absolute;left: 0px;top:0; height:100%; color: transparent;background: transparent;border: 0px;outline: 0 none;}_x000D_
.form-cus .putval::selection {color: transparent;background: lightblue;}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>_x000D_
<p>Input Number or Strong Mouse Click is Hidden... </p>_x000D_
<div class="form-cus">_x000D_
<input class="putval" type="text" id="input" maxlength="16" oninput="xText();" placeholder="Input Text" />_x000D_
<input class="getval" type="text" id="output" maxlength="16" />_x000D_
</div>
_x000D_
It is sure because the Invoke-WebRequest command has a dependency on the Internet Explorer assemblies and are invoking it to parse the result as per default behaviour. As Matt suggest, you can simply launch IE and make your selection in the settings prompt which is popping up at first launch. And the error you experience will disappear.
But this is only possible if you run your powershell scripts as the same windows user as whom you launched the IE with. The IE settings are stored under your current windows profile. So if you, like me run your task in a scheduler on a server as the SYSTEM user, this will not work.
So here you will have to change your scripts and add the -UseBasicParsing argument, as ijn this example: $WebResponse = Invoke-WebRequest -Uri $url -TimeoutSec 1800 -ErrorAction:Stop -Method:Post -Headers $headers -UseBasicParsing
I got here looking for the same thing and I found another solution. If you guys are interested I share this class:
using System;
using System.Management;
using System.Security.Cryptography;
using System.Security;
using System.Collections;
using System.Text;
namespace Security
{
/// <summary>
/// Generates a 16 byte Unique Identification code of a computer
/// Example: 4876-8DB5-EE85-69D3-FE52-8CF7-395D-2EA9
/// </summary>
public class FingerPrint
{
private static string fingerPrint = string.Empty;
public static string Value()
{
if (string.IsNullOrEmpty(fingerPrint))
{
fingerPrint = GetHash("CPU >> " + cpuId() + "\nBIOS >> " +
biosId() + "\nBASE >> " + baseId() +
//"\nDISK >> "+ diskId() + "\nVIDEO >> " +
videoId() +"\nMAC >> "+ macId()
);
}
return fingerPrint;
}
private static string GetHash(string s)
{
MD5 sec = new MD5CryptoServiceProvider();
ASCIIEncoding enc = new ASCIIEncoding();
byte[] bt = enc.GetBytes(s);
return GetHexString(sec.ComputeHash(bt));
}
private static string GetHexString(byte[] bt)
{
string s = string.Empty;
for (int i = 0; i < bt.Length; i++)
{
byte b = bt[i];
int n, n1, n2;
n = (int)b;
n1 = n & 15;
n2 = (n >> 4) & 15;
if (n2 > 9)
s += ((char)(n2 - 10 + (int)'A')).ToString();
else
s += n2.ToString();
if (n1 > 9)
s += ((char)(n1 - 10 + (int)'A')).ToString();
else
s += n1.ToString();
if ((i + 1) != bt.Length && (i + 1) % 2 == 0) s += "-";
}
return s;
}
#region Original Device ID Getting Code
//Return a hardware identifier
private static string identifier
(string wmiClass, string wmiProperty, string wmiMustBeTrue)
{
string result = "";
System.Management.ManagementClass mc =
new System.Management.ManagementClass(wmiClass);
System.Management.ManagementObjectCollection moc = mc.GetInstances();
foreach (System.Management.ManagementObject mo in moc)
{
if (mo[wmiMustBeTrue].ToString() == "True")
{
//Only get the first one
if (result == "")
{
try
{
result = mo[wmiProperty].ToString();
break;
}
catch
{
}
}
}
}
return result;
}
//Return a hardware identifier
private static string identifier(string wmiClass, string wmiProperty)
{
string result = "";
System.Management.ManagementClass mc =
new System.Management.ManagementClass(wmiClass);
System.Management.ManagementObjectCollection moc = mc.GetInstances();
foreach (System.Management.ManagementObject mo in moc)
{
//Only get the first one
if (result == "")
{
try
{
result = mo[wmiProperty].ToString();
break;
}
catch
{
}
}
}
return result;
}
private static string cpuId()
{
//Uses first CPU identifier available in order of preference
//Don't get all identifiers, as it is very time consuming
string retVal = identifier("Win32_Processor", "UniqueId");
if (retVal == "") //If no UniqueID, use ProcessorID
{
retVal = identifier("Win32_Processor", "ProcessorId");
if (retVal == "") //If no ProcessorId, use Name
{
retVal = identifier("Win32_Processor", "Name");
if (retVal == "") //If no Name, use Manufacturer
{
retVal = identifier("Win32_Processor", "Manufacturer");
}
//Add clock speed for extra security
retVal += identifier("Win32_Processor", "MaxClockSpeed");
}
}
return retVal;
}
//BIOS Identifier
private static string biosId()
{
return identifier("Win32_BIOS", "Manufacturer")
+ identifier("Win32_BIOS", "SMBIOSBIOSVersion")
+ identifier("Win32_BIOS", "IdentificationCode")
+ identifier("Win32_BIOS", "SerialNumber")
+ identifier("Win32_BIOS", "ReleaseDate")
+ identifier("Win32_BIOS", "Version");
}
//Main physical hard drive ID
private static string diskId()
{
return identifier("Win32_DiskDrive", "Model")
+ identifier("Win32_DiskDrive", "Manufacturer")
+ identifier("Win32_DiskDrive", "Signature")
+ identifier("Win32_DiskDrive", "TotalHeads");
}
//Motherboard ID
private static string baseId()
{
return identifier("Win32_BaseBoard", "Model")
+ identifier("Win32_BaseBoard", "Manufacturer")
+ identifier("Win32_BaseBoard", "Name")
+ identifier("Win32_BaseBoard", "SerialNumber");
}
//Primary video controller ID
private static string videoId()
{
return identifier("Win32_VideoController", "DriverVersion")
+ identifier("Win32_VideoController", "Name");
}
//First enabled network card ID
private static string macId()
{
return identifier("Win32_NetworkAdapterConfiguration",
"MACAddress", "IPEnabled");
}
#endregion
}
}
I won't take any credit for this because I found it here It worked faster than I expected for me. Without the graphic card, mac and drive id's I got the unique ID in about 2-3 seconds. With those above included I got it in about 4-5 seconds.
Note: Add reference to System.Management
.
They're hints to the compiler to generate the hint prefixes on branches. On x86/x64, they take up one byte, so you'll get at most a one-byte increase for each branch. As for performance, it entirely depends on the application -- in most cases, the branch predictor on the processor will ignore them, these days.
Edit: Forgot about one place they can actually really help with. It can allow the compiler to reorder the control-flow graph to reduce the number of branches taken for the 'likely' path. This can have a marked improvement in loops where you're checking multiple exit cases.
With n
being the line number:
ng
: Jump to line number n. Default is the start of the file.nG
: Jump to line number n. Default is the end of the file.So to go to line number 320123, you would type 320123g
.
Copy-pasted straight from Wikipedia.
A fragment lives inside an activity, while an activity lives by itself.
Just do it:
Django database objects use the same save() method for creating and changing objects.
obj = Product.objects.get(pk=pk)
obj.name = "some_new_value"
obj.save()
How Django knows to UPDATE vs. INSERT
If the object’s primary key attribute is set to a value that evaluates to True (i.e., a value other than None or the empty string), Django executes an UPDATE. If the object’s primary key attribute is not set or if the UPDATE didn’t update anything, Django executes an INSERT.
Ref.: https://docs.djangoproject.com/en/1.9/ref/models/instances/
You could also do:
del /s /p *.{your extension here}
The /p
will prompt you for each found file, if you're nervous about deleting something you shouldn't.
EasyFSM is a dynamic Java Library which can be used to implement an FSM.
You can find documentation for the same at : Finite State Machine in Java
Also, you can download the library at : Java FSM Library : DynamicEasyFSM
I can assure you both the answers will make first letter capital and will not make edittext single line.
If you want to do it in XMl below is the code
android:inputType="textCapWords|textCapSentences"
If want to do it in activity/fragment etc below is the code
momentTextView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS | InputType.TYPE_TEXT_FLAG_MULTI_LINE)
PS: If you are having nay other property also you can easily add it with a pipe "|" symbol, just make sure there is no space in xml between the attribute properties
I got the same warnings when I sudo -i
starting a root shell, @chakrit's solution didn't work for me.
But I found -u
switch of compinit
works, e.g. in your .zshrc/zshenv or where you called compinit
compinit -u
NB: Not recommended for production system
See also http://zsh.sourceforge.net/Doc/Release/Completion-System.html#Initialization
/usr/local/cilk/bin/../lib32/pinbin is dynamically linked to a library libstdc++.so.6 which is not present anymore. You need to recompile Cilk
add these tag in your view
app:layout_constraintCircleRadius="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
and you can right click in design mode and choose center.
Dashes don't need to be removed from HTTP request as you can see in URL of this thread. But if you want to prepare well-formed URL without dependency on data you should use URLEncoder.encode( String data, String encoding ) instead of changing standard form of you data. For UUID string representation dashes is normal.
let arr1: boolean[] = [];
console.log(arr1[1]);
arr1.push(true);
JavaScript is a scripting language and therefore stays in human readable form until it is time for it to be interpreted and executed by the JavaScript runtime.
The only way to partially hide it, at least from the less technical minds, is to obfuscate.
Obfuscation makes it harder for humans to read it, but not impossible for the technically savvy.
We can define user defined comparator: .The code below can be helpful for you.
#include<bits/stdc++.h>
using namespace std;
struct man
{
string name;
int priority;
};
class comparator
{
public:
bool operator()(const man& a, const man& b)
{
return a.priority<b.priority;
}
};
int main()
{
man arr[5];
priority_queue<man, vector<man>, comparator> pq;
for(int i=0; i<3; i++)
{
cin>>arr[i].name>>arr[i].priority;
pq.push(arr[i]);
}
while (!pq.empty())
{
cout<<pq.top().name<<" "<<pq.top().priority;
pq.pop();
cout<<endl;
}
return 0;
}
input :
batman 2
goku 9
mario 4
Output
goku 9
mario 4
batman 2
This can actually be done with only CSS, but the content inside the div must be absolutely positioned. The key is to use padding as a percentage and the box-sizing: border-box
CSS attribute:
div {_x000D_
border: 1px solid red;_x000D_
width: 40%;_x000D_
padding: 40%;_x000D_
box-sizing: border-box;_x000D_
position: relative;_x000D_
}_x000D_
p {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
}
_x000D_
<div>_x000D_
<p>Some unnecessary content.</p>_x000D_
</div>
_x000D_
Adjust percentages to your liking. Here is a JSFiddle
Install git on your PC and setup configuration values in either Command Prompt (cmd) or VS Code terminal (Ctrl + `
)
git config --global user.name "Your Name"
git config --global user.email [email protected]
Setup editor
Windows eg.:
git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -nosession"
Linux / Mac eg.:
git config --global core.editor vim
Check git settings which displays configuration details
git config --list
Login to github and create a remote repository. Copy the URL of this repository
Navigate to your project directory and execute the below commands
git init // start tracking current directory
git add -A // add all files in current directory to staging area, making them available for commit
git commit -m "commit message" // commit your changes
git remote add origin https://github.com/username/repo-name.git // add remote repository URL which contains the required details
git pull origin master // always pull from remote before pushing
git push -u origin master // publish changes to your remote repository
Let Unreal do the job.
Close all, Right click your Project File (.uproject),
"Generate VisualStudio Project Files".
I had the same issue and I resolved it with MySQL workbench, as shown in the attached screenshot:
Hope that helps!
You can use Memurai for Windows, a Redis-compatible cache and datastore for Windows, currently compatible with Redis 5. Memurai aims to fulfill the need for a supported Redis-compatible datastore on the Windows platform. At its core, it’s based on Redis source code, ported to run natively on Windows, and it’s designed to provide the level of reliability and performance required for production environments. Memurai is free for development and testing. You can learn more and download Memurai at https://www.memurai.com.
Alexis Campailla
CEO, Memurai
You can make them 1024 x 768. You can also check "Status bar is initially hidden" in the plist file.
try this
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Linuxbrew/linuxbrew/go/install)"
those are miliseconds, just divide them by 1000, since gmtime expects seconds ...
time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807/1000.0))
PHP is run server-side. JavaScript is run client-side in the browser of the user requesting the page. By the time the JavaScript is executed, there is no access to PHP on the server whatsoever. Please read this article with details about client-side vs server-side coding.
What happens in a nutshell is this:
In your case, PHP will write the JS code into the page, so it can be executed when the page is rendered in your browser. By that time, the PHP part in your JS snippet does no longer exist. It was executed on the server already. It created a variable $result
that contained a SQL query string. You didn't use it, so when the page is send back to your browser, it's gone. Have a look at the sourcecode when the page is rendered in your browser. You will see that there is nothing at the position you put the PHP code.
The only way to do what you are looking to do is either:
with the values you want to be insert into the database.
Take a look at "SET ROLE" and "SET SESSION AUTHORIZATION".
I had the same problem as OP and found was due to the options declaration being misspelled:
' Comment comment
Options Explicit
Sub someMacroMakechart()
in a sub module, instead of correct;
' Comment comment
Option Explicit
Sub someMacroMakechart()
Another Answer.
Use Black Magic Spells:
function sortArguments() {
arguments.__proto__ = Array.prototype;
return arguments.slice().sort();
}
Firefox, Chrome, Node.js, IE11 are OK.
If you want to fetch particular element/node or tag in loop for e.g.
<p class="weekday" data-today="monday">Monday</p>
<p class="weekday" data-today="tuesday">Tuesday</p>
<p class="weekday" data-today="wednesday">Wednesday</p>
<p class="weekday" data-today="thursday">Thursday</p>
So, from above code loop is executed and we want particular field to select for that we have to use jQuery selection that can select only expecting element from above loop so, code will be
$('.weekdays:eq(n)');
e.g.
$('.weekdays:eq(0)');
as well as by other method
$('.weekday').find('p').first('.weekdays').next()/last()/prev();
but first method is more efficient when HTML <tag>
has unique class name.
NOTE:Second method is use when their is no class name in target element or node.
for more follow https://api.jquery.com/eq/
Another solution is to do this:
static float NextFloat(Random random)
{
float f;
do
{
byte[] bytes = new byte[4];
random.NextBytes(bytes);
f = BitConverter.ToSingle(bytes, 0);
}
while (float.IsInfinity(f) || float.IsNaN(f));
return f;
}
For completeness, the boost way would be to use boost::format
cout << boost::format("%s %s > %s") % a % b % c;
Take your pick. The boost solution has the advantage of type safety with the sprintf
format (for those who find the <<
syntax a bit clunky).
There is equally formatDate
const format = 'dd/MM/yyyy';
const myDate = '2019-06-29';
const locale = 'en-US';
const formattedDate = formatDate(myDate, format, locale);
According to the API it takes as param either a date string, a Date object, or a timestamp.
Gotcha: Out of the box, only en-US
is supported.
If you need to add another locale, you need to add it and register it in you app.module, for example for Spanish:
import { registerLocaleData } from '@angular/common';
import localeES from "@angular/common/locales/es";
registerLocaleData(localeES, "es");
Don't forget to add corresponding import:
import { formatDate } from "@angular/common";
You should be able to utilize the asterisk and !important
elements within CSS.
html *
{
font-size: 1em !important;
color: #000 !important;
font-family: Arial !important;
}
The asterisk matches everything (you could probably get away without the html
too).
The !important
ensures that nothing can override what you've set in this style (unless it is also important). (this is to help with your requirement that it should "ignore inner formatting of text" - which I took to mean that other styles could not overwrite these)
The rest of the style within the braces is just like any other styling and you can do whatever you'd like to in there. I chose to change the font size, color and family as an example.
Don't know how to do locale, but javascript is a client side technology.
usersLocalTime = new Date();
will have the client's time and date in it (as reported by their browser, and by extension the computer they are sitting at). It should be trivial to include the server's time in the response and do some simple math to guess-timate offset.
A safer way to approach breaking a foreach
or while
loop in PHP is to nest an incrementing counter variable and if
conditional inside of the original loop. This gives you tighter control than break;
which can cause havoc elsewhere on a complicated page.
Example:
// Setup a counter
$ImageCounter = 0;
// Increment through repeater fields
while ( condition ):
$ImageCounter++;
// Only print the first while instance
if ($ImageCounter == 1) {
echo 'It worked just once';
}
// Close while statement
endwhile;
Here is a working plunkr with a filter and sortBy pipe. https://plnkr.co/edit/vRvnNUULmBpkbLUYk4uw?p=preview
As developer033 mentioned in a comment, you are passing in a single value to the filter pipe, when the filter pipe is expecting an array of values. I would tell the pipe to expect a single value instead of an array
export class FilterPipe implements PipeTransform {
transform(items: any[], term: string): any {
// I am unsure what id is here. did you mean title?
return items.filter(item => item.id.indexOf(term) !== -1);
}
}
I would agree with DeborahK that impure pipes should be avoided for performance reasons. The plunkr includes console logs where you can see how much the impure pipe is called.
Just add Quotation Mark
Example:"C:\Users\User Name"
Hope it got Solved!
I stumbled on a very similar case.
I wanted to compare on a test that an object had the same attribute values as another one, but methods like is()
, refEq()
, etc wouldn't work for reasons like my object having a null value in its id
attribute.
So this was the solution I found (well, a coworker found):
import static org.apache.commons.lang.builder.CompareToBuilder.reflectionCompare;
assertThat(reflectionCompare(expectedObject, actualObject, new String[]{"fields","to","be","excluded"}), is(0));
If the value obtained from reflectionCompare
is 0, it means they are equal. If it is -1 or 1, they differ on some attribute.
You can use: git remote -v
Documentation: https://git-scm.com/docs/git-remote
Manage the set of repositories ("remotes") whose branches you track. -v --verbose Be a little more verbose and show remote url after name. NOTE: This must be placed between remote and subcommand.
It is called Telescoping Constructor anti-pattern or constructor chaining. Yes, you can definitely do. I see many examples above and I want to add by saying that if you know that you need only two or three constructor, it might be ok. But if you need more, please try to use different design pattern like Builder pattern. As for example:
public Omar(){};
public Omar(a){};
public Omar(a,b){};
public Omar(a,b,c){};
public Omar(a,b,c,d){};
...
You may need more. Builder pattern would be a great solution in this case. Here is an article, it might be helpful https://medium.com/@modestofiguereo/design-patterns-2-the-builder-pattern-and-the-telescoping-constructor-anti-pattern-60a33de7522e
Regardless of where you put the CSS file you can simply use the CodeIgniter "html" helper called link_tag(). You would apply this helper something like this:
echo link_tag('folder/subfolder/stylesheet.css');
It is up to you to locate the CSS file in the most appropriate place (in your opinion). You would have to either autoload the "html" helper or separately load it in to use it.
People keep suggesting the usage of base_url() to achieve this but it is actually not really the "CodeIgniter" way to do it (I think this question has a few duplicates). That will work but one of the reasons for using a framework is to use the pre-made functions within it.
There are many helpers in codeigniter to do this kind of thing.
A much more accurate SQL STATEMENT
SELECT a.tablespace_name,
ROUND (((c.BYTES - NVL (b.BYTES, 0)) / c.BYTES) * 100,2) percentage_used,
c.BYTES / 1024 / 1024 space_allocated,
ROUND (c.BYTES / 1024 / 1024 - NVL (b.BYTES, 0) / 1024 / 1024,2) space_used,
ROUND (NVL (b.BYTES, 0) / 1024 / 1024, 2) space_free,
c.DATAFILES
FROM dba_tablespaces a,
( SELECT tablespace_name,
SUM (BYTES) BYTES
FROM dba_free_space
GROUP BY tablespace_name
) b,
( SELECT COUNT (1) DATAFILES,
SUM (BYTES) BYTES,
tablespace_name
FROM dba_data_files
GROUP BY tablespace_name
) c
WHERE b.tablespace_name(+) = a.tablespace_name
AND c.tablespace_name(+) = a.tablespace_name
ORDER BY NVL (((c.BYTES - NVL (b.BYTES, 0)) / c.BYTES), 0) DESC;
var path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)?.Replace("file:\\", "");
Here is another solution I wrote in C# to auto startup native node server or pm2 server on Windows.
Those are some very nice, but lengthy answers.
To sum up my experiences:
You can do this by calling the constructor each time with is slightly better
var tupleList = new List<Tuple<int, string>>
{
new Tuple<int, string>(1, "cow" ),
new Tuple<int, string>( 5, "chickens" ),
new Tuple<int, string>( 1, "airplane" )
};
When you are not sure of the number of rows, then you can do it this way:
followers_df.index = range(len(followers_df))
All Unicode-enabled Regex flavours should have a special character class like \w that match any Unicode letter. Take a look at your specific flavour here.
Here is my implementation in C#:
public static PointF PointOnCircle(float radius, float angleInDegrees, PointF origin)
{
// Convert from degrees to radians via multiplication by PI/180
float x = (float)(radius * Math.Cos(angleInDegrees * Math.PI / 180F)) + origin.X;
float y = (float)(radius * Math.Sin(angleInDegrees * Math.PI / 180F)) + origin.Y;
return new PointF(x, y);
}
select ROUND(CASE
WHEN CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then CONVERT( float, REPLACE( isnull( value3,''),',',''))
WHEN CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))!='' then CONVERT( float, REPLACE( isnull( value3,''),',',''))
WHEN CONVERT( float, REPLACE( isnull( value1,''),',',''))!='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then CONVERT( float, REPLACE( isnull( value3,''),',',''))
else CONVERT( float, REPLACE(isnull( value1,''),',','')) end,0) from Tablename where ID="123"
When IE9 comes, it will be easier. A lot of the time though, you can switch the problem to one requiring :first-child and style the opposite side of the element (IE7+).
Be careful of span
!
myspan.styles.width='100px'
doesn't want to work.
Change the span
to a div
.
I faced the same issue. I was using Java 9 and the following dependency in pom file:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
The issue was resolved after adding the dependency below in pom:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
You should take a look to the format method of python. You could then define your formatting string like this :
>>> s = '{0} BLAH BLAH {1} BLAH {2} BLAH BLIH BLEH'
>>> x = ['1', '2', '3']
>>> print s.format(*x)
'1 BLAH BLAH 2 BLAH 3 BLAH BLIH BLEH'
Prerequisites: You already have the service and published WSDL file, and you want to call your web service from C# client application.
There are 2 main way of doing this:
A) ASP.NET services, which is old way of doing SOA
B) WCF, as John suggested, which is the latest framework from MS and provides many protocols, including open and MS proprietary ones.
The simplest way is to generate proxy classes in C# application (this process is called adding service reference).
A dialog should appear shown in screenshot below. Enter the url of your wsdl file and hit Ok. Note that if you'll receive error message after hitting ok, try removing ?wsdl part from url.
I'm using http://www.dneonline.com/calculator.asmx?WSDL as an example
Expand Service References in Solution Explorer and double click CalculatorServiceReference
(or whatever you named the named the service in the previous step).
You should see generated proxy class name and namespace.
In my case, the namespace is SoapClient.CalculatorServiceReference
, the name of proxy class is CalculatorSoapClient
. As I said above, class names may vary in your case.
Go to your C# source code and add the following
using WindowsFormsApplication1.ServiceReference1
Now you can call the service this way.
Service1Client service = new Service1Client();
int year = service.getCurrentYear();
Hope this helps. If you encounter any problems, let us know.
You can also get them with pure javascript.
For example:
new URL(location.href).searchParams.get('page')
For this url: websitename.com/user/?page=1, it would return a value of 1
You can also use TypeSafeDiagnosingMatcher
private Matcher<GetPackagesRequest> expectedPackageRequest(final AvailabilityRequest request) {
return new TypeSafeDiagnosingMatcher<GetPackagesRequest>() {
StringBuilder text = new StringBuilder(500);
@Override
protected boolean matchesSafely(GetPackagesRequest req, Description desc) {
String productCode = req.getPackageIds().iterator().next().getValue();
if (productCode.equals(request.getSupplierProductCode())) {
text.append("ProductCode not equal! " + productCode + " , " + request.getSupplierProductCode());
return true;
}
text.append(req.toString());
return false;
}
@Override
public void describeTo(Description d) {
d.appendText(text.toString());
}
};
}
Then verify that invocation:
Mockito.verify(client).getPackages(Mockito.argThat(expectedPackageRequest(request)));
Your problem is that you have 64-bit eclipse
running but you have 32 bit JRE
.So please download JRE
for 64 bit windows
and let it install on the default location.
Finally add that path till bin in your PATH variable.
Try it should work.
Use Not Like
where some_column NOT LIKE '%[^0-9]%'
declare @str varchar(50)='50'--'asdarew345'
select 1 where @str NOT LIKE '%[^0-9]%'
Use this it should help.
var currentUrl = "google.com"
var partOfUrl = currentUrl.substring(0, currentUrl.length-2)
webView.setWebViewClient(object: WebViewClient() {
override fun onLoadResource(WebView view, String url) {
//call loadUrl() method here
// also check if url contains partOfUrl, if not load it differently.
if(url.contains(partOfUrl, true)) {
//it should work if you reach inside this if scope.
} else if(!(currentUrl.startWith("w", true))) {
webView.loadurl("www.$currentUrl")
} else if(!(currentUrl.startWith("h", true))) {
webView.loadurl("https://$currentUrl")
} else {
//...
}
}
override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
// you can call again loadUrl from here too if there is any error.
}
// You should also override other override method for error such as
// onReceiveError to see how all these methods are called one after another and how
// they behave while debugging with break point.
}
For modern browser, you can use flex
layout to ensure the footer stays at the bottom no matter the content length (and the bottom won't hide the content if it is too long)
HTML Layout:
<div class="layout-wrapper">
<header>My header</header>
<section class="page-content">My Main page content</section>
<footer>My footer</footer>
</div>
CSS:
html, body {
min-height: 100vh;
width: 100%;
padding: 0;
margin: 0;
}
.layout-wrapper {
min-height: 100vh;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.layout-wrapper > .page-content {
background: cornflowerblue;
color: white;
padding: 20px;
}
.layout-wrapper > header, .layout-wrapper > footer {
background: #C0C0C0;
padding: 20px 0;
}
You can add listener all video events nicluding ended, loadedmetadata, timeupdate
where ended
function gets called when video ends
$("#myVideo").on("ended", function() {_x000D_
//TO DO: Your code goes here..._x000D_
alert("Video Finished");_x000D_
});_x000D_
_x000D_
$("#myVideo").on("loadedmetadata", function() {_x000D_
alert("Video loaded");_x000D_
this.currentTime = 50;//50 seconds_x000D_
//TO DO: Your code goes here..._x000D_
});_x000D_
_x000D_
_x000D_
$("#myVideo").on("timeupdate", function() {_x000D_
var cTime=this.currentTime;_x000D_
if(cTime>0 && cTime % 2 == 0)//Alerts every 2 minutes once_x000D_
alert("Video played "+cTime+" minutes");_x000D_
//TO DO: Your code goes here..._x000D_
var perc=cTime * 100 / this.duration;_x000D_
if(perc % 10 == 0)//Alerts when every 10% watched_x000D_
alert("Video played "+ perc +"%");_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<video id="myVideo" controls="controls">_x000D_
<source src="your_video_file.mp4" type="video/mp4">_x000D_
<source src="your_video_file.mp4" type="video/ogg">_x000D_
Your browser does not support HTML5 video._x000D_
</video>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Try setting the variable CMAKE_CXX_FLAGS
instead of CMAKE_C_FLAGS
:
set (CMAKE_CXX_FLAGS "-fexceptions")
The variable CMAKE_C_FLAGS
only affects the C compiler, but you are compiling C++ code.
Adding the flag to CMAKE_EXE_LINKER_FLAGS
is redundant.
More efficient ways of concatenating strings are:
join():
Very efficent, but a bit hard to read.
>>> Section = 'C_type'
>>> new_str = ''.join(['Sec_', Section]) # inserting a list of strings
>>> print new_str
>>> 'Sec_C_type'
String formatting:
Easy to read and in most cases faster than '+' concatenating
>>> Section = 'C_type'
>>> print 'Sec_%s' % Section
>>> 'Sec_C_type'
Just to add my results, also using Matplotlib.
.eps made all my text bold and removed transparency. .svg gave me high-resolution pictures that actually looked like my graph.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# Do the plot code
fig.savefig('myimage.svg', format='svg', dpi=1200)
I used 1200 dpi because a lot of scientific journals require images in 1200 / 600 / 300 dpi, depending on what the image is of. Convert to desired dpi and format in GIMP or Inkscape.
Obviously the dpi doesn't matter since .svg are vector graphics and have "infinite resolution".
you can use ![ ](any link of image)
Also I would suggest to use https://stackedit.io/ for markdown formating and wring it is much easy than remembering all the markdown syntax
Update:
There is now the possibility to use prefix
to get the first n elements of an array. Check @mluisbrown's answer for an explanation how to use prefix.
Original Answer:
You can do it really easy without filter
, map
or reduce
by just returning a range of your array:
var wholeArray = [1, 2, 3, 4, 5, 6]
var n = 5
var firstFive = wholeArray[0..<n] // 1,2,3,4,5
String[] strArray= str.split(Pattern.quote("||"));
where
That its the correct code of background size :
<div class="html-mobile-background">
</div>
<style type="text/css">
html {
/* Whatever you want */
}
.html-mobile-background {
position: fixed;
z-index: -1;
top: 0;
left: 0;
width: 100%;
height: 100%; /* To compensate for mobile browser address bar space */
background: url(YOUR BACKGROUND URL HERE) no-repeat;
center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-size: 100% 100%
}
</style>
IUser
is the interface, you can't instantiate the interface.
You need to instantiate the concrete class that implements the interface.
IUser user = new User();
or
User user = new User();
What do you want to do with the attribute? Is it an html attribute or something of your own?
Most of the time you can simply address it as a property: want to set a title on an element? element.title = "foo"
will do it.
For your own custom JS attributes the DOM is naturally extensible (aka expando=true), the simple upshot of which is that you can do element.myCustomFlag = foo
and subsequently read it without issue.
Note that as of Microsoft SQL Server 2016, UTF-8 is supported by bcp
, BULK_INSERT
, and OPENROWSET
.
Addendum 2016-12-21: SQL Server 2016 SP1 now enables Unicode Compression (and most other previously Enterprise-only features) for all versions of MS SQL including Standard and Express. This is not the same as UTF-8 support, but it yields a similar benefit if the goal is disk space reduction for Western alphabets.
This is how I solved this problem
$scope.downloadPDF = function () {
var link = document.createElement("a");
link.setAttribute("href", "path_to_pdf_file/pdf_filename.pdf");
link.setAttribute("download", "download_name.pdf");
document.body.appendChild(link); // Required for FF
link.click(); // This will download the data file named "download_name.pdf"
}
That error kicks in when you have forgot to include the jQuery library in your page or there is conflict between libraries - for example you be using any other javascript library on your page.
Take a look at this for more info:
There is merge!
.
h = {}
h.merge!(key: "bar")
# => {:key=>"bar"}
it solved me by adjusting code from @Connor Cushion Mulhall by
iframe, object, embed {_x000D_
width: 100%;_x000D_
display: block !important;_x000D_
}
_x000D_
If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".
Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".
Based on the given answers and information in the question, this is the code you should use:
public static boolean doesURLExist(URL url) throws IOException
{
// We want to check the current URL
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// We don't need to get data
httpURLConnection.setRequestMethod("HEAD");
// Some websites don't like programmatic access so pretend to be a browser
httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
int responseCode = httpURLConnection.getResponseCode();
// We only accept response code 200
return responseCode == HttpURLConnection.HTTP_OK;
}
Of course tested and working.
This means that a TCP RST was received and the connection is now closed. This occurs when a packet is sent from your end of the connection but the other end does not recognize the connection; it will send back a packet with the RST bit set in order to forcibly close the connection.
This can happen if the other side crashes and then comes back up or if it calls close()
on the socket while there is data from you in transit, and is an indication to you that some of the data that you previously sent may not have been received.
It is up to you whether that is an error; if the information you were sending was only for the benefit of the remote client then it may not matter that any final data may have been lost. However you should close the socket and free up any other resources associated with the connection.
As of iOS 7, there is a new method on UIImage
to specify the rendering mode. Using the rendering mode UIImageRenderingModeAlwaysTemplate
will allow the image color to be controlled by the button's tint color.
Objective-C
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *image = [[UIImage imageNamed:@"image_name"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[button setImage:image forState:UIControlStateNormal];
button.tintColor = [UIColor redColor];
Swift
let button = UIButton(type: .custom)
let image = UIImage(named: "image_name")?.withRenderingMode(.alwaysTemplate)
button.setImage(image, for: .normal)
button.tintColor = UIColor.red
Just apply width:100%; to body
I use the following command to load a project quickly (in linux)
cd /project
code pwd
similar steps can be used in other Os too.
Please check my working code.
function sendMail()
{
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => '[email protected]', // change it to yours
'smtp_pass' => 'xxx', // change it to yours
'mailtype' => 'html',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
$message = '';
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('[email protected]'); // change it to yours
$this->email->to('[email protected]');// change it to yours
$this->email->subject('Resume from JobsBuddy for your Job posting');
$this->email->message($message);
if($this->email->send())
{
echo 'Email sent.';
}
else
{
show_error($this->email->print_debugger());
}
}
as far as i can remember, you need to use a HTTP CONNECT query on the proxy. this will convert the request connection to a transparent TCP/IP tunnel.
so you need to know if the proxy server you use support this protocol.
One more example of usage sorted() function with key=lambda. Let's consider you have a list of tuples. In each tuple you have a brand, model and weight of the car and you want to sort this list of tuples by brand, model or weight. You can do it with lambda.
cars = [('citroen', 'xsara', 1100), ('lincoln', 'navigator', 2000), ('bmw', 'x5', 1700)]
print(sorted(cars, key=lambda car: car[0]))
print(sorted(cars, key=lambda car: car[1]))
print(sorted(cars, key=lambda car: car[2]))
Results:
[('bmw', 'x5', '1700'), ('citroen', 'xsara', 1100), ('lincoln', 'navigator', 2000)]
[('lincoln', 'navigator', 2000), ('bmw', 'x5', '1700'), ('citroen', 'xsara', 1100)]
[('citroen', 'xsara', 1100), ('bmw', 'x5', 1700), ('lincoln', 'navigator', 2000)]
You'll have to configure the server to interpret .html
files as .php
files. This configuration is different depending on the server software. This will also add an extra step to the server and will slow down response on all your pages and is probably not ideal.
Use PHP Document Object Model:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
$DOM = new DOMDocument;
$DOM->loadHTML($str);
//get all H1
$items = $DOM->getElementsByTagName('h1');
//display all H1 text
for ($i = 0; $i < $items->length; $i++)
echo $items->item($i)->nodeValue . "<br/>";
?>
This outputs as:
T1
T2
T3
[EDIT]: After OP Clarification:
If you want the content like Lorem ipsum. etc, you can directly use this regex:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>
this outputs:
Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG
i like using the glob package:
const glob = require('glob');
glob(__dirname + '/**/*.html', {}, (err, files)=>{
console.log(files)
})
There might be a better way but here is what I have done in the past and it works quite well:
items = data.items() #Gets all the data from this Bunch - a huge list
mydata = pd.DataFrame(items[1][1]) #Gets the Attributes
mydata[len(mydata.columns)] = items[2][1] #Adds a column for the Target Variable
mydata.columns = items[-1][1] + [items[2][0]] #Gets the column names and updates the dataframe
Now mydata will have everything you need - attributes, target variable and columnnames
instead of
$('html, body').animate({scrollTop:xxx}, 'slow');
use
$('html, body').animate({scrollTop:$('#div_id').position().top}, 'slow');
this will return the absolute top position of whatever element you select as #div_id
You need to do it like this:
HttpContent httpContent = new StringContent(@"{ the json string }");
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage message = client.PostAsync(@"{url}", httpContent).Result;
Here is my code. It'll open given url in default browser (cross platform solution).
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class Browser {
public static void main(String[] args) {
String url = "http://www.google.com";
if(Desktop.isDesktopSupported()){
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(new URI(url));
} catch (IOException | URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("xdg-open " + url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Simple :::
scp remoteusername@remoteIP:/path/of/file /Local/path/to/copy
scp -r remoteusername@remoteIP:/path/of/folder /Local/path/to/copy
Modify was greyed out for me, but adding the IIS Management Console under programs and features fixed this for me. Also on Windows 10 fall update.
ArgumentException is thrown when a method is invoked and at least one of the passed arguments does not meet the parameter specification of the called method. All instances of ArgumentException should carry a meaningful error message describing the invalid argument, as well as the expected range of values for the argument.
A few subclasses also exist for specific types of invalidity. The link has summaries of the subtypes and when they should apply.
NOT a solution, rather a TEMPORARY solution which only works only for the current editor and current session:
Simply right click on the place where the line-numbers should be, and there you'll see a small menu.
then, mark the "Show Line Numbers" option.
Please note that this only works on a per-file basis, however. Enjoy.
foreach ($parsed as $key=> $poke)
{
$insert = mysql_query("insert into soal
(pertanyaan, a, b, c, d, e, jawaban)
values
('$poke[question]',
'$poke[options][A]',
'$poke[options][B]',
'$poke[options][C]',
'$poke[options][D]',
'$poke[options][E]',
'$poke[answer]')");
}
Due to this article is a good SEO site, so I suggest to use build-in function "mb_convert_variables" to solve this problem. It works with simple syntax.
mb_convert_variables('utf-8', 'original encode', array/object)
For people who are using CentOS7, In order to allow access to port 8000, you need to modify firewall rules in a new SSH connection:
sudo firewall-cmd --zone=public --permanent --add-port=8000/tcp
sudo firewall-cmd --reload
You can simply use matches
method of String class.
boolean result = someString.matches("stores.*store.*product.*");
What is the potential damage if it was possible to invoke
wait()
outside a synchronized block, retaining it's semantics - suspending the caller thread?
Let's illustrate what issues we would run into if wait()
could be called outside of a synchronized block with a concrete example.
Suppose we were to implement a blocking queue (I know, there is already one in the API :)
A first attempt (without synchronization) could look something along the lines below
class BlockingQueue {
Queue<String> buffer = new LinkedList<String>();
public void give(String data) {
buffer.add(data);
notify(); // Since someone may be waiting in take!
}
public String take() throws InterruptedException {
while (buffer.isEmpty()) // don't use "if" due to spurious wakeups.
wait();
return buffer.remove();
}
}
This is what could potentially happen:
A consumer thread calls take()
and sees that the buffer.isEmpty()
.
Before the consumer thread goes on to call wait()
, a producer thread comes along and invokes a full give()
, that is, buffer.add(data); notify();
The consumer thread will now call wait()
(and miss the notify()
that was just called).
If unlucky, the producer thread won't produce more give()
as a result of the fact that the consumer thread never wakes up, and we have a dead-lock.
Once you understand the issue, the solution is obvious: Use synchronized
to make sure notify
is never called between isEmpty
and wait
.
Without going into details: This synchronization issue is universal. As Michael Borgwardt points out, wait/notify is all about communication between threads, so you'll always end up with a race condition similar to the one described above. This is why the "only wait inside synchronized" rule is enforced.
A paragraph from the link posted by @Willie summarizes it quite well:
You need an absolute guarantee that the waiter and the notifier agree about the state of the predicate. The waiter checks the state of the predicate at some point slightly BEFORE it goes to sleep, but it depends for correctness on the predicate being true WHEN it goes to sleep. There's a period of vulnerability between those two events, which can break the program.
The predicate that the producer and consumer need to agree upon is in the above example buffer.isEmpty()
. And the agreement is resolved by ensuring that the wait and notify are performed in synchronized
blocks.
This post has been rewritten as an article here: Java: Why wait must be called in a synchronized block
Here is an example using css3:
CSS:
html, body {
height: 100%;
margin: 0;
}
#wrap {
padding: 10px;
min-height: -webkit-calc(100% - 100px); /* Chrome */
min-height: -moz-calc(100% - 100px); /* Firefox */
min-height: calc(100% - 100px); /* native */
}
.footer {
position: relative;
clear:both;
}
HTML:
<div id="wrap">
body content....
</div>
<footer class="footer">
footer content....
</footer>
Update
As @Martin pointed, the ´position: relative´ is not mandatory on the .footer
element, the same for clear:both
. These properties are only there as an example. So, the minimum css necessary to stick the footer on the bottom should be:
html, body {
height: 100%;
margin: 0;
}
#wrap {
min-height: -webkit-calc(100% - 100px); /* Chrome */
min-height: -moz-calc(100% - 100px); /* Firefox */
min-height: calc(100% - 100px); /* native */
}
Also, there is an excellent article at css-tricks showing different ways to do this: https://css-tricks.com/couple-takes-sticky-footer/
There is a PHP native function for that:
$url = 'http://www.yoururl.co.uk/sub1/sub2/?param=1¶m2/';
if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) {
// Wrong
}
else {
// Valid
}
Returns the filtered data, or FALSE if the filter fails.
We just released preview driver for Node.JS for SQL Server connectivity. You can find it here: Introducing the Microsoft Driver for Node.JS for SQL Server.
The driver supports callbacks (here, we're connecting to a local SQL Server instance):
// Query with explicit connection
var sql = require('node-sqlserver');
var conn_str = "Driver={SQL Server Native Client 11.0};Server=(local);Database=AdventureWorks2012;Trusted_Connection={Yes}";
sql.open(conn_str, function (err, conn) {
if (err) {
console.log("Error opening the connection!");
return;
}
conn.queryRaw("SELECT TOP 10 FirstName, LastName FROM Person.Person", function (err, results) {
if (err) {
console.log("Error running query!");
return;
}
for (var i = 0; i < results.rows.length; i++) {
console.log("FirstName: " + results.rows[i][0] + " LastName: " + results.rows[i][1]);
}
});
});
Alternatively, you can use events (here, we're connecting to SQL Azure a.k.a Windows Azure SQL Database):
// Query with streaming
var sql = require('node-sqlserver');
var conn_str = "Driver={SQL Server Native Client 11.0};Server={tcp:servername.database.windows.net,1433};UID={username};PWD={Password1};Encrypt={Yes};Database={databasename}";
var stmt = sql.query(conn_str, "SELECT FirstName, LastName FROM Person.Person ORDER BY LastName OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY");
stmt.on('meta', function (meta) { console.log("We've received the metadata"); });
stmt.on('row', function (idx) { console.log("We've started receiving a row"); });
stmt.on('column', function (idx, data, more) { console.log(idx + ":" + data);});
stmt.on('done', function () { console.log("All done!"); });
stmt.on('error', function (err) { console.log("We had an error :-( " + err); });
If you run into any problems, please file an issue on Github: https://github.com/windowsazure/node-sqlserver/issues
I faced the same issue, and I found out the problem was the location of my images.
Instead of saving them into the src
folder, you should store them in the public
directory and have direct access.
Kudos.
You can try 'onbeforeunload
' event.
Also take a look at this-
For showing keyboard use:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
For hiding keyboard use:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(),0);
please, be sure your connected to a ubuntu server, I Had the same problem but I was connected to other distro, check the AMI value in your details instance, it should be something like
AMI: ubuntu/images/ebs/ubuntu-precise-12.04-amd64-server-20130411.1
hope it helps
You can do it ... it may get a bit ugly and you'll be faced with some trial and error in terms of mapping types .. but heres the basic gist of it:
func FillStruct(data map[string]interface{}, result interface{}) {
t := reflect.ValueOf(result).Elem()
for k, v := range data {
val := t.FieldByName(k)
val.Set(reflect.ValueOf(v))
}
}
Working sample: http://play.golang.org/p/PYHz63sbvL
First things first. C, i.e. ISO/IEC 9899 has had a boolean type for 19 years now. That is way longer time than the expected length of the C programming career with amateur/academic/professional parts combined when visiting this question. Mine does surpass that by mere perhaps 1-2 years. It means that during the time that an average reader has learnt anything at all about C, C actually has had the boolean data type.
For the datatype, #include <stdbool.h>
, and use true
, false
and bool
. Or do not include it, and use _Bool
, 1
and 0
instead.
There are various dangerous practices promoted in the other answers to this thread. I will address them:
typedef int bool;
#define true 1
#define false 0
This is no-no, because a casual reader - who did learn C within those 19 years - would expect that bool
refers to the actual bool
data type and would behave similarly, but it doesn't! For example
double a = ...;
bool b = a;
With C99 bool
/ _Bool
, b
would be set to false
iff a
was zero, and true
otherwise. C11 6.3.1.2p1
- When any scalar value is converted to
_Bool
, the result is 0 if the value compares equal to 0; otherwise, the result is 1. 59)Footnotes
59) NaNs do not compare equal to 0 and thus convert to 1.
With the typedef
in place, the double
would be coerced to an int
- if the value of the double isn't in the range for int
, the behaviour is undefined.
Naturally the same applies to if true
and false
were declared in an enum
.
What is even more dangerous is declaring
typedef enum bool {
false, true
} bool;
because now all values besides 1 and 0 are invalid, and should such a value be assigned to a variable of that type, the behaviour would be wholly undefined.
Therefore iff you cannot use C99 for some inexplicable reason, for boolean variables you should use:
int
and values 0
and 1
as-is; and carefully do domain conversions from any other values to these with double negation !!
BOOL
, TRUE
and FALSE
!If you want the text to wrap nicely:-
.outer {_x000D_
display: table;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
height: 200px;_x000D_
display: table-cell;_x000D_
vertical-align: bottom;_x000D_
}_x000D_
_x000D_
/* Just for styling */_x000D_
.inner {_x000D_
background: #eee;_x000D_
padding: 0 20px;_x000D_
}
_x000D_
<!-- Need two parent elements -->_x000D_
<div class="outer">_x000D_
<div class="inner">_x000D_
<h3>Sample Heading</h3>_x000D_
<p>Sample Paragragh</p>_x000D_
</div>_x000D_
</div>
_x000D_
I find that I run into Net::HTTP and Net::FTP problems like this periodically, and when I do, surrounding the call with a timeout() makes all of those issues vanish. So where this will occasionally hang for 3 minutes or so and then raise an EOFError:
res = Net::HTTP.post_form(uri, args)
This always fixes it for me:
res = timeout(120) { Net::HTTP.post_form(uri, args) }
All the answers are good. The java8+ have these patterns for parsing and formatting timezone: V
, z
, O
, X
, x
, Z
.
Here's they are, for parsing, according to rules from the documentation :
Symbol Meaning Presentation Examples
------ ------- ------------ -------
V time-zone ID zone-id America/Los_Angeles; Z; -08:30
z time-zone name zone-name Pacific Standard Time; PST
O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00;
X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15;
x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;
Z zone-offset offset-Z +0000; -0800; -08:00;
But how about formatting?
Here's a sample for a date (assuming ZonedDateTime
) that show these patters behavior for different formatting patters:
// The helper function:
static void printInPattern(ZonedDateTime dt, String pattern) {
System.out.println(pattern + ": " + dt.format(DateTimeFormatter.ofPattern(pattern)));
}
// The date:
String strDate = "2020-11-03 16:40:44 America/Los_Angeles";
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss zzzz");
ZonedDateTime dt = ZonedDateTime.parse(strDate, format);
// 2020-11-03T16:40:44-08:00[America/Los_Angeles]
// Rules:
// printInPattern(dt, "V"); // exception!
printInPattern(dt, "VV"); // America/Los_Angeles
// printInPattern(dt, "VVV"); // exception!
// printInPattern(dt, "VVVV"); // exception!
printInPattern(dt, "z"); // PST
printInPattern(dt, "zz"); // PST
printInPattern(dt, "zzz"); // PST
printInPattern(dt, "zzzz"); // Pacific Standard Time
printInPattern(dt, "O"); // GMT-8
// printInPattern(dt, "OO"); // exception!
// printInPattern(dt, "OO0"); // exception!
printInPattern(dt, "OOOO"); // GMT-08:00
printInPattern(dt, "X"); // -08
printInPattern(dt, "XX"); // -0800
printInPattern(dt, "XXX"); // -08:00
printInPattern(dt, "XXXX"); // -0800
printInPattern(dt, "XXXXX"); // -08:00
printInPattern(dt, "x"); // -08
printInPattern(dt, "xx"); // -0800
printInPattern(dt, "xxx"); // -08:00
printInPattern(dt, "xxxx"); // -0800
printInPattern(dt, "xxxxx"); // -08:00
printInPattern(dt, "Z"); // -0800
printInPattern(dt, "ZZ"); // -0800
printInPattern(dt, "ZZZ"); // -0800
printInPattern(dt, "ZZZZ"); // GMT-08:00
printInPattern(dt, "ZZZZZ"); // -08:00
In the case of positive offset the +
sign character is used everywhere(where there is -
now) and never omitted.
This well works for new java.time
types. If you're about to use these for java.util.Date
or java.util.Calendar
- not all going to work as those types are broken(and so marked as deprecated, please don't use them)
location.reload();
See this MDN page for more information.
If you are refreshing after an onclick
then you'll need to return false directly after
location.reload();
return false;
For those out there who still couldn't fix this, I did so by changing my 'this' to '$(this)' when using jQuery.
E.G:
$('.icon').click(function() {
this.fadeOut();
});
Fixed:
$('.icon').click(function() {
$(this).fadeOut();
});
Use Arrays.equals()
if you want to compare the actual content of arrays that contain primitive types values (like byte).
System.out.println(Arrays.equals(aa, bb));
Use Arrays.deepEquals
for comparison of arrays that contain objects.
MYISAM:
INNODB:
Yes there is a problem with Click event handler (klik) - First argument must be an object type and second must be EventArgs.
public void klik(object sender, EventArgs e) {
//
}
If you want to paint on a form or control then use CreateGraphics
method.
public void klik(object sender, EventArgs e) {
Bitmap c = this.DrawMandel();
Graphics gr = CreateGraphics(); // Graphics gr=(sender as Button).CreateGraphics();
gr.DrawImage(b, 150, 200);
}
You can use super.dispose() method which is more similar to close operation.
In case that you need to add the http redirect in many sites, you could use it as a c# console program:
class Program
{
static int Main(string[] args)
{
if (args.Length < 3)
{
Console.WriteLine("Please enter an argument: for example insert-redirect ./web.config http://stackoverflow.com");
return 1;
}
if (args.Length == 3)
{
if (args[0].ToLower() == "-insert-redirect")
{
var path = args[1];
var value = args[2];
if (InsertRedirect(path, value))
Console.WriteLine("Redirect added.");
return 0;
}
}
Console.WriteLine("Wrong parameters.");
return 1;
}
static bool InsertRedirect(string path, string value)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(path);
// This should find the appSettings node (should be only one):
XmlNode nodeAppSettings = doc.SelectSingleNode("//system.webServer");
var existNode = nodeAppSettings.SelectSingleNode("httpRedirect");
if (existNode != null)
return false;
// Create new <add> node
XmlNode nodeNewKey = doc.CreateElement("httpRedirect");
XmlAttribute attributeEnable = doc.CreateAttribute("enabled");
XmlAttribute attributeDestination = doc.CreateAttribute("destination");
//XmlAttribute attributeResponseStatus = doc.CreateAttribute("httpResponseStatus");
// Assign values to both - the key and the value attributes:
attributeEnable.Value = "true";
attributeDestination.Value = value;
//attributeResponseStatus.Value = "Permanent";
// Add both attributes to the newly created node:
nodeNewKey.Attributes.Append(attributeEnable);
nodeNewKey.Attributes.Append(attributeDestination);
//nodeNewKey.Attributes.Append(attributeResponseStatus);
// Add the node under the
nodeAppSettings.AppendChild(nodeNewKey);
doc.Save(path);
return true;
}
catch (Exception e)
{
Console.WriteLine($"Exception adding redirect: {e.Message}");
return false;
}
}
}
Please check this out if it helps you
df<-read.csv("F:/test.csv",header=FALSE,nrows=1) df V1 V2 V3 V4 V5 1 ID GRADES GPA Teacher State a<-c(df) a[1] $V1 [1] ID Levels: ID
a[2] $V2 [1] GRADES Levels: GRADES
a[3] $V3 [1] GPA Levels: GPA
a[4] $V4 [1] Teacher Levels: Teacher
a[5] $V5 [1] State Levels: State
As the accepted answer requires you to add a Frame Layout, here how you can do it with material design.
Add this if you haven't already
implementation 'com.google.android.material:material:1.0.0'
Now change to Cardview to MaterialCardView
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:cardCornerRadius="8dp"
app:cardElevation="2dp"
app:strokeWidth="1dp"
app:strokeColor="@color/black">
Now you need to change the activity theme to Theme.Material. If you are using Theme.Appcompact I will suggest you to move to Theme.Material for future projects for having better material design in you app.
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
Flask will process one request per thread at the same time. If you have 2 processes with 4 threads each, that's 8 concurrent requests.
Flask doesn't spawn or manage threads or processes. That's the responsability of the WSGI gateway (eg. gunicorn).
Some of more advanced Oracle database features such as session trace do not work properly in Oracle 11g XE 32-bit if installed on Windows 64-bit system. I needed session trace on Windows 7 64-bit.
Apart from that it works well for me in multiple production MS Windows 64-bit systems: Windows Server 2008 R2 and Windows Server 2003 R2.
What do you think about that:
int iceu_system_GetTimeNow(long long int *res)
{
static struct timespec buffer;
//
#ifdef __CYGWIN__
if (clock_gettime(CLOCK_REALTIME, &buffer))
return 1;
#else
if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &buffer))
return 1;
#endif
*res=(long long int)buffer.tv_sec * 1000000000LL + (long long int)buffer.tv_nsec;
return 0;
}
download
attributeJust to allow user to download the image or other file you may use the HTML5 download
attribute.
Static file download
<a href="/images/image-name.jpg" download>
<!-- OR -->
<a href="/images/image-name.jpg" download="new-image-name.jpg">
Dynamic file download
In cases requesting image dynamically it is possible to emulate such download.
If your image is already loaded and you have the base64
source then:
function saveBase64AsFile(base64, fileName) {
var link = document.createElement("a");
document.body.appendChild(link); // for Firefox
link.setAttribute("href", base64);
link.setAttribute("download", fileName);
link.click();
}
Otherwise if image file is downloaded as Blob
you can use FileReader
to convert it to Base64:
function saveBlobAsFile(blob, fileName) {
var reader = new FileReader();
reader.onloadend = function () {
var base64 = reader.result ;
var link = document.createElement("a");
document.body.appendChild(link); // for Firefox
link.setAttribute("href", base64);
link.setAttribute("download", fileName);
link.click();
};
reader.readAsDataURL(blob);
}
Firefox
The anchor tag you are creating also needs to be added to the DOM in Firefox, in order to be recognized for click events (Link).
IE is not supported: Caniuse link
DirectCast(dt.Rows(0),DataRow).RowError
This directly gives the error
Another option would be to simply copy & drop the column:
df = pd.DataFrame(d)
df['new_name'] = df['two']
df = df.drop('two', axis=1)
df.head()
After that you get the result:
one three new_name
0 1 a 9
1 2 b 8
2 3 c 7
3 4 d 6
4 5 e 5
You can check it easily using Java.lang.Class.getSimpleName()
Method Only if variable has non-primitive type. It doesnt work with primitive types int ,long etc.
reference - Here is the Oracle docs link
strtok
doesn't change the parameter itself (str
). It stores that pointer (in a local static variable). It can then change what that parameter points to in subsequent calls without having the parameter passed back. (And it can advance that pointer it has kept however it needs to perform its operations.)
From the POSIX strtok
page:
This function uses static storage to keep track of the current string position between calls.
There is a thread-safe variant (strtok_r
) that doesn't do this type of magic.
Since the google policies update, you need to enable billing to access Map API.
Very old question but here's the solution. Here you have a working snippet using jquery
. It makes use of a temporary auxiliary select
into which the selected option from the main select is copied, such that one can assess the true width which the main select
should have.
$('select').change(function(){_x000D_
var text = $(this).find('option:selected').text()_x000D_
var $aux = $('<select/>').append($('<option/>').text(text))_x000D_
$(this).after($aux)_x000D_
$(this).width($aux.width())_x000D_
$aux.remove()_x000D_
}).change()
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<select>_x000D_
<option>ABC</option>_x000D_
<option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option>_x000D_
</select>
_x000D_
this works for me:
It can be used inside the dialog, but the dialog can´t be inside any componet such as panels, accordion, etc.
I would like to add my trials and my solution following rob3c's answer.
PS: My solution only concerns Windows users.
I tried the following settings without success:
// settings.json
"python.linting.pylintPath": ${workspaceFolder}\\_tools\\python3\\Scripts\\pylint
and
"python.linting.pylintPath": ${workspaceFolder}\\_tools\\python3\\Scripts\\pylint.exe
I always had the following error message:
Linter 'pylint' is not installed. Please install it or select another linter".
Error: spawn c:\WS\myproject\_tools\python3\Scripts\pylint ENOENT
Even with a pylint
file in my folder:
dir c:\WS\myproject\_tools\python3\Scripts\
...
05.07.2017 09:34 AM 52 pylint # ! no pylint.exe !
...
As my toolchain is based on MSYS, the Pylint installed is without pylint.exe.
The content of _tools\python3\Scripts\pylint
file:
#!python
from pylint import run_pylint
run_pylint()
My workaround was to create a batch file .vscode\pylint.bat with the following contents:
%PYTHON3_EXE% _prefix\python3\Scripts\pylint %*
(%PYTHON3_EXE% is an environment variable to the Python 3 interpreter C:\Python34\python.exe
)
And to configure .vscode\settings.json as follows:
// settings.json
"python.linting.pylintPath": "${workspaceFolder}\\.vscode\\pylint.bat",
Log from OUTPUT
--> Python
:
##########Linting Output - pylint##########
c:\WS\myproject> C:\Python34\python.exe _tools\python3\Scripts\pylint
--rcfile c:\WS\framework\pylintrc
--msg-template='{line},{column},{category},{msg_id}:{msg}'
--reports=n
--output-format=text
c:\WS\myproject\myScriptToLint.py
Using config file c:\WS\myproject\pylintrc
------------------------------------
Your code has been rated at 10.00/10
? Visual Studio Code uses the Pylint version from my toolchain!
You can make a json object like:
globalVariable={example_attribute:"SomeValue"};
in fileA.js
And access it from fileB.js like:
globalVariable.example_attribute
We can achieve this using Pattern and Matcher as follows:
Pattern pattern = Pattern.compile("[^A-Za-z0-9 ]");
Matcher matcher = pattern.matcher(trString);
boolean hasSpecialChars = matcher.find();
Swift 2 answer :
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Hour, .Minute], fromDate: date)
let hour = components.hour
let minutes = components.minute
In XML:
android:divider="@null"
Or in Java:
listView.setDivider(null);
There's a nice workaround for this in the sitepoint forums:
<div onclick="this.nextElementSibling.style.display='block'; this.style.display='none'">
<img src="my_thumbnail.png" style="cursor:pointer" />
</div>
<div style="display:none">
<!-- Embed code here -->
</div>
Note: To prevent having to click twice to make the video play, use autoplay=1
in the video embed code. It will start playing when the second div is displayed.
You might want to use grep "$(echo -e '\t')"
Only requirement is echo
to be capable of interpretation of backslash escapes.
I think you might not have the Android-18 sdk installed. Go to Tools > Android > SDK Manager and check to see if Android 4.3 (API 18) is installed.
For Kotlin Here is added the lambda expression and Optimized the Code.
radioGroup.setOnCheckedChangeListener { radioGroup, optionId ->
run {
when (optionId) {
R.id.radioButton1 -> {
// do something when radio button 1 is selected
}
R.id.radioButton2 -> {
// do something when radio button 2 is selected
}
// add more cases here to handle other buttons in the your RadioGroup
}
}
}
Hope this will help you. Thanks!
Simple way to initiate the message on startup:
bot.on('ready', () => {
bot.user.setStatus('available')
bot.user.setPresence({
game: {
name: 'with depression',
type: "STREAMING",
url: "https://www.twitch.tv/monstercat"
}
});
});
You can also just declare it elsewhere after startup, to change the message as needed:
bot.user.setPresence({ game: { name: 'with depression', type: "streaming", url: "https://www.twitch.tv/monstercat"}});
you can't get the expiration date of a cookie through javascript because when you try to read the cookie from javascript the document.cookie return just the name and the value of the cookie as pairs
process.hrtime() not give current ts.
This should work.
const loadNs = process.hrtime(),
loadMs = new Date().getTime(),
diffNs = process.hrtime(loadNs),
microSeconds = (loadMs * 1e6) + (diffNs[0] * 1e9) + diffNs[1]
console.log(microSeconds / 1e3)