$haystack = array (
'say hello',
'hello stackoverflow',
'hello world',
'foo bar bas'
);
$matches = preg_grep('/hello/i', $haystack);
print_r($matches);
Output
Array
(
[1] => say hello
[2] => hello stackoverflow
[3] => hello world
)
Why to use regex? PHP has some built in functionality to do that
<?php
$valid_symbols = array('-', '_');
$string1 = "This is a string*";
$string2 = "this_is-a-string";
if(preg_match('/\s/',$string1) || !ctype_alnum(str_replace($valid_symbols, '', $string1))) {
echo "String 1 not acceptable acceptable";
}
?>
preg_match('/\s/',$username)
will check for blank space
!ctype_alnum(str_replace($valid_symbols, '', $string1))
will check for valid_symbols
Not exactly the same.
From the PHP docs of is_numeric:
'42' is numeric
'1337' is numeric
'1e4' is numeric
'not numeric' is NOT numeric
'Array' is NOT numeric
'9.1' is numeric
With your regex you only check for 'basic' numeric values.
Also is_numeric()
should be faster.
You can also use T-Regx library which has automatic delimiters for you:
$matches = pattern("My name is '(.*)' and im fine")->match($string1)->all();
// ? No delimiters needed
You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:
([0-9]+)\s+((\bseconds\b)|(\bminutes\b))
Without those you were either matching a number followed by seconds OR just the word minutes
Your regex pattern needs to be in delimiters:
$numpattern="/^([0-9]+)$/";
(^|\s)
would match space or start of string and ($|\s)
for space or end of string. Together it's:
(^|\s)stackoverflow($|\s)
You left off the /
(pattern delimiter) and $
(match end string).
preg_match("/^[a-zA-Z0-9]+$/", $value)
// app.js
let db = ...; // your db object initialized
const contextMiddleware = (req, res, next) => {
req.db=db;
next();
};
app.use(contextMiddleware);
// routes.js It's just a mapping.
exports.routes = [
['/', controllers.index],
['/posts', controllers.posts.index],
['/posts/:post', controllers.posts.show]
];
// app.js
var { routes } = require('./routes');
routes.forEach(route => app.get(...route));
// You can customize this according to your own needs, like adding post request
The final app.js:
// app.js
var express = require('express');
var app = express.createServer();
let db = ...; // your db object initialized
const contextMiddleware = (req, res, next) => {
req.db=db;
next();
};
app.use(contextMiddleware);
var { routes } = require('./routes');
routes.forEach(route => app.get(...route));
app.listen(3000, function() {
console.log('Application is listening on port 3000');
});
Another version: you can customize this according to your own needs, like adding post request
// routes.js It's just a mapping.
let get = ({path, callback}) => ({app})=>{
app.get(path, callback);
}
let post = ({path, callback}) => ({app})=>{
app.post(path, callback);
}
let someFn = ({path, callback}) => ({app})=>{
// ...custom logic
app.get(path, callback);
}
exports.routes = [
get({path: '/', callback: controllers.index}),
post({path: '/posts', callback: controllers.posts.index}),
someFn({path: '/posts/:post', callback: controllers.posts.show}),
];
// app.js
var { routes } = require('./routes');
routes.forEach(route => route({app}));
The body hasn't been defined at this point yet. In general, you want to create all elements before you execute javascript that uses these elements. In this case you have some javascript in the head
section that uses body
. Not cool.
You want to wrap this code in a window.onload
handler or place it after the <body>
tag (as mentioned by e-bacho 2.0).
<head>
<title>Javascript Tests</title>
<script type="text/javascript">
window.onload = function() {
var mySpan = document.createElement("span");
mySpan.innerHTML = "This is my span!";
mySpan.style.color = "red";
document.body.appendChild(mySpan);
alert("Why does the span change after this alert? Not before?");
}
</script>
</head>
To check for the existence of a directory using Dir
, you need to specify vbDirectory
as the second argument, as in something like:
If Dir("C:\2013 Recieved Schedules" & "\" & client, vbDirectory) = "" Then
Note that, with vbDirectory
, Dir
will return a non-empty string if the specified path already exists as a directory or as a file (provided the file doesn't have any of the read-only, hidden, or system attributes). You could use GetAttr
to be certain it's a directory and not a file.
putting "\r" at the end of each row actually had the effect of line breaks in excel, but in the .csv it vanished and left an ugly mess where each row was squashed against the next with no space and no line-breaks
I would like to add required attribute in case user disabled javascript:
<input type="text" id="textbox" required/>
It works on all modern browsers.
Place the following in your jQuery mouseover
event handler:
$(this).css('color', 'red');
To set both color and size at the same time:
$(this).css({ 'color': 'red', 'font-size': '150%' });
You can set any CSS attribute using the .css()
jQuery function.
Say you have 512 RAM + 1GB Swap memory. So in theory, your CPU has access to total of 1.5GB of virtual memory.
Now, for some time everything is running fine within 1.5GB of total memory. But all of sudden (or gradually) your system has started consuming more and more memory and it reached at a point around 95% of total memory used.
Now say any process has requested large chunck of memory from the kernel. Kernel check for the available memory and find that there is no way it can allocate your process more memory. So it will try to free some memory calling/invoking OOMKiller (http://linux-mm.org/OOM).
OOMKiller has its own algorithm to score the rank for every process. Typically which process uses more memory becomes the victim to be killed.
Typically in /var/log directory. Either /var/log/kern.log or /var/log/dmesg
Hope this will help you.
Assume that you have a tr row with multiple checkboxes in it, and you want to count only if the first checkbox is checked.
You can do that by giving a class to the first checkbox
For example class='mycxk'
and you can count that using the filter, like this
$('.mycxk').filter(':checked').length
var objResponse1 =
JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
worked!
$(document).on('change', '.custom-file-input', function (event) {
$(this).next('.custom-file-label').html(event.target.files[0].name);
})
Best of all worlds. Works on dynamically created inputs, and uses actual file name.
x = [];
for( var i in myObj ) {
x[i] = myObj[i];
}
If you don't want to make the button a separate image, you can use the <area>
tag. This is done by using html similar to this:
<img src="imgsrc" width="imgwidth" height="imgheight" alt="alttext" usemap="#mapname">
<map name="mapname">
<area shape="rect" coords="see note 1" href="link" alt="alttext">
</map>
Note 1: The coords=" "
attribute must be formatted in this way: coords="x1,y1,x2,y2"
where:
x1=top left X coordinate
y1=top left Y coordinate
x2=bottom right X coordinate
y2=bottom right Y coordinate
Note 2: The usemap="#mapname"
attribute must include the #
.
EDIT:
I looked at your code and added in the <map>
and <area>
tags where they should be. I also commented out some parts that were either overlapping the image or seemed there for no use.
<div class="flexslider">
<ul class="slides" runat="server" id="Ul">
<li class="flex-active-slide" style="background: url("images/slider-bg-1.jpg") no-repeat scroll 50% 0px transparent; width: 100%; float: left; margin-right: -100%; position: relative; display: list-item;">
<div class="container">
<div class="sixteen columns contain"></div>
<img runat="server" id="imgSlide1" style="top: 1px; right: -19px; opacity: 1;" class="item" src="./test.png" data-topimage="7%" height="358" width="728" usemap="#imgmap" />
<map name="imgmap">
<area shape="rect" coords="48,341,294,275" href="http://www.example.com/">
</map>
<!--<a href="#" style="display:block; background:#00F; width:356px; height:66px; position:absolute; left:1px; top:-19px; left: 162px; top: 279px;"></a>-->
</div>
</li>
</ul>
</div>
<!-- <ul class="flex-direction-nav">
<li><a class="flex-prev" href="#"><i class="icon-angle-left"></i></a></li>
<li><a class="flex-next" href="#"><i class="icon-angle-right"></i></a></li>
</ul> -->
Notes:
coord="48,341,294,275"
is in reference to your screenshot you posted.src="./test.png"
is the location and name of the screenshot you posted on my computer.href="http://www.example.com/"
is an example link.<div :style="{ backgroundImage: `url(${post.image})` }">
there are multiple ways but i found template string easy and simple
It took me a hell of a long time to really get a handle on this. The key to me was in understanding that "@" is for stuff that you want evaluated in situ and passed through into the directive as a constant where "=" actually passes the object itself.
There's a nice blog post that explains this this at: http://blog.ramses.io/technical/AngularJS-the-difference-between-@-&-and-=-when-declaring-directives-using-isolate-scopes
From php docs:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.
Yes, the value can be NULL, but you must be explicit. I have experienced this same situation before, and it's easy to forget WHY this happens, and so it takes a little bit to remember what needs to be done.
If the data submitted is cast or interpreted as an empty string, it will fail. However, by explicitly setting the value to NULL when INSERTING or UPDATING, you're good to go.
But this is the fun of programming, isn't it? Creating our own problems and then fixing them! Cheers!
you can return a FileResult from your MVC action.
*********************MVC action************
public FileResult OpenPDF(parameters)
{
//code to fetch your pdf byte array
return File(pdfBytes, "application/pdf");
}
**************js**************
Use formpost to post your data to action
var inputTag = '<input name="paramName" type="text" value="' + payloadString + '">';
var form = document.createElement("form");
jQuery(form).attr("id", "pdf-form").attr("name", "pdf-form").attr("class", "pdf-form").attr("target", "_blank");
jQuery(form).attr("action", "/Controller/OpenPDF").attr("method", "post").attr("enctype", "multipart/form-data");
jQuery(form).append(inputTag);
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
return false;
You need to create a form to post your data, append it your dom, post your data and remove the form your document body.
However, form post wouldn't post data to new tab only on EDGE browser. But a get request works as it's just opening new tab with a url containing query string for your action parameters.
You simply type vim
into the terminal to open it and start a new file.
You can pass a filename as an option and it will open that file, e.g. vim main.c
. You can open multiple files by passing multiple file arguments.
Vim has different modes, unlike most editors you have probably used. You begin in NORMAL
mode, which is where you will spend most of your time once you become familiar with vim.
To return to NORMAL
mode after changing to a different mode, press Esc. It's a good idea to map your Caps Lock key to Esc, as it's closer and nobody really uses the Caps Lock key.
The first mode to try is INSERT
mode, which is entered with a for append after cursor, or i for insert before cursor.
To enter VISUAL
mode, where you can select text, use v. There are many other variants of this mode, which you will discover as you learn more about vim.
To save your file, ensure you're in NORMAL
mode and then enter the command :w
. When you press :
, you will see your command appear in the bottom status bar. To save and exit, use :x
. To quit without saving, use :q
. If you had made a change you wanted to discard, use :q!
.
You can edit your ~/.vimrc
file to configure vim to your liking. It's best to look at a few first (here's mine) and then decide which options suits your style.
This is how mine looks:
To get the file explorer on the left, use NERDTree. For the status bar, use vim-airline. Finally, the color scheme is solarized.
You can use man vim
for some help inside the terminal. Alternatively, run vimtutor
which is a good hands-on starting point.
It's a good idea to print out a Vim Cheatsheet and keep it in front of you while you're learning vim.
Good luck!
try this:
<div style='overflow:auto; width:400px;height:400px;'>here is some text</div>
The SQL Server Maximums are disclosed http://msdn.microsoft.com/en-us/library/ms143432.aspx (this is the 2008 version)
A SQL Query can be a varchar(max) but is shown as limited to 65,536 * Network Packet size, but even then what is most likely to trip you up is the 2100 parameters per query. If SQL chooses to parameterize the literal values in the in clause, I would think you would hit that limit first, but I havn't tested it.
Edit : Test it, even under forced parameteriztion it survived - I knocked up a quick test and had it executing with 30k items within the In clause. (SQL Server 2005)
At 100k items, it took some time then dropped with:
Msg 8623, Level 16, State 1, Line 1 The query processor ran out of internal resources and could not produce a query plan. This is a rare event and only expected for extremely complex queries or queries that reference a very large number of tables or partitions. Please simplify the query. If you believe you have received this message in error, contact Customer Support Services for more information.
So 30k is possible, but just because you can do it - does not mean you should :)
Edit : Continued due to additional question.
50k worked, but 60k dropped out, so somewhere in there on my test rig btw.
In terms of how to do that join of the values without using a large in clause, personally I would create a temp table, insert the values into that temp table, index it and then use it in a join, giving it the best opportunities to optimse the joins. (Generating the index on the temp table will create stats for it, which will help the optimiser as a general rule, although 1000 GUIDs will not exactly find stats too useful.)
You can try using parentheses around the OR expressions to make sure your query is interpreted correctly, or more concisely, use IN:
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND ads.county_id IN (2,5,7,9)
I used this method:
$(document).mousemove(function(e) {
window.x = e.pageX;
window.y = e.pageY;
});
function show_popup(str) {
$("#popup_content").html(str);
$("#popup").fadeIn("fast");
$("#popup").css("top", y);
$("#popup").css("left", x);
}
In this way I'll always have the distance from the top saved in y and the distance from the left saved in x.
Use dictionary views:
if x in d.viewvalues():
dosomething()..
You can't show dialog box ON SERVER from ASP.NET application, well of course tehnically you can do that but it makes no sense since your user is using browser and it can't see messages raised on server. You have to understand how web sites work, server side code (ASP.NET in your case) produces html, javascript etc on server and then browser loads that content and displays it to the user, so in order to present modal message box to the user you have to use Javascript, for example alert function.
Here is the example for asp.net :
gosh, i had the same problem with osCommerce
install script until i figured out the mysql system has many databases and the create table
query copies itself into each one and thus droping only the working table on active db didnt help, i had to drop the table from all dbs
When embedding same-origin SVGs using <object>
, you can access the internal contents using objectElement.contentDocument.rootElement
. From there, you can easily attach event handlers (e.g. via onclick
, addEventListener()
, etc.)
For example:
var object = /* get DOM node for <object> */;
var svg = object.contentDocument.rootElement;
svg.addEventListener('click', function() {
console.log('hooray!');
});
Note that this is not possible for cross-origin <object>
elements unless you also control the <object>
origin server and can set CORS headers there. For cross-origin cases without CORS headers, access to contentDocument
is blocked.
I don't know how exactly the bottom sheet of the new Maps app, responds to user interactions. But you can create a custom view that looks like the one in the screenshots and add it to the main view.
I assume you know how to:
1- create view controllers either by storyboards or using xib files.
2- use googleMaps or Apple's MapKit.
1- Create 2 view controllers e.g, MapViewController and BottomSheetViewController. The first controller will host the map and the second is the bottom sheet itself.
Create a method to add the bottom sheet view.
func addBottomSheetView() {
// 1- Init bottomSheetVC
let bottomSheetVC = BottomSheetViewController()
// 2- Add bottomSheetVC as a child view
self.addChildViewController(bottomSheetVC)
self.view.addSubview(bottomSheetVC.view)
bottomSheetVC.didMoveToParentViewController(self)
// 3- Adjust bottomSheet frame and initial position.
let height = view.frame.height
let width = view.frame.width
bottomSheetVC.view.frame = CGRectMake(0, self.view.frame.maxY, width, height)
}
And call it in viewDidAppear method:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
addBottomSheetView()
}
Create a method to add blur and vibrancy effects
func prepareBackgroundView(){
let blurEffect = UIBlurEffect.init(style: .Dark)
let visualEffect = UIVisualEffectView.init(effect: blurEffect)
let bluredView = UIVisualEffectView.init(effect: blurEffect)
bluredView.contentView.addSubview(visualEffect)
visualEffect.frame = UIScreen.mainScreen().bounds
bluredView.frame = UIScreen.mainScreen().bounds
view.insertSubview(bluredView, atIndex: 0)
}
call this method in your viewWillAppear
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
prepareBackgroundView()
}
Make sure that your controller's view background color is clearColor.
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
UIView.animateWithDuration(0.3) { [weak self] in
let frame = self?.view.frame
let yComponent = UIScreen.mainScreen().bounds.height - 200
self?.view.frame = CGRectMake(0, yComponent, frame!.width, frame!.height)
}
}
In your viewDidLoad method add UIPanGestureRecognizer.
override func viewDidLoad() {
super.viewDidLoad()
let gesture = UIPanGestureRecognizer.init(target: self, action: #selector(BottomSheetViewController.panGesture))
view.addGestureRecognizer(gesture)
}
And implement your gesture behaviour:
func panGesture(recognizer: UIPanGestureRecognizer) {
let translation = recognizer.translationInView(self.view)
let y = self.view.frame.minY
self.view.frame = CGRectMake(0, y + translation.y, view.frame.width, view.frame.height)
recognizer.setTranslation(CGPointZero, inView: self.view)
}
If your custom view is a scroll view or any other view that inherits from, so you have two options:
First:
Design the view with a header view and add the panGesture to the header. (bad user experience).
Second:
1 - Add the panGesture to the bottom sheet view.
2 - Implement the UIGestureRecognizerDelegate and set the panGesture delegate to the controller.
3- Implement shouldRecognizeSimultaneouslyWith delegate function and disable the scrollView isScrollEnabled property in two case:
Otherwise enable scrolling.
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
let gesture = (gestureRecognizer as! UIPanGestureRecognizer)
let direction = gesture.velocity(in: view).y
let y = view.frame.minY
if (y == fullView && tableView.contentOffset.y == 0 && direction > 0) || (y == partialView) {
tableView.isScrollEnabled = false
} else {
tableView.isScrollEnabled = true
}
return false
}
NOTE
In case you set .allowUserInteraction as an animation option, like in the sample project, so you need to enable scrolling on the animation completion closure if the user is scrolling up.
I created a sample project with more options on this repo which may give you better insights about how to customise the flow.
In the demo, addBottomSheetView() function controls which view should be used as a bottom sheet.
one more, after you create user by following cmd-1, please assign read/write/root role to the user by cmd-2. then restart mongodb by cmd "mongod --auth".
The benefit of assign role to the user is you can do read/write operation by mongo shell or python/java and so on, otherwise you will meet "pymongo.errors.OperationFailure: not authorized" when you try to read/write your db.
cmd-1:
use admin
db.createUser({
user: "newUsername",
pwd: "password",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})
cmd-2:
db.grantRolesToUser('newUsername',[{ role: "root", db: "admin" }])
OffsetDateTime.parse( "2010-03-01T00:00:00-08:00" )
The answer by BalusC is correct, but now outdated as of Java 8.
The java.time framework is the successor to both Joda-Time library and the old troublesome date-time classes bundled with the earliest versions of Java (java.util.Date/.Calendar & java.text.SimpleDateFormat).
Your input data string happens to comply with the ISO 8601 standard.
The java.time classes use ISO 8601 formats by default when parsing/generating textual representations of date-time values. So no need to define a formatting pattern.
OffsetDateTime
The OffsetDateTime
class represents a moment on the time line adjusted to some particular offset-from-UTC. In your input, the offset is 8 hours behind UTC, commonly used on much of the west coast of North America.
OffsetDateTime odt = OffsetDateTime.parse( "2010-03-01T00:00:00-08:00" );
You seem to want the date-only, in which case use the LocalDate
class. But keep in mind you are discarding data, (a) time-of-day, and (b) the time zone. Really, a date has no meaning without the context of a time zone. For any given moment the date varies around the world. For example, just after midnight in Paris is still “yesterday” in Montréal. So while I suggest sticking with date-time values, you can easily convert to a LocalDate
if you insist.
LocalDate localDate = odt.toLocalDate();
If you know the intended time zone, apply it. A time zone is an offset plus the rules to use for handling anomalies such as Daylight Saving Time (DST). Applying a ZoneId
gets us a ZonedDateTime
object.
ZoneId zoneId = ZoneId.of( "America/Los_Angeles" );
ZonedDateTime zdt = odt.atZoneSameInstant( zoneId );
To generate a string in ISO 8601 format, call toString
.
String output = odt.toString();
If you need strings in other formats, search Stack Overflow for use of the java.util.format package.
java.util.Date
Best to avoid java.util.Date
, but if you must, you can convert. Call the new methods added to the old classes such as java.util.Date.from
where you pass an Instant
. An Instant
is a moment on the timeline in UTC. We can extract an Instant
from our OffsetDateTime
.
java.util.Date utilDate = java.util.Date( odt.toInstant() );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Don't forget to run:
/opt/android-studio/bin/studio.sh
when you are done installing.
You can use xsd.exe to create schema bound classes in .Net then XmlSerializer to Deserialize the string : http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.deserialize.aspx
I ended up coding a custom solution (Firefox extension) that does this. I think by the time I developed it, the commandline mentioned in enreas wasn't there.
The Firefox extension is CmdShots. It's a good option if you need finer degree of control over the process of taking the screenshot (or you want to do some HTML/JS modifications and image processing).
You can use it and abuse it. I decided to keep it unlicensed, so you are free to play with it as you want.
Git has a fairly complete set of traces embedded which you can use to debug your git problems.
To turn them on, you can define the following variables:
GIT_TRACE
for general traces,GIT_TRACE_PACK_ACCESS
for tracing of packfile access,GIT_TRACE_PACKET
for packet-level tracing for network operations,GIT_TRACE_PERFORMANCE
for logging the performance data,GIT_TRACE_SETUP
for information about discovering the repository and environment it’s interacting with,GIT_MERGE_VERBOSITY
for debugging recursive merge strategy (values: 0-5),GIT_CURL_VERBOSE
for logging all curl messages (equivalent to curl -v
),GIT_TRACE_SHALLOW
for debugging fetching/cloning of shallow repositories.Possible values can include:
true
, 1
or 2
to write to stderr,/
to trace output to the specified file.For more details, see: Git Internals - Environment Variables
For SSH issues, try the following commands:
echo 'ssh -vvv "$*"' > ssh && chmod +x ssh
GIT_SSH="$PWD/ssh" git pull origin master
or use ssh
to validate your credentials, e.g.
ssh -vvvT [email protected]
or over HTTPS port:
ssh -vvvT -p 443 [email protected]
Note: Reduce number of -v
to reduce the verbosity level.
$ GIT_TRACE=1 git status
20:11:39.565701 git.c:350 trace: built-in: git 'status'
$ GIT_TRACE_PERFORMANCE=$PWD/gc.log git gc
Counting objects: 143760, done.
...
$ head gc.log
20:12:37.214410 trace.c:420 performance: 0.090286000 s: git command: 'git' 'pack-refs' '--all' '--prune'
20:12:37.378101 trace.c:420 performance: 0.156971000 s: git command: 'git' 'reflog' 'expire' '--all'
...
$ GIT_TRACE_PACKET=true git pull origin master
20:16:53.062183 pkt-line.c:80 packet: fetch< 93eb028c6b2f8b1d694d1173a4ddf32b48e371ce HEAD\0multi_ack thin-pack side-band side-band-64k ofs-delta shallow no-progress include-tag multi_ack_detailed symref=HEAD:refs/heads/master agent=git/2:2.6.5~update-ref-initial-update-1494-g76b680d
...
simply put this on terminal at ubuntu:
mysql -u username -h host -p
Now hit enter
terminal will ask you password, enter the password and you are into database server
There are three methods of passing an object to a function as a parameter:
Go through the following example:
class Sample
{
public:
int *ptr;
int mVar;
Sample(int i)
{
mVar = 4;
ptr = new int(i);
}
~Sample()
{
delete ptr;
}
void PrintVal()
{
cout << "The value of the pointer is " << *ptr << endl
<< "The value of the variable is " << mVar;
}
};
void SomeFunc(Sample x)
{
cout << "Say i am in someFunc " << endl;
}
int main()
{
Sample s1= 10;
SomeFunc(s1);
s1.PrintVal();
char ch;
cin >> ch;
}
Output:
Say i am in someFunc
The value of the pointer is -17891602
The value of the variable is 4
An RGB hex string is just a number from 0x0 through 0xFFFFFF, so simply generate a number in that range and convert it to hexadecimal:
function rand_color() {
return '#' . str_pad(dechex(mt_rand(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT);
}
or:
function rand_color() {
return sprintf('#%06X', mt_rand(0, 0xFFFFFF));
}
DataTable DT = ...
// Rename column to OLD:
DT.Columns["ID"].ColumnName = "ID_OLD";
// Add column with new type:
DT.Columns.Add( "ID", typeof(int) );
// copy data from old column to new column with new type:
foreach( DataRow DR in DT.Rows )
{ DR["ID"] = Convert.ToInt32( DR["ID_OLD"] ); }
// remove "OLD" column
DT.Columns.Remove( "ID_OLD" );
If you want to use a hex code, here is the best way to do so.
First, define this at the top of your class:
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
Then inside the "application didFinishLaunchingWithOptions", put this:
[[UINavigationBar appearance] setBarTintColor:UIColorFromRGB(0x00b0f0)];
Put you hex code in place of the 00b0f0.
You can't have duplicated keys in a dictionary. Use a dict of lists:
for line in data_list:
regNumber = line[0]
name = line[1]
phoneExtn = line[2]
carpark = line[3].strip()
details = (name,phoneExtn,carpark)
if not data_dict.has_key(regNumber):
data_dict[regNumber] = [details]
else:
data_dict[regNumber].append(details)
No simple way AFAIK. If the target is to keep statement cache ratio high (i.e to not create a statement per every parameter count), you may do the following:
create a statement with a few (e.g. 10) parameters:
... WHERE A IN (?,?,?,?,?,?,?,?,?,?) ...
Bind all actuall parameters
setString(1,"foo"); setString(2,"bar");
Bind the rest as NULL
setNull(3,Types.VARCHAR) ... setNull(10,Types.VARCHAR)
NULL never matches anything, so it gets optimized out by the SQL plan builder.
The logic is easy to automate when you pass a List into a DAO function:
while( i < param.size() ) {
ps.setString(i+1,param.get(i));
i++;
}
while( i < MAX_PARAMS ) {
ps.setNull(i+1,Types.VARCHAR);
i++;
}
The problem is due to lack of permissions for SQL Server to access the mdf & ldf files. All these procedures will work :
In some cases you may need a counter that may be provided by for-loop implementation. For that, LINQ provides ElementAt
which enables the following:
for (int index = 0; index < dictionary.Count; index++) {
var item = dictionary.ElementAt(index);
var itemKey = item.Key;
var itemValue = item.Value;
}
For my case, it was with Toolbar i resolved it like this:
ic_toolbar_drawble.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@drawable/ic_toolbar"
android:right="-16dp"
android:left="-16dp"/>
</layer-list>
In my Fragment, i check the api :
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
toolbar.setLogo(R.drawable.ic_toolbar);
else
toolbar.setLogo(R.drawable.ic_toolbar_draweble);
Good luck!
If you don't wish to compile bootstrap, copy the following and insert it in your custom css file. It's not recommended to change the original bootstrap css file. Also, you won't be able to modify the bootstrap original css if you are loading it from a cdn.
Paste this in your custom css file:
@media (min-width:992px)
{
.container{width:960px}
}
@media (min-width:1200px)
{
.container{width:960px}
}
I am here setting my container to 960px for anything that can accommodate it, and keeping the rest media sizes to default values. You can set it to 940px for this problem.
To avoid double encoding issue described in taras.roshko's answer and to keep possibility to easily work with query parameters, you can use uriBuilder.Uri.ParseQueryString()
instead of HttpUtility.ParseQueryString()
.
I would open another terminal on your laptop and do the scp from there, since you already know how to set that connection up.
scp username@remotecomputer:/path/to/file/you/want/to/copy where/to/put/file/on/laptop
The username@remotecomputer
is the same string you used with ssh initially.
try below code
public static int Length(String str) {
str = str + '\0';
int count = 0;
for (int i = 0; str.charAt(i) != '\0'; i++) {
count++;
}
return count;
}
Easy
Step1: Create new project. Go File->New File or Project --> Other Project -->Empty Project
Step2: Use the below code.
In .pro file
QT +=widgets
CONFIG += console
TARGET = minimal
SOURCES += \ main.cpp
Step3: Create main.cpp and copy the below code.
#include <QApplication>
#include <QtCore>
using namespace std;
QTextStream in(stdin);
QTextStream out(stdout);
int main(int argc, char *argv[]){
QApplication app(argc,argv);
qDebug() << "Please enter some text over here: " << endl;
out.flush();
QString input;
input = in.readLine();
out << "The input is " << input << endl;
return app.exec();
}
I created necessary objects in the code for your understanding.
Just Run It
If you want your program to get multiple inputs with some conditions. Then past the below code in Main.cpp
#include <QApplication>
#include <QtCore>
using namespace std;
QTextStream in(stdin);
QTextStream out(stdout);
int main(int argc, char *argv[]){
QApplication app(argc,argv);
qDebug() << "Please enter some text over here: " << endl;
out.flush();
QString input;
do{
input = in.readLine();
if(input.size()==6){
out << "The input is " << input << endl;
}
else
{
qDebug("Not the exact input man");
}
}while(!input.size()==0);
qDebug(" WE ARE AT THE END");
// endif
return app.exec();
} // end main
Hope it educates you.
Good day,
A similar alternative
/**
* @param delimiter
* @param inStr
* @return String
*/
public static String join(String delimiter, String... inStr)
{
StringBuilder sb = new StringBuilder();
if (inStr.length > 0)
{
sb.append(inStr[0]);
for (int i = 1; i < inStr.length; i++)
{
sb.append(delimiter);
sb.append(inStr[i]);
}
}
return sb.toString();
}
I had to accept the XCode license after my first install before I could run it. You can run the following to get the license prompt via command line. You have to type agree
and confirm as well.
sudo xcodebuild -license
foreach (DataRow dr in ds.Tables[0].Rows)
{
//your code here
}
Good answers so far, I want to only add that you could check the type of a node using nodeType
:
yourElement.nodeType
This will give you an integer: (taken from here)
| Value | Constant | Description | |
|-------|----------------------------------|---------------------------------------------------------------|--|
| 1 | Node.ELEMENT_NODE | An Element node such as <p> or <div>. | |
| 2 | Node.ATTRIBUTE_NODE | An Attribute of an Element. The element attributes | |
| | | are no longer implementing the Node interface in | |
| | | DOM4 specification. | |
| 3 | Node.TEXT_NODE | The actual Text of Element or Attr. | |
| 4 | Node.CDATA_SECTION_NODE | A CDATASection. | |
| 5 | Node.ENTITY_REFERENCE_NODE | An XML Entity Reference node. Removed in DOM4 specification. | |
| 6 | Node.ENTITY_NODE | An XML <!ENTITY ...> node. Removed in DOM4 specification. | |
| 7 | Node.PROCESSING_INSTRUCTION_NODE | A ProcessingInstruction of an XML document | |
| | | such as <?xml-stylesheet ... ?> declaration. | |
| 8 | Node.COMMENT_NODE | A Comment node. | |
| 9 | Node.DOCUMENT_NODE | A Document node. | |
| 10 | Node.DOCUMENT_TYPE_NODE | A DocumentType node e.g. <!DOCTYPE html> for HTML5 documents. | |
| 11 | Node.DOCUMENT_FRAGMENT_NODE | A DocumentFragment node. | |
| 12 | Node.NOTATION_NODE | An XML <!NOTATION ...> node. Removed in DOM4 specification. | |
Note that according to Mozilla:
The following constants have been deprecated and should not be used anymore: Node.ATTRIBUTE_NODE, Node.ENTITY_REFERENCE_NODE, Node.ENTITY_NODE, Node.NOTATION_NODE
>>> import os
>>> print os.path.abspath(os.curdir)
C:\Python27
>>> os.chdir("..")
>>> print os.path.abspath(os.curdir)
C:\
adding overflow:visible !important;
to the body element worked for me.
In C++20 we'll finally get std::set::contains
method.
#include <iostream>
#include <string>
#include <set>
int main()
{
std::set<std::string> example = {"Do", "not", "panic", "!!!"};
if(example.contains("panic")) {
std::cout << "Found\n";
} else {
std::cout << "Not found\n";
}
}
Use directly
$paymentDate = strtotime(date("d-m-Y"));
$contractDateBegin = strtotime("01-01-2001");
$contractDateEnd = strtotime("01-01-2015");
Then comparison will be ok cause your 01-01-2015 is valid for PHP's 32bit date-range, stated in strtotime's manual.
Nick's answer works great. Be careful when specifying a complete() function inside the animate() call because it will get executed twice since you have two selectors declared (html and body).
$("html, body").animate(
{ scrollTop: "300px" },
{
complete : function(){
alert('this alert will popup twice');
}
}
);
Here's how you can avoid the double callback.
var completeCalled = false;
$("html, body").animate(
{ scrollTop: "300px" },
{
complete : function(){
if(!completeCalled){
completeCalled = true;
alert('this alert will popup once');
}
}
}
);
A simpler way which eliminates checking if the app can open the url.
loadInBrowser = () => {
Linking.openURL(this.state.url).catch(err => console.error("Couldn't load page", err));
};
Calling it with a button.
<Button title="Open in Browser" onPress={this.loadInBrowser} />
We can no longer reset android studio to it's default state by the answers/methods given in this question from android studio 3.2.0 Here is the updated new method to do it (It consumes less time as it does not require any update/installation).
For Windows/Mac
Open my computer
Go to C:\Users\Username\.android\build-cache
Delete the cache/files found inside the folder build-cache
Note: do not delete the folder named as "3.2.0" and "3.2.1" which will be inside the build-cache
Restart Android studio.
and that would completely reset your android studio settings from Android studio 3.2.0 and up.
Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin
not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors
at your server side.
You can fetch request using mode: 'cors'
. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.
So in both condition you need to configure cors
in your server or you need to use custom proxy server.
The u in u'Some String'
means that your string is a Unicode string.
Q: I'm in a terrible, awful hurry and I landed here from Google Search. I'm trying to write this data to a file, I'm getting an error, and I need the dead simplest, probably flawed, solution this second.
A: You should really read Joel's Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) essay on character sets.
Q: sry no time code pls
A: Fine. try str('Some String')
or 'Some String'.encode('ascii', 'ignore')
. But you should really read some of the answers and discussion on Converting a Unicode string and this excellent, excellent, primer on character encoding.
document.getElementById('textbox-id').readOnly=true
should work
>>> myList = [10,20,30,40,50,60,70,80,90]
>>> myInt = 10
>>> newList = map(lambda x: x/myInt, myList)
>>> newList
[1, 2, 3, 4, 5, 6, 7, 8, 9]
You can only set the connection timeout on the connection string, the timeout for your query would normally be on the command timeout. (Assuming we are talking .net here, I can't really tell from your question).
However the command timeout has no effect when the command is executed against a context connection (a SqlConnection opened with "context connection=true" in the connection string).
I do the same task like this.
//in MessageHeader
private void SetValuesDefault()
{
MessageHeader header = this;
Framework.ObjectPropertyHelper.SetPropertiesToDefault<MessageHeader>(this);
}
//in ObjectPropertyHelper
public static void SetPropertiesToDefault<T>(T obj)
{
Type objectType = typeof(T);
System.Reflection.PropertyInfo [] props = objectType.GetProperties();
foreach (System.Reflection.PropertyInfo property in props)
{
if (property.CanWrite)
{
string propertyName = property.Name;
Type propertyType = property.PropertyType;
object value = TypeHelper.DefaultForType(propertyType);
property.SetValue(obj, value, null);
}
}
}
//in TypeHelper
public static object DefaultForType(Type targetType)
{
return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;
}
robocopy "C:\Users\Angie\My Documents" "C:\test-backup\My Documents" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"
robocopy "C:\Users\Angie\My Music" "C:\test-backup\My Music" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"
robocopy "C:\Users\Angie\My Pictures" "C:\test-backup\My Pictures" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"
I recommend use the StringTokenizer, is very efficient
List<String> list = new ArrayList<>();
StringTokenizer token = new StringTokenizer(value, LIST_SEPARATOR);
while (token.hasMoreTokens()) {
list.add(token.nextToken());
}
Although there won't be any remaining transaction in the case, as @Johan said, you can see the current transaction list in InnoDB with the query below if you want.
SELECT * FROM information_schema.innodb_trx\G
From the document:
The INNODB_TRX table contains information about every transaction (excluding read-only transactions) currently executing inside InnoDB, including whether the transaction is waiting for a lock, when the transaction started, and the SQL statement the transaction is executing, if any.
As it have been said, the issue comes from a security function of Mac OSX since "El Capitan".
Using the default system Ruby, the install process happens in the /Library/Ruby/Gems/2.0.0
directory which is not available to the user and gives the error.
You can have a look to your Ruby environments parameters with the command
$ gem env
There is an INSTALLATION DIRECTORY and a USER INSTALLATION DIRECTORY. To use the user installation directory instead of the default installation directory, you can use --user-install
parameter instead as using sudo
which is never a recommanded way of doing.
$ gem install myGemName --user-install
There should not be any rights issue anymore in the process. The gems are then installed in the user directory : ~/.gem/Ruby/2.0.0/bin
But to make the installed gems available, this directory should be available in your path. According to the Ruby’s faq, you can add the following line to your ~/.bash_profile
or ~/.bashrc
if which ruby >/dev/null && which gem >/dev/null; then
PATH="$(ruby -rubygems -e 'puts Gem.user_dir')/bin:$PATH"
fi
Then close and reload your terminal or reload your .bash_profile
or .bashrc
(. ~/.bash_profile
)
You can just forgo the quotes for alphanumeric attributes:
echo "<font color=red> XHTML is not a thing anymore. </font>";
echo "<div class=editorial-note> There, I said it. </div>";
Is perfectly valid in HTML, and though still shunned, absolutely en vogue since HTML5.
CAVEATS
htmlspecialchars
or some whitelisting).<font>
specifically is somewhat outdated however.while (listBox1.Items.Count > 0){
listBox1.Items.Remove(0);
}
Ensure debug mode is on - either add APP_DEBUG=true
to .env file or set an environment variable
Log files are in storage/logs folder. laravel.log
is the default filename. If there is a permission issue with the log folder, Laravel just halts. So if your endpoint generally works - permissions are not an issue.
In case your calls don't even reach Laravel or aren't caused by code issues - check web server's log files (check your Apache/nginx config files to see the paths).
If you use PHP-FPM, check its log files as well (you can see the path to log file in PHP-FPM pool config).
I don't think that can be done RELIABLY with built in methods on the native Date object. The toLocaleString
method gets close, but if I am remembering correctly, it won't work correctly in IE < 10. If you are able to use a library for this task, MomentJS is a really amazing library; and it makes working with dates and times easy. Otherwise, I think you will have to write a basic function to give you the format that you are after.
function formatDate(date) {
var year = date.getFullYear(),
month = date.getMonth() + 1, // months are zero indexed
day = date.getDate(),
hour = date.getHours(),
minute = date.getMinutes(),
second = date.getSeconds(),
hourFormatted = hour % 12 || 12, // hour returned in 24 hour format
minuteFormatted = minute < 10 ? "0" + minute : minute,
morning = hour < 12 ? "am" : "pm";
return month + "/" + day + "/" + year + " " + hourFormatted + ":" +
minuteFormatted + morning;
}
Great answer by F.Mörk. But if you want to update translation, or add new languages once the application is released, you're stuck, because you always have to recompile it to generate the resources.dll.
Here is a solution to manually compile a resource dll. It uses the resgen.exe and al.exe tools (installed with the sdk).
Say you have a Strings.fr.resx resource file, you can compile a resources dll with the following batch:
resgen.exe /compile Strings.fr.resx,WpfRibbonApplication1.Strings.fr.resources
Al.exe /t:lib /embed:WpfRibbonApplication1.Strings.fr.resources /culture:"fr" /out:"WpfRibbonApplication1.resources.dll"
del WpfRibbonApplication1.Strings.fr.resources
pause
Be sure to keep the original namespace in the file names (here "WpfRibbonApplication1")
You didn't provide many relevant details so I will guess that you called getInvoice
and then you used result object to set some values and call save
with assumption that your object changes will be saved.
However, persist
operation is intended for brand new transient objects and it fails if id is already assigned. In your case you probably want to call saveOrUpdate
instead of persist
.
You can find some discussion and references here "detached entity passed to persist error" with JPA/EJB code
Instead of stripping out the found character by its sole position, using Replace(Column, BadFoundCharacter, '')
could be substantially faster. Additionally, instead of just replacing the one bad character found next in each column, this replaces all those found.
WHILE 1 = 1 BEGIN
UPDATE dbo.YourTable
SET Column = Replace(Column, Substring(Column, PatIndex('%[^0-9.-]%', Column), 1), '')
WHERE Column LIKE '%[^0-9.-]%'
If @@RowCount = 0 BREAK;
END;
I am convinced this will work better than the accepted answer, if only because it does fewer operations. There are other ways that might also be faster, but I don't have time to explore those right now.
You might also try giving the full path to the binary you're trying to run. That solved my problem when trying to use ImageMagick
.
Sessions are stored on the server and are set from server side code, not client side code such as JavaScript.
What you want is a cookie, someone's given a brilliant explanation in this Stack Overflow question here: How do I set/unset cookie with jQuery?
You could potentially use sessions and set/retrieve them with jQuery and AJAX, but it's complete overkill if Cookies will do the trick.
While submitting form use reset method on form. The reset() method resets the values of all elements in a form.
$('#form-id')[0].reset();
OR
document.getElementById("form-id").reset();
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset
$("#submit-button").on("click", function(){_x000D_
//code here_x000D_
$('#form-id')[0].reset();_x000D_
});
_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<form id="form-id">_x000D_
First name:<br>_x000D_
<input type="text" name="firstname">_x000D_
<br>_x000D_
Last name:<br>_x000D_
<input type="text" name="lastname">_x000D_
<br><br>_x000D_
<input id="submit-button" type="submit" value="Submit">_x000D_
</form> _x000D_
</body>_x000D_
</html>
_x000D_
I would suggest Travis for Open source project. It's just simple to configure and use.
Simple steps to setup:
.travis.yml
file in root of your project. Add Travis as service in your repository settings page.Now every time you commit into your repository Travis will build your project. You can follow simple steps to get started with Travis CI.
for use sample touch listener just you need this code
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
view.startDrag(data, shadowBuilder, null, 0);
return true;
}
here a simple converter by using std::string
as container. it allows a negative value.
#include <iostream>
#include <string>
#include <limits>
int main()
{
int x = -14;
int n = std::numeric_limits<int>::digits - 1;
std::string s;
s.reserve(n + 1);
do
s.push_back(((x >> n) & 1) + '0');
while(--n > -1);
std::cout << s << '\n';
}
I got the solution for setting the height of the iframe dynamically based on it's content. This works for the cross domain content. There are some steps to follow to achieve this.
Suppose you have added iframe in "abc.com/page" web page
<div>
<iframe id="IframeId" src="http://xyz.pqr/contactpage" style="width:100%;" onload="setIframeHeight(this)"></iframe>
</div>
Next you have to bind windows "message" event under web page "abc.com/page"
window.addEventListener('message', function (event) {
//Here We have to check content of the message event for safety purpose
//event data contains message sent from page added in iframe as shown in step 3
if (event.data.hasOwnProperty("FrameHeight")) {
//Set height of the Iframe
$("#IframeId").css("height", event.data.FrameHeight);
}
});
On iframe load you have to send message to iframe window content with "FrameHeight" message:
function setIframeHeight(ifrm) {
var height = ifrm.contentWindow.postMessage("FrameHeight", "*");
}
window.addEventListener('message', function (event) {
// Need to check for safety as we are going to process only our messages
// So Check whether event with data(which contains any object) contains our message here its "FrameHeight"
if (event.data == "FrameHeight") {
//event.source contains parent page window object
//which we are going to use to send message back to main page here "abc.com/page"
//parentSourceWindow = event.source;
//Calculate the maximum height of the page
var body = document.body, html = document.documentElement;
var height = Math.max(body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight);
// Send height back to parent page "abc.com/page"
event.source.postMessage({ "FrameHeight": height }, "*");
}
});
To restore a file from another branch, simply use the following command from your working branch:
git restore -s my-other-branch -- ./path/to/file
The -s
flag is short for source
i.e. the branch from where you want to pull the file.
(The chosen answer is very informative but also a bit overwhelming.)
As of the current JRE implementation, Function.identity()
will always return the same instance while each occurrence of identifier -> identifier
will not only create its own instance but even have a distinct implementation class. For more details, see here.
The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x
, equivalent to return identifier;
) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.
So using Function.identity()
instead of x -> x
might save some memory but that shouldn’t drive your decision if you really think that x -> x
is more readable than Function.identity()
.
You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function
instance while debugging. In contrast, when encountering the instance returned by Function.identity()
during debugging an operation, you won’t know who has called that method and passed the instance to the operation.
I use this step, first Set delegate texfield in viewdidload.
override func viewDidLoad() {
super.viewDidLoad()
textfield.delegate = self
}
and then shouldChangeCharactersIn after you include UITextFieldDelegate.
extension viewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newLength = (textField.text?.utf16.count)! + string.utf16.count - range.length
if newLength <= 8 {
return true
} else {
return false
}
}
}
A couple of reasons I can think of for using an IDE:
And quite frankly, I like my mouse. When I use pure text-based editors it gets lonely.
yes, but only if main is declared public
I had this issue with sites running on XAMPP with private hostnames. Not so private, it turns out! They were all domain.dev
, which Google has now registered as a private gTLD, and is forcing HSTS at the domain level. Changed every virtual host to .devel
(eugh), restarted Apache and all is now well.
Try this one: https://github.com/tantau-horia/jquery-SuperCookie
Quick Usage:
create - create cookie
check - check existance
verify - verify cookie value if JSON
check_index - verify if index exists in JSON
read_values - read cookie value as string
read_JSON - read cookie value as JSON object
read_value - read value of index stored in JSON object
replace_value - replace value from a specified index stored in JSON object
remove_value - remove value and index stored in JSON object
Just use:
$.super_cookie().create("name_of_the_cookie",name_field_1:"value1",name_field_2:"value2"});
$.super_cookie().read_json("name_of_the_cookie");
One more point to all the above correct answers, it depends on what sort of programming you are doing. Kernel developing in Windows for example -> The stack is severely limited and you might not be able to take page faults like in user mode.
In such environments, new, or C-like API calls are prefered and even required.
Of course, this is merely an exception to the rule.
eduffy had a good idea. He just got it backwards in his code example. Either in JavaScript or in SQLite you can replace the apostrophe with the accent symbol.
He (accidentally I am sure) placed the accent symbol as the delimiter for the string instead of replacing the apostrophe in O'Brian. This is in fact a terrifically simple solution for most cases.
I am using the following test to see if strings have been urlencoded:
if(urlencode($str) != str_replace(['%','+'], ['%25','%2B'], $str))
If a string has already been urlencoded, the only characters that will changed by double encoding are % (which starts all encoded character strings) and + (which replaces spaces.) Change them back and you should have the original string.
Let me know if this works for you.
Handy with error_log() if you're outputting multiple lines.
I've found a lot of debug statements look weird on my windows install since the developers have assumed unix endings when breaking up strings.
The web server is prompting you for a SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) token.
This is a Microsoft invention for negotiating a type of authentication to use for Web SSO (single-sign-on):
See:
Try this
$("[id*='type']").click(
function () {
var isCheckboxChecked = this.checked;
$("[id*='type']").attr('checked', false);
this.checked = isCheckboxChecked;
});
To make it even more generic you can also find checkboxes by the common class implemented on them.
Modified...
Kendo grid is good as well as Wijmo. I know Kendo comes with Angular bindings for their datasource and I think Wijmo has an Angular plugin. Neither are free though.
You can set the DataContext for your control, form, etc. like so:
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Clarification:
The data context being set to the value above should be done at whatever element "owns" the code behind -- so for a Window, you should set it in the Window declaration.
I have your example working with this code:
<Window x:Class="MyClass"
Title="{Binding windowname}"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Height="470" Width="626">
The DataContext set at this level then is inherited by any element in the window (unless you explicitly change it for a child element), so after setting the DataContext for the Window you should be able to just do straight binding to CodeBehind properties from any control on the window.
You can also do what the "Service Reference" generated code does
public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
public ServiceXClient() { }
public ServiceXClient(string endpointConfigurationName) :
base(endpointConfigurationName) { }
public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) { }
public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) { }
public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
base(binding, remoteAddress) { }
public bool ServiceXWork(string data, string otherParam)
{
return base.Channel.ServiceXWork(data, otherParam);
}
}
Where IServiceX is your WCF Service Contract
Then your client code:
var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");
Even though it's an old question I'd like to show another solution:
Just define your own operation using java generics and java 8 streams:
public static <S, T> List<T> map(Collection<S> collection, Function<S, T> mapFunction) {
return collection.stream().map(mapFunction).collect(Collectors.toList());
}
Than you can write code like this:
List<String> hex = map(Arrays.asList(10, 20, 30, 40, 50), Integer::toHexString);
When you execute a method (i.e. function assigned to an object), inside it you can use this
variable to refer to this object, for example:
var obj = {_x000D_
someProperty: true,_x000D_
someMethod: function() {_x000D_
console.log(this.someProperty);_x000D_
}_x000D_
};_x000D_
obj.someMethod(); // logs true
_x000D_
If you assign a method from one object to another, its this
variable refers to the new object, for example:
var obj = {_x000D_
someProperty: true,_x000D_
someMethod: function() {_x000D_
console.log(this.someProperty);_x000D_
}_x000D_
};_x000D_
_x000D_
var anotherObj = {_x000D_
someProperty: false,_x000D_
someMethod: obj.someMethod_x000D_
};_x000D_
_x000D_
anotherObj.someMethod(); // logs false
_x000D_
The same thing happens when you assign requestAnimationFrame
method of window
to another object. Native functions, such as this, has build-in protection from executing it in other context.
There is a Function.prototype.call()
function, which allows you to call a function in another context. You just have to pass it (the object which will be used as context) as a first parameter to this method. For example alert.call({})
gives TypeError: Illegal invocation
. However, alert.call(window)
works fine, because now alert
is executed in its original scope.
If you use .call()
with your object like that:
support.animationFrame.call(window, function() {});
it works fine, because requestAnimationFrame
is executed in scope of window
instead of your object.
However, using .call()
every time you want to call this method, isn't very elegant solution. Instead, you can use Function.prototype.bind()
. It has similar effect to .call()
, but instead of calling the function, it creates a new function which will always be called in specified context. For example:
window.someProperty = true;_x000D_
var obj = {_x000D_
someProperty: false,_x000D_
someMethod: function() {_x000D_
console.log(this.someProperty);_x000D_
}_x000D_
};_x000D_
_x000D_
var someMethodInWindowContext = obj.someMethod.bind(window);_x000D_
someMethodInWindowContext(); // logs true
_x000D_
The only downside of Function.prototype.bind()
is that it's a part of ECMAScript 5, which is not supported in IE <= 8. Fortunately, there is a polyfill on MDN.
As you probably already figured out, you can use .bind()
to always execute requestAnimationFrame
in context of window
. Your code could look like this:
var support = {
animationFrame: (window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame).bind(window)
};
Then you can simply use support.animationFrame(function() {});
.
Create a Password generator service called PassswordGeneratorService
import { Injectable } from '@angular/core';
@Injectable()
export class PasswordGeneratorService {
generatePassword(length:number,upper:boolean,numbers:boolean,symbols:boolean) {
const passwordLength = length || 12;
const addUpper = upper;
const addNumbers = numbers;
const addSymbols = symbols;
const lowerCharacters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
const upperCharacters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
const numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
const symbols = ['!', '?', '@'];
const getRandom = array => array[Math.floor(Math.random() * array.length)];
let finalCharacters = '';
if (addUpper) {
finalCharacters = finalCharacters.concat(getRandom(upperCharacters));
}
if (addNumbers) {
finalCharacters = finalCharacters.concat(getRandom(numbers));
}
if (addSymbols) {
finalCharacters = finalCharacters.concat(getRandom(symbols));
}
for (let i = 1; i < passwordLength - 3; i++) {
finalCharacters = finalCharacters.concat(getRandom(lowerCharacters));
}
return finalCharacters.split('').sort(() => 0.5 - Math.random()).join('');
}
}
don't forget to add the service on the module your using
@NgModule({
imports: [
CommonModule,
SharedModule,
CommonModule,
RouterModule.forChild(routes),
FormsModule,
ReactiveFormsModule,
FlexLayoutModule,
TranslateModule,
ExistingUserDialogModule,
UserDocumentsUploadDialogModule
],
declarations: [
UserListComponent,
EditUserDialogComponent,
UserEditorComponent
],
entryComponents: [
EditUserDialogComponent
],
providers: [
AuthService,
PasswordGeneratorService
]
})
export class UsersModule {
}
On you controller add a method which calls the generate password method inside the service and set the result on the password field
constructor(
private passwordGenerator: PasswordGeneratorService,
)
get newPassword() {
return this.password.get('newPassword');
}
generatePassword() {
this.newPassword.setValue(this.passwordGenerator.generatePassword(8,true,true,true));
}
In my case, I was trying to call plot(x, y)
and lines(x, predict(yx.lm), col="red")
in two separate chunks in Rmarkdown file. It worked without problems when running chunk by chunk, but the corresponding document wouldn't knit. After I moved all plotting calls within one chunk, problem was resolved.
Member references are usually considered bad. They make life hard compared to member pointers. But it's not particularly unsual, nor is it some special named idiom or thing. It's just aliasing.
Here is PostgreSQL example without trigger if someone need it on PostgreSQL:
CREATE SEQUENCE messages_seq;
CREATE TABLE IF NOT EXISTS messages (
id CHAR(20) NOT NULL DEFAULT ('message_' || nextval('messages_seq')),
name CHAR(30) NOT NULL,
);
ALTER SEQUENCE messages_seq OWNED BY messages.id;
CentOS 7 uses firewalld by default now. But all the answers focus on iptables. So I wanted to add an answer related to firewalld.
Since firewalld is a "wrapper" for iptables, using antonio-fornie's answer still seems to work but I was unable to "save" that new rule. So I wasn't able to connect to my apache server as soon as a restart of the firewall happened. Luckily it is actually much more straightforward to make an equivalent change with firewalld commands. First check if firewalld is running:
firewall-cmd --state
If it is running the response will simply be one line that says "running".
To allow http (port 80) connections temporarily on the public zone:
sudo firewall-cmd --zone=public --add-service=http
The above will not be "saved", next time the firewalld service is restarted it'll go back to default rules. You should use this temporary rule to test and make sure it solves your connection issue before moving on.
To permanently allow http connections on the public zone:
sudo firewall-cmd --zone=public --permanent --add-service=http
If you do the "permanent" command without doing the "temporary" command as well, you'll need to restart firewalld to get your new default rules (this might be different for non CentOS systems):
sudo systemctl restart firewalld.service
If this hasn't solved your connection issues it may be because your interface isn't in the "public zone". The following link is a great resource for learning about firewalld. It goes over in detail how to check, assign, and configure zones: https://www.digitalocean.com/community/tutorials/how-to-set-up-a-firewall-using-firewalld-on-centos-7
For anyone who, like me, reads this because they need to update a giant legacy project to 5.6: as the answers here point out, there is no quick fix: you really do need to find each occurrence of the problem manually, and fix it.
The most convenient way I found to find all problematic lines in a project (short of using a full-blown static code analyzer, which is very accurate but I don't know any that take you to the correct position in the editor right away) was using Visual Studio Code, which has a nice PHP linter built in, and its search feature which allows searching by Regex. (Of course, you can use any IDE/Code editor for this that does PHP linting and Regex searches.)
Using this regex:
^(?!.*function).*(\&\$)
it is possible to search project-wide for the occurrence of &$
only in lines that are not a function definition.
This still turns up a lot of false positives, but it does make the job easier.
VSCode's search results browser makes walking through and finding the offending lines super easy: you just click through each result, and look out for those that the linter underlines red. Those you need to fix.
The method to use depends on the contents of the list being copied. If the list contains nested dicts
than deepcopy is the only method that works, otherwise most of the methods listed in the answers (slice, loop [for], copy, extend, combine, or unpack) will work and execute in similar time (except for loop and deepcopy, which preformed the worst).
from random import randint
from time import time
import copy
item_count = 100000
def copy_type(l1: list, l2: list):
if l1 == l2:
return 'shallow'
return 'deep'
def run_time(start, end):
run = end - start
return int(run * 1000000)
def list_combine(data):
l1 = [data for i in range(item_count)]
start = time()
l2 = [] + l1
end = time()
if type(data) == dict:
l2[0]['test'].append(1)
elif type(data) == list:
l2.append(1)
return {'method': 'combine', 'copy_type': copy_type(l1, l2),
'time_µs': run_time(start, end)}
def list_extend(data):
l1 = [data for i in range(item_count)]
start = time()
l2 = []
l2.extend(l1)
end = time()
if type(data) == dict:
l2[0]['test'].append(1)
elif type(data) == list:
l2.append(1)
return {'method': 'extend', 'copy_type': copy_type(l1, l2),
'time_µs': run_time(start, end)}
def list_unpack(data):
l1 = [data for i in range(item_count)]
start = time()
l2 = [*l1]
end = time()
if type(data) == dict:
l2[0]['test'].append(1)
elif type(data) == list:
l2.append(1)
return {'method': 'unpack', 'copy_type': copy_type(l1, l2),
'time_µs': run_time(start, end)}
def list_deepcopy(data):
l1 = [data for i in range(item_count)]
start = time()
l2 = copy.deepcopy(l1)
end = time()
if type(data) == dict:
l2[0]['test'].append(1)
elif type(data) == list:
l2.append(1)
return {'method': 'deepcopy', 'copy_type': copy_type(l1, l2),
'time_µs': run_time(start, end)}
def list_copy(data):
l1 = [data for i in range(item_count)]
start = time()
l2 = list.copy(l1)
end = time()
if type(data) == dict:
l2[0]['test'].append(1)
elif type(data) == list:
l2.append(1)
return {'method': 'copy', 'copy_type': copy_type(l1, l2),
'time_µs': run_time(start, end)}
def list_slice(data):
l1 = [data for i in range(item_count)]
start = time()
l2 = l1[:]
end = time()
if type(data) == dict:
l2[0]['test'].append(1)
elif type(data) == list:
l2.append(1)
return {'method': 'slice', 'copy_type': copy_type(l1, l2),
'time_µs': run_time(start, end)}
def list_loop(data):
l1 = [data for i in range(item_count)]
start = time()
l2 = []
for i in range(len(l1)):
l2.append(l1[i])
end = time()
if type(data) == dict:
l2[0]['test'].append(1)
elif type(data) == list:
l2.append(1)
return {'method': 'loop', 'copy_type': copy_type(l1, l2),
'time_µs': run_time(start, end)}
def list_list(data):
l1 = [data for i in range(item_count)]
start = time()
l2 = list(l1)
end = time()
if type(data) == dict:
l2[0]['test'].append(1)
elif type(data) == list:
l2.append(1)
return {'method': 'list()', 'copy_type': copy_type(l1, l2),
'time_µs': run_time(start, end)}
if __name__ == '__main__':
list_type = [{'list[dict]': {'test': [1, 1]}},
{'list[list]': [1, 1]}]
store = []
for data in list_type:
key = list(data.keys())[0]
store.append({key: [list_unpack(data[key]), list_extend(data[key]),
list_combine(data[key]), list_deepcopy(data[key]),
list_copy(data[key]), list_slice(data[key]),
list_loop(data[key])]})
print(store)
[{"list[dict]": [
{"method": "unpack", "copy_type": "shallow", "time_µs": 56149},
{"method": "extend", "copy_type": "shallow", "time_µs": 52991},
{"method": "combine", "copy_type": "shallow", "time_µs": 53726},
{"method": "deepcopy", "copy_type": "deep", "time_µs": 2702616},
{"method": "copy", "copy_type": "shallow", "time_µs": 52204},
{"method": "slice", "copy_type": "shallow", "time_µs": 52223},
{"method": "loop", "copy_type": "shallow", "time_µs": 836928}]},
{"list[list]": [
{"method": "unpack", "copy_type": "deep", "time_µs": 52313},
{"method": "extend", "copy_type": "deep", "time_µs": 52550},
{"method": "combine", "copy_type": "deep", "time_µs": 53203},
{"method": "deepcopy", "copy_type": "deep", "time_µs": 2608560},
{"method": "copy", "copy_type": "deep", "time_µs": 53210},
{"method": "slice", "copy_type": "deep", "time_µs": 52937},
{"method": "loop", "copy_type": "deep", "time_µs": 834774}
]}]
[ round(x,2) for x in [2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01]]
Though the answer solves the issue, I would like to provide a little more information on this topic as I have also undergone this issue when I started to work on Angular projects.
A beginner should understand that there are two main types of forms. They are Reactive forms and Template-driven forms. From Angular 2 onward, it is recommended to use Reactive forms for any kind of forms.
Reactive forms are more robust: they're more scalable, reusable, and testable. If forms are a key part of your application, or you're already using reactive patterns for building your application, use reactive forms.
Template-driven forms are useful for adding a simple form to an application, such as an email list signup form. They're easy to add to an application, but they don't scale as well as reactive forms. If you have very basic form requirements and logic that can be managed solely in the template, use template-driven forms.
Refer Angular documents for more details.
Coming to the question, [(ngModel)]="..."
is basically a binding syntax. In order to use this in your component HTML page, you should import FormsModule in your NgModule (where your component is present). Now [(ngModel)]
is used for a simple two-way binding or this is used in your form for any input HTML element.
On the other hand, to use reactive forms, import ReactiveFormsModule
from the @angular/forms
package and add it to your NgModule's imports array.
For example, if my component HTML content does not have [(ngmodel)] in any HTML element, then I don't need to import FormsModule.
In my below example, I have completely used Reactive Forms and hence I don't need to use FormsModule in my NgModule.
Create GroupsModule:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { GroupsRoutingModule, routedAccountComponents } from './groups-routing.module';
import { ReactiveFormsModule } from '@angular/forms';
import { SharedModule } from '../shared/shared.module';
import { ModalModule } from 'ngx-bootstrap';
@NgModule({
declarations: [
routedAccountComponents
],
imports: [
CommonModule,
ReactiveFormsModule,
GroupsRoutingModule,
SharedModule,
ModalModule.forRoot()
]
})
export class GroupsModule {
}
Create the routing module (separated to main the code and for readability):
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { GroupsComponent } from './all/index.component';
import { CreateGroupComponent } from './create/index.component';
const routes: Routes = [
{
path: '',
redirectTo: 'groups',
pathMatch: 'full'
},
{
path: 'groups',
component: GroupsComponent
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class GroupsRoutingModule { }
export const routedAccountComponents = [
GroupsComponent,
CreateGroupComponent
];
CreateGroupComponent html code
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<label for="name">Group Name</label>
<div class="form-group">
<div class="form-line">
<input type="text" formControlName="name" class="form-control">
</div>
</div>
</form>
CreateGroupComponent ts file
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { DialogResult } from 'src/app/shared/modal';
import { FormGroup, FormControl, AbstractControl } from '@angular/forms';
import { Subject } from 'rxjs';
import { ToastrService } from 'ngx-toastr';
import { validateAllFormFields } from 'src/app/services/validateAllFormFields';
import { HttpErrorResponse } from '@angular/common/http';
import { modelStateFormMapper } from 'src/app/services/shared/modelStateFormMapper';
import { GroupsService } from '../groups.service';
import { CreateGroup } from '../model/create-group.model';
@Component({
selector: 'app-create-group',
templateUrl: './index.component.html',
providers: [LoadingService]
})
export class CreateGroupComponent implements OnInit {
public form: FormGroup;
public errors: string[] = [];
private destroy: Subject<void> = new Subject<void>();
constructor(
private groupService: GroupsService,
private toastr: ToastrService
) { }
private buildForm(): FormGroup {
return new FormGroup({
name: new FormControl('', [Validators.maxLength(254)])
});
}
private getModel(): CreateGroup {
const formValue = this.form.value;
return <CreateGroup>{
name: formValue.name
};
}
public control(name: string): AbstractControl {
return this.form.get(name);
}
public ngOnInit() {
this.form = this.buildForm();
}
public onSubmit(): void {
if (this.form.valid) {
// this.onSubmit();
//do what you need to do
}
}
}
I hope this helps developers to understand as to why and when you need to use FormsModule.
C++20 std::format
This is now the cleanest method in my opinion, as it does not pollute std::cout
state with std::hex
:
main.cpp
#include <format>
#include <string>
int main() {
std::cout << std::format("{:x} {:#x} {}\n", 16, 17, 18);
}
Expected output:
10 0x11 18
Not yet implemented on GCC 10.0.1, Ubuntu 20.04.
But the awesome library that became C++20 and should be the same worked once installed with:
git clone https://github.com/fmtlib/fmt
cd fmt
git checkout 061e364b25b5e5ca7cf50dd25282892922375ddc
mkdir build
cmake ..
sudo make install
main2.cpp
#include <fmt/core.h>
#include <iostream>
int main() {
std::cout << fmt::format("{:x} {:#x} {}\n", 16, 17, 18);
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main2.out main2.cpp -lfmt
./main2.out
Documented at:
More info at: std::string formatting like sprintf
Pre-C++20: cleanly print and restore std::cout
to previous state
main.cpp
#include <iostream>
#include <string>
int main() {
std::ios oldState(nullptr);
oldState.copyfmt(std::cout);
std::cout << std::hex;
std::cout << 16 << std::endl;
std::cout.copyfmt(oldState);
std::cout << 17 << std::endl;
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
Output:
10
17
More details: Restore the state of std::cout after manipulating it
Tested on GCC 10.0.1, Ubuntu 20.04.
Both ways are viable, but they do different things when it comes to inheritance with an overridden static method. Choose the one whose behavior you expect:
class Super {
static whoami() {
return "Super";
}
lognameA() {
console.log(Super.whoami());
}
lognameB() {
console.log(this.constructor.whoami());
}
}
class Sub extends Super {
static whoami() {
return "Sub";
}
}
new Sub().lognameA(); // Super
new Sub().lognameB(); // Sub
Referring to the static property via the class will be actually static and constantly give the same value. Using this.constructor
instead will use dynamic dispatch and refer to the class of the current instance, where the static property might have the inherited value but could also be overridden.
This matches the behavior of Python, where you can choose to refer to static properties either via the class name or the instance self
.
If you expect static properties not to be overridden (and always refer to the one of the current class), like in Java, use the explicit reference.
I just discovered sshj, which seems to have a much more concise API than JSCH (but it requires Java 6). The documentation is mostly by examples-in-the-repo at this point, and usually that's enough for me to look elsewhere, but it seems good enough for me to give it a shot on a project I just started.
I had a similar problem and it was caused by the placement of the Timer initialisation.
It was placed in a method that was invoked oftener.
Try this:
Timer waitTimer;
void exampleMethod() {
if (waitTimer == null ) {
//initialize your Timer here
...
}
The "cancel()" method only canceled the latest Timer. The older ones were ignored an didn't stop running.
# here database details
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');
$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);
echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
}
echo "</select>";
# here username is the column of my table(userregistration)
# it works perfectly
I'm not 100% sure that I understand your question, so tell me if I'm wrong.
If I got it right, you are reading jbytes that are technically signed chars, but really pixel values ranging from 0 to 255, and you're wondering how you should handle them without corrupting the values in the process.
Then, you should do the following:
convert jbytes to unsigned char before doing anything else, this will definetly restore the pixel values you are trying to manipulate
use a larger signed integer type, such as int while doing intermediate calculations, this to make sure that over- and underflows can be detected and dealt with (in particular, not casting to a signed type could force to compiler to promote every type to an unsigned type in which case you wouldn't be able to detect underflows later on)
when assigning back to a jbyte, you'll want to clamp your value to the 0-255 range, convert to unsigned char and then convert again to signed char: I'm not certain the first conversion is strictly necessary, but you just can't be wrong if you do both
For example:
inline int fromJByte(jbyte pixel) {
// cast to unsigned char re-interprets values as 0-255
// cast to int will make intermediate calculations safer
return static_cast<int>(static_cast<unsigned char>(pixel));
}
inline jbyte fromInt(int pixel) {
if(pixel < 0)
pixel = 0;
if(pixel > 255)
pixel = 255;
return static_cast<jbyte>(static_cast<unsigned char>(pixel));
}
jbyte in = ...
int intermediate = fromJByte(in) + 30;
jbyte out = fromInt(intermediate);
Or use a fancy list comprehension, which are supposed to be "computationally more efficient", when working with very very large files/lists
fd = open(filename,'r')
chars = [c for line in fd for c in line if c is not " "]
fd.close()
Btw: The answer that was accepted does not account for the whitespaces...
You don't need an index match formula. You can use this array formula. You have to press CTL + SHIFT + ENTER after you enter the formula.
=MAX(IF((A1:A6=A10)*(B1:B6=B10),C1:F6))
SNAPSHOT
Make sure that you have installed the correct NuGet package
in your console application:
<package id="Microsoft.AspNet.WebApi.Client" version="4.0.20710.0" />
and that you are targeting at least .NET 4.0.
This being said, your GetAllFoos
function is defined to return an IEnumerable<Prospect>
whereas in your ReadAsAsync
method you are passing IEnumerable<Foo>
which obviously are not compatible types.
Install-Package Microsoft.AspNet.WebApi.Client
For anyone else arriving here from Google search on how to do a string replacement on all columns (for example, if one has multiple columns like the OP's 'range' column):
Pandas has a built in replace
method available on a dataframe object.
df.replace(',', '-', regex=True)
Source: Docs
This should work:
cat "$API" >> "$CONFIG"
You need to use the >>
operator to append to a file. Redirecting with >
causes the file to be overwritten. (truncated).
It looks like this can't be done in the current version of POI, based on the fact that this bug:
https://issues.apache.org/bugzilla/show_bug.cgi?id=46136
is still outstanding.
There is a difference between the navigation bar and the status bar. The confusing part is that it looks like one solid feature at the top of the screen, but the areas can actually be separated into two distinct views; a status bar and a navigation bar. The status bar spans from y=0 to y=20 points and the navigation bar spans from y=20 to y=64 points. So the navigation bar (which is where the page title and navigation buttons go) has a height of 44 points, but the status bar and navigation bar together have a total height of 64 points.
Here is a great resource that addresses this question along with a number of other sizing idiosyncrasies in iOS7: http://ivomynttinen.com/blog/the-ios-7-design-cheat-sheet/
public static byte[] ReadImageFile(string imageLocation)
{
byte[] imageData = null;
FileInfo fileInfo = new FileInfo(imageLocation);
long imageFileLength = fileInfo.Length;
FileStream fs = new FileStream(imageLocation, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
imageData = br.ReadBytes((int)imageFileLength);
return imageData;
}
You have to add a MySQL jdbc driver to the classpath.
Either put a MySQL binary jar to tomcat lib folder or add it to we application WEB-INF/lib folder.
You can find binary jar (Change version accordingly): https://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.27
You could use emscripten to compile C++ code into js.
Maybe you are asking for:
Character.toChars(65) // returns ['A']
More info: Character.toChars(int codePoint)
Converts the specified character (Unicode code point) to its UTF-16 representation stored in a char array. If the specified code point is a BMP (Basic Multilingual Plane or Plane 0) value, the resulting char array has the same value as codePoint. If the specified code point is a supplementary code point, the resulting char array has the corresponding surrogate pair.
I'd suggest looking into fetch
. It is the ES5 equivalent and uses Promises. It is much more readable and easily customizable.
const url = "https://stackoverflow.com";
fetch(url)
.then(
response => response.text() // .json(), etc.
// same as function(response) {return response.text();}
).then(
html => console.log(html)
);
_x000D_
In Node.js, you'll need to import fetch
using:
const fetch = require("node-fetch");
If you want to use it synchronously (doesn't work in top scope):
const json = await fetch(url)
.then(response => response.json())
.catch((e) => {});
More Info:
You should definitely have a look at this answer of mine:
and also have a look at all the links included therein.
Tabula/TabulaPDF is currently the best table extraction tool that is available for PDF scraping.
This might help:
git config core.longpaths true
Basic explanation: This answer suggests not to have such setting applied to the global system (to all projects so avoiding --system
or --global
tag) configurations. This command only solves the problem by being specific to the current project.
EDIT:
This is an important answer related to the "permission denied" issue for those whom does not granted to change git settings globally.
You can try this in your Action:
return DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");
And this in your Ajax success:
success: function (resultDateString) {
var date = new Date(resultDateString);
}
Or this in your View: (Javascript plus C#)
var date = new Date('@DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")');
To match pattern
or an empty string, use
^$|pattern
^
and $
are the beginning and end of the string anchors respectively.|
is used to denote alternates, e.g. this|that
.\b
\b
in most flavor is a "word boundary" anchor. It is a zero-width match, i.e. an empty string, but it only matches those strings at very specific places, namely at the boundaries of a word.
That is, \b
is located:
\w
and \W
(either order):
^
and \w
\w
\w
and $
\w
This is not trivial depending on specification.
For a matrix you can use this:
[M,I] = max(A(:))
I is the index of A(:) containing the largest element.
Now, use the ind2sub function to extract the row and column indices of A corresponding to the largest element.
[I_row, I_col] = ind2sub(size(A),I)
Another option to avoid nesting two different environments (like multicols
and enumerate
).
The environment called tasks
from the package with the same name seems to me very easy to customize thanks to a variety of options (pdf guide here).
This code:
\documentclass{article}
\usepackage{tasks}
%\settasks{style=itemize}
\begin{document}
Text text text text text text text text text text text text
text text text text text text text text text text text text
text text text text text text text text text text text text.
\begin{tasks}(2)
\task[*] a
\task[*] b
\task[*] c
\task[*] d
\task[*] e
\task[*] f
\end{tasks}
Text text text text text text text text text text text text
text text text text text text text text text text text text
text text text text text text text text text text text text.
\end{document}
produces this output
The package tasks
was updated in August 2020 and it was originally created specifically for horizontally columned lists (see the screenshot just above here), the motivations behind this are resumed in the guide. If such arrangement of the items/tasks is acceptable, then this may be a good choice since it keeps - IMHO - the code tidy and flexible.
Whatever I understood from my learning and what I think it is is here. I am Quoting some part from a book i learnt this things. Nexus Repository Manager and Nexus Repository Manager OSS started as a repository manager supporting the Maven repository format. While it supports many other repository formats now, the Maven repository format is still the most common and well supported format for build and provisioning tools running on the JVM and beyond. This chapter shows example configurations for using the repository manager with Apache Maven and a number of other tools. The setups take advantage of merging many repositories and exposing them via a repository group. Setting this up is documented in the chapter in addition to the configuration used by specific tools.
A sort of block comment uses an if statement:
if(FALSE) {
all your code
}
It works, but I almost always use the block comment options of my editors (RStudio, Kate, Kwrite).
I don't know about CLI, I had tried, but I couldn't. I deleted using IDE Idea history.
If You use an Intellij Idea, just open History changes.
Tap by main folder of the project -> right click -> local history -> show history.
Then from top to bottom revert changes.
It should help! Good luck!=)
You can use several methods to remove item(s) from an Array:
//1
someArray.shift(); // first element removed
//2
someArray = someArray.slice(1); // first element removed
//3
someArray.splice(0, 1); // first element removed
//4
someArray.pop(); // last element removed
//5
someArray = someArray.slice(0, a.length - 1); // last element removed
//6
someArray.length = someArray.length - 1; // last element removed
If you want to remove element at position x
, use:
someArray.splice(x, 1);
Or
someArray = someArray.slice(0, x).concat(someArray.slice(-x));
Reply to the comment of @chill182: you can remove one or more elements from an array using Array.filter
, or Array.splice
combined with Array.findIndex
(see MDN), e.g.
// non destructive filter > noJohn = John removed, but someArray will not change_x000D_
let someArray = getArray();_x000D_
let noJohn = someArray.filter( el => el.name !== "John" ); _x000D_
log("non destructive filter > noJohn = ", format(noJohn));_x000D_
log(`**someArray.length ${someArray.length}`);_x000D_
_x000D_
// destructive filter/reassign John removed > someArray2 =_x000D_
let someArray2 = getArray();_x000D_
someArray2 = someArray2.filter( el => el.name !== "John" );_x000D_
log("", "destructive filter/reassign John removed > someArray2 =", _x000D_
format(someArray2));_x000D_
log(`**someArray2.length ${someArray2.length}`);_x000D_
_x000D_
// destructive splice /w findIndex Brian remains > someArray3 =_x000D_
let someArray3 = getArray();_x000D_
someArray3.splice(someArray3.findIndex(v => v.name === "Kristian"), 1);_x000D_
someArray3.splice(someArray3.findIndex(v => v.name === "John"), 1);_x000D_
log("", "destructive splice /w findIndex Brian remains > someArray3 =", _x000D_
format(someArray3));_x000D_
log(`**someArray3.length ${someArray3.length}`);_x000D_
_x000D_
// Note: if you're not sure about the contents of your array, _x000D_
// you should check the results of findIndex first_x000D_
let someArray4 = getArray();_x000D_
const indx = someArray4.findIndex(v => v.name === "Michael");_x000D_
someArray4.splice(indx, indx >= 0 ? 1 : 0);_x000D_
log("", "check findIndex result first > someArray4 (nothing is removed) > ",_x000D_
format(someArray4));_x000D_
log(`**someArray4.length (should still be 3) ${someArray4.length}`);_x000D_
_x000D_
function format(obj) {_x000D_
return JSON.stringify(obj, null, " ");_x000D_
}_x000D_
_x000D_
function log(...txt) {_x000D_
document.querySelector("pre").textContent += `${txt.join("\n")}\n`_x000D_
}_x000D_
_x000D_
function getArray() {_x000D_
return [ {name: "Kristian", lines: "2,5,10"},_x000D_
{name: "John", lines: "1,19,26,96"},_x000D_
{name: "Brian", lines: "3,9,62,36"} ];_x000D_
}
_x000D_
<pre>_x000D_
**Results**_x000D_
_x000D_
</pre>
_x000D_
Given a quadratic equation: x2 − 4.0000000 x + 3.9999999 = 0, the exact roots to 10 significant digits are, r1 = 2.000316228 and r2 = 1.999683772.
Using float
and double
, we can write a test program:
#include <stdio.h>
#include <math.h>
void dbl_solve(double a, double b, double c)
{
double d = b*b - 4.0*a*c;
double sd = sqrt(d);
double r1 = (-b + sd) / (2.0*a);
double r2 = (-b - sd) / (2.0*a);
printf("%.5f\t%.5f\n", r1, r2);
}
void flt_solve(float a, float b, float c)
{
float d = b*b - 4.0f*a*c;
float sd = sqrtf(d);
float r1 = (-b + sd) / (2.0f*a);
float r2 = (-b - sd) / (2.0f*a);
printf("%.5f\t%.5f\n", r1, r2);
}
int main(void)
{
float fa = 1.0f;
float fb = -4.0000000f;
float fc = 3.9999999f;
double da = 1.0;
double db = -4.0000000;
double dc = 3.9999999;
flt_solve(fa, fb, fc);
dbl_solve(da, db, dc);
return 0;
}
Running the program gives me:
2.00000 2.00000
2.00032 1.99968
Note that the numbers aren't large, but still you get cancellation effects using float
.
(In fact, the above is not the best way of solving quadratic equations using either single- or double-precision floating-point numbers, but the answer remains unchanged even if one uses a more stable method.)
You'll get it as part of a Visual Studio install (if you included the SDK), or in a standalone SDK install. It'll live somewhere like C:\program files\Microsoft Visual Studio 8\SDK\v2.0\Bin
If you don't already have it, you can download the .NET SDKs from
http://msdn.microsoft.com/en-us/netframework/aa569263.aspx
I was using .net core 3.1 with postgres 12.3. Building on the answer from Tadija Bagaric I ended up with:
using (var connection = new NpgsqlConnection(AppConfig.CommentFilesConnection))
{
string insertUserSql = @"INSERT INTO mytable(comment_id,filename,content)
VALUES( @commentId, @filename, @content) returning id;";
int newUserId = connection.QuerySingle<int>(
insertUserSql,
new
{
commentId = 1,
filename = "foobar!",
content = "content"
}
);
}
where AppConfig is my own class which simply gets a string set for my connection details. This is set within the Startup.cs ConfigureServices method.
i was also getting the same Error, if you are using TortoiseSVN-1.9.5 just do two step Process 1:Click on TSVN.exe tool and 2:Select there on Second Window the Command line for Save on Local Drive with giving the path 3:Click ok Now Restart You Android Studio/IntelliJ
setTimeout
may help out here
$("#message_link").click(function(){
setTimeout(function() {
if (some_conditions...){
$("#header").append("<div><img alt=\"Loader\"src=\"/images/ajax-loader.gif\" /></div>");
}
}, 100);
});
That will cause the div to be appended ~100ms after the click event occurs, if some_conditions are met.
You cannot change the manifest or the resource in the signed-and-sealed APK, except through a software upgrade.
As Wingman said, Google App Engine is a great solution for your scenario.
You can get some information about GAE+Android here: https://developers.google.com/eclipse/docs/appengine_connected_android
And from this Google IO 2012 session: http://www.youtube.com/watch?v=NU_wNR_UUn4
There is a faster way to fix this:
list = [1, 1.0, 1.41, 1.73, 2, 2, 2.0, 2.24, 3, 3, 4, 4, 4, 5, 6, 6, 8, 8, 9, 10]
list2=[]
for value in list:
try:
list2.index(value)
except:
list2.append(value)
list.clear()
for value in list2:
list.append(value)
list2.clear()
print(list)
print(list2)
@Egidius, when creating an XMLHttpRequest, you should use
var xhr = new XMLHttpRequest({mozSystem: true});
What is mozSystem?
mozSystem Boolean: Setting this flag to true allows making cross-site connections without requiring the server to opt-in using CORS. Requires setting mozAnon: true, i.e. this can't be combined with sending cookies or other user credentials. This only works in privileged (reviewed) apps; it does not work on arbitrary webpages loaded in Firefox.
Changes to your Manifest
On your manifest, do not forget to include this line on your permissions:
"permissions": {
"systemXHR" : {},
}
Use minDate as string:
$('#datePickerId').datepicker({minDate: '0'});
This would set today as minimum selectable date .
SQLite doesn't define any particular extension for this, it's your own choice. Personally, I name them with the .sqlite
extension, just so there isn't any ambiguity when I'm looking at my files later.
The problem with me is that I have so many different versions of python, so it opens up a different python3.7 even after I did brew link. I did the following additional steps to make it default after linking
First, open up the document setting up the path of python
nano ~/.bash_profile
Then something like this shows up:
# Setting PATH for Python 3.7
# The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.7/bin:${PATH}"
export PATH
# Setting PATH for Python 3.6
# The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.6/bin:${PATH}"
export PATH
The thing here is that my Python for brew framework is not in the Library Folder!! So I changed the framework for python 3.7, which looks like follows in my system
# Setting PATH for Python 3.7
# The original version is saved in .bash_profile.pysave
PATH="/usr/local/Frameworks/Python.framework/Versions/3.7/bin:${PATH}"
export PATH
Change and save the file. Restart the computer, and typing in python3.7
, I get the python I installed for brew.
Not sure if my case is applicable to everyone, but worth a try. Not sure if the framework path is the same for everyone, please made sure before trying out.
If (list.Count==0){
//you can show your error messages here
} else {
//here comes your datagridview databind
}
You can make your datagrid visible false and make it visible on the else section.
If you are using .net core 2.0 this would be:
Context.Request.Query["id"]
Sample usage:
<a href="@Url.Action("Query",new {parm1=Context.Request.Query["queryparm1"]})">GO</a>
Textarea respects the white-space attribute for the placeholder. https://www.w3schools.com/cssref/pr_text_white-space.asp
Setting it to pre-line solved the problem for me.
textarea {_x000D_
white-space: pre-line;_x000D_
}
_x000D_
<textarea placeholder='This is a line _x000D_
should this be a new line'></textarea>
_x000D_
I have read all answers, but this link was more clear explanation for me about difference between CPU(Processor) and Core. So I'm leaving here some notes from there.
The main difference between CPU and Core is that the CPU is an electronic circuit inside the computer that carries out instruction to perform arithmetic, logical, control and input/output operations while the core is an execution unit inside the CPU that receives and executes instructions.
Take this as a sample code. Replace imageheight and image width with your image dimensions.
<div style="background:yourimage.jpg no-repeat;height:imageheight px;width:imagewidth px">
</div>
<< Mean any given number will be multiply by 2the power
for exp:- 2<<2=2*2'1=4
6<<2'4=6*2*2*2*2*2=64
Try this runner I wrote. It could be helpful.
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
public class ProxyAuthHelper {
public static void main(String[] args) throws Exception {
String tmp = System.getProperty("http.proxyUser", System.getProperty("https.proxyUser"));
if (tmp == null) {
System.out.println("Proxy username: ");
tmp = new Scanner(System.in).nextLine();
}
final String userName = tmp;
tmp = System.getProperty("http.proxyPassword", System.getProperty("https.proxyPassword"));
if (tmp == null) {
System.out.println("Proxy password: ");
tmp = new Scanner(System.in).nextLine();
}
final char[] password = tmp.toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
System.out.println("\n--------------\nProxy auth: " + userName);
return new PasswordAuthentication (userName, password);
}
});
Class<?> clazz = Class.forName(args[0]);
Method method = clazz.getMethod("main", String[].class);
String[] newArgs = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, newArgs.length);
method.invoke(null, new Object[]{newArgs});
}
}
You can flow this code:
Scanner obj= new Scanner(System.in);
String s = obj.nextLine();
I've seen scripts just use variable assignment to do the job:
$ xyz=`echo -e 'foo \n bar'`
$ echo $xyz
foo bar
Whitespace is automatically coalesced and trimmed. One has to be careful of shell metacharacters (potential injection risk).
I would also recommend always double-quoting variable substitutions in shell conditionals:
if [ -n "$var" ]; then
since something like a -o or other content in the variable could amend your test arguments.
Had this problem in vs2017, I already got MVC via nuget but System.Web.Mvc didn't appear in the "Assemblies" list under "Add Reference".
The solution was to select "Extensions" under "Assemblies" in the "Add Reference" dialog.
A big advantage of implementing functions as functors is that they can maintain and reuse state between calls. For example, many dynamic programming algorithms, like the Wagner-Fischer algorithm for calculating the Levenshtein distance between strings, work by filling in a large table of results. It's very inefficient to allocate this table every time the function is called, so implementing the function as a functor and making the table a member variable can greatly improve performance.
Below is an example of implementing the Wagner-Fischer algorithm as a functor. Notice how the table is allocated in the constructor, and then reused in operator()
, with resizing as necessary.
#include <string>
#include <vector>
#include <algorithm>
template <typename T>
T min3(const T& a, const T& b, const T& c)
{
return std::min(std::min(a, b), c);
}
class levenshtein_distance
{
mutable std::vector<std::vector<unsigned int> > matrix_;
public:
explicit levenshtein_distance(size_t initial_size = 8)
: matrix_(initial_size, std::vector<unsigned int>(initial_size))
{
}
unsigned int operator()(const std::string& s, const std::string& t) const
{
const size_t m = s.size();
const size_t n = t.size();
// The distance between a string and the empty string is the string's length
if (m == 0) {
return n;
}
if (n == 0) {
return m;
}
// Size the matrix as necessary
if (matrix_.size() < m + 1) {
matrix_.resize(m + 1, matrix_[0]);
}
if (matrix_[0].size() < n + 1) {
for (auto& mat : matrix_) {
mat.resize(n + 1);
}
}
// The top row and left column are prefixes that can be reached by
// insertions and deletions alone
unsigned int i, j;
for (i = 1; i <= m; ++i) {
matrix_[i][0] = i;
}
for (j = 1; j <= n; ++j) {
matrix_[0][j] = j;
}
// Fill in the rest of the matrix
for (j = 1; j <= n; ++j) {
for (i = 1; i <= m; ++i) {
unsigned int substitution_cost = s[i - 1] == t[j - 1] ? 0 : 1;
matrix_[i][j] =
min3(matrix_[i - 1][j] + 1, // Deletion
matrix_[i][j - 1] + 1, // Insertion
matrix_[i - 1][j - 1] + substitution_cost); // Substitution
}
}
return matrix_[m][n];
}
};
When you first read the body, you have to store it so once you're done with it, you can set a new io.ReadCloser
as the request body constructed from the original data. So when you advance in the chain, the next handler can read the same body.
One option is to read the whole body using ioutil.ReadAll()
, which gives you the body as a byte slice.
You may use bytes.NewBuffer()
to obtain an io.Reader
from a byte slice.
The last missing piece is to make the io.Reader
an io.ReadCloser
, because bytes.Buffer
does not have a Close()
method. For this you may use ioutil.NopCloser()
which wraps an io.Reader
, and returns an io.ReadCloser
, whose added Close()
method will be a no-op (does nothing).
Note that you may even modify the contents of the byte slice you use to create the "new" body. You have full control over it.
Care must be taken though, as there might be other HTTP fields like content-length and checksums which may become invalid if you modify only the data. If subsequent handlers check those, you would also need to modify those too!
If you also want to read the response body, then you have to wrap the http.ResponseWriter
you get, and pass the wrapper on the chain. This wrapper may cache the data sent out, which you can inspect either after, on on-the-fly (as the subsequent handlers write to it).
Here's a simple ResponseWriter
wrapper, which just caches the data, so it'll be available after the subsequent handler returns:
type MyResponseWriter struct {
http.ResponseWriter
buf *bytes.Buffer
}
func (mrw *MyResponseWriter) Write(p []byte) (int, error) {
return mrw.buf.Write(p)
}
Note that MyResponseWriter.Write()
just writes the data to a buffer. You may also choose to inspect it on-the-fly (in the Write()
method) and write the data immediately to the wrapped / embedded ResponseWriter
. You may even modify the data. You have full control.
Care must be taken again though, as the subsequent handlers may also send HTTP response headers related to the response data –such as length or checksums– which may also become invalid if you alter the response data.
Putting the pieces together, here's a full working example:
func loginmw(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Printf("Error reading body: %v", err)
http.Error(w, "can't read body", http.StatusBadRequest)
return
}
// Work / inspect body. You may even modify it!
// And now set a new body, which will simulate the same data we read:
r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
// Create a response wrapper:
mrw := &MyResponseWriter{
ResponseWriter: w,
buf: &bytes.Buffer{},
}
// Call next handler, passing the response wrapper:
handler.ServeHTTP(mrw, r)
// Now inspect response, and finally send it out:
// (You can also modify it before sending it out!)
if _, err := io.Copy(w, mrw.buf); err != nil {
log.Printf("Failed to send out response: %v", err)
}
})
}
function isMobileNumber(evt, sender) { // Allows only 10 numbers // ONKEYPRESS FUNCTION
//evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
var NumValue = $(sender).val();
if (charCode > 31 && (charCode < 48 || charCode > 57)) {//|| NumValue.length > 9) {
return false;
}
return true;}
function isProperMobileNumber(txtMobId) { //// VALIDATOR FUNCTION
var txtMobile = document.getElementById(txtMobId);
if (!isNumeric(txtMobile.value)) { $(txtMobile).css("border-color", "red"); return false; }
if (txtMobile.value.length < 10) {
$(txtMobile).css("border-color", "red");
return false;
}
$(txtMobile).css("border-color", "")
return true; }
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n) }
Why...
This is likely overkill for most people's needs, but, it addresses a number of things that each individual answer above does not. Of the items it addresses, three of them were needed for my needs. With tight bracketing and dropping the comments, this could still remain readable at only 13 lines of code.
This addresses the following:
Usage:
Send original string, search char/string, "R"/"L" for start on right or left side, true/false for case sensitivity. For example, search for "here" case insensitive, in string, start right side.
echo TruncStringAfterString("Now Here Are Some Words Here Now","here","R",false);
Output would be "Now Here Are Some Words ". Changing the "R" to an "L" would output: "Now ".
Here's the function:
function TruncStringAfterString($origString,$truncChar,$startSide,$caseSensitive)
{
if ($caseSensitive==true && strstr($origString,$truncChar)!==false)
{
// IF START RIGHT SIDE:
if (strtoupper($startSide)=="R" || $startSide==false)
{ // Found, strip off all chars from truncChar to end
return substr($origString,0,strrpos($origString,$truncChar));
}
// IF START LEFT SIDE:
elseif (strtoupper($startSide)=="L" || $startSide="" || $startSide==true)
{ // Found, strip off all chars from truncChar to end
return strstr($origString,$truncChar,true);
}
}
elseif ($caseSensitive==false && stristr($origString,$truncChar)!==false)
{
// IF START RIGHT SIDE:
if (strtoupper($startSide)=="R" || $startSide==false)
{ // Found, strip off all chars from truncChar to end
return substr($origString,0,strripos($origString,$truncChar));
}
// IF START LEFT SIDE:
elseif (strtoupper($startSide)=="L" || $startSide="" || $startSide==true)
{ // Found, strip off all chars from truncChar to end
return stristr($origString,$truncChar,true);
}
}
else
{ // NOT found - return origString untouched
return $origString; // Nothing to do here
}
}
to detect when the iframe has loaded and its document is ready?
It's ideal if you can get the iframe to tell you itself from a script inside the frame. For example it could call a parent function directly to tell it it's ready. Care is always required with cross-frame code execution as things can happen in an order you don't expect. Another alternative is to set ‘var isready= true;’ in its own scope, and have the parent script sniff for ‘contentWindow.isready’ (and add the onload handler if not).
If for some reason it's not practical to have the iframe document co-operate, you've got the traditional load-race problem, namely that even if the elements are right next to each other:
<img id="x" ... />
<script type="text/javascript">
document.getElementById('x').onload= function() {
...
};
</script>
there is no guarantee that the item won't already have loaded by the time the script executes.
The ways out of load-races are:
on IE, you can use the ‘readyState’ property to see if something's already loaded;
if having the item available only with JavaScript enabled is acceptable, you can create it dynamically, setting the ‘onload’ event function before setting source and appending to the page. In this case it cannot be loaded before the callback is set;
the old-school way of including it in the markup:
<img onload="callback(this)" ... />
Inline ‘onsomething’ handlers in HTML are almost always the wrong thing and to be avoided, but in this case sometimes it's the least bad option.
An "em" is a typographical unit of width, the width of a wide-ish letter like "m" pronounced "em". Similarly there is an "en". Similarly "en-dash" and "em-dash" for – and —
for my script of python, I use...
To START python script :
start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --exec $DAEMON
To STOP python script :
PID=$(cat $PIDFILE)
kill -9 $PID
rm -f $PIDFILE
P.S.: sorry for poor English, I'm from CHILE :D
I don't understand
days, hours, minutes = td.days, td.seconds // 3600, td.seconds // 60 % 60
how about this
days, hours, minutes = td.days, td.seconds // 3600, td.seconds % 3600 / 60.0
You get minutes and seconds of a minute as a float.
In Python, You can Try...
from encodings.aliases import aliases
alias_values = set(aliases.values())
for encoding in set(aliases.values()):
try:
df=pd.read_csv("test.csv", encoding=encoding)
print('successful', encoding)
except:
pass
This can be one of several solutions:
var text = "http://example.com";
JSON.stringify(text).replace('\"', '\"\'').replace(/.$/, '\'"')
In Linear Search (as per exercise given in book), we need to find value V in given array.
Its simple as scanning the array from 0 <= k < length and comparing each element. If V found, or if scanning reaches length of array, just terminate the loop.
As per my understanding in above problem-
Loop Invariants(Initialization): V is not found in k - 1 iteration. Very first iteration, this would be -1 hence we can say V not found at position -1
Maintainance: In next iteration,V not found in k-1 holds true
Terminatation: If V found in k position or k reaches the length of the array, terminate the loop.
You can use like this:
if (your_edittext.getText().length() > 0 ) {
your_edittext.setSelection(your_edittext.getText().length());
}
Can you add this line to your EditText xml
android:gravity="right"
android:ellipsize="end"
android:paddingLeft="10dp"//you set this as you need
But when any Text writing you should set the paddingleft to zero
you should use this on addTextChangedListener
Another example if you are using Titanium Alloy:
collection.fetch({
data: {
where : JSON.stringify({
page: 1
})
}
});
SELECT dateadd(dd,DAYS,'2013-09-07 00:00:00') DATES
INTO #TEMP1
FROM
(SELECT TOP 365 colorder - 1 AS DAYS from master..syscolumns
WHERE id = -519536829 order by colorder) a
WHERE datediff(dd,dateadd(dd,DAYS,'2013-09-07 00:00:00'),'2013-09-13 00:00:00' ) >= 0
AND dateadd(dd,DAYS,'2013-09-07 00:00:00') <= '2013-09-13 00:00:00'
SELECT * FROM #TEMP1
I found a real cool Grid which I also use for columns. Check it out Simple Grid. Wich this CSS you can simply use:
<div class="grid">
<div class="col-1-2">
<div class="content">
<p>...insert content left side...</p>
</div>
</div>
<div class="col-1-2">
<div class="content">
<p>...insert content right side...</p>
</div>
</div>
</div>
I use it for all my projects.
While running the tensorboard give one more option --host=ip of your system and then you can access it from other system using http://ip of your host system:6006
Do i need to modify the headers and just echo it or something?
exactly.
Send a header("content-type: image/your_image_type");
and the data afterwards.
If you have LaTeX installed you can download as PDF directly from Jupyter notebook with File -> Download as -> PDF via LaTeX (.pdf). Otherwise follow these two steps.
For HTML output, you should now use Jupyter in place of IPython and select File -> Download as -> HTML (.html) or run the following command:
jupyter nbconvert --to html notebook.ipynb
This will convert the Jupyter document file notebook.ipynb into the html output format.
Google Colaboratory is Google's free Jupyter notebook environment that requires no setup and runs entirely in the cloud. If you are using Google Colab the commands are the same, but Google Colab only lets you download .ipynb or .py formats.
Convert the html file notebook.html into a pdf file called notebook.pdf. In Windows, Mac or Linux, install wkhtmltopdf. wkhtmltopdf is a command line utility to convert html to pdf using WebKit. You can download wkhtmltopdf from the linked webpage, or in many Linux distros it can be found in their repositories.
wkhtmltopdf notebook.html notebook.pdf
Original (now almost obsolete) revision: Convert the IPython notebook file to html.
ipython nbconvert --to html notebook.ipynb
You can use the following library: https://github.com/ink-spot/UPCarouselFlowLayout
It's very simple and ofc you do not need to think about details like other answers contain.
Anyone using ButterKnife. You can use like:
@OnTextChanged(R.id.zip_code)
void onZipCodeTextChanged(CharSequence zipCode, int start, int count, int after) {
}
if you state a.redLink{color:red;}
then to keep this on hover and such add a.redLink:hover{color:red;}
This will make sure no other hover states will change the color of your links
Use to_datetime
, there is no need for a format string the parser is man/woman enough to handle it:
In [51]:
pd.to_datetime(df['I_DATE'])
Out[51]:
0 2012-03-28 14:15:00
1 2012-03-28 14:17:28
2 2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]
To access the date/day/time component use the dt
accessor:
In [54]:
df['I_DATE'].dt.date
Out[54]:
0 2012-03-28
1 2012-03-28
2 2012-03-28
dtype: object
In [56]:
df['I_DATE'].dt.time
Out[56]:
0 14:15:00
1 14:17:28
2 14:50:50
dtype: object
You can use strings to filter as an example:
In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]
Out[59]:
date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09
Your string is wider than your format width of 2. So there's no padding to be done.
To substantiate @deceze's claim that the default JSON encoding is UTF-8...
From IETF RFC4627:
JSON text SHALL be encoded in Unicode. The default encoding is UTF-8.
Since the first two characters of a JSON text will always be ASCII characters [RFC0020], it is possible to determine whether an octet stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking at the pattern of nulls in the first four octets.
00 00 00 xx UTF-32BE 00 xx 00 xx UTF-16BE xx 00 00 00 UTF-32LE xx 00 xx 00 UTF-16LE xx xx xx xx UTF-8
functionNameAsString = sys._getframe().f_code.co_name
I wanted a very similar thing because I wanted to put the function name in a log string that went in a number of places in my code. Probably not the best way to do that, but here's a way to get the name of the current function.
It look's as if you forgot to activate you virtual environment
try running python3 -m venv venv
or if you already have virtual environment
set up try to activate it by running source venv/bin/activate
Problem fixed, download https://curl.haxx.se/ca/cacert.pem and put it "somewhere", and add this line in php.ini
:
curl.cainfo = "C:/somewhere/cacert.pem"
PS: I got this error by trying to install module on drupal with xampp.
Add this line into Manifiest File:
android:windowSoftInputMode="adjustResize"
Try this..Worked for me!
public void webLaunch(View view) {
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setVisibility(View.VISIBLE);
View view1=findViewById(R.id.recharge);
view1.setVisibility(View.GONE);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("<your link>");
}
xml code :-
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:visibility="gone"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
--------- OR------------------
String url = "";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
You can do
var color = System.Drawing.ColorTranslator.FromHtml("#FFFFFF");
Or this (you will need the System.Windows.Media
namespace)
var color = (Color)ColorConverter.ConvertFromString("#FFFFFF");
Mark, this is already answered in your previous topic. But OK, here it is again:
Suppose ${list}
points to a List<Object>
, then the following
<c:forEach items="${list}" var="item">
${item}<br>
</c:forEach>
does basically the same as as following in "normal Java":
for (Object item : list) {
System.out.println(item);
}
If you have a List<Map<K, V>>
instead, then the following
<c:forEach items="${list}" var="map">
<c:forEach items="${map}" var="entry">
${entry.key}<br>
${entry.value}<br>
</c:forEach>
</c:forEach>
does basically the same as as following in "normal Java":
for (Map<K, V> map : list) {
for (Entry<K, V> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
The key
and value
are here not special methods or so. They are actually getter methods of Map.Entry
object (click at the blue Map.Entry
link to see the API doc). In EL (Expression Language) you can use the .
dot operator to access getter methods using "property name" (the getter method name without the get
prefix), all just according the Javabean specification.
That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".
For CentOS, RHEL, Amazon Linux: sudo yum install jq
It's netstat -ano|findstr port no
Result would show process id in last column
You can read it from Request
using Request.Form
, your dropdown name is ddlVendor
so pass ddlVendor
key in the formCollection to get its value that is posted by form:
string strDDLValue = Request.Form["ddlVendor"].ToString();
or Use FormCollection
:
[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV,FormCollection form)
{
string strDDLValue = form["ddlVendor"].ToString();
return View(MV);
}
If you want with Model binding then add a property in Model:
public class MobileViewModel
{
public List<tbInsertMobile> MobileList;
public SelectList Vendor { get; set; }
public string SelectedVendor {get;set;}
}
and in View:
@Html.DropDownListFor(m=>m.SelectedVendor , Model.Vendor, "Select Manufacurer")
and in Action:
[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV)
{
string SelectedValue = MV.SelectedVendor;
return View(MV);
}
If you want to post the text of selected item as well, you have to add a hidden field and on drop down selection change set selected item text in the hidden field:
public class MobileViewModel
{
public List<tbInsertMobile> MobileList;
public SelectList Vendor { get; set; }
public string SelectVendor {get;set;}
public string SelectedvendorText { get; set; }
}
use jquery to set hidden field:
<script type="text/javascript">
$(function(){
$("#SelectedVendor").on("change", function {
$("#SelectedvendorText").val($(this).text());
});
});
</script>
@Html.DropDownListFor(m=>m.SelectedVendor , Model.Vendor, "Select Manufacurer")
@Html.HiddenFor(m=>m.SelectedvendorText)
Try to declare these functions as extern "C++"
if your compiler supports this, http://msdn.microsoft.com/en-us/library/s6y4zxec(VS.80).aspx
I tried the solution below, it works on my machine.
<context:property-placeholder location="classpath*:connection.properties" ignore-unresolvable="true" order="1" />
<context:property-placeholder location="classpath*:general.properties" order="2"/>
In case multiple elements are present in the Spring context, there are a few best practices that should be followed:
the order attribute needs to be specified to fix the order in which these are processed by Spring all property placeholders minus the last one (highest order) should have
ignore-unresolvable=”true”
to allow the resolution mechanism to pass to others in the context without throwing an exception
source: http://www.baeldung.com/2012/02/06/properties-with-spring/
If it's an NSMutableString (which I would recommend since you're changing it dynamically), you can use:
[myString deleteCharactersInRange:NSMakeRange([myRequestString length]-1, 1)];