The functions have different purposes. vector::insert
allows you to insert an object at a specified position in the vector
, whereas vector::push_back
will just stick the object on the end. See the following example:
using namespace std;
vector<int> v = {1, 3, 4};
v.insert(next(begin(v)), 2);
v.push_back(5);
// v now contains {1, 2, 3, 4, 5}
You can use insert
to perform the same job as push_back
with v.insert(v.end(), value)
.
Instead of
paste
(default spaces), paste0
(force the inclusion of missing NA
as character) or unite
(constrained to 2 columns and 1 separator), I'd suggest an alternative as flexible as paste0
but more careful with NA
: stringr::str_c
library(tidyverse)
# check the missing value!!
df <- tibble(
n = c(2, 2, 8),
s = c("aa", "aa", NA_character_),
b = c(TRUE, FALSE, TRUE)
)
df %>%
mutate(
paste = paste(n,"-",s,".",b),
paste0 = paste0(n,"-",s,".",b),
str_c = str_c(n,"-",s,".",b)
) %>%
# convert missing value to ""
mutate(
s_2=str_replace_na(s,replacement = "")
) %>%
mutate(
str_c_2 = str_c(n,"-",s_2,".",b)
)
#> # A tibble: 3 x 8
#> n s b paste paste0 str_c s_2 str_c_2
#> <dbl> <chr> <lgl> <chr> <chr> <chr> <chr> <chr>
#> 1 2 aa TRUE 2 - aa . TRUE 2-aa.TRUE 2-aa.TRUE "aa" 2-aa.TRUE
#> 2 2 aa FALSE 2 - aa . FALSE 2-aa.FALSE 2-aa.FALSE "aa" 2-aa.FALSE
#> 3 8 <NA> TRUE 8 - NA . TRUE 8-NA.TRUE <NA> "" 8-.TRUE
Created on 2020-04-10 by the reprex package (v0.3.0)
extra note from str_c
documentation
Like most other R functions, missing values are "infectious": whenever a missing value is combined with another string the result will always be missing. Use
str_replace_na()
to convertNA
to"NA"
It is actually called file:///android_asset/index.html
file:///android_assets/index.html
will give you a build error.
The followings are my 9 solutions. Feel free to insert text into the divs or svg elements.
var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');
ctx.beginPath();
ctx.arc(50, 50, 50, 0, 2 * Math.PI);
ctx.fillStyle = '#B90136';
ctx.fill();
_x000D_
#circle1 {
background-color: #B90136;
width: 100px;
height: 100px;
border-radius: 50px;
}
#circle2 {
background-color: #B90136;
width: 100px;
height: 100px;
clip-path: circle();
}
#circle3 {
color: #B90136;
font-size: 100px;
line-height: 100px;
}
#circle4::before {
content: "";
display: block;
width: 100px;
height: 100px;
border-radius: 50px;
background-color: #B90136;
}
#circle5 {
background-image: radial-gradient(#B90136 70%, transparent 30%);
height: 100px;
width: 100px;
}
_x000D_
<h3>1 border-radius</h3>
<div id="circle1"></div>
<hr/>
<h3>2 clip-path</h3>
<div id="circle2"></div>
<hr/>
<h3>3 html entity</h3>
<div id="circle3">⬤</div>
<hr/>
<h3>4 pseudo element</h3>
<div id="circle4"></div>
<hr/>
<h3>5 radial-gradient</h3>
<div id="circle5"></div>
<hr/>
<h3>6 svg circle & path</h3>
<svg width="100" height="100">
<circle cx="50" cy="50" r="50" fill="#B90136" />
</svg>
<hr/>
<h3>7 canvas arc()</h3>
<canvas id="myCanvas" width="100" height="100"></canvas>
<hr/>
<h3>8 img tag</h3>
<img src="circle.png" width="100" height="100" />
<hr/>
<h3>9 pre tag</h3>
<pre style="line-height:8px;">
+++
+++++
+++++++
+++++++++
+++++++++++
+++++++++++
+++++++++++
+++++++++
+++++++
+++++
+++
</pre>
_x000D_
Just multiply the number by 100, round, and divide the resulting number by 100.
Look into System.Threading.Timer
class. I think this is what you're looking for.
The code example on MSDN seems to show this class doing very similar to what you're trying to do (check status after certain time).
The mentioned code example from the MSDN link:
using System;
using System.Threading;
class TimerExample
{
static void Main()
{
// Create an AutoResetEvent to signal the timeout threshold in the
// timer callback has been reached.
var autoEvent = new AutoResetEvent(false);
var statusChecker = new StatusChecker(10);
// Create a timer that invokes CheckStatus after one second,
// and every 1/4 second thereafter.
Console.WriteLine("{0:h:mm:ss.fff} Creating timer.\n",
DateTime.Now);
var stateTimer = new Timer(statusChecker.CheckStatus,
autoEvent, 1000, 250);
// When autoEvent signals, change the period to every half second.
autoEvent.WaitOne();
stateTimer.Change(0, 500);
Console.WriteLine("\nChanging period to .5 seconds.\n");
// When autoEvent signals the second time, dispose of the timer.
autoEvent.WaitOne();
stateTimer.Dispose();
Console.WriteLine("\nDestroying timer.");
}
}
class StatusChecker
{
private int invokeCount;
private int maxCount;
public StatusChecker(int count)
{
invokeCount = 0;
maxCount = count;
}
// This method is called by the timer delegate.
public void CheckStatus(Object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
Console.WriteLine("{0} Checking status {1,2}.",
DateTime.Now.ToString("h:mm:ss.fff"),
(++invokeCount).ToString());
if(invokeCount == maxCount)
{
// Reset the counter and signal the waiting thread.
invokeCount = 0;
autoEvent.Set();
}
}
}
// The example displays output like the following:
// 11:59:54.202 Creating timer.
//
// 11:59:55.217 Checking status 1.
// 11:59:55.466 Checking status 2.
// 11:59:55.716 Checking status 3.
// 11:59:55.968 Checking status 4.
// 11:59:56.218 Checking status 5.
// 11:59:56.470 Checking status 6.
// 11:59:56.722 Checking status 7.
// 11:59:56.972 Checking status 8.
// 11:59:57.223 Checking status 9.
// 11:59:57.473 Checking status 10.
//
// Changing period to .5 seconds.
//
// 11:59:57.474 Checking status 1.
// 11:59:57.976 Checking status 2.
// 11:59:58.476 Checking status 3.
// 11:59:58.977 Checking status 4.
// 11:59:59.477 Checking status 5.
// 11:59:59.977 Checking status 6.
// 12:00:00.478 Checking status 7.
// 12:00:00.980 Checking status 8.
// 12:00:01.481 Checking status 9.
// 12:00:01.981 Checking status 10.
//
// Destroying timer.
I think 2 update calls should do
update VersionedFields
set Value = replace(value,'<iframe','<a><iframe')
update VersionedFields
set Value = replace(value,'> </iframe>','</a>')
This code will let you have a variable number of rows (with a variable number of DIVs on each row) and it will make all of the DIVs on each row match the height of its tallest neighbour:
If we assumed all the DIVs, that are floating, are inside a container with the id "divContainer", then you could use the following:
$(document).ready(function() {
var currentTallest = 0;
var currentRowStart = 0;
var rowDivs = new Array();
$('div#divContainer div').each(function(index) {
if(currentRowStart != $(this).position().top) {
// we just came to a new row. Set all the heights on the completed row
for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) rowDivs[currentDiv].height(currentTallest);
// set the variables for the new row
rowDivs.length = 0; // empty the array
currentRowStart = $(this).position().top;
currentTallest = $(this).height();
rowDivs.push($(this));
} else {
// another div on the current row. Add it to the list and check if it's taller
rowDivs.push($(this));
currentTallest = (currentTallest < $(this).height()) ? ($(this).height()) : (currentTallest);
}
// do the last row
for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) rowDivs[currentDiv].height(currentTallest);
});
});
From what the other answers have proposed, I believe this might help:
var object = ips[ipId];
var name = "Joe";
var anothername = "Fred";
var value = "Thingy";
var anothervalue = "Fingy";
object[name] = value;
object[anothername] = anothervalue;
However, this is not tested, just an assumption based on the constant repetition of:
object["string"] = value;
//object = {string: value}
Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
This should work:
function valthisform()
{
var checkboxs=document.getElementsByName("c1");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
break;
}
}
if(okay)alert("Thank you for checking a checkbox");
else alert("Please check a checkbox");
}
If you have a question about the code, just comment.
I use l=checkboxs.length
to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/
I'd recommend the Range object's AutoFill method for this:
rngSource.AutoFill Destination:=rngDest
Specify the Source range that contains the values or formulas you want to fill down, and the Destination range as the whole range that you want the cells filled to. The Destination range must include the Source range. You can fill across as well as down.
It works exactly the same way as it would if you manually "dragged" the cells at the corner with the mouse; absolute and relative formulas work as expected.
Here's an example:
'Set some example values'
Range("A1").Value = "1"
Range("B1").Formula = "=NOW()"
Range("C1").Formula = "=B1+A1"
'AutoFill the values / formulas to row 20'
Range("A1:C1").AutoFill Destination:=Range("A1:C20")
Hope this helps.
I know I am very late to the party, but I finaly found out how we can register the MaxLengthAttribute
.
First we need a validator:
public class MaxLengthClientValidator : DataAnnotationsModelValidator<MaxLengthAttribute>
{
private readonly string _errorMessage;
private readonly int _length;
public MaxLengthClientValidator(ModelMetadata metadata, ControllerContext context, MaxLengthAttribute attribute)
: base(metadata, context, attribute)
{
_errorMessage = attribute.FormatErrorMessage(metadata.DisplayName);
_length = attribute.Length;
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
var rule = new ModelClientValidationRule
{
ErrorMessage = _errorMessage,
ValidationType = "length"
};
rule.ValidationParameters["max"] = _length;
yield return rule;
}
}
Nothing realy special. In the constructor we save some values from the attribute. In the GetClientValidationRules
we set a rule. ValidationType = "length"
is mapped to data-val-length
by the framework. rule.ValidationParameters["max"]
is for the data-val-length-max
attribute.
Now since you have a validator, you only need to register it in global.asax
:
protected void Application_Start()
{
//...
//Register Validator
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MaxLengthAttribute), typeof(MaxLengthClientValidator));
}
Et voila, it just works.
Most of the answers are correct but I want to add little more. The ternary operator is right-associative, which means it can be chained in the following way if … else-if … else-if … else
:
function example() {
return condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: value4;
}
Equivalent to:
function example() {
if (condition1) { return value1; }
else if (condition2) { return value2; }
else if (condition3) { return value3; }
else { return value4; }
}
More details is here
The fastest way is to do a*a
or a**2
or np.square(a)
whereas np.power(a, 2)
showed to be considerably slower.
np.power()
allows you to use different exponents for each element if instead of 2
you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2
or a*a
, which become important in cases where you have small tolerances.
I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:
In [29]: a = np.random.random((1000, 1000))
In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop
In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop
In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop
The way I do it, taking advantage of some modern C# features:
Option 1)
public static class Utils {
public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) {
return !(list?.Any() ?? false);
}
}
Option 2)
public static class Utils {
public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) {
return !(list?.Any()).GetValueOrDefault();
}
}
And by the way, never use Count == 0
or Count() == 0
just to check if a collection is empty. Always use Linq's .Any()
This is the hardware serial number. To access it on
Android Q (>= SDK 29)
android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE
is required. Only system apps can require this permission. If the calling package is the device or profile owner then the READ_PHONE_STATE
permission suffices.
Android 8 and later (>= SDK 26) use android.os.Build.getSerial()
which requires the dangerous permission READ_PHONE_STATE. Using android.os.Build.SERIAL
returns android.os.Build.UNKNOWN.
Android 7.1 and earlier (<= SDK 25) and earlier android.os.Build.SERIAL
does return a valid serial.
It's unique for any device. If you are looking for possibilities on how to get/use a unique device id you should read here.
For a solution involving reflection without requiring a permission see this answer.
Try disabling and enabling the textbox.
refer below link for getting ScanResult with redundant ssid removed from the list
I was getting this problem while using a tunnel because I:
once i started punching the tunnel url:port into the browser, i was good to go.
i'm using Rails and Facebooker, but might help others just the same.
If you paste
A.do() {
if (condition1) {
X.doSomething
} else if (condition2) {
Y.doSomethingElse
} else {
donotDoAnything
}
}
onto https://www.zenuml.com. It will generate a diagram for you.
You must make your foreign key nullable:
public class User
{
public int Id { get; set; }
public int? CountryId { get; set; }
public virtual Country Country { get; set; }
}
You can decode it to str with receive.decode('utf_8')
.
You can also use lib-auto
xmlns:app="http://schemas.android.com/apk/lib-auto"
pyPDF works fine (assuming that you're working with well-formed PDFs). If all you want is the text (with spaces), you can just do:
import pyPdf
pdf = pyPdf.PdfFileReader(open(filename, "rb"))
for page in pdf.pages:
print page.extractText()
You can also easily get access to the metadata, image data, and so forth.
A comment in the extractText code notes:
Locate all text drawing commands, in the order they are provided in the content stream, and extract the text. This works well for some PDF files, but poorly for others, depending on the generator used. This will be refined in the future. Do not rely on the order of text coming out of this function, as it will change if this function is made more sophisticated.
Whether or not this is a problem depends on what you're doing with the text (e.g. if the order doesn't matter, it's fine, or if the generator adds text to the stream in the order it will be displayed, it's fine). I have pyPdf extraction code in daily use, without any problems.
A fast solution is using the gnu utility truncate
:
[ -z $(tail -c1 file) ] && truncate -s-1 file
The test will be true if the file does have a trailing new line.
The removal is very fast, truly in place, no new file is needed and the search is also reading from the end just one byte (tail -c1
).
Try changing the app/config/email.php
smtp
to mail
You could also use a CSS "calc" to get the same effect instead of using the negative margin or transform properties (in case you want to use those properties for anything else).
.hero:after,
.hero:after {
z-index: -1;
position: absolute;
top: 98.1%;
left: calc(50% - 25px);
content: '';
width: 0;
height: 0;
border-top: solid 50px #e15915;
border-left: solid 50px transparent;
border-right: solid 50px transparent;
}
for me the "workaround" solution was to remove the "_normal" from the end of the string
Check it out below:
In Mvc 4 you can use AcceptVerbsAttribute, I think this is a very clean solution
[AcceptVerbs(WebRequestMethods.Http.Get, WebRequestMethods.Http.Post)]
public IHttpActionResult Login()
{
// Login logic
}
Config file:
worker_processes 4; # 2 * Number of CPUs
events {
worker_connections 19000; # It's the key to high performance - have a lot of connections available
}
worker_rlimit_nofile 20000; # Each connection needs a filehandle (or 2 if you are proxying)
# Total amount of users you can serve = worker_processes * worker_connections
more info: Optimizing nginx for high traffic loads
I know some things have changed in AC 2010. However, the old-fashioned ADODB is, as far as I know, the best way to go in VBA. An Example:
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter
Dim rs As ADODB.Recordset
Dim colReturn As New Collection
Dim SQL As String
SQL = _
"SELECT c.ClientID, c.LastName, c.FirstName, c.MI, c.DOB, c.SSN, " & _
"c.RaceID, c.EthnicityID, c.GenderID, c.Deleted, c.RecordDate " & _
"FROM tblClient AS c " & _
"WHERE c.ClientID = @ClientID"
Set cn = New ADODB.Connection
Set cmd = New ADODB.Command
With cn
.Provider = DataConnection.MyADOProvider
.ConnectionString = DataConnection.MyADOConnectionString
.Open
End With
With cmd
.CommandText = SQL
.ActiveConnection = cn
Set prm = .CreateParameter("@ClientID", adInteger, adParamInput, , mlngClientID)
.Parameters.Append prm
End With
Set rs = cmd.Execute
With rs
If Not .EOF Then
Do Until .EOF
mstrLastName = Nz(!LastName, "")
mstrFirstName = Nz(!FirstName, "")
mstrMI = Nz(!MI, "")
mdDOB = !DOB
mstrSSN = Nz(!SSN, "")
mlngRaceID = Nz(!RaceID, -1)
mlngEthnicityID = Nz(!EthnicityID, -1)
mlngGenderID = Nz(!GenderID, -1)
mbooDeleted = Deleted
mdRecordDate = Nz(!RecordDate, "")
.MoveNext
Loop
End If
.Close
End With
cn.Close
Set rs = Nothing
Set cn = Nothing
Below is my simple approach to the issue.
JQuery function:
jQuery.fn.trackClicks = function () {
if ($(this).attr("data-clicks") === undefined) $(this).attr("data-clicks", 0);
var timer;
$(this).click(function () {
$(this).attr("data-clicks", parseInt($(this).attr("data-clicks")) + 1);
if (timer) clearTimeout(timer);
var item = $(this);
timer = setTimeout(function() {
item.attr("data-clicks", 0);
}, 1000);
});
}
Implementation:
$(function () {
$("a").trackClicks();
$("a").click(function () {
if ($(this).attr("data-clicks") === "2") {
// Double clicked
}
});
});
Inspect the clicked element in Firefox/Chrome to see data-clicks go up and down as you click, adjust time (1000) to suit.
One way is (this is with Bash)
grep -P '\t'
-P
turns on Perl regular expressions so \t will work.
As user unwind says, it may be specific to GNU grep. The alternative is to literally insert a tab in there if the shell, editor or terminal will allow it.
In my case, this causes error:
return response->json(["message" => "Model status successfully updated!", "data" => $model], 200);
but this not:
return response->json(["message" => "Model status successfully updated!", "data" => $model->toJson()], 200);
I've written a tutorial that expands on the answer posted by JVitela. Basically, it uses the same idea, but instead of rendering each string to a texture, it renders all characters from a font file to a texture and uses that to allow for full dynamic text rendering with no further slowdowns (once the initialization is complete).
The main advantage of my method, compared to the various font atlas generators, is that you can ship small font files (.ttf .otf) with your project instead of having to ship large bitmaps for every font variation and size. It can generate perfect quality fonts at any resolution using only a font file :)
The tutorial includes full code that can be used in any project :)
data = []
n = int(raw_input('Enter how many elements you want: '))
for i in range(0, n):
x = raw_input('Enter the numbers into the array: ')
data.append(x)
print(data)
Now this doesn't do any error checking and it stores data as a string.
I've found this to work for me:
to hide:
$('.mapWrapper')
.css({
visibility: 'hidden',
height: 0
});
to show:
$('.mapWrapper').css({
visibility: 'visible',
height: 'auto'
});
The posted answers are very good when working with data.frame
s. However, these tasks can be pretty inefficient from a memory perspective. With large data, removing a column can take an unusually long amount of time and/or fail due to out of memory
errors. Package data.table
helps address this problem with the :=
operator:
library(data.table)
> dt <- data.table(a = 1, b = 1, c = 1)
> dt[,a:=NULL]
b c
[1,] 1 1
I should put together a bigger example to show the differences. I'll update this answer at some point with that.
Swift 3+
button.setImage(UIImage(named: "selected_image"), for: [.selected, .highlighted])
OR
button.setImage(UIImage(named: "selected_image"), for: UIControlState.selected.union(.highlighted))
It means that the button current in selected
state, then you touch it, show the highlight
state.
I've seen various suggestions how code can find out whether it runs on the emulator, but none are quite satisfactory, or "future-proof". For the time being I've settled on reading the device ID, which is all zeros for the emulator:
TelephonyManager telmgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); boolean isEmulator = "000000000000000".equals(telmgr.getDeviceId());
But on a deployed app that requires the READ_PHONE_STATE permission
You can increase body size in nginx configuration file as
sudo nano /etc/nginx/nginx.conf
client_max_body_size 100M;
Restart nginx to apply the changes.
sudo service nginx restart
I have found that this error can occur in DESIGN MODE as opposed to ? execution mode... If you are doing something such as creating a class member which requires access to an .INI or .HTM file (configuration file, help file) you might want to NOT initialize the item in the declaration, but initialize it later in FORM_Load() etc... When you DO initialize... Use a guard IF statement:
/// <summary>FORM: BasicApp - Load</summary>
private void BasicApp_Load(object sender, EventArgs e)
{
// Setup Main Form Caption with App Name and Config Control Info
if (!DesignMode)
{
m_Globals = new Globals();
Text = TGG.GetApplicationConfigInfo();
}
}
This will keep the MSVS Designer from trying to create an INI or HTM file when you are in design mode.
I had to use un function which finds every elements in an array. So I modified the function done by Jakub Trunecek as follow:
function search_in_array_r($needle, $array) {
$found = array();
foreach ($array as $key => $val) {
if ($val[1] == $needle) {
array_push($found, $val[1]);
}
}
if (count($found) != 0)
return $found;
else
return null;
}
<font color="red">This is some text!</font>
This worked the best for me when I only wanted to change one word into the color red in a sentence.
For Expose.class Error i.e
java.util.zip.ZipException: duplicate entry: com/google/gson/annotations/Expose.class
use the below code
configurations {
all*.exclude module: 'gson'
}
public static void main(String[] args) {
Scanner input= new Scanner(System.in);`
String data=input.nextLine();
int cnt=0;
System.out.println(data);
for(int i=0;i<data.length()-1;i++)
{if(data.charAt(i)==' ')
{
cnt++;
}
}
System.out.println("Total number of Spaces in a given String are " +cnt);
}
/*
Input from command line using atoi, and strtol
*/
#include <stdio.h>//printf, scanf
#include <stdlib.h>//atoi, strtol
//strtol - converts a string to a long int
//atoi - converts string to an int
int main(int argc, char *argv[]){
char *p;//used in strtol
int i;//used in for loop
long int longN = strtol( argv[1],&p, 10);
printf("longN = %ld\n",longN);
//cast (int) to strtol
int N = (int) strtol( argv[1],&p, 10);
printf("N = %d\n",N);
int atoiN;
for(i = 0; i < argc; i++)
{
//set atoiN equal to the users number in the command line
//The C library function int atoi(const char *str) converts the string argument str to an integer (type int).
atoiN = atoi(argv[i]);
}
printf("atoiN = %d\n",atoiN);
//-----------------------------------------------------//
//Get string input from command line
char * charN;
for(i = 0; i < argc; i++)
{
charN = argv[i];
}
printf("charN = %s\n", charN);
}
Hope this helps. Good luck!
As a refinement of simplest solution, and if you can’t or don’t want to install Powershell, just run:
dir /s /b | sort /r /+261 > out.txt
or (faster):
dir /s /b | sort /r /+261 /o out.txt
And lines longer than 260 will get to the top of listing. Note that you must add 1 to SORT column parameter (/+n).
On my Slovenian keyboard it is ALT + Ð
First you have to install a module call Serial. To do that go to the folder call Scripts which is located in python installed folder. If you are using Python 3 version it's normally located in location below,
C:\Python34\Scripts
Once you open that folder right click on that folder with shift key. Then click on 'open command window here'. After that cmd
will pop up. Write the below code in that cmd
window,
pip install PySerial
and press enter.after that PySerial module will be installed. Remember to install the module u must have an INTERNET connection.
after successfully installed the module open python IDLE and write down the bellow code and run it.
import serial
# "COM11" is the port that your Arduino board is connected.set it to port that your are using
ser = serial.Serial("COM11", 9600)
while True:
cc=str(ser.readline())
print(cc[2:][:-5])
You need to click Log Navigator icon (far right in left sidebar). Then choose your Debug/Run session in left sidebar, and you will have console in editor area.
If all you want to do is store some static values in a lookup table, you can use an Object Literal (the same format used by JSON) to do it compactly:
var table = { one: [1,10,5], two: [2], three: [3, 30, 300] }
And then access them using JavaScript's associative array syntax:
alert(table['one']); // Will alert with [1,10,5]
alert(table['one'][1]); // Will alert with 10
I could be wrong because I've never used Angular, but I believe you are probably using ng-bind
, which will create just a TextNode.
You will want to use ng-bind-html
instead.
http://docs.angularjs.org/api/ngSanitize.directive:ngBindHtml
Update: It looks like you'll need to use ng-bind-html-unsafe='q.category'
http://docs.angularjs.org/api/ng.directive:ngBindHtmlUnsafe
Here's a demo:
Tcpdf is also a good liabrary for generating pdf in php http://www.tcpdf.org/
Unsure what dbms you're using however I'd do it this way in Microsoft SQL:
select [date]
from tbemp
order by cast([date] as datetime) asc
For that kind of behavior I always use the jQueryUI button
widget, I use it for links and buttons.
Define the tag within HTML:
<button id="sampleButton">Sample Button</button>
<a id="linkButton" href="yourHttpReferenceHere">Link Button</a>
Use jQuery to initialize the buttons:
$("#sampleButton").button();
$("#linkButton").button();
Use the button
widget methods to disable/enable them:
$("#sampleButton").button("enable"); //enable the button
$("#linkButton").button("disable"); //disable the button
That will take care of the button and cursor behavior, but if you need to get deeper and change the button style when disabled then overwrite the following CSS classes within your page CSS style file.
.ui-state-disabled,
.ui-widget-content .ui-state-disabled,
.ui-widget-header .ui-state-disabled {
background-color:aqua;
color:black;
}
But remember: those CSS classes (if changed) will change the style for other widgets too.
As an example of the difference -- if you have a task the does something with the UI thread (e.g. a task that represents an animation in a Storyboard) if you Task.WaitAll()
then the UI thread is blocked and the UI is never updated. if you use await Task.WhenAll()
then the UI thread is not blocked, and the UI will be updated.
I think it's just for your convenience (and the readers of your code)
Your code, and your unit tests should be ideally self documenting which this API helps with,
Think abt what is more clear to read:
AssertTrue(!(a > 3));
or
AssertFalse(a > 3);
When you open your tests after xx months when your tests suddenly fail, it would take you much less time to understand what went wrong in the second case (my opinion). If you disagree, you can always stick with AssertTrue for all cases :)
As another poster said, it's typically preferable to have interfaces define capabilities not types. I would tend not to "implement" something like a "User," and this is why "IUser" often isn't really necessary in the way described here. I often see classes as nouns and interfaces as adjectives:
class Number implements Comparable{...}
class MyThread implements Runnable{...}
class SessionData implements Serializable{....}
Sometimes an Adjective doesn't make sense, but I'd still generally be using interfaces to model behavior, actions, capabilities, properties, etc,... not types.
Also, If you were really only going to make one User and call it User then what's the point of also having an IUser interface? And if you are going to have a few different types of users that need to implement a common interface, what does appending an "I" to the interface save you in choosing names of the implementations?
I think a more realistic example would be that some types of users need to be able to login to a particular API. We could define a Login interface, and then have a "User" parent class with SuperUser, DefaultUser, AdminUser, AdministrativeContact, etc suclasses, some of which will or won't implement the Login (Loginable?) interface as necessary.
I think this will do:
$('#'+div_id+' .widget-head > span').text("new dialog title");
With nginx you can send both tokens like this (even though it's against the standard):
Authorization: Basic basic-token,Bearer bearer-token
This works as long as the basic token is first - nginx successfully forwards it to the application server.
And then you need to make sure your application can properly extract the Bearer from the above string.
I adjusted the code of @madprops for Python 3
# getem.py
# python2 script to download all images in a given url
# use: python getem.py http://url.where.images.are
from bs4 import BeautifulSoup
import urllib.request
import shutil
import requests
from urllib.parse import urljoin
import sys
import time
def make_soup(url):
req = urllib.request.Request(url, headers={'User-Agent' : "Magic Browser"})
html = urllib.request.urlopen(req)
return BeautifulSoup(html, 'html.parser')
def get_images(url):
soup = make_soup(url)
images = [img for img in soup.findAll('img')]
print (str(len(images)) + " images found.")
print('Downloading images to current working directory.')
image_links = [each.get('src') for each in images]
for each in image_links:
try:
filename = each.strip().split('/')[-1].strip()
src = urljoin(url, each)
print('Getting: ' + filename)
response = requests.get(src, stream=True)
# delay to avoid corrupted previews
time.sleep(1)
with open(filename, 'wb') as out_file:
shutil.copyfileobj(response.raw, out_file)
except:
print(' An error occured. Continuing.')
print('Done.')
if __name__ == '__main__':
get_images('http://www.wookmark.com')
android:windowSoftInputMode="adjustPan"
android:isScrollContainer="true"
works for android EditText, while it not works for webview or xwalkview. When soft keyboard hide the input in webview or xwalkview you have use android:windowSoftInputMode="adjustResize"
This is really a tricky thing to have a sticky header on your table. I had same requirement but with asp:GridView and then I found it really thought to have sticky header on gridview. There are many solutions available and it took me 3 days trying all the solution but none of them could satisfy.
The main issue that I faced with most of these solutions was the alignment problem. When you try to make the header floating, somehow the alignment of header cells and body cells get off track.
With some solutions, I also got issue of getting header overlapped to first few rows of body, which cause body rows getting hidden behind the floating header.
So now I had to implement my own logic to achieve this, though I also not consider this as perfect solution but this could also be helpful for someone,
Below is the sample table.
<div class="table-holder">
<table id="MyTable" cellpadding="4" cellspacing="0" border="1px" class="customerTable">
<thead>
<tr><th>ID</th><th>First Name</th><th>Last Name</th><th>DOB</th><th>Place</th></tr>
</thead>
<tbody>
<tr><td>1</td><td>Customer1</td><td>LastName</td><td>1-1-1</td><td>SUN</td></tr>
<tr><td>2</td><td>Customer2</td><td>LastName</td><td>2-2-2</td><td>Earth</td></tr>
<tr><td>3</td><td>Customer3</td><td>LastName</td><td>3-3-3</td><td>Mars</td></tr>
<tr><td>4</td><td>Customer4</td><td>LastName</td><td>4-4-4</td><td>Venus</td></tr>
<tr><td>5</td><td>Customer5</td><td>LastName</td><td>5-5-5</td><td>Saturn</td></tr>
<tr><td>6</td><td>Customer6</td><td>LastName</td><td>6-6-6</td><td>Jupitor</td></tr>
<tr><td>7</td><td>Customer7</td><td>LastName</td><td>7-7-7</td><td>Mercury</td></tr>
<tr><td>8</td><td>Customer8</td><td>LastName</td><td>8-8-8</td><td>Moon</td></tr>
<tr><td>9</td><td>Customer9</td><td>LastName</td><td>9-9-9</td><td>Uranus</td></tr>
<tr><td>10</td><td>Customer10</td><td>LastName</td><td>10-10-10</td><td>Neptune</td></tr>
</tbody>
</table>
</div>
Note: The table is wrapped into a DIV with class attribute equal to 'table-holder'.
Below is the JQuery script that I added in my html page header.
<script src="../Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="../Scripts/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
//create var for table holder
var originalTableHolder = $(".table-holder");
// set the table holder's with
originalTableHolder.width($('table', originalTableHolder).width() + 17);
// Create a clone of table holder DIV
var clonedtableHolder = originalTableHolder.clone();
// Calculate height of all header rows.
var headerHeight = 0;
$('thead', originalTableHolder).each(function (index, element) {
headerHeight = headerHeight + $(element).height();
});
// Set the position of cloned table so that cloned table overlapped the original
clonedtableHolder.css('position', 'relative');
clonedtableHolder.css('top', headerHeight + 'px');
// Set the height of cloned header equal to header height only so that body is not visible of cloned header
clonedtableHolder.height(headerHeight);
clonedtableHolder.css('overflow', 'hidden');
// reset the ID attribute of each element in cloned table
$('*', clonedtableHolder).each(function (index, element) {
if ($(element).attr('id')) {
$(element).attr('id', $(element).attr('id') + '_Cloned');
}
});
originalTableHolder.css('border-bottom', '1px solid #aaa');
// Place the cloned table holder before original one
originalTableHolder.before(clonedtableHolder);
});
</script>
and at last below is the CSS class for bit of coloring purpose.
.table-holder
{
height:200px;
overflow:auto;
border-width:0px;
}
.customerTable thead
{
background: #4b6c9e;
color:White;
}
So the whole idea of this logic is to place the table into a table holder div and create clone of that holder at client side when page loaded. Now hide the body of table inside clone holder and position the remaining header part over to original header.
Same solution also works for asp:gridview, you need to add two more steps to achieve this in gridview,
In OnPrerender event of gridview object in your web page, set the table section of header row equal to TableHeader.
if (this.HeaderRow != null)
{
this.HeaderRow.TableSection = TableRowSection.TableHeader;
}
And wrap your grid into <div class="table-holder"></div>
.
Note: if your header has clickable controls then you may need to add some more jQuery script to pass the events raised in cloned header to original header. This code is already available in jQuery sticky-header plugin create by jmosbech
jQuery Solution!
Demo: http://jsfiddle.net/69wP6/2/
Another Demo Below(updated!)
I needed something similar in a case when i had some fixed Options and i wanted one other option to be editable! In this case i made a hidden input that would overlap the select option and would be editable and used jQuery to make it all work seamlessly.
I am sharing the fiddle with all of you!
HTML
<div id="billdesc">
<select id="test">
<option class="non" value="option1">Option1</option>
<option class="non" value="option2">Option2</option>
<option class="editable" value="other">Other</option>
</select>
<input class="editOption" style="display:none;"></input>
</div>
CSS
body{
background: blue;
}
#billdesc{
padding-top: 50px;
}
#test{
width: 100%;
height: 30px;
}
option {
height: 30px;
line-height: 30px;
}
.editOption{
width: 90%;
height: 24px;
position: relative;
top: -30px
}
jQuery
var initialText = $('.editable').val();
$('.editOption').val(initialText);
$('#test').change(function(){
var selected = $('option:selected', this).attr('class');
var optionText = $('.editable').text();
if(selected == "editable"){
$('.editOption').show();
$('.editOption').keyup(function(){
var editText = $('.editOption').val();
$('.editable').val(editText);
$('.editable').html(editText);
});
}else{
$('.editOption').hide();
}
});
Edit : Added some simple touches design wise, so people can clearly see where the input ends!
JS Fiddle : http://jsfiddle.net/69wP6/4/
Use FileUtils to handle all these headaches.
Edit: For example, use below code to write to a file, this method will 'checking and creating the parent directory if it does not exist'.
openOutputStream(File file [, boolean append])
There is no agreed upon naming convention for HTML and CSS. But you could structure your nomenclature around object design. More specifically what I call Ownership and Relationship.
Ownership
Keywords that describe the object, could be separated by hyphens.
car-new-turned-right
Keywords that describe the object can also fall into four categories (which should be ordered from left to right): Object, Object-Descriptor, Action, and Action-Descriptor.
car - a noun, and an object
new - an adjective, and an object-descriptor that describes the object in more detail
turned - a verb, and an action that belongs to the object
right - an adjective, and an action-descriptor that describes the action in more detail
Note: verbs (actions) should be in past-tense (turned, did, ran, etc).
Relationship
Objects can also have relationships like parent and child. The Action and Action-Descriptor belongs to the parent object, they don't belong to the child object. For relationships between objects you could use an underscore.
car-new-turned-right_wheel-left-turned-left
- car-new-turned-right (follows the ownership rule)
- wheel-left-turned-left (follows the ownership rule)
- car-new-turned-right_wheel-left-turned-left (follows the relationship rule)
Final notes:
Unless you have some really compelling reason not to, I suggest ditching the MS JDBC driver.
Instead, use the jtds jdbc driver. Read the README.SSO file in the jtds distribution on how to configure for single-sign-on (native authentication) and where to put the native DLL to ensure it can be loaded by the JVM.
I don't think the Chrome Developer tools pretty print XHR content. See: Viewing HTML response from Ajax call through Chrome Developer tools?
$('.div').html(val) will set the HTML values of all selected elements, $('.div').text(val) will set the text values of all selected elements.
I would guess that they correspond to Node#textContent and Element#innerHTML, respectively. (Gecko DOM references).
You should try this syntax - assuming you want to have @OrderID
as a parameter for your stored procedure:
CREATE PROCEDURE dbo.YourStoredProcNameHere
@OrderID INT
AS
BEGIN
DECLARE @OrderItemID AS INT
DECLARE @AppointmentID AS INT
DECLARE @PurchaseOrderID AS INT
DECLARE @PurchaseOrderItemID AS INT
DECLARE @SalesOrderID AS INT
DECLARE @SalesOrderItemID AS INT
SELECT @OrderItemID = OrderItemID
FROM [OrderItem]
WHERE OrderID = @OrderID
SELECT @AppointmentID = AppoinmentID
FROM [Appointment]
WHERE OrderID = @OrderID
SELECT @PurchaseOrderID = PurchaseOrderID
FROM [PurchaseOrder]
WHERE OrderID = @OrderID
END
OF course, that only works if you're returning exactly one value (not multiple values!)
The visual studio default setting should be the same as the interpreter path.
Change VS code default setting: windows: File > Preferences > Settings
{
"python.pythonPath": "C:\\Users\\Anaconda3\\pythonw.exe",
"workbench.startupEditor": "newUntitledFile"
}
Find the right interpreter: windows: Ctrl+Shift+P->select interpreter:
the path of that interpreter should be same as the version you are working on.
ToAddress = "[email protected]"
ToAddress1 = "[email protected]"
ToAddress2 = "[email protected]"
MessageSubject = "It works!."
Set ol = CreateObject("Outlook.Application")
Set newMail = ol.CreateItem(olMailItem)
newMail.Subject = MessageSubject
newMail.RecipIents.Add(ToAddress)
newMail.RecipIents.Add(ToAddress1)
newMail.RecipIents.Add(ToAddress2)
newMail.Send
Use the Soot Java Optimization framework to directly modify the bytecode. http://www.sable.mcgill.ca/soot/
Soot is completely written in Java and works with new Java versions.
While C++ (excluding C++11) has enums, the values in them are "leaked" into the global namespace.
If you don't want to have them leaked (and don't NEED to use the enum type), consider the following:
class EnumName {
public:
static int EnumVal1;
(more definitions)
};
EnumName::EnumVal1 = {value};
if ([your value] == EnumName::EnumVal1) ...
I just found this question and thought it needs a more comprehensive answer:
As of PHP 5.4 there are three methods to accomplish this:
The header()
function has a special use-case that detects a HTTP response line and lets you replace that with a custom one
header("HTTP/1.1 200 OK");
However, this requires special treatment for (Fast)CGI PHP:
$sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cgi')
header("Status: 404 Not Found");
else
header("HTTP/1.1 404 Not Found");
Note: According to the HTTP RFC, the reason phrase can be any custom string (that conforms to the standard), but for the sake of client compatibility I do not recommend putting a random string there.
Note: php_sapi_name()
requires PHP 4.0.1
There are obviously a few problems when using that first variant. The biggest of which I think is that it is partly parsed by PHP or the web server and poorly documented.
Since 4.3, the header
function has a 3rd argument that lets you set the response code somewhat comfortably, but using it requires the first argument to be a non-empty string. Here are two options:
header(':', true, 404);
header('X-PHP-Response-Code: 404', true, 404);
I recommend the 2nd one. The first does work on all browsers I have tested, but some minor browsers or web crawlers may have a problem with a header line that only contains a colon. The header field name in the 2nd. variant is of course not standardized in any way and could be modified, I just chose a hopefully descriptive name.
The http_response_code()
function was introduced in PHP 5.4, and it made things a lot easier.
http_response_code(404);
That's all.
Here is a function that I have cooked up when I needed compatibility below 5.4 but wanted the functionality of the "new" http_response_code
function. I believe PHP 4.3 is more than enough backwards compatibility, but you never know...
// For 4.3.0 <= PHP <= 5.4.0
if (!function_exists('http_response_code'))
{
function http_response_code($newcode = NULL)
{
static $code = 200;
if($newcode !== NULL)
{
header('X-PHP-Response-Code: '.$newcode, true, $newcode);
if(!headers_sent())
$code = $newcode;
}
return $code;
}
}
In C and languages based on the C syntax, the prefix 0x
means hexadecimal (base 16).
Thus, 0x400 = 4×(162) + 0×(161) + 0×(160) = 4×((24)2) = 22 × 28 = 210 = 1024, or one binary K.
And so 0x6400 = 0x4000 + 0x2400 = 0x19×0x400 = 25K
I think
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div>Testing</div>
<div id="result" style="margin:1em 4em; background:rgb(200,200,255); height:500px"></div>
<div style="background:rgb(200,255,200); height:3000px; width:5000px;"></div>
<script>
(function(){
var link=$("#result");
var top = link.offset().top; // position from $(document).offset().top
var bottom = top + link.height(); // position from $(document).offset().top
var left = link.offset().left; // position from $(document).offset().left
var right = left + link.width(); // position from $(document).offset().left
var bottomFromBottom = $(document).height() - bottom;
// distance from document's bottom
var rightFromRight = $(document).width() - right;
// distance from document's right
var str="";
str+="top: "+top+"<br>";
str+="bottom: "+bottom+"<br>";
str+="left: "+left+"<br>";
str+="right: "+right+"<br>";
str+="bottomFromBottom: "+bottomFromBottom+"<br>";
str+="rightFromRight: "+rightFromRight+"<br>";
link.html(str);
})();
</script>
The result are
top: 44
bottom: 544
left: 72
right: 1277
bottomFromBottom: 3068
rightFromRight: 3731
in chrome browser of mine.
When the document is scrollable, $(window).height()
returns height of browser viewport, not the width of document of which some parts are hiden in scroll. See http://api.jquery.com/height/ .
This is what I ended up doing. I'm sure there is a more efficient way of doing this but this is what i came up with.
Model/User.php
protected $rules = [
'email_address' => 'sometimes|required|email|unique:users,email_address, {{$id}}',
];
Model/BaseModel.php
public function validate($data, $id = null) {
$rules = $this->$rules_string;
//let's loop through and explode the validation rules
foreach($rules as $keys => $value) {
$validations = explode('|', $value);
foreach($validations as $key=>$value) {
// Seearch for {{$id}} and replace it with $id
$validations[$key] = str_replace('{{$id}}', $id, $value);
}
//Let's create the pipe seperator
$implode = implode("|", $validations);
$rules[$keys] = $implode;
}
....
}
I pass the $user_id to the validation in the controller
Controller/UserController.php
public function update($id) {
.....
$user = User::find($user_id);
if($user->validate($formRequest, $user_id)) {
//validation succcess
}
....
}
I tried guava-libraries from google. It has a FluentIterable
which I think is close to LINQ. Also see FunctionalExplained.
List<String> parts = new ArrayList<String>(); // add parts to the collection.
FluentIterable<Integer> partsStartingA =
FluentIterable.from(parts).filter(new Predicate<String>() {
@Override
public boolean apply(final String input) {
return input.startsWith("a");
}
}).transform(new Function<String, Integer>() {
@Override
public Integer apply(final String input) {
return input.length();
}
});
Seems to be an extensive library for Java. Certainly not as succinct as LINQ but looks interesting.
Just wanted to add something to Kamil's answer
After following the steps, I still got an error,
error Could not find device with the name: "....'s Xr"
After removing special characters from the device name (Go to Settings -> General -> About -> Name)
Eg: '
It Worked !
Hope this will help someone who faced similar issue.
Tested with - react-native-cli: 2.0.1 | react-native: 0.59.8 | VSCode 1.32 | Xcode 10.2.1 | iOS 12.3
You can also use DateTime class:
$time1 = new DateTime('09:00:59');
$time2 = new DateTime('09:01:00');
$interval = $time1->diff($time2);
echo $interval->format('%s second(s)');
Result:
1 second(s)
My solution:
let isEmpty = (val) => {
let typeOfVal = typeof val;
switch(typeOfVal){
case 'object':
return (val.length == 0) || !Object.keys(val).length;
break;
case 'string':
let str = val.trim();
return str == '' || str == undefined;
break;
case 'number':
return val == '';
break;
default:
return val == '' || val == undefined;
}
};
console.log(isEmpty([1,2,4,5])); // false
console.log(isEmpty({id: 1, name: "Trung",age: 29})); // false
console.log(isEmpty('TrunvNV')); // false
console.log(isEmpty(8)); // false
console.log(isEmpty('')); // true
console.log(isEmpty(' ')); // true
console.log(isEmpty([])); // true
console.log(isEmpty({})); // true
Because the numbers after point is only zero, the best solution is to use the Math.Round(MyNumber)
You write like this-:
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
day: '%d %b %Y' //ex- 01 Jan 2016
}
}
also check for other datetime format
http://api.highcharts.com/highcharts#xAxis.dateTimeLabelFormats
What you put inside the </dependencies>
tag of the root pom will be included by all child modules of the root pom. If all your modules use that dependency, this is the way to go.
However, if only 3 out of 10 of your child modules use some dependency, you do not want this dependency to be included in all your child modules. In that case, you can just put the dependency inside the </dependencyManagement>
. This will make sure that any child module that needs the dependency must declare it in their own pom file, but they will use the same version of that dependency as specified in your </dependencyManagement>
tag.
You can also use the </dependencyManagement>
to modify the version used in transitive dependencies, because the version declared in the upper most pom file is the one that will be used. This can be useful if your project A includes an external project B v1.0 that includes another external project C v1.0. Sometimes it happens that a security breach is found in project C v1.0 which is corrected in v1.1, but the developers of B are slow to update their project to use v1.1 of C. In that case, you can simply declare a dependency on C v1.1 in your project's root pom inside `, and everything will be good (assuming that B v1.0 will still be able to compile with C v1.1).
AngularJS' orderBy filter does just support arrays - no objects. So you have to write an own small filter, which does the sorting for you.
Or change the format of data you handle with (if you have influence on that). An array containing objects is sortable by native orderBy filter.
Here is my orderObjectBy filter for AngularJS:
app.filter('orderObjectBy', function(){
return function(input, attribute) {
if (!angular.isObject(input)) return input;
var array = [];
for(var objectKey in input) {
array.push(input[objectKey]);
}
array.sort(function(a, b){
a = parseInt(a[attribute]);
b = parseInt(b[attribute]);
return a - b;
});
return array;
}
});
Usage in your view:
<div class="item" ng-repeat="item in items | orderObjectBy:'position'">
//...
</div>
The object needs in this example a position attribute, but you have the flexibility to use any attribute in objects (containing an integer), just by definition in view.
Example JSON:
{
"123": {"name": "Test B", "position": "2"},
"456": {"name": "Test A", "position": "1"}
}
Here is a fiddle which shows you the usage: http://jsfiddle.net/4tkj8/1/
The minium sdk version should be same as of the modules/lib you are using For example: Your module min sdk version is 26 and your app min sdk version is 21 It should be same.
Using JDOM:
String xml = "<message>HELLO!</message>";
org.jdom.input.SAXBuilder saxBuilder = new SAXBuilder();
try {
org.jdom.Document doc = saxBuilder.build(new StringReader(xml));
String message = doc.getRootElement().getText();
System.out.println(message);
} catch (JDOMException e) {
// handle JDOMException
} catch (IOException e) {
// handle IOException
}
Using the Xerces DOMParser
:
String xml = "<message>HELLO!</message>";
DOMParser parser = new DOMParser();
try {
parser.parse(new InputSource(new java.io.StringReader(xml)));
Document doc = parser.getDocument();
String message = doc.getDocumentElement().getTextContent();
System.out.println(message);
} catch (SAXException e) {
// handle SAXException
} catch (IOException e) {
// handle IOException
}
Using the JAXP interfaces:
String xml = "<message>HELLO!</message>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
try {
Document doc = db.parse(is);
String message = doc.getDocumentElement().getTextContent();
System.out.println(message);
} catch (SAXException e) {
// handle SAXException
} catch (IOException e) {
// handle IOException
}
} catch (ParserConfigurationException e1) {
// handle ParserConfigurationException
}
None of these worked for me.
I was experiencing this issue in only once particular class. What finally worked for me was to delete the offending class and recreate it. Problem solved... mystery not so much!
EDIT: Use this Solution here: https://stackoverflow.com/a/20559175/2033223 Works perfect!
First of, thank for your solution @luizfelipetx
I changed your solution a little bit. This works for me:
public static String getRealPathFromDocumentUri(Context context, Uri uri){
String filePath = "";
Pattern p = Pattern.compile("(\\d+)$");
Matcher m = p.matcher(uri.toString());
if (!m.find()) {
Log.e(ImageConverter.class.getSimpleName(), "ID for requested image not found: " + uri.toString());
return filePath;
}
String imgId = m.group();
String[] column = { MediaStore.Images.Media.DATA };
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ imgId }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
Note: So we got documents and image, depending, if the image comes from 'recents', 'gallery' or what ever. So I extract the image ID first before looking it up.
The three options that come to mind:
1st) End void loop()
with while(1)
... or equally as good... while(true)
void loop(){
//the code you want to run once here,
//e.g., If (blah == blah)...etc.
while(1) //last line of main loop
}
This option runs your code once and then kicks the Ard into
an endless "invisible" loop. Perhaps not the nicest way to
go, but as far as outside appearances, it gets the job done.
The Ard will continue to draw current while it spins itself in
an endless circle... perhaps one could set up a sort of timer
function that puts the Ard to sleep after so many seconds,
minutes, etc., of looping... just a thought... there are certainly
various sleep libraries out there... see
e.g., Monk, Programming Arduino: Next Steps, pgs., 85-100
for further discussion of such.
2nd) Create a "stop main loop" function with a conditional control
structure that makes its initial test fail on a second pass.
This often requires declaring a global variable and having the
"stop main loop" function toggle the value of the variable
upon termination. E.g.,
boolean stop_it = false; //global variable
void setup(){
Serial.begin(9600);
//blah...
}
boolean stop_main_loop(){ //fancy stop main loop function
if(stop_it == false){ //which it will be the first time through
Serial.println("This should print once.");
//then do some more blah....you can locate all the
// code you want to run once here....eventually end by
//toggling the "stop_it" variable ...
}
stop_it = true; //...like this
return stop_it; //then send this newly updated "stop_it" value
// outside the function
}
void loop{
stop_it = stop_main_loop(); //and finally catch that updated
//value and store it in the global stop_it
//variable, effectively
//halting the loop ...
}
Granted, this might not be especially pretty, but it also works.
It kicks the Ard into another endless "invisible" loop, but this
time it's a case of repeatedly checking the if(stop_it == false)
condition in stop_main_loop()
which of course fails to pass every time after the first time through.
3rd) One could once again use a global variable but use a simple if (test == blah){}
structure instead of a fancy "stop main loop" function.
boolean start = true; //global variable
void setup(){
Serial.begin(9600);
}
void loop(){
if(start == true){ //which it will be the first time through
Serial.println("This should print once.");
//the code you want to run once here,
//e.g., more If (blah == blah)...etc.
}
start = false; //toggle value of global "start" variable
//Next time around, the if test is sure to fail.
}
There are certainly other ways to "stop" that pesky endless main loop but these three as well as those already mentioned should get you started.
Had the same problem while trying to run WCF app from Visual Studio. Solved it by running Visual Studio as administrator.
No you would have to create your own solution. Like using the Observer design pattern or something.
If you have no control over the variable or who is using it, I'm afraid you're doomed. EDIT: Or use Skilldrick's solution!
Mike
There are some good answers here already. But it's worthwhile to drive home the difference in parallelism offered:
success()
returns the original promisethen()
returns a new promiseThe difference is then()
drives sequential operations, since each call returns a new promise.
$http.get(/*...*/).
then(function seqFunc1(response){/*...*/}).
then(function seqFunc2(response){/*...*/})
$http.get()
seqFunc1()
seqFunc2()
success()
drives parallel operations, since handlers are chained on the same promise.
$http(/*...*/).
success(function parFunc1(data){/*...*/}).
success(function parFunc2(data){/*...*/})
$http.get()
parFunc1()
, parFunc2()
in parallelFinally in .NET 4.5, the CLR allows one to hint/suggest1 method inlining using MethodImplOptions.AggressiveInlining
value. It is also available in the Mono's trunk (committed today).
// The full attribute usage is in mscorlib.dll,
// so should not need to include extra references
using System.Runtime.CompilerServices;
...
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void MyMethod(...)
1. Previously "force" was used here. Since there were a few downvotes, I'll try to clarify the term. As in the comments and the documentation, The method should be inlined if possible.
Especially considering Mono (which is open), there are some mono-specific technical limitations considering inlining or more general one (like virtual functions). Overall, yes, this is a hint to compiler, but I guess that is what was asked for.
I know that this is not the C#, but in the framework (VB.NET) there is already such a function
Dim str As String = "UPPERlower"
Dim b As Boolean = InStr(str, "UpperLower")
C# variant:
string myString = "Hello World";
bool contains = Microsoft.VisualBasic.Strings.InStr(myString, "world");
Query string and parameters are different.
You need to use both in single routing url
Please check below example may be useful for you.
app.get('/sample/:id', function(req, res) {
var id = req.params.id; //or use req.param('id')
................
});
Get the link to pass your second segment is your id example: http://localhost:port/sample/123
If you facing problem please use Passing variables as query string using '?' operator
app.get('/sample', function(req, res) {
var id = req.query.id;
................
});
Get link your like this example: http://localhost:port/sample?id=123
Both in a single example
app.get('/sample/:id', function(req, res) {
var id = req.params.id; //or use req.param('id')
var id2 = req.query.id;
................
});
Get link example: http://localhost:port/sample/123?id=123
Let me add here that one very minor issue that could generate this type of error is the missing .git
extension in the repository URL. Ensure you enter the fully qualified URL ending with .git
. I use bitbucket so what I do do is do click 'clone' and the fully qualified URL is automatically generated for me. There is a similar approach with github.
I was getting this same error on my server - PHP 7.0 with the mysqlnd extension already enabled.
Solution was for me (thanks to this page) was to deselect the mysqli extension and select nd_mysqli instead.
NB - You may be able to access the extensions selector in your cPanel. (I access mine via the Select PHP Version option.)
This is simple way to convert files to Base64 and avoid "maximum call stack size exceeded at FileReader.reader.onload" with the file has big size.
document.querySelector('#fileInput').addEventListener('change', function () {_x000D_
_x000D_
var reader = new FileReader();_x000D_
var selectedFile = this.files[0];_x000D_
_x000D_
reader.onload = function () {_x000D_
var comma = this.result.indexOf(',');_x000D_
var base64 = this.result.substr(comma + 1);_x000D_
console.log(base64);_x000D_
}_x000D_
reader.readAsDataURL(selectedFile);_x000D_
}, false);
_x000D_
<input id="fileInput" type="file" />
_x000D_
I have a better way:
http
.authorizeRequests()
.antMatchers("/api/v1/signup/**").permitAll()
.anyRequest().authenticated()
you need to call the function like this
$this->assign()
instead of just assign()
Use this:
$('a[href^="#"]').on('click', function(event) {
var target = $( $(this).attr('href') );
if( target.length ) {
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 500);
}
});
It is because it's being converted from a binary representation. Just because it has printed all those decimal digits doesn't mean it can represent all decimal values to that precision. Take, for example, this in Python:
>>> 0.14285714285714285
0.14285714285714285
>>> 0.14285714285714286
0.14285714285714285
Notice how I changed the last digit, but it printed out the same number anyway.
A layer in a neural network without a bias is nothing more than the multiplication of an input vector with a matrix. (The output vector might be passed through a sigmoid function for normalisation and for use in multi-layered ANN afterwards but that’s not important.)
This means that you’re using a linear function and thus an input of all zeros will always be mapped to an output of all zeros. This might be a reasonable solution for some systems but in general it is too restrictive.
Using a bias, you’re effectively adding another dimension to your input space, which always takes the value one, so you’re avoiding an input vector of all zeros. You don’t lose any generality by this because your trained weight matrix needs not be surjective, so it still can map to all values previously possible.
2d ANN:
For a ANN mapping two dimensions to one dimension, as in reproducing the AND or the OR (or XOR) functions, you can think of a neuronal network as doing the following:
On the 2d plane mark all positions of input vectors. So, for boolean values, you’d want to mark (-1,-1), (1,1), (-1,1), (1,-1). What your ANN now does is drawing a straight line on the 2d plane, separating the positive output from the negative output values.
Without bias, this straight line has to go through zero, whereas with bias, you’re free to put it anywhere. So, you’ll see that without bias you’re facing a problem with the AND function, since you can’t put both (1,-1) and (-1,1) to the negative side. (They are not allowed to be on the line.) The problem is equal for the OR function. With a bias, however, it’s easy to draw the line.
Note that the XOR function in that situation can’t be solved even with bias.
curl -X PUT -T "/path/to/file" "http://myputserver.com/puturl.tmp"
Recently, I have seen this problem too. Below, you have my solution:
Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart
or fix it up
I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):
ssh -T [email protected]
Upon receiving a successful response, I could fetch/push to the repo with ssh.
I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.
@Bryce, really nice answer.
VB.NET version:
Public Shared Iterator Function FindVisualChildren(Of T As DependencyObject)(depObj As DependencyObject) As IEnumerable(Of T)
If depObj IsNot Nothing Then
For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(depObj) - 1
Dim child As DependencyObject = VisualTreeHelper.GetChild(depObj, i)
If child IsNot Nothing AndAlso TypeOf child Is T Then
Yield DirectCast(child, T)
End If
For Each childOfChild As T In FindVisualChildren(Of T)(child)
Yield childOfChild
Next
Next
End If
End Function
Usage (this disables all TextBoxes in a window):
For Each tb As TextBox In FindVisualChildren(Of TextBox)(Me)
tb.IsEnabled = False
Next
From C# 5.0, you can specify the method as
public async Task<bool> doAsyncOperation()
{
// do work
return true;
}
bool result = await doAsyncOperation();
Probably the easiest way:
<input type='text' id='abc' value="hel'lo">
It's the '+' operator at the beginning of the line that trips things up (not just that you are using two '+' operators consecutively). The '+' operator can be used at the end of lines, but not at the beginning.
This works:
ggplot(combined.data, aes(x = region, y = expression, fill = species)) +
geom_boxplot()
The does not:
ggplot(combined.data, aes(x = region, y = expression, fill = species))
+ geom_boxplot()
*Error in + geom_boxplot():
invalid argument to unary operator*
You also can't use two '+' operators, which in this case you've done. But to fix this, you'll have to selectively remove those at the beginning of lines.
First make sure you have installed Nginx with the HTTP rewrite module. To install this we need to have pcre-library
If the above mentioned are done or if you already have them, then just add the below code in your nginx server block
if ($host !~* ^www\.) {
rewrite ^(.*)$ http://www.$host$1 permanent;
}
To remove www from every request you can use
if ($host = 'www.your_domain.com' ) {
rewrite ^/(.*)$ http://your_domain.com/$1 permanent;
}
so your server block will look like
server {
listen 80;
server_name test.com;
if ($host !~* ^www\.) {
rewrite ^(.*)$ http://www.$host$1 permanent;
}
client_max_body_size 10M;
client_body_buffer_size 128k;
root /home/test/test/public;
passenger_enabled on;
rails_env production;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
strip colons from the $time, $to and $from strings, convert to int and then use the following condition to check if the time is between from and to. Example is in php, but shouldn't matter.
if(($to < $from && ($time >= $from || $time <= $to)) ||
($time >= $from && $time <= $to)) {
return true;
}
Implemented with swift on Xcode 6.1
self.tableView.tableFooterView = UIView(frame: CGRectZero)
self.tableView.tableFooterView?.hidden = true
The second line of code does not cause any effect on presentation, you can use to check if is hidden or not.
Answer taken from this link Fail to hide empty cells in UITableView Swift
Set PYTHONPATH
environment variable in root project directory.
Considering UNIX-like:
export PYTHONPATH=.
If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?
you can use LocalDate
:
Days.daysBetween(new LocalDate(start), new LocalDate(end)).getDays()
Remember set sendfile off;
or cache headers doesn't work.
I use this snipped:
location / {
index index.php index.html index.htm;
try_files $uri $uri/ =404; #.s. el /index.html para html5Mode de angular
#.s. kill cache. use in dev
sendfile off;
add_header Last-Modified $date_gmt;
add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
if_modified_since off;
expires off;
etag off;
proxy_no_cache 1;
proxy_cache_bypass 1;
}
I was having this issue when testing my Cordova app on android. It just so happens that this android device does not persist its date, and will reset back to its factory date somehow. The API that it calls has a cert that is valid starting this year, while the device date after bootup is in 2017. For now, I have to adb shell
and change the date manually.
I know this may not be your specific error, but I once had a leading space in my path and java would work but javac would not.
For what it's worth, I offer the sage advice: "Examine your Path closely".
What you are doing is pass by value not pass by reference. Because you are sending the value of a variable 'p' to the function 'f' (in main as f(p);)
The same program in C with pass by reference will look like,(!!!this program gives 2 errors as pass by reference is not supported in C)
#include <stdio.h>
void f(int &j) { //j is reference variable to i same as int &j = i
j++;
}
int main() {
int i = 20;
f(i);
printf("i = %d\n", i);
return 0;
}
Output:-
3:12: error: expected ';', ',' or ')' before '&' token void f(int &j); ^ 9:3: warning: implicit declaration of function 'f' f(a); ^
$blog is an object, not an array, so you should access it like so:
$blog->id;
$blog->title;
$blog->content;
Guide link: http://www.pip-installer.org/en/latest/installing.html#install-pip
Note: Make sure scripts path like this (C:\Python27\Scripts) is added int %PATH% environment variable as well.
Maybe
if (inventory.contains("bread") && !inventory.contains("water"))
Or
if (inventory.contains("bread")) {
if (!inventory.contains("water")) {
// do something here
}
}
Here is my summary of this problem: 5 Ways of Calling Java from Python
http://baojie.org/blog/2014/06/16/call-java-from-python/ (cached)
Short answer: Jpype works pretty well and is proven in many projects (such as python-boilerpipe), but Pyjnius is faster and simpler than JPype
I have tried Pyjnius/Jnius, JCC, javabridge, Jpype and Py4j.
Py4j is a bit hard to use, as you need to start a gateway, adding another layer of fragility.
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
public class GetJsonFromUrl {
String url = null;
public GetJsonFromUrl(String url) {
this.url = url;
}
public String GetJsonData() {
try {
URL Url = new URL(url);
HttpURLConnection connection = (HttpURLConnection) Url.openConnection();
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
line = sb.toString();
connection.disconnect();
is.close();
sb.delete(0, sb.length());
return line;
} catch (Exception e) {
return null;
}
}
}
and this class use for post data
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by user on 11/2/16.
*/
public class sendDataToServer {
public String postdata(String requestURL,HashMap<String,String> postDataParams){
try {
String response = "";
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
Log.d("test", response);
return response;
}catch (Exception e){
return e.toString();
}
}
public String postjson(String url,String json){
try {
URL obj = new URL(url);
HttpURLConnection con= (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
String urlParameters = ""+json;
// Send post request
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
return response.toString();
}catch(Exception e){
return e.toString();
}
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
/* public String postdata(String url) {
}*/
}
If I recall correctly Twig doesn't support ||
and &&
operators, but requires or
and and
to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.
{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}
Expressions
Expressions can be used in {% blocks %} and ${ expressions }.
Operator Description
== Does the left expression equal the right expression?
+ Convert both arguments into a number and add them.
- Convert both arguments into a number and substract them.
* Convert both arguments into a number and multiply them.
/ Convert both arguments into a number and divide them.
% Convert both arguments into a number and calculate the rest of the integer division.
~ Convert both arguments into a string and concatenate them.
or True if the left or the right expression is true.
and True if the left and the right expression is true.
not Negate the expression.
For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:
{% if (foo and bar) or (fizz and (foo + bar == 3)) %}
Based on the comment we are removing one property from style attribute.
Here this was not affect, but when more property are used within the style it helpful.
$('#msform').css('display', '')
After this we use
$("#msform").show();
To call GET,POST,DELETE,PUT All kind of request, i have created one common function
function CallAPI($method, $api, $data) {
$url = "http://localhost:82/slimdemo/RESTAPI/" . $api;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
switch ($method) {
case "GET":
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
break;
case "POST":
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
break;
case "PUT":
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
break;
case "DELETE":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
break;
}
$response = curl_exec($curl);
$data = json_decode($response);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// Check the HTTP Status code
switch ($httpCode) {
case 200:
$error_status = "200: Success";
return ($data);
break;
case 404:
$error_status = "404: API Not found";
break;
case 500:
$error_status = "500: servers replied with an error.";
break;
case 502:
$error_status = "502: servers may be down or being upgraded. Hopefully they'll be OK soon!";
break;
case 503:
$error_status = "503: service unavailable. Hopefully they'll be OK soon!";
break;
default:
$error_status = "Undocumented error: " . $httpCode . " : " . curl_error($curl);
break;
}
curl_close($curl);
echo $error_status;
die;
}
CALL Delete Method
$data = array('id'=>$_GET['did']);
$result = CallAPI('DELETE', "DeleteCategory", $data);
CALL Post Method
$data = array('title'=>$_POST['txtcategory'],'description'=>$_POST['txtdesc']);
$result = CallAPI('POST', "InsertCategory", $data);
CALL Get Method
$data = array('id'=>$_GET['eid']);
$result = CallAPI('GET', "GetCategoryById", $data);
CALL Put Method
$data = array('id'=>$_REQUEST['eid'],m'title'=>$_REQUEST['txtcategory'],'description'=>$_REQUEST['txtdesc']);
$result = CallAPI('POST', "UpdateCategory", $data);
Try this to Convert from Decimal to Hex
#include<stdio.h>
#include<conio.h>
int main(void)
{
int count=0,digit,n,i=0;
int hex[5];
clrscr();
printf("enter a number ");
scanf("%d",&n);
if(n<10)
{
printf("%d",n);
}
switch(n)
{
case 10:
printf("A");
break;
case 11:
printf("B");
break;
case 12:
printf("B");
break;
case 13:
printf("C");
break;
case 14:
printf("D");
break;
case 15:
printf("E");
break;
case 16:
printf("F");
break;
default:;
}
while(n>16)
{
digit=n%16;
hex[i]=digit;
i++;
count++;
n=n/16;
}
hex[i]=n;
for(i=count;i>=0;i--)
{
switch(hex[i])
{
case 10:
printf("A");
break;
case 11:
printf("B");
break;
case 12:
printf("C");
break;
case 13:
printf("D");
break;
case 14:
printf("E");
break;
case 15:
printf("F");
break;
default:
printf("%d",hex[i]);
}
}
getch();
return 0;
}
Use defaultdict instead:
from collections import defaultdict
data = defaultdict(list)
data[1].append('hello')
This way you don't have to initialize all the keys you want to use to lists beforehand.
What is happening in your example is that you use one (mutable) list:
alist = [1]
data = dict.fromkeys(range(2), alist)
alist.append(2)
print data
would output {0: [1, 2], 1: [1, 2]}
.
The basic difference between Web Services and Web APIs
Web Service:
1) It is a SOAP-based service and returns data as XML.
2) It only supports the HTTP protocol.
3) It is not open source but can be used by any client that understands XML.
5) It requires a SOAP protocol to receive and send data over the network, so it is not a light-weight architecture.
Web API:
1) A Web API is an HTTP based service and returns JSON or XML data by default.
2) It supports the HTTP protocol.
3) It can be hosted within an application or IIS.
4) It is open source and it can be used by any client that understands JSON or XML.
5) It has light-weight architecture and good for devices which have limited bandwidth, like mobile devices.
Use MySQL's STR_TO_DATE()
function to parse the string that you're attempting to insert:
INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES
(STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))
I don't see why you shouldn't be able to send html content via a post.
if you encounter any issues, you could perhaps use some kind of encoding / decoding - but I don't see that you will.
Faster clearing than Arrays.fill is with this (From Fast Serialization Lib). I just use arrayCopy (is native) to clear the array:
static Object[] EmptyObjArray = new Object[10000];
public static void clear(Object[] arr) {
final int arrlen = arr.length;
clear(arr, arrlen);
}
public static void clear(Object[] arr, int arrlen) {
int count = 0;
final int length = EmptyObjArray.length;
while( arrlen - count > length) {
System.arraycopy(EmptyObjArray,0,arr,count, length);
count += length;
}
System.arraycopy(EmptyObjArray,0,arr,count, arrlen -count);
}
From a purely "make it fit in the div" perspective, add the following to your table class (jsfiddle):
table-layout: fixed;
width: 100%;
Set your column widths as desired; otherwise, the fixed layout algorithm will distribute the table width evenly across your columns.
For quick reference, here are the table layout algorithms, emphasis mine:
With this (fast) algorithm, the horizontal layout of the table does not depend on the contents of the cells; it only depends on the table's width, the width of the columns, and borders or cell spacing.
In this algorithm (which generally requires no more than two passes), the table's width is given by the width of its columns [, as determined by content] (and intervening borders).
[...] This algorithm may be inefficient since it requires the user agent to have access to all the content in the table before determining the final layout and may demand more than one pass.
Click through to the source documentation to see the specifics for each algorithm.
numpy.append
is pretty different from list.append in python. I know that's thrown off a few programers new to numpy. numpy.append
is more like concatenate, it makes a new array and fills it with the values from the old array and the new value(s) to be appended. For example:
import numpy
old = numpy.array([1, 2, 3, 4])
new = numpy.append(old, 5)
print old
# [1, 2, 3, 4]
print new
# [1, 2, 3, 4, 5]
new = numpy.append(new, [6, 7])
print new
# [1, 2, 3, 4, 5, 6, 7]
I think you might be able to achieve your goal by doing something like:
result = numpy.zeros((10,))
result[0:2] = [1, 2]
# Or
result = numpy.zeros((10, 2))
result[0, :] = [1, 2]
Update:
If you need to create a numpy array using loop, and you don't know ahead of time what the final size of the array will be, you can do something like:
import numpy as np
a = np.array([0., 1.])
b = np.array([2., 3.])
temp = []
while True:
rnd = random.randint(0, 100)
if rnd > 50:
temp.append(a)
else:
temp.append(b)
if rnd == 0:
break
result = np.array(temp)
In my example result will be an (N, 2) array, where N is the number of times the loop ran, but obviously you can adjust it to your needs.
new update
The error you're seeing has nothing to do with types, it has to do with the shape of the numpy arrays you're trying to concatenate. If you do np.append(a, b)
the shapes of a
and b
need to match. If you append an (2, n) and (n,) you'll get a (3, n) array. Your code is trying to append a (1, 0) to a (2,). Those shapes don't match so you get an error.
private static void GrantAccess(string file)
{
bool exists = System.IO.Directory.Exists(file);
if (!exists)
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(file);
Console.WriteLine("The Folder is created Sucessfully");
}
else
{
Console.WriteLine("The Folder already exists");
}
DirectoryInfo dInfo = new DirectoryInfo(file);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
dInfo.SetAccessControl(dSecurity);
}
You could just loop the rows and read the same cell from each row (doesn't this comprise a column?).
In case anyone's wondering why Eclipse still puts a J2SE-1.5 library on the Java Build Path in a Maven project even if a Java version >= 9 is specified by the maven.compiler.release
property (as of October 2020, that is Eclipse version 2020-09 including Maven version 3.6.3): Maven by default uses version 3.1 of the Maven compiler plugin, while the release property has been introduced only in version 3.6.
So don't forget to include a current version of the Maven compiler plugin in your pom.xml when using the release property:
<properties>
<maven.compiler.release>15</maven.compiler.release>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</plugin>
</plugins>
</build>
Or alternatively but possibly less prominent, specify the Java version directly in the plugin configuration:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>15</release>
</configuration>
</plugin>
</plugins>
</build>
This picks up Line's comment on the accepted answer which, had I seen it earlier, would have saved me another hour of searching.
Check out ActiveModel::Dirty (available on all models by default). The documentation is really good, but it lets you do things such as:
@user.street1_changed? # => true/false
You need to use the various Bootstrap 4 centering methods...
text-center
for inline elements.justify-content-center
for flexbox elements (ie; form-inline
)https://codeply.com/go/Am5LvvjTxC
Also, to offset the column, the col-sm-*
must be contained within a .row
, and the .row
must be in a container...
<section id="cover">
<div id="cover-caption">
<div id="container" class="container">
<div class="row">
<div class="col-sm-10 offset-sm-1 text-center">
<h1 class="display-3">Welcome to Bootstrap 4</h1>
<div class="info-form">
<form action="" class="form-inline justify-content-center">
<div class="form-group">
<label class="sr-only">Name</label>
<input type="text" class="form-control" placeholder="Jane Doe">
</div>
<div class="form-group">
<label class="sr-only">Email</label>
<input type="text" class="form-control" placeholder="[email protected]">
</div>
<button type="submit" class="btn btn-success ">okay, go!</button>
</form>
</div>
<br>
<a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">?</a>
</div>
</div>
</div>
</div>
</section>
I knew that i am too late for this answer, but i hope this will help to other who are facing and who will face.
As you have written h_url is global var like var = h_url;
so you can use that variable anywhere in your file.
h_url=document.getElementById("u").value;
Here h_url contain value of your search box text value whatever user has typed.
document.getElementById("u");
This is the identifier of your form field with some specific ID
.
Your Search Field without id
<input type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
Alter Search Field with id
<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
When you click on submit that will try to fetch value from document.getElementById("u").value;
which is syntactically right but you haven't define id so that will return null
.
So, Just make sure while you use form fields first define that ID and do other task letter.
I hope this helps you and never get Cannot set property 'value' of null
Error.
Here is the proper documentation for the jQueryUI widget. There isn't a built-in parameter for limiting max results, but you can accomplish it easily:
$("#auto").autocomplete({
source: function(request, response) {
var results = $.ui.autocomplete.filter(myarray, request.term);
response(results.slice(0, 10));
}
});
You can supply a function to the source
parameter and then call slice
on the filtered array.
Here's a working example: http://jsfiddle.net/andrewwhitaker/vqwBP/
If you want to remove n item from end of array in javascript, you can easily use:
arr.splice(-n, n);
You can get around this by using a traits class:
It requires you set up a specialsed traits class for each actuall class you use.
template<typename SubClass>
class SubClass_traits
{};
template<typename Subclass>
class A {
public:
void action(typename SubClass_traits<Subclass>::mytype var)
{
(static_cast<Subclass*>(this))->do_action(var);
}
};
// Definitions for B
class B; // Forward declare
template<> // Define traits for B. So other classes can use it.
class SubClass_traits<B>
{
public:
typedef int mytype;
};
// Define B
class B : public A<B>
{
// Define mytype in terms of the traits type.
typedef SubClass_traits<B>::mytype mytype;
public:
B() {}
void do_action(mytype var) {
// Do stuff
}
};
int main(int argc, char** argv)
{
B myInstance;
return 0;
}
I believe it makes sense revisit this question as also pointed out in the comments, the introduction of OpenID Connect may have brought more confusion.
OpenID Connect is an authentication protocol like OpenID 1.0/2.0 but it is actually built on top of OAuth 2.0, so you'll get authorization features along with authentication features. The difference between the two is pretty well explained in detail in this (relatively recent, but important) article: http://oauth.net/articles/authentication/
For example: com.paresh.mainpackage
Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com. This information i have found at http://download.oracle.com/javase/tutorial/java/package/namingpkgs.html
Compile your application with -g
, then you'll have debug symbols in the binary file.
Use gdb
to open the gdb console.
Use file
and pass it your application's binary file in the console.
Use run
and pass in any arguments your application needs to start.
Do something to cause a Segmentation Fault.
Type bt
in the gdb
console to get a stack trace of the Segmentation Fault.
Assign a int -1
to an unsigned
: As -1
does not fit in the range [0...UINT_MAX]
, multiples of UINT_MAX+1
are added until the answer is in range. Evidently UINT_MAX
is pow(2,32)-1 or 429496725
on OP's machine so a
has the value of 4294967295.
unsigned int a = -1;
The "%x"
, "%u"
specifier expects a matching unsigned
. Since these do not match, "If a conversion specification is invalid, the behavior is undefined.
If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined." C11 §7.21.6.1 9. The printf specifier does not change b
.
printf("%x\n", b); // UB
printf("%u\n", b); // UB
The "%d"
specifier expects a matching int
. Since these do not match, more UB.
printf("%d\n", a); // UB
Given undefined behavior, the conclusions are not supported.
both cases, the bytes are the same (ffffffff).
Even with the same bit pattern, different types may have different values. ffffffff
as an unsigned
has the value of 4294967295. As an int
, depending signed integer encoding, it has the value of -1, -2147483647 or TBD. As a float
it may be a NAN.
what is unsigned word for?
unsigned
stores a whole number in the range [0 ... UINT_MAX]
. It never has a negative value. If code needs a non-negative number, use unsigned
. If code needs a counting number that may be +, - or 0, use int
.
Update: to avoid a compiler warning about assigning a signed int
to unsigned
, use the below. This is an unsigned
1u
being negated - which is well defined as above. The effect is the same as a -1
, but conveys to the compiler direct intentions.
unsigned int a = -1u;
CREATE OR REPLACE PROCEDURE insert_into (
p_errcode OUT NUMBER,
p_errmesg OUT VARCHAR2,
p_rowsaffected OUT INTEGER
)
AS
v_param0 VARCHAR2 (30) := '0.25,2.25,33.689, abc, 99';
v_param1 VARCHAR2 (30) := '2.65,66.32, abc-def, 21.5';
BEGIN
FOR i IN (SELECT COLUMN_VALUE
FROM TABLE (SPLIT (v_param0, ',')))
LOOP
INSERT INTO tempo
(col1
)
VALUES (i.COLUMN_VALUE
);
END LOOP;
FOR i IN (SELECT COLUMN_VALUE
FROM TABLE (SPLIT (v_param1, ',')))
LOOP
INSERT INTO tempo
(col2
)
VALUES (i.COLUMN_VALUE
);
END LOOP;
END;
Vector and list aren't conceptually tied to C++. Similar structures can be implemented in C, just the syntax (and error handling) would look different. For example LodePNG implements a dynamic array with functionality very similar to that of std::vector. A sample usage looks like:
uivector v = {};
uivector_push_back(&v, 1);
uivector_push_back(&v, 42);
for(size_t i = 0; i < v.size; ++i)
printf("%d\n", v.data[i]);
uivector_cleanup(&v);
As can be seen the usage is somewhat verbose and the code needs to be duplicated to support different types.
nothings/stb gives a simpler implementation that works with any types, but compiles only in C:
double *v = 0;
sb_push(v, 1.0);
sb_push(v, 42.0);
for(int i = 0; i < sb_count(v); ++i)
printf("%g\n", v[i]);
sb_free(v);
A lot of C code, however, resorts to managing the memory directly with realloc:
void* newMem = realloc(oldMem, newSize);
if(!newMem) {
// handle error
}
oldMem = newMem;
Note that realloc
returns null in case of failure, yet the old memory is still valid. In such situation this common (and incorrect) usage leaks memory:
oldMem = realloc(oldMem, newSize);
if(!oldMem) {
// handle error
}
Compared to std::vector
and the C equivalents from above, the simple realloc
method does not provide O(1) amortized guarantee, even though realloc
may sometimes be more efficient if it happens to avoid moving the memory around.
In some cases, when you check your default encoding (print sys.getdefaultencoding()
), it returns that you are using ASCII. If you change to UTF-8, it doesn't work, depending on the content of your variable.
I found another way:
import sys
reload(sys)
sys.setdefaultencoding('Cp1252')
You can use setCustomValidity
function when oninvalid
event occurs.
Like below:-
<input class="form-control" type="email" required=""
placeholder="username" oninvalid="this.setCustomValidity('Please Enter valid email')">
</input>
To clear the message once you start entering use oninput="setCustomValidity('')
attribute to clear the message.
<input class="form-control" type="email" required="" placeholder="username"
oninvalid="this.setCustomValidity('Please Enter valid email')"
oninput="setCustomValidity('')"></input>
According to the Java docs, it looks like you need to use the MemoryImageSource Class to put your byte array into an object in memory, and then use Component.createImage(ImageProducer) next (passing in your MemoryImageSource, which implements ImageProducer).
Fixed positioning doesn't work on iOS like it does on computers.
Imagine you have a sheet of paper (the webpage) under a magnifying glass(the viewport), if you move the magnifying glass and your eye, you see a different part of the page. This is how iOS works.
Now there is a sheet of clear plastic with a word on it, this sheet of plastic stays stationary no matter what (the position:fixed elements). So when you move the magnifying glass the fixed element appears to move.
Alternatively, instead of moving the magnifying glass, you move the paper (the webpage), keeping the sheet of plastic and magnifying glass still. In this case the word on the sheet of plastic will appear to stay fixed, and the rest of the content will appear to move (because it actually is) This is a traditional desktop browser.
So in iOS the viewport moves, in a traditional browser the webpage moves. In both cases the fixed elements stay still in reality; although on iOS the fixed elements appear to move.
The way to get around this, is to follow the last few paragraphs in this article
(basically disable scrolling altogether, have the content in a separate scrollable div (see the blue box at the top of the linked article), and the fixed element positioned absolutely)
"position:fixed" now works as you'd expect in iOS5.
The most simple solution for me has been to:
1)Select the Range and copy it (ctrl+c)
2)Create a new text file (anywhere, it will be deleted soon), open the text file and then paste in the excel information (ctrl+v)
3)Now that the information in Excel is in the text file, perform a select all in the text file (ctrl+a), and then copy (ctrl+c)
4)Go to the beginning of the original range in step 1, and paste over that old information from the copy in step 3.
DONE! No more false blanks! (you can now delete the temp text file)
you might consider using the Relative and Absolute positining.
`.container {
position: relative;
}
.tag {
position: absolute;
}`
I have tested it there, also if you want it to change its position use this as its margin:
top: 20px;
left: 10px;
It will place it 20 pixels from top and 10 pixels from left; but leave this one if not necessary.
Having the following XML:
<node>Text1<subnode/>text2</node>
How do I select either the first or the second text node via XPath?
Use:
/node/text()
This selects all text-node children of the top element (named "node") of the XML document.
/node/text()[1]
This selects the first text-node child of the top element (named "node") of the XML document.
/node/text()[2]
This selects the second text-node child of the top element (named "node") of the XML document.
/node/text()[someInteger]
This selects the someInteger-th text-node child of the top element (named "node") of the XML document. It is equivalent to the following XPath expression:
/node/text()[position() = someInteger]
Old Thread but I found this on my journey to the below answer and figure someone else might need it too.
=IFERROR(ArrayFormula(query(index(Sheet3!A:C&""),"select* Where Col1="""&B1&""" ")), ARRAYFORMULA({"* *","no cells","match"}));
Here is a simply built text Filter from a 3 column data set (A,B and C) located in "sheet3" into the current sheet and calling a comparison to a cell from the current sheet to filter within Col1(A)
.
This bit is just to get rid of the #N/A
error if the filter turns up no results //ARRAYFORMULA({"* *","no cells","match"}))
opt
is new for ruby 1.9. The various options are documented in IO.new
: www.ruby-doc.org/core/IO.html
It's only blank for you because you have not set the sql_mode. If you set it, then that query will show you the details:
mysql> SELECT @@sql_mode;
+------------+
| @@sql_mode |
+------------+
| |
+------------+
1 row in set (0.00 sec)
mysql> set sql_mode=ORACLE;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @@sql_mode;
+----------------------------------------------------------------------------------------------------------------------+
| @@sql_mode |
+----------------------------------------------------------------------------------------------------------------------+
| PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ORACLE,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,NO_AUTO_CREATE_USER |
+----------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
Now this answer is for those lost souls that got here with this problem because they force-unmounted the drive but their hard drive is NTFS Formatted. Assuming you have ntfs-3g installed (sudo apt-get install ntfs-3g).
sudo ntfs-3g /dev/hdd /mnt/mount_point -o force
Where hdd is the hard drive in question and the "/mnt/mount_point" directory exists.
NOTES: This fixed the issue on an Ubuntu 18.04 machine using NTFS drives that had their journal files reset through sudo ntfsfix /dev/hdd and unmounted by force using sudo umount -l /mnt/mount_point
Leaving my answer here in case this fix can aid anyone!
This may work:
SELECT Count(tag) AS 'Tag Count'
FROM Table
GROUP BY tag
and
SELECT Count(tag) AS 'Negative Tag Count'
FROM Table
WHERE entryID > 0
GROUP BY tag
function doesNotContainAbcOrDef(x) {
return (x.match('abc') || x.match('def')) === null;
}
jQuery has a nice function for removing elements from the DOM.
The closest() function is cool because it will "get the first element that matches the selector by testing the element itself and traversing up through its ancestors."
$(this).closest("tr").remove();
Each delete button could run that very succinct code with a function call.
Doing this works for me:
moment(new Date("27/04/2016")).format
When this error occurred to me was because Pods folder was in iCloud and had no local copy on my computer. Go to your project's folder in Finder and check if there is iCloud's symbol in any of the folders inside it!
In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])
In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]:
A B C D
1 0.319124 0.296653 0.138206 0.246017
2 0.376994 0.326481 0.230464 0.066062
3 0.036134 0.192954 0.430341 0.340571
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "scr", "javascript:test();", true);
If the long string to multiple lines confuses you. Then you may install mz-tools addin which is a freeware and has the utility which splits the line for you.
If your string looks like below
SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & "','" & txtContractStartDate.Value & "','" & txtSeatNo.Value & "','" & txtFloor.Value & "','" & txtLeaves.Value & "')"
Simply select the string > right click on VBA IDE > Select MZ-tools > Split Lines
You can do this really easily with ack:
ack -l 'cats' | ack -xl 'dogs'
-l
: return a list of files -x
: take the files from STDIN (the previous search) and only search those filesAnd you can just keep piping until you get just the files you want.
I had pip
referring by default to pip3, which made me download the libs for python3. On the contrary I launched the shell as python
(which opened python 2) and the library wasn't installed there obviously.
Once I matched the names pip3 -> python3, pip -> python (2) all worked.
In onViewHolder set onClickListiner to any view and in side click use this code :
Toast.makeText(Drawer_bar.this, "position" + position, Toast.LENGTH_SHORT).show();
Replace Drawer_Bar
with your Activity name.
For e.g. when a user has login.Now lets say the user want to create a forum topic, How will I know that the user is already logged in?
Think about it - there must be some handshake that tells your "Create Forum" API that this current request is from an authenticated user. Since REST APIs are typically stateless, the state must be persisted somewhere. Your client consuming the REST APIs is responsible for maintaining that state. Usually, it is in the form of some token that gets passed around since the time the user was logged in. If the token is good, your request is good.
Check how Amazon AWS does authentications. That's a perfect example of "passing the buck" around from one API to another.
*I thought of adding some practical response to my previous answer. Try Apache Shiro (or any authentication/authorization library). Bottom line, try and avoid custom coding. Once you have integrated your favorite library (I use Apache Shiro, btw) you can then do the following:
/api/v1/login
and api/v1/logout
JSESSIONID
) that is sent back to the client (web, mobile, whatever)/api/v1/findUser
That's all. Hope this helps.
Assume you were:
There are many more examples, but these are the most common, in my experience.
The problem I had was related to SOAP version. The asmx
service was configured to accept both versions, 1.1 and 1.2, so, I think that when you are consuming the service, the client or the server doesn't know what version resolve.
To fix that, is necessary add:
using (wsWebService yourService = new wsWebService())
{
yourService.Url = "https://myUrlService.com/wsWebService.asmx?op=someOption";
yourService.UseDefaultCredentials = true; // this line depends on your authentication type
yourService.SoapVersion = SoapProtocolVersion.Soap11; // asign the version of SOAP
var result = yourService.SomeMethod("Parameter");
}
Where wsWebService
is the name of the class generated as a reference.
Make (or rather a Makefile) is a buildsystem - it drives the compiler and other build tools to build your code.
CMake is a generator of buildsystems. It can produce Makefiles, it can produce Ninja build files, it can produce KDEvelop or Xcode projects, it can produce Visual Studio solutions. From the same starting point, the same CMakeLists.txt file. So if you have a platform-independent project, CMake is a way to make it buildsystem-independent as well.
If you have Windows developers used to Visual Studio and Unix developers who swear by GNU Make, CMake is (one of) the way(s) to go.
I would always recommend using CMake (or another buildsystem generator, but CMake is my personal preference) if you intend your project to be multi-platform or widely usable. CMake itself also provides some nice features like dependency detection, library interface management, or integration with CTest, CDash and CPack.
Using a buildsystem generator makes your project more future-proof. Even if you're GNU-Make-only now, what if you later decide to expand to other platforms (be it Windows or something embedded), or just want to use an IDE?
I have had a similar issue recently and realised that it's not due to background-size:cover
but background-attachment:fixed
.
I solved the issue by using a media query for iPhone and setting background-attachment
property to scroll
.
For my case:
.cover {
background-size: cover;
background-attachment: fixed;
background-position: center center;
@media (max-width: @iphone-screen) {
background-attachment: scroll;
}
}
Edit: The code block is in LESS and assumes a pre-defined variable for @iphone-screen
. Thanks for the notice @stephband.
public partial class Form1 : Form
{
private Thread n_server;
private Thread n_client;
private Thread n_send_server;
private TcpClient client;
private TcpListener listener;
private int port = 2222;
private string IP = " ";
private Socket socket;
byte[] bufferReceive = new byte[4096];
byte[] bufferSend = new byte[4096];
public Form1()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
public void Server()
{
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
try
{
socket = listener.AcceptSocket();
if (socket.Connected)
{
textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = "Client : " + socket.RemoteEndPoint.ToString(); });
}
while (true)
{
int length = socket.Receive(bufferReceive);
if (length > 0)
{
label2.Invoke((MethodInvoker)delegate { label2.Text = Encoding.Unicode.GetString(bufferReceive); });
}
}
}
catch
{
}
}
public void Client()
{
IP = "localhost";
client = new TcpClient();
try
{
client.Connect(IP, port);
while (true)
{
NetworkStream nts = client.GetStream();
int length;
while ((length = nts.Read(bufferReceive, 0, bufferReceive.Length)) != 0)
{
label3.Invoke((MethodInvoker)delegate { label3.Text = Encoding.Unicode.GetString(bufferReceive); });
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
if (client.Connected)
{
textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = "Connected..."; });
}
}
private void button1_Click(object sender, EventArgs e)
{
n_server = new Thread(new ThreadStart(Server));
n_server.IsBackground = true;
n_server.Start();
textBox1.Text = "Server up";
}
private void button2_Click(object sender, EventArgs e)
{
n_client = new Thread(new ThreadStart(Client));
n_client.IsBackground = true;
n_client.Start();
}
private void send()
{
if (socket!=null)
{
bufferSend = Encoding.Unicode.GetBytes(textBox2.Text);
socket.Send(bufferSend);
}
else
{
if (client.Connected)
{
bufferSend = Encoding.Unicode.GetBytes(textBox3.Text);
NetworkStream nts = client.GetStream();
if (nts.CanWrite)
{
nts.Write(bufferSend,0,bufferSend.Length);
}
}
}
}
private void button3_Click(object sender, EventArgs e)
{
n_send_server = new Thread(new ThreadStart(send));
n_send_server.IsBackground = true;
n_send_server.Start();
}
}
To find the distance between 2 points, you need to find the length of the hypotenuse in a right angle triangle with a width and height equal to the vertical and horizontal distance:
Math.hypot(endX - startX, endY - startY)
There is actually, a less heavy-handed way of doing a stream copy. Take note however, that this implies that you can store the entire file in memory. Don't try and use this if you are working with files that go into the hundreds of megabytes or more, without caution.
public static void CopySmallTextStream(Stream input, Stream output)
{
using (StreamReader reader = new StreamReader(input))
using (StreamWriter writer = new StreamWriter(output))
{
writer.Write(reader.ReadToEnd());
}
}
NOTE: There may also be some issues concerning binary data and character encodings.
if you want include Id
async getMarkers() {
const events = await firebase.firestore().collection('events')
events.get().then((querySnapshot) => {
const tempDoc = querySnapshot.docs.map((doc) => {
return { id: doc.id, ...doc.data() }
})
console.log(tempDoc)
})
}
Same way with array
async getMarkers() {
const events = await firebase.firestore().collection('events')
events.get().then((querySnapshot) => {
const tempDoc = []
querySnapshot.forEach((doc) => {
tempDoc.push({ id: doc.id, ...doc.data() })
})
console.log(tempDoc)
})
}
Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.
You've got:
//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]
Which translates into:
Get me all the elements that have an ID
that contains ctl00_btnAircraftMapCell
. Out of these elements, get any child elements that have a title
that contains Select Seat
.
What you actually want is:
//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]
Which translates into:
Get me all the anchor elements that have both: an id
that contains ctl00_btnAircraftMapCell
and a title
that contains Select Seat
.
Probably I have found myself:
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();
Maven plugin uses a settings file where the configuration can be set. Its path is available in Eclipse at Window|Preferences|Maven|User Settings
. If the file doesn't exist, create it and put on something like this:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository/>
<interactiveMode/>
<usePluginRegistry/>
<offline/>
<pluginGroups/>
<servers/>
<mirrors/>
<proxies>
<proxy>
<id>myproxy</id>
<active>true</active>
<protocol>http</protocol>
<host>192.168.1.100</host>
<port>6666</port>
<username></username>
<password></password>
<nonProxyHosts>localhost|127.0.0.1</nonProxyHosts>
</proxy>
</proxies>
<profiles/>
<activeProfiles/>
</settings>
After editing the file, it's just a matter of clicking on Update Settings
button and it's done. I've just done it and it worked :)
I suspect you haven't authorize your Excel installation to run macro from an automated Excel. It is a security protection by default at installation. To change this:
Run:
pip list
You should get a list of packages (including panda) and their versions, e.g.:
beautifulsoup4 (4.5.1)
cycler (0.10.0)
jdcal (1.3)
matplotlib (1.5.3)
numpy (1.11.1)
openpyxl (2.2.0b1)
pandas (0.18.1)
pip (8.1.2)
pyparsing (2.1.9)
python-dateutil (2.2)
python-nmap (0.6.1)
pytz (2016.6.1)
requests (2.11.1)
setuptools (20.10.1)
six (1.10.0)
SQLAlchemy (1.0.15)
xlrd (1.0.0)
Just for the shake of completing the answer given by eipi10.
I was facing the same problem, without using scale_y_continuous
nor coord_cartesian
.
The conflict was coming from the x axis, where I defined limits = c(1, 30)
. It seems such limits do not provide enough space if you want to "dodge" your bars, so R still throws the error
Removed 8 rows containing missing values (geom_bar)
Adjusting the limits of the x axis to limits = c(0, 31)
solved the problem.
In conclusion, even if you are not putting limits to your y axis, check out your x axis' behavior to ensure you have enough space
make your class public
access modifier,
just add public
keyword infront of your class name
namespace Test
{
public class Delivery
{
private string name;
private string address;
private DateTime arrivalTime;
public string Name
{
get { return name; }
set { name = value; }
}
public string Address
{
get { return address; }
set { address = value; }
}
public DateTime ArrivlaTime
{
get { return arrivalTime; }
set { arrivalTime = value; }
}
public string ToString()
{
{ return name + address + arrivalTime.ToString(); }
}
}
}
Use the PasteSpecial method:
sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
BUT your big problem is that you're changing your ActiveSheet to "Data" and not changing it back. You don't need to do the Activate and Select, as per my code (this assumes your button is on the sheet you want to copy to).
For those coming here and are using Java config you can set the Bean to lazy-init using annotations like this:
In the configuration class:
@Configuration
// @Lazy - For all Beans to load lazily
public class AppConf {
@Bean
@Lazy
public Demo demo() {
return new Demo();
}
}
For component scanning and auto-wiring:
@Component
@Lazy
public class Demo {
....
....
}
@Component
public class B {
@Autowired
@Lazy // If this is not here, Demo will still get eagerly instantiated to satisfy this request.
private Demo demo;
.......
}
You can use the regex
(\s)\1
and
replace it with $1
.
Java code:
str = str.replaceAll("(\\s)\\1","$1");
If the input is "foo\t\tbar "
you'll get "foo\tbar "
as output
But if the input is "foo\t bar"
it will remain unchanged because it does not have any consecutive whitespace characters.
If you treat all the whitespace characters(space, vertical tab, horizontal tab, carriage return, form feed, new line) as space then you can use the following regex to replace any number of consecutive white space with a single space:
str = str.replaceAll("\\s+"," ");
But if you want to replace two consecutive white space with a single space you should do:
str = str.replaceAll("\\s{2}"," ");
List
dict = {'Neetu':22,'Shiny':21,'Poonam':23}
print sorted(dict.items())
sv = sorted(dict.values())
print sv
Dictionary
d = []
l = len(sv)
while l != 0 :
d.append(sv[l - 1])
l = l - 1
print d`