Take a look at this example: JS Fiddle
function toggleClass(element, className){
if (!element || !className){
return;
}
var classString = element.className, nameIndex = classString.indexOf(className);
if (nameIndex == -1) {
classString += ' ' + className;
}
else {
classString = classString.substr(0, nameIndex) + classString.substr(nameIndex+className.length);
}
element.className = classString;
}
There is no such method as slideLeft() and slideRight() which looks like slideUp() and slideDown(), but you can simulate these effects using jQuery’s animate() function.
HTML Code:
<div class="text">Lorem ipsum.</div>
JQuery Code:
$(document).ready(function(){
var DivWidth = $(".text").width();
$(".left").click(function(){
$(".text").animate({
width: 0
});
});
$(".right").click(function(){
$(".text").animate({
width: DivWidth
});
});
});
You can see an example here: How to slide toggle a DIV from Left to Right?
I used this way to do that for multiple blocks without conjuring new JavaScript code:
<a href="#" data-toggle="thatblock">Show/Hide Content</a>
<div id="thatblock" style="display: none">
Here is some description that will appear when we click on the button
</div>
Then a JavaScript portion for all such cases:
$(function() {
$('*[data-toggle]').click(function() {
$('#'+$(this).attr('data-toggle')).toggle();
return false;
});
});
.switch {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
width: 90px;_x000D_
height: 34px;_x000D_
}_x000D_
_x000D_
.switch input {display:none;}_x000D_
_x000D_
.slider {_x000D_
position: absolute;_x000D_
cursor: pointer;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
background-color: #ca2222;_x000D_
-webkit-transition: .4s;_x000D_
transition: .4s;_x000D_
}_x000D_
_x000D_
.slider:before {_x000D_
position: absolute;_x000D_
content: "";_x000D_
height: 26px;_x000D_
width: 26px;_x000D_
left: 4px;_x000D_
bottom: 4px;_x000D_
background-color: white;_x000D_
-webkit-transition: .4s;_x000D_
transition: .4s;_x000D_
}_x000D_
_x000D_
input:checked + .slider {_x000D_
background-color: #2ab934;_x000D_
}_x000D_
_x000D_
input:focus + .slider {_x000D_
box-shadow: 0 0 1px #2196F3;_x000D_
}_x000D_
_x000D_
input:checked + .slider:before {_x000D_
-webkit-transform: translateX(55px);_x000D_
-ms-transform: translateX(55px);_x000D_
transform: translateX(55px);_x000D_
}_x000D_
_x000D_
/*------ ADDED CSS ---------*/_x000D_
.on_x000D_
{_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.on, .off_x000D_
{_x000D_
color: white;_x000D_
position: absolute;_x000D_
transform: translate(-50%,-50%);_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
font-size: 10px;_x000D_
font-family: Verdana, sans-serif;_x000D_
}_x000D_
_x000D_
input:checked+ .slider .on_x000D_
{display: block;}_x000D_
_x000D_
input:checked + .slider .off_x000D_
{display: none;}_x000D_
_x000D_
/*--------- END --------*/_x000D_
_x000D_
/* Rounded sliders */_x000D_
.slider.round {_x000D_
border-radius: 34px;_x000D_
}_x000D_
_x000D_
.slider.round:before {_x000D_
border-radius: 50%;}
_x000D_
<label class="switch"><input type="checkbox" id="togBtn"><div class="slider round"><!--ADDED HTML --><span class="on">Confirmed</span><span class="off">NA</span><!--END--></div></label>
_x000D_
The getElementsByClassName
method is now natively supported by the most recent versions of Firefox, Safari, Chrome, IE and Opera, you could make a function to check if a native implementation is available, otherwise use the Dustin Diaz method:
function getElementsByClassName(node,classname) {
if (node.getElementsByClassName) { // use native implementation if available
return node.getElementsByClassName(classname);
} else {
return (function getElementsByClass(searchClass,node) {
if ( node == null )
node = document;
var classElements = [],
els = node.getElementsByTagName("*"),
elsLen = els.length,
pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
})(classname, node);
}
}
Usage:
function toggle_visibility(className) {
var elements = getElementsByClassName(document, className),
n = elements.length;
for (var i = 0; i < n; i++) {
var e = elements[i];
if(e.style.display == 'block') {
e.style.display = 'none';
} else {
e.style.display = 'block';
}
}
}
var jPlayPause = $("#play-pause");
jPlayPause.text(jPlayPause.hasClass("playing") ? "play" : "pause");
jPlayPause.toggleClass("playing");
This is a piece of thought using jQuery's toggleClass() method.
Suppose you have an element with id="play-pause" and you want to toggle the text between "play" and "pause".
The best option would be to set a class style in CSS like .showMenu
and .hideMenu
with the various styles inside. Then you can do something like
$("#user_button").addClass("showMenu");
Easiest solution
$('.offer').click(function(){
var cc = $(this).attr('checked') == undefined ? false : true;
$(this).find(':checkbox').attr('checked',cc);
});
I dont think adding dual functions inside the toggle function works for a registered click event (Unless I'm missing something)
For example:
$('.btnName').click(function() {
top.$('#panel').toggle(function() {
$(this).animate({
// style change
}, 500);
},
function() {
$(this).animate({
// style change back
}, 500);
});
Use a custom ID if possible if you would like to apply the action to only that button.
<button class="pushDontpush">PUSH ME</button>
$("#pushDontpush").click(function() {
if ($(this).text() == "PUSH ME") {
$(this).text("DON'T PUSH ME");
} else {
$(this).text("PUSH ME");
};
});
Working CodePen: Toggle text in button
Quite a while later, and thanks to @arne, I created this similar small function to handle where the input should be disabled AND hidden, or enabled AND shown:
function toggleInputState(el, on) {
// 'on' = true(visible) or false(hidden)
// If a field is to be shown, enable it; if hidden, disable it.
// Disabling will prevent the field's value from being submitted
$(el).prop('disabled', !on).toggle(on);
}
Then a jQuery object (such as $('input[name="something"]') ) is simply switched using:
toggleInputState(myElement, myBoolean)
To clean this up a little bit and maintain a single line of code (like you would with a toggle()
), you can use a ternary operator so your code winds up looking like this (also using jQuery):
$('#video-over').css('visibility', $('#video-over').css('visibility') == 'hidden' ? 'visible' : 'hidden');
I would suggest you use the below css
.showhideoverlay {
width: 100%;
height: 100%;
right: 0px;
top: 0px;
position: fixed;
background: #000;
opacity: 0.75;
}
You can then use a simple toggle function:
$('a.open').click(function() {
$('div.showhideoverlay').toggle("slow");
});
This will display the overlay menu from right to left. Alternatively, you can use the positioning for changing the effect from top or bottom, i.e. use bottom: 0;
instead of top: 0;
- you will see menu sliding from right-bottom corner.
I just added class hide to the div before "card-body" and it hidden by default.
<div id="collapseOne" class="collapse hide" aria-labelledby="headingOne" data-parent="#accordion">
Setting 'checked' or null instead of true or false respectively will do the work.
// checkbox selection
var $chk=$(':checkbox');
$chk.prop('checked',$chk.is(':checked') ? null:'checked');
Try this...
$('#myelement').toggle(
function () {
$('#another-element').show("slide", {
direction: "right"
}, 1000);
},
function () {
$('#another-element').hide("slide", {
direction: "right"
}, 1000);
});
Note: This method signature was deprecated in jQuery 1.8 and removed in jQuery 1.9. jQuery also provides an animation method named .toggle() that toggles the visibility of elements. Whether the animation or the event method is fired depends on the set of arguments passed, jQuery docs.
The .toggle() method is provided for convenience. It is relatively straightforward to implement the same behavior by hand, and this can be necessary if the assumptions built into .toggle() prove limiting. For example, .toggle() is not guaranteed to work correctly if applied twice to the same element. Since .toggle() internally uses a click handler to do its work, we must unbind click to remove a behavior attached with .toggle(), so other click handlers can be caught in the crossfire. The implementation also calls .preventDefault() on the event, so links will not be followed and buttons will not be clicked if .toggle() has been called on the element, jQuery docs
You toggle between visibility using show and hide with click. You can put condition on visibility if element is visible then hide else show it. Note you will need jQuery UI to use addition effects with show / hide like direction.
$( "#myelement" ).click(function() {
if($('#another-element:visible').length)
$('#another-element').hide("slide", { direction: "right" }, 1000);
else
$('#another-element').show("slide", { direction: "right" }, 1000);
});
Or, simply use toggle instead of click. By using toggle you wont need a condition (if-else) statement. as suggested by T.J.Crowder.
$( "#myelement" ).click(function() {
$('#another-element').toggle("slide", { direction: "right" }, 1000);
});
You are always passing in true to the toggleMethod, so it will always "show" the table. I would create a global variable that you can flip inside the toggle method instead.
Alternatively you can check the visibility state of the table instead of an explicit variable
For a Django solution (which has not been mentioned in the question):
from django.utils.text import Truncator
value = Truncator(value).chars(75)
Have a look at Truncator's source code to appreciate the problem: https://github.com/django/django/blob/master/django/utils/text.py#L66
Concerning truncation with Django: Django HTML truncation
The inArray
function returns the index of the object supplied as the first argument to the function in the array supplied as the second argument to the function.
When inArray
returns 0
it is indicating that the first argument was found at the first position of the supplied array.
To use inArray
within an if statement use:
if(jQuery.inArray("test", myarray) != -1) {
console.log("is in array");
} else {
console.log("is NOT in array");
}
inArray
returns -1
when the first argument passed to the function is not found in the array passed as the second argument.
You can use strcmp()
if you wish to order/compare strings lexicographically. If you just wish to check for equality then ==
is just fine.
If you http request is Post and request.Accept = "application/x-www-form-urlencoded";
then i think you can to get text of respone by code bellow:
var contentEncoding = response.Headers["content-encoding"];
if (contentEncoding != null && contentEncoding.Contains("gzip")) // cause httphandler only request gzip
{
// using gzip stream reader
using (var responseStreamReader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress)))
{
strResponse = responseStreamReader.ReadToEnd();
}
}
else
{
// using ordinary stream reader
using (var responseStreamReader = new StreamReader(response.GetResponseStream()))
{
strResponse = responseStreamReader.ReadToEnd();
}
}
For aspnetcore-3.1, you can also use Problem()
like below;
https://docs.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-3.1
[Route("/error-local-development")]
public IActionResult ErrorLocalDevelopment(
[FromServices] IWebHostEnvironment webHostEnvironment)
{
if (webHostEnvironment.EnvironmentName != "Development")
{
throw new InvalidOperationException(
"This shouldn't be invoked in non-development environments.");
}
var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
return Problem(
detail: context.Error.StackTrace,
title: context.Error.Message);
}
try this
$ cmd='mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'
$ eval $cmd
CONVERT(datetime, '24.04.2012', 104)
Should do the trick. See here for more info: CAST and CONVERT (Transact-SQL)
every minute:
* * * * * /path/to/php /var/www/html/a.php
every 24hours (every midnight):
0 0 * * * /path/to/php /var/www/html/reset.php
See this reference for how crontab works: http://adminschoice.com/crontab-quick-reference, and this handy tool to build cron jobx: http://www.htmlbasix.com/crontab.shtml
If you created imageview using xml file then follow the steps.
Solution 1:
Step 1: Create an XML file
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#cc8181"
>
<ImageView
android:id="@+id/image"
android:layout_width="50dip"
android:layout_height="fill_parent"
android:src="@drawable/icon"
android:layout_marginLeft="3dip"
android:scaleType="center"/>
</LinearLayout>
Step 2: create an Activity
ImageView img= (ImageView) findViewById(R.id.image);
img.setImageResource(R.drawable.my_image);
Solution 2:
If you created imageview from Java Class
ImageView img = new ImageView(this);
img.setImageResource(R.drawable.my_image);
Try using date and time functions (MONTH(), YEAR(), DAY(), MySQL Manual)
This week:
SELECT * FROM jokes WHERE WEEKOFYEAR(date)=WEEKOFYEAR(NOW());
Last week:
SELECT * FROM jokes WHERE WEEKOFYEAR(date)=WEEKOFYEAR(NOW())-1;
It seems that your selector returns an undefined element (Therefore undefined error
is returned)
In case the element really exists, you are calling select2 on an input
element without supplying anything to select2, where it should fetch the data from. Typically, one calls .select2({data: [{id:"firstid", text:"firsttext"}])
.
I have taken Vlad's idea and changed it a little bit. Instead of
grep -rl oldstr path | xargs sed -i 's/oldstr/newstr/g' /dev/null
Which yields
sed: couldn't edit /dev/null: not a regular file
I'm doing in 3 different connections to the remote server
touch deleteme
grep -rl oldstr path | xargs sed -i 's/oldstr/newstr/g' ./deleteme
rm deleteme
Although this is less elegant and requires 2 more connections to the server (maybe there's a way to do it all in one line) it does the job efficiently as well
jars use zip compression so you can use any unzip utility.
Example:
$ unzip myJar.jar -d ./directoryToExtractTo
GregorianCalendar c = GregorianCalendar.from((LocalDate.parse("2016-06-22")).atStartOfDay(ZoneId.systemDefault()));
XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
You can either use the css property Fixed, or if you need something more fine-tuned then you need to use javascript and track the scrollTop property which defines where the user agent's scrollbar location is (0 being at the top ... and x being at the bottom)
.Fixed
{
position: fixed;
top: 20px;
}
or with jQuery:
$('#ParentContainer').scroll(function() {
$('#FixedDiv').css('top', $(this).scrollTop());
});
You can use SUBSTRING
and CONVERT
:
SELECT stuff
FROM table
WHERE conditions
ORDER BY CONVERT(SUBSTRING(name_column, 6), SIGNED INTEGER);
Where name_column
is the column with the "name-" values. The SUBSTRING
removes everything up before the sixth character (i.e. the "name-" prefix) and then the CONVERT
converts the left over to a real integer.
UPDATE: Given the changing circumstances in the comments (i.e. the prefix can be anything), you'll have to throw a LOCATE
in the mix:
ORDER BY CONVERT(SUBSTRING(name_column, LOCATE('-', name_column) + 1), SIGNED INTEGER);
This of course assumes that the non-numeric prefix doesn't have any hyphens in it but the relevant comment says that:
name
can be any sequence of letters
so that should be a safe assumption.
You seem to be doing file name comparisons, so I would just add that OrdinalIgnoreCase
is closest to what NTFS does (it's not exactly the same, but it's closer than InvariantCultureIgnoreCase
)
Chiming in a bit late here, but couldn't resist.
You're question is half-flawed. Let me explain:
The first half of your question, on image replacement, is a valid question, and my opinion is that for a logo, a simple image; an alt attribute; and CSS for its positioning are sufficient.
The second half of your question, on the "SEO value" of the H1 for a logo is the wrong approach to deciding on which elements to use for different types of content.
A logo isn't a primary heading, or even a heading at all, and using the H1 element to markup the logo on each page of your site will do (slightly) more harm than good for your rankings. Semantically, headings (H1 - H6) are appropriate for, well, just that: headings and subheadings for content.
In HTML5, more than one heading is allowed per page, but a logo isn't deserving of one of them. Your logo, which might be a fuzzy green widget and some text is in an image off to the side of the header for a reason - it's sort of a "stamp", not a hierarchical element to structure your content. The first (whether you use more depends on your heading hierarchy) H1 of each page of your site should headline its subject matter. The main primary heading of your index page might be 'The Best Source For Fuzzy Green Widgets in NYC'. The primary heading on another page might be 'Shipping Details for Our Fuzzy Widgets'. On another page, it may be 'About Bert's Fuzzy Widgets Inc.'. You get the idea.
Side note: As incredible as it sounds, don't look at the source of Google-owned web properties for examples of correct markup. This is a whole post unto itself.
To get the most "SEO value" out HTML and its elements, take a look at the HTML5 specs, and make make markup decisions based on (HTML) semantics and value to users before search engines, and you'll have better success with your SEO.
All previous answers are great, and I'd like to plug in one more point.
From generative algorithm models, we can derive any distribution; while we can only obtain the conditional distribution P(Y|X) from the discriminative algorithm models(or we can say they are only useful for discriminating Y’s label), and that's why it is called discriminative model. The discriminative model doesn't assume that the X's are independent given the Y($X_i \perp X_{-i} | Y$) and hence is usually more powerful for calculating that conditional distribution.
Here's a solution that may work better in the case you are referencing objWorksheet.UsedRange.
Excel.Worksheet mySheet = ...(load a workbook, etc);
Excel.Range myRange = mySheet.UsedRange;
var values = (myRange.Value as Object[,]);
int rowNumber = 3, columnNumber = 5;
string cellValue = Convert.ToString(values[rowNumber, columnNumber]);
Following up on Mat's answer (use Cygwin), here are some detailed instructions for : installing gcc on Windows The packages you want are gcc, gdb and make. Cygwin installer lets you install additional packages if you need them.
For me it was like this...
Window->Show View->Other->General->Project Explorer
Or
Window->Open Perspective->Other->Java (default)
This is a common question. In base, the option you're looking for is aggregate
. Assuming your data.frame
is called "mydf", you can use the following.
> aggregate(B ~ A, mydf, sum)
A B
1 1 5
2 2 3
3 3 11
I would also recommend looking into the "data.table" package.
> library(data.table)
> DT <- data.table(mydf)
> DT[, sum(B), by = A]
A V1
1: 1 5
2: 2 3
3: 3 11
You can iterate using the index access,
To avoid O(n^2) complexity you can use two indices, i - current testing index, j - index to store next item and at the end of the cycle new size of the vector.
code:
void erase(std::vector<int>& v, int num)
{
size_t j = 0;
for (size_t i = 0; i < v.size(); ++i) {
if (v[i] != num) v[j++] = v[i];
}
// trim vector to new size
v.resize(j);
}
In such case you have no invalidating of iterators, complexity is O(n), and code is very concise and you don't need to write some helper classes, although in some case using helper classes can benefit in more flexible code.
This code does not use erase
method, but solves your task.
Using pure stl you can do this in the following way (this is similar to the Motti's answer):
#include <algorithm>
void erase(std::vector<int>& v, int num) {
vector<int>::iterator it = remove(v.begin(), v.end(), num);
v.erase(it, v.end());
}
For Windows:
Method 1 (Two keys pressed at a time)
Method 2 (3 keys pressed at a time)
Please note: If you press and hold Ctrl+K for more than two seconds it will start deleting text so try to be quick with it.
I use the above shortcuts, and they work on my Windows system.
Your question almost spells the SQL for this:
DELETE FROM table WHERE id IN (1, 4, 6, 7)
You can save image , save the file in your current directory application and move the file to any directory .
Bitmap btm = new Bitmap(image.width,image.height);
Image img = btm;
img.Save(@"img_" + x + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
FileInfo img__ = new FileInfo(@"img_" + x + ".jpg");
img__.MoveTo("myVideo\\img_" + x + ".jpg");
You need to do it like this,
void Yourfunction(List<DateTime> dates )
{
}
From the docs:
Passes each entry in enum to block. Returns the first for which block is not false. If no object matches, calls ifnone and returns its result when it is specified, or returns nil otherwise.
If no block is given, an enumerator is returned instead.
(1..10).detect {|i| i % 5 == 0 and i % 7 == 0 } #=> nil
(1..100).detect {|i| i % 5 == 0 and i % 7 == 0 } #=> 35
This worked for me:
clients.detect{|client| client.last['client_id'] == '2180' } #=> ["orange", {"client_id"=>"2180"}]
clients.detect{|client| client.last['client_id'] == '999999' } #=> nil
See: http://rubydoc.info/stdlib/core/1.9.2/Enumerable#find-instance_method
I wrote up a way to easily read each line from a file. The Readln(*bufio.Reader) function returns a line (sans \n) from the underlying bufio.Reader struct.
// Readln returns a single line (without the ending \n)
// from the input buffered reader.
// An error is returned iff there is an error with the
// buffered reader.
func Readln(r *bufio.Reader) (string, error) {
var (isPrefix bool = true
err error = nil
line, ln []byte
)
for isPrefix && err == nil {
line, isPrefix, err = r.ReadLine()
ln = append(ln, line...)
}
return string(ln),err
}
You can use Readln to read every line from a file. The following code reads every line in a file and outputs each line to stdout.
f, err := os.Open(fi)
if err != nil {
fmt.Printf("error opening file: %v\n",err)
os.Exit(1)
}
r := bufio.NewReader(f)
s, e := Readln(r)
for e == nil {
fmt.Println(s)
s,e = Readln(r)
}
Cheers!
use panTo(x,y).This will help u
If you wish to have an GUI based broker testing without installing any tool you can use Hive Mqtt web socket for testing your Mosquitto
server
just visit http://www.hivemq.com/demos/websocket-client/ and enter server connection details.
If you got connected means your server is configured properly.
You can also test publish
and subscribe
of messages using this mqtt web socket
You should not calculate speed from position change per time. GPS may have inaccurate positions, but it has accurate speed (above 5km/h). So use the speed from GPS location stamp. And further you should not do that with course, although it works most of the times.
GPS positions, as delivered, are already Kalman filtered, you probably cannot improve, in postprocessing usually you have not the same information like the GPS chip.
You can smooth it, but this also introduces errors.
Just make sure that your remove the positions when the device stands still, this removes jumping positions, that some devices/Configurations do not remove.
I like to do this
input[type="text"]
{
background: rgba(0, 0, 0, 0);
border: none;
outline: none;
}
Setting the outline
property to none
stops the browser from highlighting the box when the cursor enters
One of the advantages of the static factory methods with private constructor(object creation must have been restricted for external classes to ensure instances are not created externally) is that you can create instance-controlled classes. And instance-controlled classes guarantee that no two equal distinct instances exist(a.equals(b) if and only if a==b) during your program is running that means you can check equality of objects with == operator instead of equals method, according to Effective java.
The ability of static factory methods to return the same object from repeated invocations allows classes to maintain strict control over what instances exist at any time. Classes that do this are said to be instance-controlled. There are several reasons to write instance-controlled classes. Instance control allows a class to guarantee that it is a singleton (Item 3) or noninstantiable (Item 4). Also, it allows an immutable class (Item 15) to make the guarantee that no two equal instances exist: a.equals(b) if and only if a==b. If a class makes this guarantee, then its clients can use the == operator instead of the equals(Object) method, which may result in improved performance. Enum types (Item 30) provide this guarantee.
From Effective Java, Joshua Bloch(Item 1,page 6)
Env: macOS Mojave 10.14.4
Install: homebrew
Location:/usr/local/Cellar/mongodb/4.0.3_1
Note :If update version by
brew upgrade mongo
,the folder 4.0.4_1
will be removed and replace with the new version folder
With the release of iOS 7 (September 18th, 2013) apple increased the over-the-air cellular download limit to 100MBs.
Maximum app size remains 2GBs.
If you want to analyze, repair and optimize all tables in all databases in your MySQL server, you can do this in one go from the command line. You will need root to do that though.
mysqlcheck -u root -p --auto-repair --optimize --all-databases
Once you run that, you will be prompted to enter your MySQL root password. After that, it will start and you will see results as it's happening.
Example output:
yourdbname1.yourdbtable1 OK
yourdbname2.yourdbtable2 Table is already up to date
yourdbname3.yourdbtable3
note : Table does not support optimize, doing recreate + analyze instead
status : OK
etc..
etc...
Repairing tables
yourdbname10.yourdbtable10
warning : Number of rows changed from 121378 to 81562
status : OK
If you don't know the root password and are using WHM, you can change it from within WHM by going to: Home > SQL Services > MySQL Root Password
1 is most readable not compatible with all compilers.
No ISO C compiler has a built in type called bool
. ISO C99 compilers have a type _Bool
, and a header which typedef's bool
. So compatability is simply a case of providing your own header if the compiler is not C99 compliant (VC++ for example).
Of course a simpler approach is to compile your C code as C++.
While the OP may be working on a nix platform this answer could help non-nix platforms. I have not experienced the shebang approach work in Microsoft Windows.
Rephrased: The shebang line answers your question of "within my script" but I believe only for Unix-like platforms. Even though it is the Unix shell, outside the script, that actually interprets the shebang line to determine which version of Python interpreter to call. I am not sure, but I believe that solution does not solve the problem for Microsoft Windows platform users.
In the Microsoft Windows world, the simplify the way to run a specific Python version, without environment variables setup specifically for each specific version of Python installed, is just by prefixing the python.exe with the path you want to run it from, such as C:\Python25\python.exe mymodule.py or D:\Python27\python.exe mymodule.py
However you'd need to consider the PYTHONPATH and other PYTHON... environment variables that would point to the wrong version of Python libraries.
For example, you might run: C:\Python2.5.2\python.exe mymodule
Yet, the environment variables may point to the wrong version as such:
PYTHONPATH = D:\Python27
PYTHONLIB = D:\Python27\lib
Loads of horrible fun!
So a non-virtualenv way, in Windows, would be to use a batch file that sets up the environment and calls a specific Python executable via prefixing the python.exe with the path it resides in. This way has additional details you'll have to manage though; such as using command line arguments for either of the "start" or "cmd.exe" command to "save and replace the "console" environment" if you want the console to stick around after the application exits.
Your question leads me to believe you have several Python modules, each expecting a certain version of Python. This might be solvable "within" the script by having a launching module which uses the subprocess module. Instead of calling mymodule.py you would call a module that calls your module; perhaps launch_mymodule.py
import sys
import subprocess
if sys.argv[2] == '272':
env272 = {
'PYTHONPATH': 'blabla',
'PYTHONLIB': 'blabla', }
launch272 = subprocess.Popen('D:\\Python272\\python.exe mymodule.py', env=env272)
if sys.argv[1] == '252'
env252 = {
'PYTHONPATH': 'blabla',
'PYTHONLIB': 'blabla', }
launch252 = subprocess.Popen('C:\\Python252\\python.exe mymodule.py', env=env252)
I have not tested this.
Try the Select helper class and see if that makes any difference?
String valueToSelect= "Germany";
WebElement select = driver.findElement(By.id("selection"));
Select dropDown = new Select(select);
String selected = dropDown.getFirstSelectedOption().getText();
if(selected.equals(valueToSelect)) {//do stuff already selected}
List<WebElement> Options = dropDown.getOptions();
for(WebElement option:Options){
if(option.getText().equals(valueToSelect)){
option.click();
}
}
Use a Requirements File (see link to JetBrains documentation)
In my case I needed arrow
. So, I added
arrow==0.7.0
to my projects requirements.txt
Then Intellij prompted me to add the library the first time that I wrote import arrow
in a Python script
I would checkout the remote file from the "master" (the remote/origin repository) like this:
git checkout master <FileWithPath>
Example: git checkout master components/indexTest.html
SELECT *
FROM sys.tables t
INNER JOIN sys.objects o on o.object_id = t.object_id
WHERE o.is_ms_shipped = 0;
This answer to a similar question describes how to extend the properties plugin so it can use a remote descriptor for the properties file. The descriptor is basically a jar artifact containing a properties file (the properties file is included under src/main/resources).
The descriptor is added as a dependency to the extended properties plugin so it is on the plugin's classpath. The plugin will search the classpath for the properties file, read the file''s contents into a Properties instance, and apply those properties to the project's configuration so they can be used elsewhere.
Beautiful! Your solution was 99%... instead of "this.scrollY", I used "$(window).scrollTop()". What's even better is that this solution only requires the jQuery1.2.6 library (no additional libraries needed).
The reason I wanted that version in particular is because that's what ships with MVC currently.
Here's the code:
$(document).ready(function() {
$("#topBar").css("position", "absolute");
});
$(window).scroll(function() {
$("#topBar").css("top", $(window).scrollTop() + "px");
});
you get the detail information from Apple Dateformatter Document.If you want to set the dateformat for your dateString, see this link , the detail dateformat you can get here for e.g , do like
let formatter = DateFormatter()
// initially set the format based on your datepicker date / server String
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: Date()) // string purpose I add here
// convert your string to date
let yourDate = formatter.date(from: myString)
//then again set the date format whhich type of output you need
formatter.dateFormat = "dd-MMM-yyyy"
// again convert your date to string
let myStringafd = formatter.string(from: yourDate!)
print(myStringafd)
you get the output as
nginx is useful for forwarding HTTP on many platforms including Windows. It's easy to setup and extend with more advanced configuration. A basic configuration could look something like this:
events {}
http {
server {
listen 192.168.1.111:4422;
location / {
proxy_pass http://192.168.2.33:80/;
}
}
}
When you receive this exception, make sure to expand the detail and look at the inner exception details as it will provide details on why the login failed. In my case the connection string contained a user that did not have access to my database.
Regardless of whether you use Integrated Security (the context of the logged in Windows User) or an individual SQL account, make sure that the user has proper access under 'Security' for the database you are trying to access to prevent this issue.
Here is the most recent code. Simply include #import "UIViewController+NumPadReturn.h" in your viewController.
Here is the .h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface UIViewController (NumPadReturn)
@end
And the .m
#import "UIViewController+NumPadReturn.h"
@implementation UIViewController (NumPadReturn)
-(void) viewDidLoad{
// add observer for the respective notifications (depending on the os version)
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification
object:nil];
} else {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
}
}
- (void)keyboardWillShow:(NSNotification *)note {
// if clause is just an additional precaution, you could also dismiss it
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 3.2) {
[self addButtonToKeyboard];
}
}
- (void)keyboardDidShow:(NSNotification *)note {
// if clause is just an additional precaution, you could also dismiss it
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
[self addButtonToKeyboard];
}
}
- (void)addButtonToKeyboard {
// create custom button
UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
doneButton.frame = CGRectMake(0, 163, 106, 53);
doneButton.adjustsImageWhenHighlighted = NO;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.0) {
[doneButton setImage:[UIImage imageNamed:@"DoneUp3.png"] forState:UIControlStateNormal];
[doneButton setImage:[UIImage imageNamed:@"DoneDown3.png"] forState:UIControlStateHighlighted];
} else {
[doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal];
[doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted];
}
[doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];
// locate keyboard view
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
UIView* keyboard;
for(int i=0; i<[tempWindow.subviews count]; i++) {
keyboard = [tempWindow.subviews objectAtIndex:i];
// keyboard found, add the button
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES)
[keyboard addSubview:doneButton];
} else {
if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
[keyboard addSubview:doneButton];
}
}
}
- (void)doneButton:(id)sender {
NSLog(@"doneButton");
[self.view endEditing:TRUE];
}
@end
A very simple hack is to use the json import instead of csv. For example instead of csv.writer just do the following:
fd = codecs.open(tempfilename, 'wb', 'utf-8')
for c in whatever :
fd.write( json.dumps(c) [1:-1] ) # json dumps writes ["a",..]
fd.write('\n')
fd.close()
Basically, given the list of fields in correct order, the json formatted string is identical to a csv line except for [ and ] at the start and end respectively. And json seems to be robust to utf-8 in python 2.*
This is almost like the other answer but you don't need a scatter
plot at all, you can simply specify a scatter-plot-like format (fmt
-parameter) for errorbar
:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
e = [0.5, 1., 1.5, 2.]
plt.errorbar(x, y, yerr=e, fmt='o')
plt.show()
Result:
A list of the avaiable fmt
parameters can be found for example in the plot
documentation:
character description
'-' solid line style
'--' dashed line style
'-.' dash-dot line style
':' dotted line style
'.' point marker
',' pixel marker
'o' circle marker
'v' triangle_down marker
'^' triangle_up marker
'<' triangle_left marker
'>' triangle_right marker
'1' tri_down marker
'2' tri_up marker
'3' tri_left marker
'4' tri_right marker
's' square marker
'p' pentagon marker
'*' star marker
'h' hexagon1 marker
'H' hexagon2 marker
'+' plus marker
'x' x marker
'D' diamond marker
'd' thin_diamond marker
'|' vline marker
'_' hline marker
I don't know much about jQuery, but try this:
row_id = "#5";
row = $("body").find(row_id);
Edit: Of course, if the variable is a number, you have to add "#"
to the front:
row_id = 5
row = $("body").find("#"+row_id);
try
block should be around open. Not around prompt.
while True:
prompt = input("\n Hello to Sudoku valitator,"
"\n \n Please type in the path to your file and press 'Enter': ")
try:
sudoku = open(prompt, 'r').readlines()
except FileNotFoundError:
print("Wrong file or file path")
else:
break
request.stream
is the stream of raw data passed to the application by the WSGI server. No parsing is done when reading it, although you usually want request.get_data()
instead.
data = request.stream.read()
The stream will be empty if it was previously read by request.data
or another attribute.
Use exceljs library for creating and writing into existing excel sheets.
You can check this tutorial for detailed explanation.
I have always used the following:
If Request.QueryString("MyQueryString") IsNot Nothing Then
But only because syntactically it reads better.
When testing for a valid QueryString entry I also use the following:
If Not String.IsNullOrEmpty(Request.QueryString("MyQueryString")) Then
These are just the methods I have always used so I could not justify their usage other than they make the most sense to me when reading back code.
Keep in mind regexp are greedy, so if you are just searching within the version number string and not within a bigger text, use ^ and $ to mark start and end of your string. The regexp from Greg seems to work fine (just gave it a quick try in my editor), but depending on your library/language the first part can still match the "*" within the wrong version numbers. Maybe I am missing something, as I haven't used Regexp for a year or so.
This should make sure you can only find correct version numbers:
^(\*|\d+(\.\d+)*(\.\*)?)$
edit: actually greg added them already and even improved his solution, I am too slow :)
You want the list items to line up next to each other, but not really be inline elements. So float them instead:
ol.widgets li {
float: left;
margin-left: 10px;
}
I don't know any MATLAB and I've never used it, but it seems to me you are dividing. Why? Something like this will be much faster:
d = 1/norm(V)
V1 = V * d
@Autowired + @Qualifier will work only with spring DI, if you want to use some other DI in future @Resource is good option.
other difference which I found very significant is @Qualifier does not support dynamic bean wiring, as @Qualifier does not support placeholder, while @Resource does it very well.
For example: if you have an interface with multiple implementations like this
interface parent {
}
@Service("actualService")
class ActualService implements parent{
}
@Service("stubbedService")
class SubbedService implements parent{
}
with @Autowired & @Qualifier you need to set specific child implementation like
@Autowired
@Qualifier("actualService") or
@Qualifier("stubbedService")
Parent object;
which does not provide placeholder while with @Resource you can put placeholder and use property file to inject specific child implementation like
@Resource(name="${service.name}")
Parent object;
where service.name is set in property file as
#service.name=actualService
service.name=stubbedService
Hope that helps someone :)
Not just mvn
, for any util, you can find out yourself by giving yum whatprovides {command_name}
If a parameter is expected to have a specific property, you can document that property by providing an additional @param tag. For example, if an employee parameter is expected to have name and department properties, you can document it as follows:
/**
* Assign the project to a list of employees.
* @param {Object[]} employees - The employees who are responsible for the project.
* @param {string} employees[].name - The name of an employee.
* @param {string} employees[].department - The employee's department.
*/
function(employees) {
// ...
}
If a parameter is destructured without an explicit name, you can give the object an appropriate one and document its properties.
/**
* Assign the project to an employee.
* @param {Object} employee - The employee who is responsible for the project.
* @param {string} employee.name - The name of the employee.
* @param {string} employee.department - The employee's department.
*/
Project.prototype.assign = function({ name, department }) {
// ...
};
Source: JSDoc
HTML: text/html
, full-stop.
XHTML: application/xhtml+xml
, or only if following HTML compatbility guidelines, text/html
. See the W3 Media Types Note.
XML: text/xml
, application/xml
(RFC 2376).
There are also many other media types based around XML, for example application/rss+xml
or image/svg+xml
. It's a safe bet that any unrecognised but registered ending in +xml
is XML-based. See the IANA list for registered media types ending in +xml
.
(For unregistered x-
types, all bets are off, but you'd hope +xml
would be respected.)
You can use .on() to capture multiple events and then test for touch on the screen, e.g.:
$('#selector')
.on('touchstart mousedown', function(e){
e.preventDefault();
var touch = e.touches[0];
if(touch){
// Do some stuff
}
else {
// Do some other stuff
}
});
If you've got the Java EE JDK with Glassfish, it's in glassfish3/glassfish/modules/javax.servlet-api.jar.
Checking if line segments intersect is very easy with Shapely library using intersects
method:
from shapely.geometry import LineString
line = LineString([(0, 0), (1, 1)])
other = LineString([(0, 1), (1, 0)])
print(line.intersects(other))
# True
line = LineString([(0, 0), (1, 1)])
other = LineString([(0, 1), (1, 2)])
print(line.intersects(other))
# False
import com.thoughtworks.selenium.Selenium;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
//-------------------------------------------------------------------------
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.Action; /*
Move only
@param o WebElement to move
@param d WebElement destination element
*/
m.drag={o,d->
def lo=o.location;
def ld=d.location;
int di=ld.y - lo.y;
int inc,lim
if (di<0)
{ inc=-1
lim=ld.y+d.size.height
}
else
{ inc=1
lim=ld.y
}
def fes={
int act=o.location.y;
println "act=${act} ${lim}";
if (inc > 0)
return !(act>lim)
else
return !(act<lim)
}
def b =new Actions(driver);
b.clickAndHold(o).perform();
while ( fes() ){
b.moveByOffset(0,inc);b.perform();sleep(20);
}
//
b.release(m.ori).perform();
}//drag
It appears that completely uninstalling Git, restarting (the classic Windows cure), and reinstalling Git was the cure. I also wiped out all bash config files which were left over (they were manually created). Everything is fast again.
If for some reason reinstalling isn't possible (or desirable), then I would definitely try changing the PS1 variable referenced in Chris Dolan's answer; it resulted in significant speedups in certain operations.
Kind of depends on where the value you want to insert is coming from. If you want to insert the current time you can use CURRENT_TIMESTAMP
as shown in other answers (or SYSTIMESTAMP
).
If you have a time as a string and want to convert it to a timestamp, use an expression like
to_timestamp(:timestamp_as_string,'MM/DD/YYYY HH24:MI:SS.FF3')
The time format components are, I hope, self-explanatory, except that FF3
means 3 digits of sub-second precision. You can go as high as 6 digits of precision.
If you are inserting from an application, the best answer may depend on how the date/time value is stored in your language. For instance you can map certain Java objects directly to a TIMESTAMP
column, but you need to understand the JDBC
type mappings.
As some people have mentioned before, this very well could be a simpler problem having to do with one java installation taking precedence over the other.
In my case it was java 8 being overshadowed by a default newer java.
I installed java 8:
sudo apt-get install openjdk-8-jdk
Then I updated the installed java to be the new default:
sudo update-alternatives --config java
Whereby I selected java 8's id number.
After doing these (pretty simple) steps, I could just run sdkmanager without error.
Hope this helps someone!
// Before C++11
// I used following methods:
// 1.
int A[] = {10, 20, 30}; // original array A
unsigned sizeOfA = sizeof(A)/sizeof(A[0]); // calculate the number of elements
// declare vector vArrayA,
std::vector<int> vArrayA(sizeOfA); // make room for all
// array A integers
// and initialize them to 0
for(unsigned i=0; i<sizeOfA; i++)
vArrayA[i] = A[i]; // initialize vector vArrayA
//2.
int B[] = {40, 50, 60, 70}; // original array B
std::vector<int> vArrayB; // declare vector vArrayB
for (unsigned i=0; i<sizeof(B)/sizeof(B[0]); i++)
vArrayB.push_back(B[i]); // initialize vArrayB
//3.
int C[] = {1, 2, 3, 4}; // original array C
std::vector<int> vArrayC; // create an empty vector vArrayC
vArrayC.resize(sizeof(C)/sizeof(C[0])); // enlarging the number of
// contained elements
for (unsigned i=0; i<sizeof(C)/sizeof(C[0]); i++)
vArrayC.at(i) = C[i]; // initialize vArrayC
// A Note:
// Above methods will work well for complex arrays
// with structures as its elements.
Say your string is:
let str = `word1
word2;word3,word4,word5;word7
word8,word9;word10`;
You want to split the string by the following delimiters:
You could split the string like this:
let rawElements = str.split(new RegExp('[,;\n]', 'g'));
Finally, you may need to trim the elements in the array:
let elements = rawElements.map(element => element.trim());
Use the following method.
self.imageView_VedioContainer
is the container view of your AVPlayer
.
- (void)playMedia:(UITapGestureRecognizer *)tapGesture
{
playerViewController = [[AVPlayerViewController alloc] init];
playerViewController.player = [AVPlayer playerWithURL:[[NSBundle mainBundle]
URLForResource:@"VID"
withExtension:@"3gp"]];
[playerViewController.player play];
playerViewController.showsPlaybackControls =YES;
playerViewController.view.frame=self.imageView_VedioContainer.bounds;
[playerViewController.view setAutoresizingMask:UIViewAutoresizingNone];// you can comment this line
[self.imageView_VedioContainer addSubview: playerViewController.view];
}
Actually, there are two ways to include images in email.
The first way ensures that the user will see the image, even if in some cases it’s only as an attachment to the message. This method is exactly what we call as “embedding images in email" in daily life.
Essentially, you’re attaching the image to the email. The plus side is that, in one way or another, the user is sure to get the image. While the downside is two fold. Firstly, spam filters look for large, embedded images and often give you a higher spam score for embedding images in email (Lots of spammers use images to avoid having the inappropriate content in their emails read by the spam filters.). Secondly, if you pay to send your email by weight or kilobyte, this increases the size of your message. If you’re not careful, it can even make your message too big for the parameters of the email provider.
The second way to include images (and the far more common way) is the same way that you put an image on a web page. Within the email, you provide a url that is the reference to the image’s location on your server, exactly the same way that you would on a web page. This has several benefits. Firstly, you won’t get caught for spamming or for your message “weighing” too much because of the image. Secondly, you can make changes to the images after the email has been sent if you find errors in them. On the flip side, your recipient will need to actively turn on image viewing in their email client to see your images.
jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div
(or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.
There are two other solutions which involve assigning to an index one past the end of the list. Here is a solution that does use append
.
resultsa <- list(1,2,3,4,5)
resultsb <- list(6,7,8,9,10)
resultsc <- list(11,12,13,14,15)
outlist <- list(resultsa)
outlist <- append(outlist, list(resultsb))
outlist <- append(outlist, list(resultsc))
which gives your requested format
> str(outlist)
List of 3
$ :List of 5
..$ : num 1
..$ : num 2
..$ : num 3
..$ : num 4
..$ : num 5
$ :List of 5
..$ : num 6
..$ : num 7
..$ : num 8
..$ : num 9
..$ : num 10
$ :List of 5
..$ : num 11
..$ : num 12
..$ : num 13
..$ : num 14
..$ : num 15
How about this?
enum class ErrorCodes : int{
InvalidInput = 0
};
std::cout << ((int)error == 0 ? "InvalidInput" : "") << std::endl;
etc... I know this is a highly contrived example but I think it has application where applicable and needed and is certainly shorter than writing a script for it.
In C++, nested classes are not connected to any instance of the outer class. If you want bar
to access non-static members of foo
, then bar
needs to have access to an instance of foo
. Maybe something like:
class bar {
public:
int getA(foo & f ) {return foo.a;}
};
Or maybe
class bar {
private:
foo & f;
public:
bar(foo & g)
: f(g)
{
}
int getA() { return f.a; }
};
In any case, you need to explicitly make sure you have access to an instance of foo
.
Assuming that both data1()
and data2()
are in the same class, then another alternative is to make data1()
static.
private static void data1()
{
}
private static void data2()
{
data1();
}
In order to remove all subviews Syntax :
- (void)makeObjectsPerformSelector:(SEL)aSelector;
Usage :
[self.View.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
This method is present in NSArray.h file and uses NSArray(NSExtendedArray) interface
another solution, cut the string in 2 and put a string in between.
var str = jQuery('#selector').text();
var strlength = str.length;
strf = str.substr(0 , strlength - 5);
strb = str.substr(strlength - 5 , 5);
jQuery('#selector').html(strf + 'inserted' + strb);
disable the button on click, enable it after the operation completes
$(document).ready(function () {
$("#btn").on("click", function() {
$(this).attr("disabled", "disabled");
doWork(); //this method contains your logic
});
});
function doWork() {
alert("doing work");
//actually this function will do something and when processing is done the button is enabled by removing the 'disabled' attribute
//I use setTimeout so you can see the button can only be clicked once, and can't be clicked again while work is being done
setTimeout('$("#btn").removeAttr("disabled")', 1500);
}
I know this is the old one. But this may help others.
I have added SP calling function between BEGIN/END. Here is a working script.
ALTER Proc [dbo].[DepartmentAddOrEdit]
@Id int,
@Code varchar(100),
@Name varchar(100),
@IsActive bit ,
@LocationId int,
@CreatedBy int,
@UpdatedBy int
AS
IF(@Id = 0)
BEGIN
INSERT INTO Department (Code,Name,IsActive,LocationId,CreatedBy,UpdatedBy,CreatedAt)
VALUES(@Code,@Name,@IsActive,@LocationId,@CreatedBy,@UpdatedBy,CURRENT_TIMESTAMP)
EXEC dbo.LogAdd @CreatedBy,'DEPARTMENT',@Name
END
ELSE
UPDATE Department SET
Code = @Code,
Name = @Name,
IsActive = @IsActive,
LocationId = @LocationId,
CreatedBy = @CreatedBy,
UpdatedBy = @UpdatedBy,
UpdatedAt = CURRENT_TIMESTAMP
where Id = @Id
I prefer using a separate file for ie rules, as described earlier.
<!--[if IE]><link rel="stylesheet" type="text/css" href="ie-style.css"/><![endif]-->
And inside it you can set up rules for different versions of ie using this:
.abc {...} /* ALL MSIE */
*html *.abc {...} /* MSIE 6 */
*:first-child+html .abc {...} /* MSIE 7 */
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
private const string strconneciton = "Data Source=.;Initial Catalog=Employees;Integrated Security=True";
SqlConnection con = new SqlConnection(strconneciton);
private void button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into EmployeeData (Name,S/O,Address,Phone,CellNo,CNICNO,LicenseNo,LicenseDistrict,LicenseValidPhoto,ReferenceName,ReferenceContactNo) values ( '" + textName.Text + "','" + textSO.Text + "','" + textAddress.Text + "','" + textPhone.Text + "','" + textCell.Text + "','" + textCNIC.Text + "','" + textLicenseNo.Text + "','" + textLicenseDistrict.Text + "','" + textLicensePhoto.Text + "','" + textReferenceName.Text + "','" + textContact.Text + "' )", con);
cmd.ExecuteNonQuery();
con.Close();
}
basically set.seed() function will help to reuse the same set of random variables , which we may need in future to again evaluate particular task again with same random varibales
we just need to declare it before using any random numbers generating function.
The default pager is stdout. The stdout has the column limitation, so the output would be wrapped. You could set other tools as pager to format the output. There are two methods. One is to limit the column, the other is to processed it in vim.
The first method:
? ~ echo $COLUMNS
179
mysql> nopager
PAGER set to stdout
mysql> pager cut -c -179
PAGER set to 'cut -c -179'
mysql> select * from db;
+-----------+------------+------------+-------------+-------------+-------------+-------------+-------------+-----------+------------+-----------------+------------+------------+-
| Host | Db | User | Select_priv | Insert_priv | Update_priv | Delete_priv | Create_priv | Drop_priv | Grant_priv | References_priv | Index_priv | Alter_priv |
+-----------+------------+------------+-------------+-------------+-------------+-------------+-------------+-----------+------------+-----------------+------------+------------+-
| % | test | | Y | Y | Y | Y | Y | Y | N | Y | Y | Y |
| % | test\_% | | Y | Y | Y | Y | Y | Y | N | Y | Y | Y |
| localhost | phpmyadmin | phpmyadmin | Y | Y | Y | Y | Y | Y | N | Y | Y | Y |
| localhost | it | it | Y | Y | Y | Y | Y | Y | N | Y | Y | Y |
+-----------+------------+------------+-------------+-------------+-------------+-------------+-------------+-----------+------------+-----------------+------------+------------+-
4 rows in set (0.00 sec)
mysql>
The output is not complete. The content fits to your screen.
The second one:
Set vim mode to nowrap in your .vimrc
? ~ tail ~/.vimrc
" no-wrap for myslq cli
set nowrap
mysql> pager vim -
PAGER set to 'vim -'
mysql> select * from db;
Vim: Reading from stdin...
+-----------+------------+------------+-------------+-------------+----------
| Host | Db | User | Select_priv | Insert_priv | Update_pr
+-----------+------------+------------+-------------+-------------+----------
| % | test | | Y | Y | Y
| % | test\_% | | Y | Y | Y
| localhost | phpmyadmin | phpmyadmin | Y | Y | Y
| localhost | it | it | Y | Y | Y
+-----------+------------+------------+-------------+-------------+----------
~
~
~
Use the below method to allow css styles in innerhtml
.
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
.
.
.
.
html: SafeHtml;
constructor(protected _sanitizer: DomSanitizer) {
this.html = this._sanitizer.bypassSecurityTrustHtml(`
<html>
<head></head>
<body>
<div style="display:flex; color: blue;">
<div>
<h1>Hello World..!!!!!</h1>
</div>
</div>
</body>
</html>`);
}
Example code stackblitz
Or use the below method to write directly in html. https://gist.github.com/klihelp/4dcac910124409fa7bd20f230818c8d1
This algorithm is not optimal for winning the game, but it is fairly optimal in terms of performance and amount of code needed:
if(can move neither right, up or down)
direction = left
else
{
do
{
direction = random from (right, down, up)
}
while(can not move in "direction")
}
While awk
's printf
can be used, you may want to look into pr
or (on BSDish systems) rs
for formatting.
An instance variable is a variable that is a member of an instance of a class (i.e., associated with something created with a new
), whereas a class variable is a member of the class itself.
Every instance of a class will have its own copy of an instance variable, whereas there is only one of each static (or class) variable, associated with the class itself.
What’s the difference between a class variable and an instance variable?
This test class illustrates the difference:
public class Test {
public static String classVariable = "I am associated with the class";
public String instanceVariable = "I am associated with the instance";
public void setText(String string){
this.instanceVariable = string;
}
public static void setClassText(String string){
classVariable = string;
}
public static void main(String[] args) {
Test test1 = new Test();
Test test2 = new Test();
// Change test1's instance variable
test1.setText("Changed");
System.out.println(test1.instanceVariable); // Prints "Changed"
// test2 is unaffected
System.out.println(test2.instanceVariable); // Prints "I am associated with the instance"
// Change class variable (associated with the class itself)
Test.setClassText("Changed class text");
System.out.println(Test.classVariable); // Prints "Changed class text"
// Can access static fields through an instance, but there still is only one
// (not best practice to access static variables through instance)
System.out.println(test1.classVariable); // Prints "Changed class text"
System.out.println(test2.classVariable); // Prints "Changed class text"
}
}
It seems daft, but I think when you use the same bind variable twice you have to set it twice:
cmd.Parameters.Add("VarA", "24");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarC", "1234");
cmd.Parameters.Add("VarC", "1234");
Certainly that's true with Native Dynamic SQL in PL/SQL:
SQL> begin
2 execute immediate 'select * from emp where ename=:name and ename=:name'
3 using 'KING';
4 end;
5 /
begin
*
ERROR at line 1:
ORA-01008: not all variables bound
SQL> begin
2 execute immediate 'select * from emp where ename=:name and ename=:name'
3 using 'KING', 'KING';
4 end;
5 /
PL/SQL procedure successfully completed.
I use laravel 7.x and I used this as a workaround:->get()->pluck('id')->toArray();
it gives back an array of ids [50,2,3]
and this is the whole query I used:
$article_tags = DB::table('tags')
->join('taggables', function ($join) use ($id) {
$join->on('tags.id', '=', 'taggables.tag_id');
$join->where([
['taggable_id', '=', $id],
['taggable_type','=','article']
]);
})->select('tags.id')->get()->pluck('id')->toArray();
Try your code like this:
var app = express();
app.get('/test', function(req, res) {
res.sendFile('views/test.html', {root: __dirname })
});
Use res.sendFile instead of reading the file manually so express can handle setting the content-type properly for you.
You don't need the app.engine
line, as that is handled internally by express.
Make sure your .NET version 4.5 or greater
The comparison needs to be evaluated fully inside EL ${ ... }
, not outside.
<c:if test="${values.type eq 'object'}">
As to the docs, those ${}
things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.
<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />
By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass()
and then Class#getSimpleName()
instead of adding a custom getter.
<c:forEach items="${list}" var="value">
<c:if test="${value['class'].simpleName eq 'Object'}">
<!-- code here -->
</c:if>
</c:forEeach>
It's only possible when the server sends this header: Access-Control-Allow-Origin: *
If this is your code then you can setup it like this (PHP):
header('Access-Control-Allow-Origin: *');
In a Helper file,
Your can use Route::current()->uri()
to get current URL.
Hence, If you compare your route name to set active class on menu then it would be good if you use
Route::currentRouteName()
to get the name of route and compare
You can get everything through ExternalContext
. In JSF 1.x, you can get the raw HttpServletResponse
object by ExternalContext#getResponse()
. In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream()
without the need to grab the HttpServletResponse
from under the JSF hoods.
On the response, you should set the Content-Type
header so that the client knows which application to associate with the provided file. And, you should set the Content-Length
header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition
header to attachment
if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.
Most important part is to call FacesContext#responseComplete()
to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException
with a message like getoutputstream() has already been called for this response
when the JSF implementation calls getWriter()
to render HTML.
You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink>
and <h:commandButton>
. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.
In case you're using e.g. PrimeFaces <p:commandXxx>
, then you need to make sure that you explicitly turn off ajax via ajax="false"
attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" />
in the command component.
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = ec.getResponseOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = response.getOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
In case you need to stream a static file from the local disk file system, substitute the code as below:
File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();
// ...
Files.copy(file.toPath(), output);
In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output
there where the API being used expects an OutputStream
.
E.g. iText PDF:
String fileName = "dynamic.pdf";
String contentType = "application/pdf";
// ...
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();
E.g. Apache POI HSSF:
String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";
// ...
HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();
Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.
If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile()
methods taking either a File
, or an InputStream
, or a byte[]
, and specifying whether the file should be downloaded as an attachment (true
) or inline (false
).
public void download() throws IOException {
Faces.sendFile(file, true);
}
Yes, this code is complete as-is. You don't need to invoke responseComplete()
and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.
Updated 5 September 2010
Seeing as everyone seems to get directed here for this issue, I'm adding my answer to a similar question, which contains the same code as this answer but with full background for those who are interested:
IE's document.selection.createRange doesn't include leading or trailing blank lines
To account for trailing line breaks is tricky in IE, and I haven't seen any solution that does this correctly, including any other answers to this question. It is possible, however, using the following function, which will return you the start and end of the selection (which are the same in the case of a caret) within a <textarea>
or text <input>
.
Note that the textarea must have focus for this function to work properly in IE. If in doubt, call the textarea's focus()
method first.
function getInputSelection(el) {
var start = 0, end = 0, normalizedValue, range,
textInputRange, len, endRange;
if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
start = el.selectionStart;
end = el.selectionEnd;
} else {
range = document.selection.createRange();
if (range && range.parentElement() == el) {
len = el.value.length;
normalizedValue = el.value.replace(/\r\n/g, "\n");
// Create a working TextRange that lives only in the input
textInputRange = el.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());
// Check if the start and end of the selection are at the very end
// of the input, since moveStart/moveEnd doesn't return what we want
// in those cases
endRange = el.createTextRange();
endRange.collapse(false);
if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
start = end = len;
} else {
start = -textInputRange.moveStart("character", -len);
start += normalizedValue.slice(0, start).split("\n").length - 1;
if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
end = len;
} else {
end = -textInputRange.moveEnd("character", -len);
end += normalizedValue.slice(0, end).split("\n").length - 1;
}
}
}
}
return {
start: start,
end: end
};
}
just add different .gitignore files to mini project 1 and mini project 2. Each of the .gitignore files should /node_modules and you're good to go.
Try to use the rack-cors gem. And add the header field in your Ajax call.
==
is the correct operator to compare strings in Go. However, the strings that you read from STDIN with reader.ReadString
do not contain "a"
, but "a\n"
(if you look closely, you'll see the extra line break in your example output).
You can use the strings.TrimRight
function to remove trailing whitespaces from your input:
if strings.TrimRight(input, "\n") == "a" {
// ...
}
If you want to generate a random float in a range, try a next solution.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
float
random_float(const float min, const float max)
{
if (max == min) return min;
else if (min < max) return (max - min) * ((float)rand() / RAND_MAX) + min;
// return 0 if min > max
return 0;
}
int
main (const int argc, const char *argv[])
{
srand(time(NULL));
char line[] = "-------------------------------------------";
float data[10][2] = {
{-10, 10},
{-5., 5},
{-1, 1},
{-0.25, -0.15},
{1.5, 1.52},
{-1700, 8000},
{-0.1, 0.1},
{-1, 0},
{-1, -2},
{1.2, 1.1}
};
puts(line);
puts(" From | Result | To");
puts(line);
int i;
for (i = 0; i < 10; ++i) {
printf("%12f | %12f | %12f\n", data[i][0], random_float(data[i][0], data[i][1]), data[i][1]);
}
puts(line);
return 0;
}
A result (values is fickle)
-------------------------------------------
From | Result | To
-------------------------------------------
-10.000000 | 2.330828 | 10.000000
-5.000000 | -4.945523 | 5.000000
-1.000000 | 0.004242 | 1.000000
-0.250000 | -0.203197 | -0.150000
1.500000 | 1.513431 | 1.520000
-1700.000000 | 3292.941895 | 8000.000000
-0.100000 | -0.021541 | 0.100000
-1.000000 | -0.148299 | 0.000000
-1.000000 | 0.000000 | -2.000000
1.200000 | 0.000000 | 1.100000
-------------------------------------------
$('#datepicker').datepicker().change(evt => {_x000D_
var selectedDate = $('#datepicker').datepicker('getDate');_x000D_
var now = new Date();_x000D_
now.setHours(0,0,0,0);_x000D_
if (selectedDate < now) {_x000D_
console.log("Selected date is in the past");_x000D_
} else {_x000D_
console.log("Selected date is NOT in the past");_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>_x000D_
<input type="text" id="datepicker" name="event_date" class="datepicker">
_x000D_
Just look at this solution, make sure you've turned access on to less secure apps on your google account :javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25
Annotate your method in controller with @ResponseBody
:
@RequestMapping(value="/controller", method=GET)
@ResponseBody
public String foo() {
return "Response!";
}
From: 15.3.2.6 Mapping the response body with the @ResponseBody
annotation:
The
@ResponseBody
annotation [...] can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name).
I had the same issue, but the other answers only supplied one part of the solution.
The solution is two fold:
Remove the 64bit from the Register.
or
Register it as 32bit:
C:\Windows\SysWOW64\regsvr32 <file.dll>
Registering it as 32bit without removing the 64bit registration does not resolve my issue.
You can read it from the input stream:
public ActionResult ManagePhotos(ManagePhotos model)
{
if (ModelState.IsValid)
{
byte[] image = new byte[model.File.ContentLength];
model.File.InputStream.Read(image, 0, image.Length);
// TODO: Do something with the byte array here
}
...
}
And if you intend to directly save the file to the disk you could use the model.File.SaveAs
method. You might find the following blog post useful.
$cfg['Servers'][$i]['auth_type'] = 'HTTP';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '1234';
This solves my problem too. It just logs in automatically.
I believe you can do the following to get the extension of a file name.
var path = require('path')
path.extname('index.html')
// returns
'.html'
You can get table/view details through below query.
For table :sp_help table_name For View :sp_help view_name
EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245
To see exactly what is happening, use nc -l
and an user agent like a browser or cURL.
Save the form to an .html
file:
<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
<p><input type="text" name="text" value="text default">
<p><input type="file" name="file1">
<p><input type="file" name="file2">
<p><button type="submit">Submit</button>
</form>
Create files to upload:
echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html
Run:
nc -l localhost 8000
Open the HTML on your browser, select the files and click on submit and check the terminal.
nc
prints the request received. Firefox sent:
POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"
text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain
Content of a.txt.
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html
<!DOCTYPE html><title>Content of a.html.</title>
-----------------------------9051914041544843365972754266--
Aternativelly, cURL should send the same POST request as your a browser form:
nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000
You can do multiple tests with:
while true; do printf '' | nc -l localhost 8000; done
Simply declare it as below if you want to us the STL queue container.
std::queue<myclass*> my_queue;
This is the easy way to do it. If you're going backwards, just add
$("#Prefix").val($("#Prefix").val());
after you set the focus
This is the more proper (cleaner) way:
function SetCaretAtEnd(elem) {
var elemLen = elem.value.length;
// For IE Only
if (document.selection) {
// Set focus
elem.focus();
// Use IE Ranges
var oSel = document.selection.createRange();
// Reset position to 0 & then set at end
oSel.moveStart('character', -elemLen);
oSel.moveStart('character', elemLen);
oSel.moveEnd('character', 0);
oSel.select();
}
else if (elem.selectionStart || elem.selectionStart == '0') {
// Firefox/Chrome
elem.selectionStart = elemLen;
elem.selectionEnd = elemLen;
elem.focus();
} // if
} // SetCaretAtEnd()
just put the $.browser code in your js
var matched, browser;
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
matched = jQuery.uaMatch( navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
You could write a Kotlin extension like this:
fun String.isValidEmail() =
isNotEmpty() && android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()
And then call it like this:
email.isValidEmail()
By default all class methods are public. To make them private you can use Module#private_class_method like @tjwallace wrote or define them differently, as you did:
class << self
private
def method_name
...
end
end
class << self
opens up self's singleton class, so that methods can be redefined for the current self object. This is used to define class/module ("static") method. Only there, defining private methods really gives you private class methods.
With existing Hamcrest libraries (as of v.2.0.0.0) you are forced to use Collection.toArray() method on your Collection in order to use containsInAnyOrder Matcher. Far nicer would be to add this as a separate method to org.hamcrest.Matchers:
public static <T> org.hamcrest.Matcher<java.lang.Iterable<? extends T>> containsInAnyOrder(Collection<T> items) {
return org.hamcrest.collection.IsIterableContainingInAnyOrder.<T>containsInAnyOrder((T[]) items.toArray());
}
Actually I ended up adding this method to my custom test library and use it to increase readability of my test cases (due to less verbosity).
This is a good one: apps-for-android
DateTime.Now.Ticks
is not safe, Guid.NewGuid()
is too ugly, if you need something clean and almost safe (it's not 100% safe for example if you call it 1,000,000 times in 1ms), try:
Math.Abs(Guid.NewGuid().GetHashCode())
By safe I mean safe to be unique when you call it so many times in very short period few ms of time.
Yeap, you just need to make .
match newline :
$string =~ /(START)(.+?)(END)/s;
$watch first parameter can be angular expression or function. See documentation on $scope.$watch. It contains a lot of useful info about how $watch method works: when watchExpression is called, how angular compares results, etc.
After looking for an answer for the question for months, I finally find a really best solution: writing a simple script.
#!/usr/bin/expect
set timeout 20
set cmd [lrange $argv 1 end]
set password [lindex $argv 0]
eval spawn $cmd
expect "assword:" # matches both 'Password' and 'password'
send "$password\r";
interact
Put it to /usr/bin/exp
, then you can use:
exp <password> ssh <anything>
exp <password> scp <anysrc> <anydst>
Done!
You can do this also in kotlin like this:
contentView.apply {
// Set the content view to 0% opacity but visible, so that it is visible
// (but fully transparent) during the animation.
alpha = 0f
visibility = View.VISIBLE
// Animate the content view to 100% opacity, and clear any animation
// listener set on the view.
animate()
.alpha(1f)
.setDuration(resources.getInteger(android.R.integer.config_mediumAnimTime).toLong())
.setListener(null)
}
_ [$%-4009] * #,##0_ ;_ [$%-4009] * -#,##0_ ;_ [$%-4009] * "-"??_ ;_ @_
This may help you find what you're looking for... Batch script loop
My answer is as follows:
@echo off
:start
set /a var+=1
if %var% EQU 100 goto end
:: Code you want to run goes here
goto start
:end
echo var has reached %var%.
pause
exit
The first set of commands under the start label loops until a variable, %var% reaches 100. Once this happens it will notify you and allow you to exit. This code can be adapted to your needs by changing the 100 to 17 and putting your code or using a call command followed by the batch file's path (Shift+Right Click on file and select "Copy as Path") where the comment is placed.
If you renamed Xcode.app since first launch, the iOS Simulator becomes unavailable. This is mentioned in the Xcode 6.1 Release Notes:
Renaming Xcode.app after running any of the Xcode tools in that bundle may cause iOS Simulator to be no longer be available. Either rename Xcode.app back to what it was when first launched or restart your Mac. (16646772)
This works, at least in Android API 15
ImageView = imgv;
Resources res = getResources(); // need this to fetch the drawable
Drawable draw = res.getDrawable( R.drawable.image_name_in_drawable );
imgv.setImageDrawable(draw);
You could use setImageResource(), but the documentation specifies that "does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup ... consider using setImageDrawable() or setImageBitmap()." as stated by chetto
Yes, just add multiple FileAppenders to your logger. For example:
<log4net>
<appender name="File1Appender" type="log4net.Appender.FileAppender">
<file value="log-file-1.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %message%newline" />
</layout>
</appender>
<appender name="File2Appender" type="log4net.Appender.FileAppender">
<file value="log-file-2.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="File1Appender" />
<appender-ref ref="File2Appender" />
</root>
</log4net>
You're thinking too complicated. It's actually just $('#'+openaddress)
.
Try this:
public void ringtone(){
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
One of the simplest way: use Link as follows:
import { Link } from 'react-router-dom';
<Link to={`your-path`} activeClassName="current">{your-link-name}</Link>
If we want to cover the whole div section as link:
<div>
<Card as={Link} to={'path-name'}>
....
card content here
....
</Card>
</div>
Go to File > Settings > Builds,Execution,Deployment > Build Tools > Gradle >Gradle home path
Now, set Use default gradle wrapper and edit Project\gradle\wrapper\gradle-wrapper.properties files field distributionUrl like this
distributionUrl=https://services.gradle.org/distributions/gradle-2.10-all.zip
For Query parameters like domain.com/test?format=json&type=mini
format, then you can easily receive it via - req.query.
app.get('/test', function(req, res){
var format = req.query.format,
type = req.query.type;
});
With any sensible compiler, you should observe no difference; they should be compiled to identical machine code as they're equivalent.
Here you go:
>>> data = """a,b,c
d,e,f
g,h,i
j,k,l"""
>>> data.split() # split automatically splits through \n and space
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']
>>>
In reference to the error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified.
That error means that the Data Source Name (DSN) you are specifying in your connection configuration is not being found in the windows registry.
It is important that your ODBC driver's executable and linking format (ELF) is the same as your application. In other words, you need a 32-bit driver for a 32-bit application or a 64-bit driver for a 64-bit application.
If these do not match, it is possible to configure a DSN for a 32-bit driver and when you attempt to use that DSN in a 64-bit application, the DSN won't be found because the registry holds DSN information in different places depending on ELF (32-bit versus 64-bit).
Be sure you are using the correct ODBC Administrator tool. On 32-bit and 64-bit Windows, the default ODBC Administrator tool is in c:\Windows\System32\odbcad32.exe
. However, on a 64-bit Windows machine, the default is the 64-bit version. If you need to use the 32-bit ODBC Administrator tool on a 64-bit Windows system, you will need to run the one found here: C:\Windows\SysWOW64\odbcad32.exe
Where I see this tripping people up is when a user uses the default 64-bit ODBC Administrator to configure a DSN; thinking it is for a 32-bit DSN. Then when the 32-bit application attempts to connect using that DSN, "Data source not found..." occurs.
It's also important to make sure the spelling of the DSN matches that of the configured DSN in the ODBC Administrator. One letter wrong is all it takes for a DSN to be mismatched.
Here is an article that may provide some additional details
It may not be the same product brand that you have, however; it is a generic problem that is encountered when using ODBC data source names.
In reference to the OLE DB Provider portion of your question, it appears to be a similar type of problem where the application is not able to locate the configuration for the specified provider.
Use Immersive Full-Screen Mode
call fullScreen()
on ImageView
click.
public void fullScreen() {
// BEGIN_INCLUDE (get_current_ui_flags)
// The UI options currently enabled are represented by a bitfield.
// getSystemUiVisibility() gives us that bitfield.
int uiOptions = getWindow().getDecorView().getSystemUiVisibility();
int newUiOptions = uiOptions;
// END_INCLUDE (get_current_ui_flags)
// BEGIN_INCLUDE (toggle_ui_flags)
boolean isImmersiveModeEnabled =
((uiOptions | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) == uiOptions);
if (isImmersiveModeEnabled) {
Log.i(TAG, "Turning immersive mode mode off. ");
} else {
Log.i(TAG, "Turning immersive mode mode on.");
}
// Navigation bar hiding: Backwards compatible to ICS.
if (Build.VERSION.SDK_INT >= 14) {
newUiOptions ^= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
}
// Status bar hiding: Backwards compatible to Jellybean
if (Build.VERSION.SDK_INT >= 16) {
newUiOptions ^= View.SYSTEM_UI_FLAG_FULLSCREEN;
}
// Immersive mode: Backward compatible to KitKat.
// Note that this flag doesn't do anything by itself, it only augments the behavior
// of HIDE_NAVIGATION and FLAG_FULLSCREEN. For the purposes of this sample
// all three flags are being toggled together.
// Note that there are two immersive mode UI flags, one of which is referred to as "sticky".
// Sticky immersive mode differs in that it makes the navigation and status bars
// semi-transparent, and the UI flag does not get cleared when the user interacts with
// the screen.
if (Build.VERSION.SDK_INT >= 18) {
newUiOptions ^= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
}
getWindow().getDecorView().setSystemUiVisibility(newUiOptions);
//END_INCLUDE (set_ui_flags)
}
Read more
Example Download
A proper string data structure. Almost every programmer settles for whatever native support that a language has for the structure and that's usually inefficient (especially for building strings, you need a separate class or something else).
The worst is treating a string as a character array in C and relying on the NULL byte for safety.
From the Java API of CharSequence:
A CharSequence is a readable sequence of characters. This interface provides uniform, read-only access to many different kinds of character sequences.
This interface is then used by String, CharBuffer and StringBuffer to keep consistency for all method names.
[System.Net.Dns]::GetHostByName('remotehost').HostName
Similar to Julien's answer above, I had success with the following:
fig, ax = plt.subplots(figsize=(10,4))
for key, grp in df.groupby(['ticker']):
ax.plot(grp['Date'], grp['adj_close'], label=key)
ax.legend()
plt.show()
This solution might be more relevant if you want more control in matlab.
Solution inspired by: https://stackoverflow.com/a/52526454/10521959
Here is a Swift 5 solution for downloading and saving an image or in general a file to the documents directory by using Alamofire
:
func dowloadAndSaveFile(from url: URL) {
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
documentsURL.appendPathComponent(url.lastPathComponent)
return (documentsURL, [.removePreviousFile])
}
let request = SessionManager.default.download(url, method: .get, to: destination)
request.validate().responseData { response in
switch response.result {
case .success:
if let destinationURL = response.destinationURL {
print(destinationURL)
}
case .failure(let error):
print(error.localizedDescription)
}
}
}
I'm adding this answer because none of the others worked for me.
I had to add a Header Handler to the Proxy:
import java.util.Set;
import java.util.TreeSet;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPHeader;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
public class SOAPHeaderHandler implements SOAPHandler<SOAPMessageContext> {
private final String authenticatedToken;
public SOAPHeaderHandler(String authenticatedToken) {
this.authenticatedToken = authenticatedToken;
}
public boolean handleMessage(SOAPMessageContext context) {
Boolean outboundProperty =
(Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outboundProperty.booleanValue()) {
try {
SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope();
SOAPFactory factory = SOAPFactory.newInstance();
String prefix = "urn";
String uri = "urn:xxxx";
SOAPElement securityElem =
factory.createElement("Element", prefix, uri);
SOAPElement tokenElem =
factory.createElement("Element2", prefix, uri);
tokenElem.addTextNode(authenticatedToken);
securityElem.addChildElement(tokenElem);
SOAPHeader header = envelope.addHeader();
header.addChildElement(securityElem);
} catch (Exception e) {
e.printStackTrace();
}
} else {
// inbound
}
return true;
}
public Set<QName> getHeaders() {
return new TreeSet();
}
public boolean handleFault(SOAPMessageContext context) {
return false;
}
public void close(MessageContext context) {
//
}
}
In the proxy, I just add the Handler:
BindingProvider bp =(BindingProvider)basicHttpBindingAuthentication;
bp.getBinding().getHandlerChain().add(new SOAPHeaderHandler(authenticatedToken));
bp.getBinding().getHandlerChain().add(new SOAPLoggingHandler());
Here's how to do it in Prototype: $(id).update(data)
And jQuery: $('#id').replaceWith(data)
But document.getElementById(id).innerHTML=data
should work too.
EDIT: Prototype and jQuery automatically evaluate scripts for you.
I know this is an old question, but here is an alternative approach that I have found more useful in some situations. I believe the master.dbo.fn_varbintohexstr function has been available in SQL Server at least since SQL2K. Adding it here just for completeness. Some readers may also find it instructive to look at the source code of this function.
declare @source varbinary(max);
set @source = 0x21232F297A57A5A743894A0E4A801FC3;
select varbin_source = @source
,string_result = master.dbo.fn_varbintohexstr (@source)
After I removed
\usepackage{fontspec}% font selecting commands
\usepackage{xunicode}% unicode character macros
\usepackage{xltxtra} % some fixes/extras
it seems to have worked "correctly".
It may be worth noting that the headers and footers only appear from page 2 onwards. Although I've tried the fix for this given in the fancyhdr documentation, I can't get it to work either.
FYI: MikTeX 2.7 under Vista
The Date object will do what you want - construct one for each date, then compare them using the >
, <
, <=
or >=
.
The ==
, !=
, ===
, and !==
operators require you to use date.getTime()
as in
var d1 = new Date();
var d2 = new Date(d1);
var same = d1.getTime() === d2.getTime();
var notSame = d1.getTime() !== d2.getTime();
to be clear just checking for equality directly with the date objects won't work
var d1 = new Date();
var d2 = new Date(d1);
console.log(d1 == d2); // prints false (wrong!)
console.log(d1 === d2); // prints false (wrong!)
console.log(d1 != d2); // prints true (wrong!)
console.log(d1 !== d2); // prints true (wrong!)
console.log(d1.getTime() === d2.getTime()); // prints true (correct)
I suggest you use drop-downs or some similar constrained form of date entry rather than text boxes, though, lest you find yourself in input validation hell.
I experienced the very same problem and it turned out I was on a different (local) branch than I thought I was AND the correct local branch was behind in commits from remote.
My solution: checkout the correct branch, cherry-pick the commit from the other local branch, git pull and git push
Without need to know potential encoding types, in which wrong encoding types will give you nil/null, this should cover all your bases:
NSString *dataString = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];
Done!
Note: In the event this somehow fails, you can unpack your NSData with NSKeyedUnarchiver
, then repack the (id)unpacked
again via NSKeyedArchiver
, and that NSData form should be base64 encodeable.
id unpacked = [NSKeyedUnarchiver unarchiveObjectWithData:data];
data = [NSKeyedArchiver archivedDataWithRootObject:unpacked];
A combination of TRANSCRIPT_MODE_ALWAYS_SCROLL and setSelection made it work for me
ChatAdapter adapter = new ChatAdapter(this);
ListView lv = (ListView) findViewById(R.id.chatList);
lv.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
lv.setAdapter(adapter);
adapter.registerDataSetObserver(new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
lv.setSelection(adapter.getCount() - 1);
}
});
You can add --force-with-lease to the command, it will works.
git push --force-with-lease
--force is destructive because it unconditionally overwrites the remote repository with whatever you have locally. But --force-with-lease ensure you don't overwrite other's work.
See more info here.
cast (
case
when FC.CourseId is not null then 1 else 0
end
as bit)
The CAST spec is "CAST (expression AS type)". The CASE is an expression in this context.
If you have multiple such expressions, I'd declare bit vars @true and @false and use them. Or use UDFs if you really wanted...
DECLARE @True bit, @False bit;
SELECT @True = 1, @False = 0; --can be combined with declare in SQL 2008
SELECT
case when FC.CourseId is not null then @True ELSE @False END AS ...
file = open('parsed_data.txt', 'w')
for link in soup.findAll('a', attrs={'href': re.compile("^http")}): print (link)
soup_link = str(link)
print (soup_link)
file.write(soup_link)
file.flush()
file.close()
In my case, I used BeautifulSoup to write a .txt with Python 3.x. It had the same issue. Just as @tsduteba said, change the 'wb' in the first line to 'w'.
$myArr = array();
function someFuntion(array $myArr) {
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
return $myArr;
}
$myArr = someFunction($myArr);
Try this.
var string = " string 1";
string = string.trim().replace(/\s+/g, ' ');
the result will be
string 1
What happened here is that it will trim the outside spaces first using trim()
then trim the inside spaces using .replace(/\s+/g, ' ')
.
nothing to be done for running your wamp sites to another computer. 1. first turn off the firewall. 2. Set Put Online in wamp by clcking in wamp icon at near to clock.
Finally run your browser in another computer and type http:\ip address or computer name e.g. http:\192.168.1.100
This is python regex, but it probably works in other languages that implement it, too.
I guess it depends on what you consider a character to be. If it's letters, numbers, and underscores:
\w{3,}
if just letters and digits:
[a-zA-Z0-9]{3,}
Python also has a regex method to return all matches from a string.
>>> import re
>>> re.findall(r'\w{3,}', 'This is a long string, yes it is.')
['This', 'long', 'string', 'yes']
In startup.cs, add the constructor
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
Access the settings using Configuration["SecureCookies"]
You can use a full path with the fstream classes. The folowing code attempts to open the file demo.txt in the root of the C: drive. Note that as this is an input operation, the file must already exist.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream ifs( "c:/demo.txt" ); // note no mode needed
if ( ! ifs.is_open() ) {
cout <<" Failed to open" << endl;
}
else {
cout <<"Opened OK" << endl;
}
}
What does this code produce on your system?
Create a new toolbar and add the commands
Select your custom tookbar to show it.
You will then see the icons as mention by moriartyn
Natural Number (Strings) Quick Sort
Just to pile onto the topic. Normally, if you sort strings with numbers you'll get something like this:
Text1
Text10
Text100
Text11
Text2
Text20
But you really want it to recognize the numerical values and be sorted like
Text1
Text2
Text10
Text11
Text20
Text100
Here's how to do it...
Note:
Natural Number Quick Sort
Public Sub QuickSortNaturalNum(strArray() As String, intBottom As Integer, intTop As Integer)
Dim strPivot As String, strTemp As String
Dim intBottomTemp As Integer, intTopTemp As Integer
intBottomTemp = intBottom
intTopTemp = intTop
strPivot = strArray((intBottom + intTop) \ 2)
Do While (intBottomTemp <= intTopTemp)
' < comparison of the values is a descending sort
Do While (CompareNaturalNum(strArray(intBottomTemp), strPivot) < 0 And intBottomTemp < intTop)
intBottomTemp = intBottomTemp + 1
Loop
Do While (CompareNaturalNum(strPivot, strArray(intTopTemp)) < 0 And intTopTemp > intBottom) '
intTopTemp = intTopTemp - 1
Loop
If intBottomTemp < intTopTemp Then
strTemp = strArray(intBottomTemp)
strArray(intBottomTemp) = strArray(intTopTemp)
strArray(intTopTemp) = strTemp
End If
If intBottomTemp <= intTopTemp Then
intBottomTemp = intBottomTemp + 1
intTopTemp = intTopTemp - 1
End If
Loop
'the function calls itself until everything is in good order
If (intBottom < intTopTemp) Then QuickSortNaturalNum strArray, intBottom, intTopTemp
If (intBottomTemp < intTop) Then QuickSortNaturalNum strArray, intBottomTemp, intTop
End Sub
Natural Number Compare(Used in Quick Sort)
Function CompareNaturalNum(string1 As Variant, string2 As Variant) As Integer
'string1 is less than string2 -1
'string1 is equal to string2 0
'string1 is greater than string2 1
Dim n1 As Long, n2 As Long
Dim iPosOrig1 As Integer, iPosOrig2 As Integer
Dim iPos1 As Integer, iPos2 As Integer
Dim nOffset1 As Integer, nOffset2 As Integer
If Not (IsNull(string1) Or IsNull(string2)) Then
iPos1 = 1
iPos2 = 1
Do While iPos1 <= Len(string1)
If iPos2 > Len(string2) Then
CompareNaturalNum = 1
Exit Function
End If
If isDigit(string1, iPos1) Then
If Not isDigit(string2, iPos2) Then
CompareNaturalNum = -1
Exit Function
End If
iPosOrig1 = iPos1
iPosOrig2 = iPos2
Do While isDigit(string1, iPos1)
iPos1 = iPos1 + 1
Loop
Do While isDigit(string2, iPos2)
iPos2 = iPos2 + 1
Loop
nOffset1 = (iPos1 - iPosOrig1)
nOffset2 = (iPos2 - iPosOrig2)
n1 = Val(Mid(string1, iPosOrig1, nOffset1))
n2 = Val(Mid(string2, iPosOrig2, nOffset2))
If (n1 < n2) Then
CompareNaturalNum = -1
Exit Function
ElseIf (n1 > n2) Then
CompareNaturalNum = 1
Exit Function
End If
' front padded zeros (put 01 before 1)
If (n1 = n2) Then
If (nOffset1 > nOffset2) Then
CompareNaturalNum = -1
Exit Function
ElseIf (nOffset1 < nOffset2) Then
CompareNaturalNum = 1
Exit Function
End If
End If
ElseIf isDigit(string2, iPos2) Then
CompareNaturalNum = 1
Exit Function
Else
If (Mid(string1, iPos1, 1) < Mid(string2, iPos2, 1)) Then
CompareNaturalNum = -1
Exit Function
ElseIf (Mid(string1, iPos1, 1) > Mid(string2, iPos2, 1)) Then
CompareNaturalNum = 1
Exit Function
End If
iPos1 = iPos1 + 1
iPos2 = iPos2 + 1
End If
Loop
' Everything was the same so far, check if Len(string2) > Len(String1)
' If so, then string1 < string2
If Len(string2) > Len(string1) Then
CompareNaturalNum = -1
Exit Function
End If
Else
If IsNull(string1) And Not IsNull(string2) Then
CompareNaturalNum = -1
Exit Function
ElseIf IsNull(string1) And IsNull(string2) Then
CompareNaturalNum = 0
Exit Function
ElseIf Not IsNull(string1) And IsNull(string2) Then
CompareNaturalNum = 1
Exit Function
End If
End If
End Function
isDigit(Used in CompareNaturalNum)
Function isDigit(ByVal str As String, pos As Integer) As Boolean
Dim iCode As Integer
If pos <= Len(str) Then
iCode = Asc(Mid(str, pos, 1))
If iCode >= 48 And iCode <= 57 Then isDigit = True
End If
End Function
As stated by Luke you need to use a server side language, like php. This is a really simple php example:
<?php
if ($_GET['run']) {
# This code will run if ?run=true is set.
exec("/path/to/name.sh");
}
?>
<!-- This link will add ?run=true to your URL, myfilename.php?run=true -->
<a href="?run=true">Click Me!</a>
Save this as myfilename.php
and place it on a machine with a web server with php installed. The same thing can be accomplished with asp, java, ruby, python, ...
Below is the fixed code:
#!/bin/ksh
safeRunCommand() {
typeset cmnd="$*"
typeset ret_code
echo cmnd=$cmnd
eval $cmnd
ret_code=$?
if [ $ret_code != 0 ]; then
printf "Error : [%d] when executing command: '$cmnd'" $ret_code
exit $ret_code
fi
}
command="ls -l | grep p"
safeRunCommand "$command"
Now if you look into this code few things that I changed are:
typeset
is not necessary but a good practice. It make cmnd
and ret_code
local to safeRunCommand
ret_code
is not necessary but a good practice to store return code in some variable (and store it ASAP) so that you can use it later like I did in printf "Error : [%d] when executing command: '$command'" $ret_code
safeRunCommand "$command"
. If you dont then cmnd
will get only the value ls
and not ls -l
. And it is even more important if your command contains pipes.typeset cmnd="$*"
instead of typeset cmnd="$1"
if you want to keep the spaces. You can try with both depending upon how complex is your command argument.NOTE: Do remember some commands give 1 as return code even though there is no error like grep
. If grep
found something it will return 0 else 1.
I had tested with KSH/BASH. And it worked fine. Let me know if u face issues running this.
No, according to Apple here:
Note: You cannot install apps from the App Store in simulation environments.
Router Link
routerLink with brackets and none - simple explanation.
The difference between routerLink= and [routerLink] is mostly like relative and absolute path.
Similar to a href you may want to navigate to ./about.html or https://your-site.com/about.html.
When you use without brackets then you navigate relative and without params;
my-app.com/dashboard/client
"jumping" from my-app.com/dashboard to my-app.com/dashboard/client
<a routerLink="client/{{ client.id }}" .... rest the same
When you use routerLink with brackets then you execute app to navigate absolute and you can add params how is the puzzle of your new link
first of all it will not include the "jump" from dashboard/ to dashboard/client/client-id and bring you data of client/client-id which is more helpful for EDIT CLIENT
<a [routerLink]="['/client', client.id]" ... rest the same
The absolute way or brackets routerLink require additional set up of you components and app.routing.module.ts
The code without error will "tell you more/what is the purpose of []" when you make the test. Just check this with or without []. Than you may experiments with selectors which - as mention above - helps with dynamics routing.
See whats the routerLink construct
The example by user11617 is incorrect; it will report that the file exists even in cases where it does not, but there was an error of some other sort.
The signature should be Exists(string) (bool, error). And then, as it happens, the call sites are no better.
The code he wrote would better as:
func Exists(name string) bool {
_, err := os.Stat(name)
return !os.IsNotExist(err)
}
But I suggest this instead:
func Exists(name string) (bool, error) {
_, err := os.Stat(name)
if os.IsNotExist(err) {
return false, nil
}
return err != nil, err
}
I've created a tool called Rector, that handles instant upgrades. There is also mysql ? mysqli set.
It handles:
function renaming
constant renaming
switched arguments
non-1:1 function calls changes, e.g.
$data = mysql_db_name($result, $row);
?
mysqli_data_seek($result, $row);
$fetch = mysql_fetch_row($result);
$data = $fetch[0];
composer require rector/rector --dev
// or in case of composer conflicts
composer require rector/rector-prefixed --dev
rector.php
in project root directory with the Mysql to Mysqli set<?php
use Rector\Core\Configuration\Option;
use Rector\Set\ValueObject\SetList;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$parameters->set(Option::SETS, [
SetList::MYSQL_TO_MYSQLI,
]);
};
vendor/bin/rector process src --dry-run
vendor/bin/rector process src
I've already run it on 2 big PHP projects and it works perfectly.
finalName is created as:
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
</build>
One of the solutions is to add own property:
<properties>
<finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
<finalName>${finalName}</finalName>
</build>
And now try:
mvn -DfinalName=build clean package
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
$id = implode(',',$_POST['id']);
echo $id
you cannot echo an array because it will just print out Array. If you wanna print out an array use print_r
.
print_r($_POST['id']);
When writing my own unique_ptr, I found this case. Given std::unique_ptr
's operator==
:
template<class T1, class D1, class T2, class D2>
bool operator==(const unique_ptr<T1, D1>& x, const unique_ptr<T2, D2>& y);
template <class T, class D>
bool operator==(const unique_ptr<T, D>& x, nullptr_t) noexcept;
template <class T, class D>
bool operator==(nullptr_t, const unique_ptr<T, D>& x) noexcept;
And this test case from libstdcxx:
std::unique_ptr<int> ptr;
if (ptr == 0)
{ }
if (0 == ptr)
{ }
if (ptr != 0)
{ }
if (0 != ptr)
{ }
Note because that ptr
has a explicit operator bool() const noexcept;
, so operator overload resolution
works fine here, e.g., ptr == 0
chooses
template <class T, class D>
bool operator==(const unique_ptr<T, D>& x, nullptr_t) noexcept;`.
If it has no explicit
keyword here, ptr
in ptr == 0
will be converted into bool
, then bool
will be converted into int
, because bool operator==(int, int)
is built-in and 0
is int
. What is waiting for us is ambiguous overload resolution error.
Here is a Minimal, Complete, and Verifiable example:
#include <cstddef>
struct A
{
constexpr A(std::nullptr_t) {}
operator bool()
{
return true;
}
};
constexpr bool operator ==(A, A) noexcept
{
return true;
}
constexpr bool operator ==(A, std::nullptr_t) noexcept
{
return true;
}
constexpr bool operator ==(std::nullptr_t, A) noexcept
{
return true;
}
int main()
{
A a1(nullptr);
A a2(0);
a1 == 0;
}
gcc:
prog.cc: In function 'int main()':
prog.cc:30:8: error: ambiguous overload for 'operator==' (operand types are 'A' and 'int')
30 | a1 == 0;
| ~~ ^~ ~
| | |
| A int
prog.cc:30:8: note: candidate: 'operator==(int, int)' <built-in>
30 | a1 == 0;
| ~~~^~~~
prog.cc:11:16: note: candidate: 'constexpr bool operator==(A, A)'
11 | constexpr bool operator ==(A, A) noexcept
| ^~~~~~~~
prog.cc:16:16: note: candidate: 'constexpr bool operator==(A, std::nullptr_t)'
16 | constexpr bool operator ==(A, std::nullptr_t) noexcept
| ^~~~~~~~
prog.cc:30:8: error: use of overloaded operator '==' is ambiguous (with operand types 'A' and 'int')
a1 == 0;
~~ ^ ~
prog.cc:16:16: note: candidate function
constexpr bool operator ==(A, std::nullptr_t) noexcept
^
prog.cc:11:16: note: candidate function
constexpr bool operator ==(A, A) noexcept
^
prog.cc:30:8: note: built-in candidate operator==(int, int)
a1 == 0;
^
prog.cc:30:8: note: built-in candidate operator==(float, int)
prog.cc:30:8: note: built-in candidate operator==(double, int)
prog.cc:30:8: note: built-in candidate operator==(long double, int)
prog.cc:30:8: note: built-in candidate operator==(__float128, int)
prog.cc:30:8: note: built-in candidate operator==(int, float)
prog.cc:30:8: note: built-in candidate operator==(int, double)
prog.cc:30:8: note: built-in candidate operator==(int, long double)
prog.cc:30:8: note: built-in candidate operator==(int, __float128)
prog.cc:30:8: note: built-in candidate operator==(int, long)
prog.cc:30:8: note: built-in candidate operator==(int, long long)
prog.cc:30:8: note: built-in candidate operator==(int, __int128)
prog.cc:30:8: note: built-in candidate operator==(int, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(int, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(int, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(int, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(long, int)
prog.cc:30:8: note: built-in candidate operator==(long long, int)
prog.cc:30:8: note: built-in candidate operator==(__int128, int)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, int)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, int)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, int)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, int)
prog.cc:30:8: note: built-in candidate operator==(float, float)
prog.cc:30:8: note: built-in candidate operator==(float, double)
prog.cc:30:8: note: built-in candidate operator==(float, long double)
prog.cc:30:8: note: built-in candidate operator==(float, __float128)
prog.cc:30:8: note: built-in candidate operator==(float, long)
prog.cc:30:8: note: built-in candidate operator==(float, long long)
prog.cc:30:8: note: built-in candidate operator==(float, __int128)
prog.cc:30:8: note: built-in candidate operator==(float, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(float, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(float, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(float, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(double, float)
prog.cc:30:8: note: built-in candidate operator==(double, double)
prog.cc:30:8: note: built-in candidate operator==(double, long double)
prog.cc:30:8: note: built-in candidate operator==(double, __float128)
prog.cc:30:8: note: built-in candidate operator==(double, long)
prog.cc:30:8: note: built-in candidate operator==(double, long long)
prog.cc:30:8: note: built-in candidate operator==(double, __int128)
prog.cc:30:8: note: built-in candidate operator==(double, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(double, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(double, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(double, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(long double, float)
prog.cc:30:8: note: built-in candidate operator==(long double, double)
prog.cc:30:8: note: built-in candidate operator==(long double, long double)
prog.cc:30:8: note: built-in candidate operator==(long double, __float128)
prog.cc:30:8: note: built-in candidate operator==(long double, long)
prog.cc:30:8: note: built-in candidate operator==(long double, long long)
prog.cc:30:8: note: built-in candidate operator==(long double, __int128)
prog.cc:30:8: note: built-in candidate operator==(long double, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(long double, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(long double, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(long double, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(__float128, float)
prog.cc:30:8: note: built-in candidate operator==(__float128, double)
prog.cc:30:8: note: built-in candidate operator==(__float128, long double)
prog.cc:30:8: note: built-in candidate operator==(__float128, __float128)
prog.cc:30:8: note: built-in candidate operator==(__float128, long)
prog.cc:30:8: note: built-in candidate operator==(__float128, long long)
prog.cc:30:8: note: built-in candidate operator==(__float128, __int128)
prog.cc:30:8: note: built-in candidate operator==(__float128, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(__float128, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(__float128, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(__float128, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(long, float)
prog.cc:30:8: note: built-in candidate operator==(long, double)
prog.cc:30:8: note: built-in candidate operator==(long, long double)
prog.cc:30:8: note: built-in candidate operator==(long, __float128)
prog.cc:30:8: note: built-in candidate operator==(long, long)
prog.cc:30:8: note: built-in candidate operator==(long, long long)
prog.cc:30:8: note: built-in candidate operator==(long, __int128)
prog.cc:30:8: note: built-in candidate operator==(long, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(long, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(long, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(long, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(long long, float)
prog.cc:30:8: note: built-in candidate operator==(long long, double)
prog.cc:30:8: note: built-in candidate operator==(long long, long double)
prog.cc:30:8: note: built-in candidate operator==(long long, __float128)
prog.cc:30:8: note: built-in candidate operator==(long long, long)
prog.cc:30:8: note: built-in candidate operator==(long long, long long)
prog.cc:30:8: note: built-in candidate operator==(long long, __int128)
prog.cc:30:8: note: built-in candidate operator==(long long, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(long long, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(long long, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(long long, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(__int128, float)
prog.cc:30:8: note: built-in candidate operator==(__int128, double)
prog.cc:30:8: note: built-in candidate operator==(__int128, long double)
prog.cc:30:8: note: built-in candidate operator==(__int128, __float128)
prog.cc:30:8: note: built-in candidate operator==(__int128, long)
prog.cc:30:8: note: built-in candidate operator==(__int128, long long)
prog.cc:30:8: note: built-in candidate operator==(__int128, __int128)
prog.cc:30:8: note: built-in candidate operator==(__int128, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(__int128, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(__int128, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(__int128, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, float)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, double)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, long double)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, __float128)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, long)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, long long)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, __int128)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(unsigned int, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, float)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, double)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, long double)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, __float128)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, long)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, long long)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, __int128)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(unsigned long, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, float)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, double)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, long double)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, __float128)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, long)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, long long)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, __int128)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(unsigned long long, unsigned __int128)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, float)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, double)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, long double)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, __float128)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, long)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, long long)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, __int128)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, unsigned int)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, unsigned long)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, unsigned long long)
prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, unsigned __int128)
1 error generated.
Answers based on using external web services are not exactly correct, because they do not actually answer the stated question:
... information on finding my routers public IP
Explanation
All online services return the external IP address, but it does not essentially mean, that this address is assigned to the user's router.
Router may be assigned with another local IP address of ISP infrastructure networks. Practically this means, that router can not host any services available on Internet. This may be good for safety of most home users, but not good for geeks who host servers at home.
Here's how to check if router has external IP:
According to Wikipedia article, the IP address ranges 10.0.0.0 – 10.255.255.255
, 172.16.0.0 – 172.31.255.255
and 192.168.0.0 – 192.168.255.255
are used for private i.e. local networks.
See what happens when you trace route to some remote host with router being assigned with external IP address:
Gotcha! First hop starts from 31.*
now. This clearly means that there's nothing between your router and Internet.
Solution
Ttl = 2
TTL=2 must be not enough to reach remote host. Hop #1 host will emit "Reply from <ip address>: TTL expired in transit."
revealing its IP address.
Implementation
try
{
using (var ping = new Ping())
{
var pingResult = ping.Send("google.com");
if (pingResult?.Status == IPStatus.Success)
{
pingResult = ping.Send(pingResult.Address, 3000, "ping".ToAsciiBytes(), new PingOptions { Ttl = 2 });
var isRealIp = !Helpers.IsLocalIp(pingResult?.Address);
Console.WriteLine(pingResult?.Address == null
? $"Has {(isRealIp ? string.Empty : "no ")}real IP, status: {pingResult?.Status}"
: $"Has {(isRealIp ? string.Empty : "no ")}real IP, response from: {pingResult.Address}, status: {pingResult.Status}");
Console.WriteLine($"ISP assigned REAL EXTERNAL IP to your router, response from: {pingResult?.Address}, status: {pingResult?.Status}");
}
else
{
Console.WriteLine($"Your router appears to be behind ISP networks, response from: {pingResult?.Address}, status: {pingResult?.Status}");
}
}
}
catch (Exception exc)
{
Console.WriteLine("Failed to resolve external ip address by ping");
}
Small helper is used to check if IP belongs to private or public network:
public static bool IsLocalIp(IPAddress ip) {
var ipParts = ip.ToString().Split(new [] { "." }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
return (ipParts[0] == 192 && ipParts[1] == 168)
|| (ipParts[0] == 172 && ipParts[1] >= 16 && ipParts[1] <= 31)
|| ipParts[0] == 10;
}
I would say in some cases it's ok to do nothing. Probably not something you should be doing by default, but in case there should be no way for the interrupt to happen, I'm not sure what else to do (probably logging error, but that does not affect program flow).
One case would be in case you have a task (blocking) queue. In case you have a daemon Thread handling these tasks and you do not interrupt the Thread by yourself (to my knowledge the jvm does not interrupt daemon threads on jvm shutdown), I see no way for the interrupt to happen, and therefore it could be just ignored. (I do know that a daemon thread may be killed by the jvm at any time and therefore are unsuitable in some cases).
EDIT: Another case might be guarded blocks, at least based on Oracle's tutorial at: http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html
Avoid for loops whenever possible.
sum(A(:))
is great however if you have some logical indexing going on you can't use the (:) but you can write
% Sum all elements under 45 in the matrix
sum ( sum ( A *. ( A < 45 ) )
Since sum sums the columns and sums the row vector that was created by the first sum. Note that this only works if the matrix is 2-dim.
With regards to your first question, the array is passed by reference UNLESS it is modified within the method / function you're calling. If you attempt to modify the array within the method / function, a copy of it is made first, and then only the copy is modified. This makes it seem as if the array is passed by value when in actual fact it isn't.
For example, in this first case, even though you aren't defining your function to accept $my_array by reference (by using the & character in the parameter definition), it still gets passed by reference (ie: you don't waste memory with an unnecessary copy).
function handle_array($my_array) {
// ... read from but do not modify $my_array
print_r($my_array);
// ... $my_array effectively passed by reference since no copy is made
}
However if you modify the array, a copy of it is made first (which uses more memory but leaves your original array unaffected).
function handle_array($my_array) {
// ... modify $my_array
$my_array[] = "New value";
// ... $my_array effectively passed by value since requires local copy
}
FYI - this is known as "lazy copy" or "copy-on-write".
Checking the extension_dir is one of the thing you like to check from phpinfo().In my case it was extension_dir = "./" by default which was wrong. Change it to extension_dir = './ext/' or where all your extension dlls are currently residing.
Your method must read byte by byte and fully understand and appreciate the byte wise construction of characters. The simplest method is to use an editor which will read anything but only output UTF-8 characters. Textpad is one choice.
File - Settings - Appearance & Behavior - Appearance - CHOOSE Darcula in "Theme" - Press Apply.
or
Choose File - Settings - Editor - Colors & Fonts - Then SELECT Darcula in scheme name - Press Apply - restart Studio (sometimes not all elements implement theme)
NOTE: this answer was written in 2008. At the time the best cross-browser solution for most people really was to use jQuery. I'm leaving the answer here for posterity and, if you're using jQuery, this is a good way to do it. If you're using some other framework or pure JavaScript the accepted answer is probably the way to go.
As of jQuery 1.2.6 you can use one of the core CSS functions, height
and width
(or outerHeight
and outerWidth
, as appropriate).
var height = $("#myDiv").height();
var width = $("#myDiv").width();
var docHeight = $(document).height();
var docWidth = $(document).width();
So, here's what I did based on an amalgamation of the above answers... We already had a GlobalExceptionHandler
annotated with @ControllerAdvice
and I also wanted to find a way to re-use that code to handle exceptions that come from filters.
The simplest solution I could find was to leave the exception handler alone, and implement an error controller as follows:
@Controller
public class ErrorControllerImpl implements ErrorController {
@RequestMapping("/error")
public void handleError(HttpServletRequest request) throws Throwable {
if (request.getAttribute("javax.servlet.error.exception") != null) {
throw (Throwable) request.getAttribute("javax.servlet.error.exception");
}
}
}
So, any errors caused by exceptions first pass through the ErrorController
and are re-directed off to the exception handler by rethrowing them from within a @Controller
context, whereas any other errors (not caused directly by an exception) pass through the ErrorController
without modification.
Any reasons why this is actually a bad idea?
You can simply use the following syntax to create a new class (this is handy if you're creating a factory):
$className = $whatever;
$object = new $className;
As an (exceptionally crude) example factory method:
public function &factory($className) {
require_once($className . '.php');
if(class_exists($className)) return new $className;
die('Cannot create new "' . $className . '" class - includes not found or class unavailable.');
}
Convert timeofday to string to use indexOf
var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;
console.log(typeof(timeofday)) // for testing will log number
function timeD2C(time) { // Converts 11.5 (decimal) to 11:30 (colon)
var pos = time.indexOf('.');
var hrs = time.substr(1, pos - 1);
var min = (time.substr(pos, 2)) * 60;
if (hrs > 11) {
hrs = (hrs - 12) + ":" + min + " PM";
} else {
hrs += ":" + min + " AM";
}
return hrs;
}
// "" for typecasting to string
document.getElementById("oset").innerHTML = timeD2C(""+timeofday);
Solution 2
use toString()
to convert to string
document.getElementById("oset").innerHTML = timeD2C(timeofday.toString());
Below are provided steps to fix your issue.
you also should specify def name in the project settings here:
Configuration > Properties/Input/Advanced/Module > Definition File
Use hashlib.md5 in Python 3.
import hashlib
source = '000005fab4534d05api_key9a0554259914a86fb9e7eb014e4e5d52permswrite'.encode()
md5 = hashlib.md5(source).hexdigest() # returns a str
print(md5) # a02506b31c1cd46c2e0b6380fb94eb3d
If you need byte type output, use digest()
instead of hexdigest()
.
You're not actually returning anything from your run_cmd function.
function run_cmd(cmd, args, done) {
var spawn = require("child_process").spawn;
var child = spawn(cmd, args);
var result = { stdout: "" };
child.stdout.on("data", function (data) {
result.stdout += data;
});
child.stdout.on("end", function () {
done();
});
return result;
}
> foo = run_cmd("ls", ["-al"], function () { console.log("done!"); });
{ stdout: '' }
done!
> foo.stdout
'total 28520...'
Works just fine. :)
I admire all these efforts to convert a menu to a menubar because I detest trying to hack CSS. It just feels like I'm meddling with powers I can't possibly ever understand! I think it's much easier to add the menubar files available at the menubar branch of jquery ui.
I downloaded the full jquery ui css bundled file from the jquery ui download site
In the head of my document I put the jquery ui css file that contains everything (I'm on version 1.9.x at the moment) followed by the specific CSS file for the menubar widget downloaded from the menubar branch of jquery ui
<link type="text/css" href="css/jquery-ui.css" rel="stylesheet" />
<link type="text/css" href="css/jquery.ui.menubar.css" rel="stylesheet" />
Don't forget the images folder with all the little icons used by jQuery UI needs to be in the same folder as the jquery-ui.css file.
Then at the end the body I have:
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.9.0.custom.min.js"></script>
<script type="text/javascript" src="js/menubar/jquery.ui.menubar.js"></script>
That's a copy of an up-to-date version of jQuery, followed by a copy of the jQuery UI file, then the menubar module downloaded from the menubar branch of jquery ui
The menubar CSS file is refreshingly short:
.ui-menubar { list-style: none; margin: 0; padding-left: 0; }
.ui-menubar-item { float: left; }
.ui-menubar .ui-button { float: left; font-weight: normal; border-top-width: 0 !important; border-bottom-width: 0 !important; margin: 0; outline: none; }
.ui-menubar .ui-menubar-link { border-right: 1px dashed transparent; border-left: 1px dashed transparent; }
.ui-menubar .ui-menu { width: 200px; position: absolute; z-index: 9999; font-weight: normal; }
but the menubar JavaScript file is 328 lines - too long to quote here. With it, you can simply call menubar() like this example:
$("#menu").menubar({
autoExpand: true,
menuIcon: true,
buttons: true,
select: select
});
As I said, I admire all the attempts to hack the menu object to turn it into a horizontal bar, but I found all of them lacked some standard feature of a horizontal menu bar. I'm not sure why this widget is not bundled with jQuery UI yet, but presumably there are still some bugs to iron out. For instance, I tried it in IE 7 Quirks Mode and the positioning was strange, but it looks great in Firefox, Safari and IE 8+.
Copy your system's other android project local.properties and paste in android folder of React-native project it will work.
sdk.dir=C\:\\Users\\paul\\AppData\\Local\\Android\\Sdk
If you're looking to also get the port number out of the request you'll need to access it through the Request.Host
property for AspNet Core.
The Request.Host
property is not simply a string but, instead, an object that holds both the host domain and the port number. If the port number is specifically written out in the URL (i.e. "https://example.com:8080/path/to/resource"
), then calling Request.Host
will give you the host domain and the port number like so: "example.com:8080"
.
If you only want the value for the host domain or only want the value for the port number then you can access those properties individually (i.e. Request.Host.Host
or Request.Host.Port
).
Just to clarify, the reason why there is no member like contains()
in these container types is because it would open you up to writing inefficient code. Such a method would probably just do a this->find(key) != this->end()
internally, but consider what you do when the key is indeed present; in most cases you'll then want to get the element and do something with it. This means you'd have to do a second find()
, which is inefficient. It's better to use find directly, so you can cache your result, like so:
auto it = myContainer.find(key);
if (it != myContainer.end())
{
// Do something with it, no more lookup needed.
}
else
{
// Key was not present.
}
Of course, if you don't care about efficiency, you can always roll your own, but in that case you probably shouldn't be using C++... ;)
Using a third-party library (Newtonsoft.Json) as alternative:
public static string XmlEscape(string unescaped)
{
if (unescaped == null) return null;
return JsonConvert.SerializeObject(unescaped); ;
}
public static string XmlUnescape(string escaped)
{
if (escaped == null) return null;
return JsonConvert.DeserializeObject(escaped, typeof(string)).ToString();
}
Examples of escaped string:
a<b
==> "a<b"
<foo></foo>
==> "foo></foo>"
NOTE: In newer versions, the code written above may not work with escaping, so you need to specify how the strings will be escaped:
public static string XmlEscape(string unescaped)
{
if (unescaped == null) return null;
return JsonConvert.SerializeObject(unescaped, new JsonSerializerSettings()
{
StringEscapeHandling = StringEscapeHandling.EscapeHtml
});
}
Examples of escaped string:
a<b
==> "a\u003cb"
<foo></foo>
==> "\u003cfoo\u003e\u003c/foo\u003e"
There is no cross-browser way of styling option elements, certainly not to the extent of your second screenshot. You might be able to make them bold, and set the font-size, but that will be about it...
Using the Apache Commons IO API https://commons.apache.org/proper/commons-io/ I was able to establish this using FileUtils.readFileToString(file).contains(stringToFind)
The documentation for this function is at https://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#readFileToString(java.io.File)
Managed to get the input field value by doing something like this:
import React, { Component } from 'react';
class App extends Component {
constructor(props){
super(props);
this.state = {
username : ''
}
this.updateInput = this.updateInput.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
updateInput(event){
this.setState({username : event.target.value})
}
handleSubmit(){
console.log('Your input value is: ' + this.state.username)
//Send state to the server code
}
render(){
return (
<div>
<input type="text" onChange={this.updateInput}></input>
<input type="submit" onClick={this.handleSubmit} ></input>
</div>
);
}
}
//output
//Your input value is: x
You can use the csv
module to parse tab seperated value files easily.
import csv
with open("tab-separated-values") as tsv:
for line in csv.reader(tsv, dialect="excel-tab"): #You can also use delimiter="\t" rather than giving a dialect.
...
Where line
is a list of the values on the current row for each iteration.
Edit: As suggested below, if you want to read by column, and not by row, then the best thing to do is use the zip()
builtin:
with open("tab-separated-values") as tsv:
for column in zip(*[line for line in csv.reader(tsv, dialect="excel-tab")]):
...