As Mark C points out, you can use the MSXML Base64 encoding functionality as described here.
I prefer late binding because it's easier to deploy, so here's the same function that will work without any VBA references:
Function EncodeBase64(text As String) As String
Dim arrData() As Byte
arrData = StrConv(text, vbFromUnicode)
Dim objXML As Variant
Dim objNode As Variant
Set objXML = CreateObject("MSXML2.DOMDocument")
Set objNode = objXML.createElement("b64")
objNode.dataType = "bin.base64"
objNode.nodeTypedValue = arrData
EncodeBase64 = objNode.text
Set objNode = Nothing
Set objXML = Nothing
End Function
For finding value use below
if let a = companies["AAPL"] {
// a is the value
}
For traversing through the dictionary
for (key, value) in companies {
print(key,"---", value)
}
Finally for searching key by value you firstly add the extension
extension Dictionary where Value: Equatable {
func findKey(forValue val: Value) -> Key? {
return first(where: { $1 == val })?.key
}
}
Then just call
companies.findKey(val : "Apple Inc")
On my system, I don't have the rename
command. Here is a simple one liner. It finds all the HTML files recursively and adds prefix_
in front of their names:
for f in $(find . -name '*.html'); do mv "$f" "$(dirname "$f")/prefix_$(basename "$f")"; done
Here is a basic example of how an image file with certain restrictions (listed below) can be uploaded to the server.
Checks for image size.
<?php
$newfilename = "newfilename";
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$expensions= array("jpeg","jpg","png");
if(file_exists($file_name)) {
echo "Sorry, file already exists.";
}
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$newfilename.".".$file_ext);
echo "Success";
echo "<script>window.close();</script>";
}
else{
print_r($errors);
}
}
?>
<html>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit"/>
</form>
</body>
</html>
Credit to this page.
I found best example on Dzone.com which is really helpfull to understand the real different between IOC and DI
“IoC is when you have someone else create objects for you.” So instead of writing "new " keyword (For example, MyCode c=new MyCode())in your code, the object is created by someone else. This ‘someone else’ is normally referred to as an IoC container. It means we handover the rrsponsibility (control )to the container to get instance of object is called Inversion of Control., means instead of you are creating object using new operator, let the container do that for you.
DI(Dependency Injection): Way of injecting properties to an object is
called
Dependency injection.
We have three types of Dependency injection
1) Constructor Injection
2) Setter/Getter Injection
3) Interface Injection
Spring will support only Constructor Injection and Setter/Getter Injection.
You can also use get_object_or_404 django shortcut. It raises a 404 error if object is not found.
function scroll_down(){
$.noConflict();
jQuery(document).ready(function($) {
$('html, body').animate({
scrollTop : $("#bottom").offset().top
}, 1);
});
return false;
}
here "bottom" is the div tag id where you want to scroll to. For changing the animation effects, you can change the time from '1' to a different value
The following snippet is used to take screenshot :
UIGraphicsBeginImageContext(self.muUIView.bounds.size);
[myUIView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Use renderInContext:
method instead of drawInContext:
method
renderInContext:
method renders the receiver and its sublayers into current context. This method
renders directly from the layer tree.
I could not get the keypress
event to fire for the enter button, and scratched my head for some time, until I read the jQuery docs:
"The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events." (https://api.jquery.com/keypress/)
I had to use the keyup
or keydown
event to catch a press of the enter button.
The explanation for how it works:
JUnit wraps your test method in a Statement object so statement and Execute()
runs your test. Then instead of calling statement.Execute()
directly to run your test, JUnit passes the Statement to a TestRule with the @Rule
annotation. The TestRule's "apply" function returns a new Statement given the Statement with your test. The new Statement's Execute()
method can call the test Statement's execute method (or not, or call it multiple times), and do whatever it wants before and after
.
Now, JUnit has a new Statement that does more than just run the test, and it can again pass that to any more rules before finally calling Execute.
Another option I would recommend is to create a separate application that is stateless that would take the large file. On your main app open a new window or iframe that will accept the file and send it through that window then hide the window or iframe once the upload has started using Javascript.
For Gradle
users, if you are using Eclipse or one of its offshoots(I am using STS 4.5.1.RELEASE
), all that you need to do is:
In build.gradle, you ONLY need these 2 "extra" instructions:
dependencies {
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
}
Right-click on your project > Gradle > Refresh Gradle Project. The lombok-"version".jar
will appear inside your project's Project and External Dependencies
Right-click on that lombok-"version".jar
> Run As > Java Application (similar to double-clicking on the actual jar or running java -jar lombok-"version".jar
on the command line.)
A GUI will appear, follow the instructions and one of the thing it does is to copy lombok.jar
to your IDE's root.
The only other thing you will need to do(outside of the GUI) is to add that lombok.jar
to your project build path
That's it!
You should implement a Custom List View, such that you define a Layout once and draw it for every row in the list view.
For whatever it's worth now: here is yet another solution:
display: inline-block
tabhead
)tabfull
)setTimeout(() => {/*...*/})
to execute code after render / after filling the table with results from fetch
clientWidth
) With a few tweaks, this is the method to use (for brevity / simplicity, I used d3js, the same operations can be done using plain DOM):
setTimeout(() => { // pass one cycle
d3.select('#tabfull')
.style('margin-top', (-1 * d3.select('#tabscroll').select('thead').node().getBoundingClientRect().height) + 'px')
.select('thead')
.style('visibility', 'hidden');
let widths=[]; // really rely on COMPUTED values
d3.select('#tabfull').select('thead').selectAll('th')
.each((n, i, nd) => widths.push(nd[i].clientWidth));
d3.select('#tabhead').select('thead').selectAll('th')
.each((n, i, nd) => d3.select(nd[i])
.style('padding-right', 0)
.style('padding-left', 0)
.style('width', widths[i]+'px'));
})
Waiting on render cycle has the advantage of using the browser layout engine thoughout the process - for any type of header; it's not bound to special condition or cell content lengths being somehow similar. It also adjusts correctly for visible scrollbars (like on Windows)
I've put up a codepen with a full example here: https://codepen.io/sebredhh/pen/QmJvKy
I had the same issue during building my app in AppVeyor.
c:\php
echo extension=php_openssl.dll >> c:\php\php.ini
echo curl.cainfo=c:\php\cacert.pem >> c:\php\php.ini
NanoHttpd works like a charm on Android -- we have code in production, in users hands, that's built on it.
The license absolutely allows commercial use of NanoHttpd, without any "viral" implications.
I needed to figure out the system host IP address for the emulator "Nox App Player". Here is how I figured out it was 172.17.100.2
.
ip link show
command to show all network interfaces. Of particular interest was the eth1 interfaceifconfig eth1
command, shows net as 172.17.100.15/255.255.255.0
172.17.100.1
, got a hit on `172.17.100.2'. Not sure if a firewall would interfere but it didn't in my caseMaybe this can help someone else figure it out for other emulators.
According to the error message, you declared myLoc
as a pointer to an NSInteger (NSInteger *myLoc
) rather than an actual NSInteger (NSInteger myLoc
). It needs to be the latter.
Some time this error in Joomla appear because some thing incorrect with SESSION or coockie. That may because incorrect HTTPd server setting or because some before CURL or Server http requests
so PHP code like:
curl_setopt($ch, CURLOPT_URL, $url_page);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_REFERER, $url_page);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);
will need replace to PHP code
curl_setopt($ch, CURLOPT_URL, $url_page);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
//curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_REFERER, $url_page);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
//curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // !!!!!!!!!!!!!
//if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);
May be some body reply how this options connected with "Curl error: Operation timed out after .."
Out of the box Swift Mailer can't do STARTTLS, however some nice guys have written a patch for it.
I found patching it was a bit of a chore (probably went about it the wrong way), so have zipped it up ready for download here: Swift Mailer with STARTTLS
Try using a div
instead of the span
or using the CSS display: block;
or display: inline-block;
—span
is by default an inline element which cannot take width
and height
properties.
if you want the color to change when you have simply add the :hover
pseudo
div.e:hover {
background-color:red;
}
You can use strtok()
char string[]= "abc/qwe/jkh";
char *array[10];
int i=0;
array[i] = strtok(string,"/");
while(array[i]!=NULL)
{
array[++i] = strtok(NULL,"/");
}
Junit is included by default with Eclipse (at least the Java EE version I'm sure). You may just need to add the view to your perspective.
Careful with the eval, the JSON specs http://json.org/js.html recommend something like
var myObject = eval('(' + myJSONtext + ')');
And there may be some more gotchas. There is a plugin for jQuery that will take care of it, i guess:
An old question with lots of answers, so another one won't be an issue. Some general functions to get the start and end of all sorts of time units.
For startOf and endOf week, the start day of the week defaults to Sunday (0) but any day can be passed (Monday - 1, Tuesday - 2, etc.). Only uses Gregorian calendar though.
The functions don't mutate the source date, so to see if a date is in the same week as some other date (week starting on Monday):
if (d >= startOf('week', d1, 1) && d <= endOf('week', d1, 1)) {
// d is in same week as d1
}
or in the current week starting on Sunday:
if (d >= startOf('week') && d <= endOf('week')) {
// d is in the current week
}
// Returns a new Date object set to start of given unit_x000D_
// For start of week, accepts any day as start_x000D_
function startOf(unit, date = new Date(), weekStartDay = 0) {_x000D_
// Copy original so don't modify it_x000D_
let d = new Date(date);_x000D_
let e = new Date(d);_x000D_
e.setHours(23,59,59,999);_x000D_
// Define methods_x000D_
let start = {_x000D_
second: d => d.setMilliseconds(0),_x000D_
minute: d => d.setSeconds(0,0),_x000D_
hour : d => d.setMinutes(0,0,0),_x000D_
day : d => d.setHours(0,0,0,0),_x000D_
week : d => {_x000D_
start.day(d);_x000D_
d.setDate(d.getDate() - d.getDay() + weekStartDay);_x000D_
if (d > e) d.setDate(d.getDate() - 7);_x000D_
},_x000D_
month : d => {_x000D_
start.day(d);_x000D_
d.setDate(1);_x000D_
},_x000D_
year : d => {_x000D_
start.day(d);_x000D_
d.setMonth(0, 1);_x000D_
},_x000D_
decade: d => {_x000D_
start.year(d);_x000D_
let year = d.getFullYear();_x000D_
d.setFullYear(year - year % 10);_x000D_
},_x000D_
century: d => {_x000D_
start.year(d);_x000D_
let year = d.getFullYear();_x000D_
d.setFullYear(year - year % 100);_x000D_
},_x000D_
millenium: d => {_x000D_
start.year(d);_x000D_
let year = d.getFullYear();_x000D_
d.setFullYear(year - year % 1000);_x000D_
}_x000D_
}_x000D_
start[unit](d);_x000D_
return d;_x000D_
}_x000D_
_x000D_
// Returns a new Date object set to end of given unit_x000D_
// For end of week, accepts any day as start day_x000D_
// Requires startOf_x000D_
function endOf(unit, date = new Date(), weekStartDay = 0) {_x000D_
// Copy original so don't modify it_x000D_
let d = new Date(date);_x000D_
let e = new Date(date);_x000D_
e.setHours(23,59,59,999);_x000D_
// Define methods_x000D_
let end = {_x000D_
second: d => d.setMilliseconds(999),_x000D_
minute: d => d.setSeconds(59,999),_x000D_
hour : d => d.setMinutes(59,59,999),_x000D_
day : d => d.setHours(23,59,59,999),_x000D_
week : w => {_x000D_
w = startOf('week', w, weekStartDay);_x000D_
w.setDate(w.getDate() + 6);_x000D_
end.day(w);_x000D_
d = w;_x000D_
},_x000D_
month : d => {_x000D_
d.setMonth(d.getMonth() + 1, 0);_x000D_
end.day(d);_x000D_
}, _x000D_
year : d => {_x000D_
d.setMonth(11, 31);_x000D_
end.day(d);_x000D_
},_x000D_
decade: d => {_x000D_
end.year(d);_x000D_
let y = d.getFullYear();_x000D_
d.setFullYear(y - y % 10 + 9);_x000D_
},_x000D_
century: d => {_x000D_
end.year(d);_x000D_
let y = d.getFullYear();_x000D_
d.setFullYear(y - y % 100 + 99);_x000D_
},_x000D_
millenium: d => {_x000D_
end.year(d);_x000D_
let y = d.getFullYear();_x000D_
d.setFullYear(y - y % 1000 + 999);_x000D_
}_x000D_
}_x000D_
end[unit](d);_x000D_
return d;_x000D_
}_x000D_
_x000D_
// Examples_x000D_
let d = new Date();_x000D_
_x000D_
['second','minute','hour','day','week','month','year',_x000D_
'decade','century','millenium'].forEach(unit => {_x000D_
console.log(('Start of ' + unit).padEnd(18) + ': ' +_x000D_
startOf(unit, d).toString());_x000D_
console.log(('End of ' + unit).padEnd(18) + ': ' +_x000D_
endOf(unit, d).toString());_x000D_
});
_x000D_
It's a little tricky because of the nested IFs but here is my answer (confirmed in Google Spreadsheets):
=IF(AND(A2>=0, A2<500), "Less than 500",
IF(AND(A2>=500, A2<1000), "Between 500 and 1000",
IF(AND(A2>=1000, A2<1500), "Between 1000 and 1500",
IF(AND(A2>=1500, A2<2000), "Between 1500 and 2000", "Undefined"))))
I known this is old, but I found a easier solution and it works on ie10, firefox and chrome:
<div id="wrapper">
<div id="one">One</div>
<div id="two">Two</div>
<div id="three">Three</div>
</div>
This is the css:
#wrapper {display:table;}
#one {display:table-footer-group;}
#three {display:table-header-group;}
And the result:
"Three"
"Two"
"One"
I found it here.
Create a user first. You must do this as user postgres. Because the postgres system account has no password assigned, you can either set a password first, or you go like this:
sudo /bin/bash
# you should be root now
su postgres
# you are postgres now
createuser --interactive
and the programm will prompt you.
I know there's a lot of answers here, but they all seem a bit confusing. So after doing some research from the Java oracle study guide, I've come up with three different scenarios of when to use && or &. The three scenarios are logical AND, bitwise AND, and boolean AND.
Logical AND:
Logical AND (aka Conditional AND) uses the && operator. It's short-circuited meaning: if the left operand is false, then the right operand will not be evaluated.
Example:
int x = 0;
if (false && (1 == ++x) {
System.out.println("Inside of if");
}
System.out.println(x); // "0"
In the above example the value printed to the console of x will be 0, because the first operand in the if statement is false, hence java has no need to compute (1 == ++x) therefore x will not be computed.
Bitwise AND: Bitwise AND uses the & operator. It's used to preform a bitwise operation on the value. It's much easier to see what's going on by looking at operation on binary numbers ex:
int a = 5; // 5 in binary is 0101
int b = 12; // 12 in binary is 1100
int c = a & b; // bitwise & preformed on a and b is 0100 which is 4
As you can see in the example, when the binary representations of the numbers 5 and 12 are lined up, then a bitwise AND preformed will only produce a binary number where the same digit in both numbers have a 1. Hence 0101 & 1100 == 0100. Which in decimal is 5 & 12 == 4.
Boolean AND: Now the boolean AND operator behaves similarly and differently to both the bitwise AND and logical AND. I like to think of it as preforming a bitwise AND between two boolean values (or bits), therefore it uses & operator. The boolean values can be the result of a logical expression too.
It returns either a true or false value, much like the logical AND, but unlike the logical AND it is not short-circuited. The reason being, is that for it to preform that bitwise AND, it must know the value of both left and right operands. Here's an ex:
int x = 0;
if (false & (1 == ++x) {
System.out.println("Inside of if");
}
System.out.println(x); //"1"
Now when that if statement is ran, the expression (1 == ++x) will be executed, even though the left operand is false. Hence the value printed out for x will be 1 because it got incremented.
This also applies to Logical OR (||), bitwise OR (|), and boolean OR (|) Hope this clears up some confusion.
Do not use the *
selector as that will apply to all elements on the page. Suppose you have a structure like this:
...
<body>
<div id="content">
<b>This is the main container.</b>
</div>
</body>
</html>
You can then center the #content
div using:
#content {
width: 400px;
margin: 0 auto;
background-color: #66ffff;
}
Don't know what you've seen elsewhere but this is the way to go. The * { margin: 0; padding: 0; }
snippet you've seen is for resetting browser's default definitions for all browsers to make your site behave similarly on all browsers, this has nothing to do with centering the main container.
Most browsers apply a default margin and padding to some elements which usually isn't consistent with other browsers' implementations. This is why it is often considered smart to use this kind of 'resetting'. The reset snippet you presented is the most simplest of reset stylesheets, you can read more about the subject here:
What if you set the timezone of the role you are using?
ALTER ROLE my_db_user IN DATABASE my_database
SET "TimeZone" TO 'UTC';
Will this be of any use?
I don't think you can its an operator and its suppose to return one or the other. It's not if else statement replacement although it can be use for that on certain case.
One of the Related posts gave me the (simple) answer.
Apparently the auto
value on the grid-template-rows
property does exactly what I was looking for.
.grid {
display:grid;
grid-template-columns: 1fr 1.5fr 1fr;
grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
grid-gap:10px;
height: calc(100vh - 10px);
}
You could hard code it.
<div class="col-md-6" style="background-color:blue;">
</div>
<div class="col-md-6" style="background-color:white;">
</div>
What's wrong with just simply using a single, simple UPDATE
statement??
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
That's all that's needed ! No messy and complicated cursor, no looping, no RBAR (row-by-agonizing-row) processing ..... just a nice, simple, clean set-based SQL statement.
You can use "\\r\\n"
also for the new line in powershell
. I have used this in servicenow tool.
In my case "\r\n"
s not working so i tried "\\r\\n"
as "\"
this symbol work as escape character in powershell
.
This would do the trick, returning the values at indeces 0, 2 and 3.
Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))
This solve my problem.
Just change the Bundle identifier from Build Setting.
Navigate to Project >> Build Setting >> Product Bundle Identifier
user.dir
is the "User working directory" according to the Java Tutorial, System Properties
A simple pure-Python implementation would be:
import math
import re
from collections import Counter
WORD = re.compile(r"\w+")
def get_cosine(vec1, vec2):
intersection = set(vec1.keys()) & set(vec2.keys())
numerator = sum([vec1[x] * vec2[x] for x in intersection])
sum1 = sum([vec1[x] ** 2 for x in list(vec1.keys())])
sum2 = sum([vec2[x] ** 2 for x in list(vec2.keys())])
denominator = math.sqrt(sum1) * math.sqrt(sum2)
if not denominator:
return 0.0
else:
return float(numerator) / denominator
def text_to_vector(text):
words = WORD.findall(text)
return Counter(words)
text1 = "This is a foo bar sentence ."
text2 = "This sentence is similar to a foo bar sentence ."
vector1 = text_to_vector(text1)
vector2 = text_to_vector(text2)
cosine = get_cosine(vector1, vector2)
print("Cosine:", cosine)
Prints:
Cosine: 0.861640436855
The cosine formula used here is described here.
This does not include weighting of the words by tf-idf, but in order to use tf-idf, you need to have a reasonably large corpus from which to estimate tfidf weights.
You can also develop it further, by using a more sophisticated way to extract words from a piece of text, stem or lemmatise it, etc.
I find object.constructor.toString()
return [object objectClass]
in IE ,rather than function objectClass () {}
returned in chome. So,I think the code in http://blog.magnetiq.com/post/514962277/finding-out-class-names-of-javascript-objects may not work well in IE.And I fixed the code as follows:
var getObjectClass = function (obj) {
if (obj && obj.constructor && obj.constructor.toString()) {
/*
* for browsers which have name property in the constructor
* of the object,such as chrome
*/
if(obj.constructor.name) {
return obj.constructor.name;
}
var str = obj.constructor.toString();
/*
* executed if the return of object.constructor.toString() is
* "[object objectClass]"
*/
if(str.charAt(0) == '[')
{
var arr = str.match(/\[\w+\s*(\w+)\]/);
} else {
/*
* executed if the return of object.constructor.toString() is
* "function objectClass () {}"
* for IE Firefox
*/
var arr = str.match(/function\s*(\w+)/);
}
if (arr && arr.length == 2) {
return arr[1];
}
}
return undefined;
};
To get the text of the selected option
$("#your_select :selected").text();
To get the value of the selected option
$("#your_select").val();
I use your exact proposed code with only some few additional lines. The idea is more or less the same of the one proposed by @elias, but in this solution there cannot be conflicts on the keys since each file in the directory has a different filename and so adding it to the key solves the conflicts. The first part of the key is the datetime string formatted in a manner such that I can lexicographically compare two of them.
if ($handle = opendir('.')) {
$result = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$lastModified = date('F d Y, H:i:s',filemtime($file));
if(strlen($file)-strpos($file,".swf")== 4){
$result [date('Y-m-d H:i:s',filemtime($file)).$file] =
"<tr><td><input type=\"checkbox\" name=\"box[]\"></td><td><a href=\"$file\" target=\"_blank\">$file</a></td><td>$lastModified</td></tr>";
}
}
}
closedir($handle);
krsort($result);
echo implode('', $result);
}
Several solutions come to mind:
The reason this doesn't work out of the box is that containers run with their own network namespace by default. That means localhost (or 127.0.0.1 pointing to the loopback interface) is unique per container. Connecting to this will connect to the container itself, and not services running outside of docker or inside of a different docker container.
Option 1: If your dependency can be moved into a container, I would do this first. It makes your application stack portable as others try to run your container on their own environment. And you can still publish the port on your host where other services that have not been migrated can still reach it. You can even publish the port to the localhost interface on your docker host to avoid it being externally accessible with a syntax like: -p 127.0.0.1:3306:3306
for the published port.
Option 2: There are a variety of ways to detect the host IP address from inside of the container, but each have a limited number of scenarios where they work (e.g. requiring Docker for Mac). The most portable option is to inject your host IP into the container with something like an environment variable or configuration file, e.g.:
docker run --rm -e "HOST_IP=$(ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p')" ...
This does require that your service is listening on that external interface, which could be a security concern. For other methods to get the host IP address from inside of the container, see this post.
Slightly less portable is to use host.docker.internal
. This works in current versions of Docker for Windows and Docker for Mac. And in 20.10, the capability has been added to Docker for Linux when you pass a special host entry with:
docker run --add-host host.docker.internal:host-gateway ...
The host-gateway
is a special value added in Docker 20.10 that automatically expands to a host IP. For more details see this PR.
Option 3: Running without network isolation, i.e. running with --net host
, means your application is running on the host network namespace. This is less isolation for the container, and it means you cannot access other containers over a shared docker network with DNS (instead, you need to use published ports to access other containerized applications). But for applications that need to access other services on the host that are only listening on 127.0.0.1
on the host, this can be the easiest option.
Option 4: Various services also allow access over a filesystem based socket. This socket can be mounted into the container as a bind mounted volume, allowing you to access the host service without going over the network. For access to the docker engine, you often see examples of mounting /var/run/docker.sock
into the container (giving that container root access to the host). With mysql, you can try something like -v /var/run/mysqld/mysqld.sock:/var/run/mysqld/mysql.sock
and then connect to localhost
which mysql converts to using the socket.
You could add it between your <head></head>
tag like so:
<head>
<link href="./node_modules/font-awesome/css/font-awesome.css" rel="stylesheet" type="text/css">
</head>
Or whatever your path to your node_modules
is.
Edit (2017-06-26) - Disclaimer: THERE ARE BETTER ANSWERS. PLEASE DO NOT USE THIS METHOD. At the time of this original answer, good tools weren't as prevalent. With current build tools such as webpack or browserify, it probably doesn't make sense to use this answer. I can delete it, but I think it's important to highlight the various options one has and the possible dos and do nots.
Simple solution
myDivObj = document.getElementById("myDivID")
let myDivObjBgColor = window.getComputedStyle(myDivObj).backgroundColor;
Now the background color is stored in the new variable.
I've had this same error, without your whole code it is difficult to pinpoint exactly how to fix it but it is caused by not having a __set function.
The way that I have gotten around it in the past is I have done things like this:
$user = createUser();
$role = $user->role;
$role->rolename = 'Test';
now if you do this:
echo $user->role->rolename;
you should see 'Test'
Yes, it is called Inline CSS, Here you styling the div
using some height, width, and background.
Here the example:
<div style="width:50px;height:50px;background color:red">
You can achieve same using Internal or External CSS
2.Internal CSS:
<head>
<style>
div {
height:50px;
width:50px;
background-color:red;
foreground-color:white;
}
</style>
</head>
<body>
<div></div>
</body>
3.External CSS:
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div></div>
</body>
style.css /external css file/
div {
height:50px;
width:50px;
background-color:red;
}
I'd recommend using the Buffer
class:
var someEncodedString = Buffer.from('someString', 'utf-8');
This avoids any unnecessary dependencies that other answers require, since Buffer
is included with node.js
, and is already defined in the global scope.
In Cocoa for Mac OS X, you have the next responder chain, where you can ask the text field what control should have focus next. This is what makes tabbing between text fields work. But since iOS devices do not have a keyboard, only touch, this concept has not survived the transition to Cocoa Touch.
This can be easily done anyway, with two assumptions:
UITextField
s are on the same parent view.Assuming this you can override textFieldShouldReturn: as this:
-(BOOL)textFieldShouldReturn:(UITextField*)textField
{
NSInteger nextTag = textField.tag + 1;
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
} else {
// Not found, so remove keyboard.
[textField resignFirstResponder];
}
return NO; // We do not want UITextField to insert line-breaks.
}
Add some more code, and the assumptions can be ignored as well.
Swift 4.0
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let nextTag = textField.tag + 1
// Try to find next responder
let nextResponder = textField.superview?.viewWithTag(nextTag) as UIResponder!
if nextResponder != nil {
// Found next responder, so set it
nextResponder?.becomeFirstResponder()
} else {
// Not found, so remove keyboard
textField.resignFirstResponder()
}
return false
}
If the superview of the text field will be a UITableViewCell then next responder will be
let nextResponder = textField.superview?.superview?.superview?.viewWithTag(nextTag) as UIResponder!
perl: warning: Falling back to the standard locale ("C").
locale: Cannot set LC_ALL to default locale: No such file or directory
Solution:
Try this (uk_UA.UTF-8 is my current locale. Write your locale, for example en_US.UTF-8 !)
sudo locale-gen uk_UA.UTF-8
and this.
sudo dpkg-reconfigure locales
I think the terms and most of the examples are a bit overwhelming,
The main issue i had personally with the difference is understanding what a "Block" is.
At some point i realized, a block would be any curly brackets except for IF
statement.
an opening bracket {
of a function or loop will define a new block, anything defined with let
within it, will not be available after the closing bracket }
of the same thing (function or loop);
With that in mind, it was easier to understand:
let msg = "Hello World";_x000D_
_x000D_
function doWork() { // msg will be available since it was defined above this opening bracket!_x000D_
let friends = 0;_x000D_
console.log(msg);_x000D_
_x000D_
// with VAR though:_x000D_
for (var iCount2 = 0; iCount2 < 5; iCount2++) {} // iCount2 will be available after this closing bracket!_x000D_
console.log(iCount2);_x000D_
_x000D_
for (let iCount1 = 0; iCount1 < 5; iCount1++) {} // iCount1 will not be available behind this closing bracket, it will return undefined_x000D_
console.log(iCount1);_x000D_
_x000D_
} // friends will no be available after this closing bracket!_x000D_
doWork();_x000D_
console.log(friends);
_x000D_
If you have your project saved as a local copy of a repository, it may be better to import from git. Select local, and then browse to your git repository folder. That worked better for me than importing it as an existing project. Attempting the latter did not allow me to "finish".
the answers above doesn't work in my case. You need to specify utf-8 in meta tag
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<!-- you content goes here -->
</body>
</html>
Yes, you need to use global foo
if you are going to write to it.
foo = []
def bar():
global foo
...
foo = [1]
This is a more user-friendly one I guess :
#include<stdio.h>
/* This program checks if the entered input is an integer
* or provides an option for the user to re-enter.
*/
int getint()
{
int x;
char c;
printf("\nEnter an integer (say -1 or 26 or so ): ");
while( scanf("%d",&x) != 1 )
{
c=getchar();
printf("You have entered ");
putchar(c);
printf(" in the input which is not an integer");
while ( getchar() != '\n' )
; //wasting the buffer till the next new line
printf("\nEnter an integer (say -1 or 26 or so ): ");
}
return x;
}
int main(void)
{
int x;
x=getint();
printf("Main Function =>\n");
printf("Integer : %d\n",x);
return 0;
}
You can work around that via a Live Template. Go to Settings -> Live Template, click the "Add"-Button (green plus on the right).
In the "Abbreviation" field, enter the string that should activate the template (e.g. @a
), and in the "Template Text" area enter the string to complete (e.g. @author - My Name
). Set the "Applicable context" to Java (Comments only maybe) and set a key to complete (on the right).
I tested it and it works fine, however IntelliJ seems to prefer the inbuild templates, so "@a + Tab" only completes "author". Setting the completion key to Space worked however.
To change the user name that is automatically inserted via the File Templates (when creating a class for example), can be changed by adding
-Duser.name=Your name
to the idea.exe.vmoptions or idea64.exe.vmoptions (depending on your version) in the IntelliJ/bin directory.
Restart IntelliJ
From the docs
IF boolean-expression THEN
statements
ELSE
statements
END IF;
So in your above example the code should look as follows:
IF select count(*) from orders > 0
THEN
DELETE from orders
ELSE
INSERT INTO orders values (1,2,3);
END IF;
You were missing: END IF;
Naturally, my approach was to loop through the first array once and check the index of each value in the second array. If the index is > -1
, then push
it onto the returned array.
?Array.prototype.diff = function(arr2) {
var ret = [];
for(var i in this) {
if(arr2.indexOf(this[i]) > -1){
ret.push(this[i]);
}
}
return ret;
};
?
My solution doesn't use two loops like others do so it may run a bit faster. If you want to avoid using for..in
, you can sort both arrays first to reindex all their values:
Array.prototype.diff = function(arr2) {
var ret = [];
this.sort();
arr2.sort();
for(var i = 0; i < this.length; i += 1) {
if(arr2.indexOf(this[i]) > -1){
ret.push(this[i]);
}
}
return ret;
};
Usage would look like:
var array1 = ["cat", "sum","fun", "run", "hut"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];
console.log(array1.diff(array2));
If you have an issue/problem with extending the Array prototype, you could easily change this to a function.
var diff = function(arr, arr2) {
And you'd change anywhere where the func originally said this
to arr2
.
At the time of my writing this answer, the accepted answer to this question appears to state that browsers are not required to delete a cookie when receiving a replacement cookie whose Expires
value is in the past. That claim is false. Setting Expires
to be in the past is the standard, spec-compliant way of deleting a cookie, and user agents are required by spec to respect it.
Using an Expires
attribute in the past to delete a cookie is correct and is the way to remove cookies dictated by the spec. The examples section of RFC 6255 states:
Finally, to remove a cookie, the server returns a Set-Cookie header with an expiration date in the past. The server will be successful in removing the cookie only if the Path and the Domain attribute in the Set-Cookie header match the values used when the cookie was created.
The User Agent Requirements section includes the following requirements, which together have the effect that a cookie must be immediately expunged if the user agent receives a new cookie with the same name whose expiry date is in the past
If [when receiving a new cookie] the cookie store contains a cookie with the same name, domain, and path as the newly created cookie:
- ...
- ...
- Update the creation-time of the newly created cookie to match the creation-time of the old-cookie.
- Remove the old-cookie from the cookie store.
Insert the newly created cookie into the cookie store.
A cookie is "expired" if the cookie has an expiry date in the past.
The user agent MUST evict all expired cookies from the cookie store if, at any time, an expired cookie exists in the cookie store.
Points 11-3, 11-4, and 12 above together mean that when a new cookie is received with the same name, domain, and path, the old cookie must be expunged and replaced with the new cookie. Finally, the point below about expired cookies further dictates that after that is done, the new cookie must also be immediately evicted. The spec offers no wiggle room to browsers on this point; if a browser were to offer the user the option to disable cookie expiration, as the accepted answer suggests some browsers do, then it would be in violation of the spec. (Such a feature would also have little use, and as far as I know it does not exist in any browser.)
Why, then, did the OP of this question observe this approach failing? Though I have not dusted off a copy of Internet Explorer to check its behaviour, I suspect it was because the OP's Expires
value was malformed! They used this value:
expires=Thu, Jan 01 1970 00:00:00 UTC;
However, this is syntactically invalid in two ways.
The syntax section of the spec dictates that the value of the Expires
attribute must be a
rfc1123-date, defined in [RFC2616], Section 3.3.1
Following the second link above, we find this given as an example of the format:
Sun, 06 Nov 1994 08:49:37 GMT
and find that the syntax definition...
requires that dates be written in day month year format, not month day year format as used by the question asker.
Specifically, it defines rfc1123-date
as follows:
rfc1123-date = wkday "," SP date1 SP time SP "GMT"
and defines date1
like this:
date1 = 2DIGIT SP month SP 4DIGIT
; day month year (e.g., 02 Jun 1982)
and
doesn't permit UTC
as a timezone.
The spec contains the following statement about what timezone offsets are acceptable in this format:
All HTTP date/time stamps MUST be represented in Greenwich Mean Time (GMT), without exception.
What's more if we dig deeper into the original spec of this datetime format, we find that in its initial spec in https://tools.ietf.org/html/rfc822, the Syntax section lists "UT" (meaning "universal time") as a possible value, but does not list not UTC (Coordinated Universal Time) as valid. As far as I know, using "UTC" in this date format has never been valid; it wasn't a valid value when the format was first specified in 1982, and the HTTP spec has adopted a strictly more restrictive version of the format by banning the use of all "zone" values other than "GMT".
If the question asker here had instead used an Expires
attribute like this, then:
expires=Thu, 01 Jan 1970 00:00:00 GMT;
then it would presumably have worked.
Great answer from Anonymous. \ solved my problem when I tried to escape quotes in HTML strings.
So if you use sed to return some HTML templates (on a server), use double backslash instead of single:
var htmlTemplate = "<div style=\\"color:green;\\"></div>";
int var1 = int.Parse(ds.Tables[0].Rows[0][3].ToString());
int var2 = int.Parse(ds.Tables[0].Rows[0][4].ToString());
use this command for run every service just write name service for example :
for xrdp :
sudo /etc/init.d/xrdp start
for redis :
sudo /etc/init.d/redis start
(for any other service, check the init.d folder for filenames)
I find, if the data is imported, you may need to use the trim command on top of it, to get your details. =LEFT(TRIM(B2),8) In my case, I was using it to find a IP range. 10.3.44.44 with mask 255.255.255.0, so response is: 10.3.44 Kind of handy.
You can select elements with multiple classes like so:
$("element.firstClass.anotherClass");
Simply chain the next class onto the first one, without a space (spaces mean "children of").
using Apache IO could be another option for copy the Stream
@RequestMapping(path = "/file/{fileId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> downloadFile(@PathVariable(value="fileId") String fileId,HttpServletResponse response) throws Exception {
InputStream yourInputStream = ...
IOUtils.copy(yourInputStream, response.getOutputStream());
response.flushBuffer();
return ResponseEntity.ok().build();
}
maven dependency
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
const PASSENGER_API = 'api/passengers';
getPassengers(): Observable<Passenger[]> {
return this.http
.get<Passenger[]>(PASSENGER_API)
.pipe(catchError((error: HttpErrorResponse) => throwError(error)));
}
Since GNU parallel was not mentioned yet, let me give another way:
cat url.list | parallel -j 8 wget -O {#}.html {}
If you want your current uncommited changes on the current branch to move to a new branch, use the following command to create a new branch and copy the uncommitted changes automatically.
git checkout -b branch_name
This will create a new branch from your current branch (assuming it to be master), copy the uncommited changes and switch to the new branch.
Add files to stage & commit your changes to the new branch.
git add .
git commit -m "First commit"
Since, a new branch is created, before pushing it to remote, you need to set the upstream. Use the below command to set the upstream and push it to remote.
git push --set-upstream origin feature/feature/NEWBRANCH
Once you hit this command, a new branch will be created at the remote and your new local branch will be pushed to remote.
Now, if you want to throw away your uncommited changes from master branch, use:
git checkout master -f
This will throw away any uncommitted local changes on checkout.
You are mixing the deprecated mysql extension with mysqli.
Try something like:
$sql = mysqli_query($success, "SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
$row = mysqli_num_rows($sql);
You could use find
to solve your problem
const data = [{"a": 1}, {"b": 2}]
const item = {"b": 2}
find(data, item)
// > true
In Objective-C
CGFloat spacing = 5;
UICollectionViewFlowLayout *flow = (UICollectionViewFlowLayout*)_habbitCollectionV.collectionViewLayout;
flow.sectionInset = UIEdgeInsetsMake(0, spacing, 0, spacing);
CGFloat itemsPerRow = 2;
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat oneMore = itemsPerRow + 1;
CGFloat width = screenRect.size.width - spacing * oneMore;
CGFloat height = width / itemsPerRow;
flow.itemSize = CGSizeMake(floor(height), height);
flow.minimumInteritemSpacing = spacing;
flow.minimumLineSpacing = spacing;
All you have to do is change the itemsPerRow value and it will update the number of items per row accordingly. Furthermore, you can change the spacing value if you want more or less general spacing.
head -1000 file.txt > first100lines.txt
tail --lines=+1001 file.txt > restoffile.txt
Try this one in your css document,
-fx-background-color : #ffaadd;
or
-fx-base : #ffaadd;
Also, you can set background color on your object with this code directly.
yourPane.setBackground(new Background(new BackgroundFill(Color.DARKGREEN, CornerRadii.EMPTY, Insets.EMPTY)));
As a lighter alternative to the existing answers, you can set the build result with a simple HTTP POST to access the Groovy script console REST API:
curl -X POST \
--silent \
--user "$YOUR_CREDENTIALS" \
--data-urlencode "script=Jenkins.instance.getItemByFullName( '$JOB_NAME' ).getBuildByNumber( $BUILD_NUMBER ).setResult( hudson.model.Result.UNSTABLE )" $JENKINS_URL/scriptText
Advantages:
For this solution, your environment must meet these conditions:
What’s the difference between \n (newline) and \r (carriage return)?
In particular, are there any practical differences between
\n
and\r
? Are there places where one should be used instead of the other?
I would like to make a short experiment with the respective escape sequences of \n
for newline and \r
for carriage return to illustrate where the distinct difference between them is.
I know, that this question was asked as language-independent. Nonetheless, We need a language at least in order to fulfill the experiment. In my case, I`ve chosen C++, but the experiment shall generally be applicable in any programming language.
The program simply just iterates to print a sentence into the console, done by a for-loop iteration.
Newline program:
#include <iostream>
int main(void)
{
for(int i = 0; i < 7; i++)
{
std::cout << i + 1 <<".Walkthrough of the for-loop \n"; // Notice `\n` at the end.
}
return 0;
}
Output:
1.Walkthrough of the for-loop
2.Walkthrough of the for-loop
3.Walkthrough of the for-loop
4.Walkthrough of the for-loop
5.Walkthrough of the for-loop
6.Walkthrough of the for-loop
7.Walkthrough of the for-loop
Notice, that this result will not be provided on any system, you are executing this C++ code. But it shall work for the most modern systems. Read below for more details.
Now, the same program, but with the difference, that \n
is replaced by \r
at the end of the print sequence.
Carriage return program:
#include <iostream>
int main(void)
{
for(int i = 0; i < 7; i++)
{
std::cout << i + 1 <<".Walkthrough of the for-loop \r"; // Notice `\r` at the end.
}
return 0;
}
Output:
7.Walkthrough of the for-loop
Noticed where the difference is? The difference is simply as that, when you using the Carriage return escape sequence \r
at the end of each print sequence, the next iteration of this sequence do not getting into the following text line - At the end of each print sequence, the cursor did not jumped to the *beginning of the next line.
Instead, the cursor jumped back to the beginning of the line, on which he has been at the end of, before using the \r
character. - The result is that each following iteration of the print sequence is replacing the previous one.
*Note: A \n
do not necessarily jump to the beginning of following text line. On some, in general more elder, operation systems the result of the \n
newline character can be, that it jumps to anywhere in the following line, not just to the beginning. That is why, they rquire to use \r \n
to get at the start of the next text line.
This experiment showed us the difference between newline and carriage return in the context of the output of the iteration of a print sequence.
When discussing about the input in a program, some terminals/consoles may convert a carriage return into a newline implicitly for better portability, compatibility and integrity.
But if you have the choice to choose one for another or want or need to explicitly use only a specific one, you should always operate with the one, which fits to its purpose and strictly distinguish between.
In general, the error ValueError: Wrong number of items passed 3, placement implies 1
suggests that you are attempting to put too many pigeons in too few pigeonholes. In this case, the value on the right of the equation
results['predictedY'] = predictedY
is trying to put 3 "things" into a container that allows only one. Because the left side is a dataframe column, and can accept multiple items on that (column) dimension, you should see that there are too many items on another dimension.
Here, it appears you are using sklearn for modeling, which is where gaussian_process.GaussianProcess()
is coming from (I'm guessing, but correct me and revise the question if this is wrong).
Now, you generate predicted values for y here:
predictedY, MSE = gp.predict(testX, eval_MSE = True)
However, as we can see from the documentation for GaussianProcess, predict()
returns two items. The first is y, which is array-like (emphasis mine). That means that it can have more than one dimension, or, to be concrete for thick headed people like me, it can have more than one column -- see that it can return (n_samples, n_targets)
which, depending on testX
, could be (1000, 3)
(just to pick numbers). Thus, your predictedY
might have 3 columns.
If so, when you try to put something with three "columns" into a single dataframe column, you are passing 3 items where only 1 would fit.
CREATE OR REPLACE PACKAGE BODY TEST AS
FUNCTION GET_UPS(
TIMESPAN_IN IN VARCHAR2 DEFAULT 'MONTLHY',
STARTING_DATE_IN DATE,
ENDING_DATE_IN DATE
)RETURN MEASURE_TABLE IS
T MEASURE_TABLE;
BEGIN
**SELECT MEASURE_RECORD(L4_ID , L6_ID ,L8_ID ,YEAR ,
PERIOD,VALUE ) BULK COLLECT INTO T
FROM ...**
;
RETURN T;
END GET_UPS;
END TEST;
I had this part enabled in my php.ini
extension=php_memcache.dll
[Memcache]
memcache.allow_failover = 1
memcache.max_failover_attempts=20
memcache.chunk_size =8192
memcache.default_port = 11211
After commenting these lines composer was installed in my windows 10
I have been faced with this problem.
The cause is your table doesn't have a primary key field.
And I have a simple solution: Set a field to primary key to specific field that suits your business logic.
For example, I have database thesis_db
and field thesis_id
, I will press button Primary (key icon) to set thesis_id
to become primary key field:
To test multiple variables with one single value: if 1 in {a,b,c}:
To test multiple values with one variable: if a in {1, 2, 3}:
Are you using a UNIX based OS such as Linux? If so, add a shebang line to the very top of your script:
#!/usr/bin/python
Underneath which you would have the rest of the code (xx.py
in your case) that you already have. Then run that same command at the terminal:
$ python xx.py
This should then work fine, as it is now interpreting this as Python code. However when running from the terminal this does not matter as python
tells how to interpret it here. What it does allow you to do is execute it outside the terminal, i.e. executing it from a file browser.
If you really want to count all rows. You can use this in model function:
$this->db->select('count(*)');
$query = $this->db->get('home');
$cnt = $query->row_array();
return $cnt['count(*)'];
It returns single value, that is row count
I was unable to find the root cause of the issue but got a workaround. I started by setting my the java home variable as such.
vi ~/.bash_profile
(this is for macs only. bash profiles are different on linux)i
for insert and then set the JAVA_HOME variable as such export JAVA_HOME=/Applications/Android\Studio.app/Contents/jre/jdk/Contents/Home/
esc
then type :wq
We were able to solve a similar issue here using Oracle LISTAGG. There was a point where what we were grouping on exceeded the 4K limit but this was easily solved by having the first dataset take the first 15 items to aggregate, each of which have a 256K limit.
More info: We have projects, which have change orders, which in turn have explanations. Why the database is set up to take change text in chunks of 256K limits is not known but its one of the design constraints. So the application that feeds change explanations into the table stops at 254K and inserts, then gets the next set of text and if > 254K generates another row, etc. So we have a project to a change order, a 1:1. Then we have these as 1:n for explanations. LISTAGG concatenates all these. We have RMRKS_SN values, 1 for each remark and/or for each 254K of characters.
The largest RMRKS_SN was found to be 31, so I did the first dataset pulling SN 0 to 15, the 2nd dataset 16 to 30 and the last dataset 31 to 45 -- hey, let's plan on someone adding a LOT of explanation to some change orders!
In the SQL report, the Tablix ties to the first dataset. To get the other data, here's the expression:
=First(Fields!NON_STD_TXT.Value, "DataSet_EXPLAN") & First(Fields!NON_STD_TXT.Value, "ds_EXPLAN_SN_16_TO_30") & First(Fields!NON_STD_TXT.Value, "ds_EXPLAN_SN_31_TO_45")
For us, we have to have DB Group create functions, etc. because of security constraints. So with a bit of creativity, we didn't have to do a User Aggregate or a UDF.
If your application has some sort of SN to aggregate by, this method should work. I don't know what the equivalent TSQL is -- we're fortunate to be dealing with Oracle for this report, for which LISTAGG is a Godsend.
The code is:
SELECT
LT.C_O_NBR AS LT_CO_NUM,
RT.C_O_NBR AS RT_CO_NUM,
LT.STD_LN_ITM_NBR,
RT.NON_STD_LN_ITM_NBR,
RT.NON_STD_PRJ_NBR,
LT.STD_PRJ_NBR,
NVL(LT.PRPSL_LN_NBR, RT.PRPSL_LN_NBR) AS PRPSL_LN_NBR,
LT.STD_CO_EXPL_TXT AS STD_TXT,
LT.STD_CO_EXPLN_T,
LT.STD_CO_EXPL_SN,
RT.NON_STD_CO_EXPLN_T,
LISTAGG(RT.RMRKS_TXT_FLD, '')
WITHIN GROUP(ORDER BY RT.RMRKS_SN) AS NON_STD_TXT
FROM ...
WHERE RT.RMRKS_SN BETWEEN 0 AND 15
GROUP BY
LT.C_O_NBR,
RT.C_O_NBR,
...
And in the other 2 datasets just select the LISTAGG only for the subqueries in the FROM:
SELECT
LISTAGG(RT.RMRKS_TXT_FLD, '')
WITHIN GROUP(ORDER BY RT.RMRKS_SN) AS NON_STD_TXT
FROM ...
WHERE RT.RMRKS_SN BETWEEN 31 AND 45
...
... and so on.
Try this:
<?php
/*
Template Name: [contact us]
*/
get_header();
echo do_shortcode('[CONTACT-US-FORM]');
?>
Below is the code I used to replace some text, with colored text. It's simple, took the text and replace it within an HTML
tag. It works for each words in that class tags.
$('.hightlight').each(function(){
//highlight_words('going', this);
var high = 'going';
high = high.replace(/\W/g, '');
var str = high.split(" ");
var text = $(this).text();
text = text.replace(str, "<span style='color: blue'>"+str+"</span>");
$(this).html(text);
});
$(".location table tbody tr td:first-child").addClass("black");
$(".location table tbody tr td:nth-child(2)").addClass("black");
From client side, I cant solve this problem. From nodejs express side, you can use cors module to handle it.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var cors = require('cors');
var port = 3000;
var ip = '127.0.0.1';
app.use('*/myapi',
cors(), // with this row OPTIONS has handled
bodyParser.text({type:'text/*'}),
function( req, res, next ){
console.log( '\n.----------------' + req.method + '------------------------' );
console.log( '| prot:'+req.protocol );
console.log( '| host:'+req.get('host') );
console.log( '| url:'+req.originalUrl );
console.log( '| body:',req.body );
//console.log( '| req:',req );
console.log( '.----------------' + req.method + '------------------------' );
next();
});
app.listen(port, ip, function() {
console.log('Listening to port: ' + port );
});
console.log(('dir:'+__dirname ));
console.log('The server is up and running at http://'+ip+':'+port+'/');
Without cors() this OPTIONS has appears before POST.
.----------------OPTIONS------------------------
| prot:http
| host:localhost:3000
| url:/myapi
| body: {}
.----------------OPTIONS------------------------
.----------------POST------------------------
| prot:http
| host:localhost:3000
| url:/myapi
| body: <SOAP-ENV:Envelope .. P-ENV:Envelope>
.----------------POST------------------------
The ajax call:
$.ajax({
type: 'POST',
contentType: "text/xml; charset=utf-8",
// these does not works
//beforeSend: function(request) {
// request.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
// request.setRequestHeader('Accept', 'application/vnd.realtime247.sct-giro-v1+cms');
// request.setRequestHeader('Access-Control-Allow-Origin', '*');
// request.setRequestHeader('Access-Control-Allow-Methods', 'POST, GET');
// request.setRequestHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type');
//},
//headers: {
// 'Content-Type': 'text/xml; charset=utf-8',
// 'Accept': 'application/vnd.realtime247.sct-giro-v1+cms',
// 'Access-Control-Allow-Origin': '*',
// 'Access-Control-Allow-Methods': 'POST, GET',
// 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type'
//},
url: 'http://localhost:3000/myapi',
data: '<SOAP-ENV:Envelope .. P-ENV:Envelope>',
success: function( data ) {
console.log(data.documentElement.innerHTML);
},
error: function(jqXHR, textStatus, err) {
console.log( jqXHR,'\n', textStatus,'\n', err )
}
});
There is a nice way of doing conditional INSERT in PostgreSQL using WITH query: Like:
WITH a as(
select
id
from
schema.table_name
where
column_name = your_identical_column_value
)
INSERT into
schema.table_name
(col_name1, col_name2)
SELECT
(col_name1, col_name2)
WHERE NOT EXISTS (
SELECT
id
FROM
a
)
RETURNING id
if anyone needs this for NGINX
configuration file here is the snippet:
location ~* \.(js|css|xml|gz)$ {
add_header Vary "Accept-Encoding";
(... other headers or rules ...)
}
To parse a DateTime, use one of the following methods:
Alternatively, you may use try-parse pattern:
Read more about Custom Date and Time Format Strings.
To return a DateTime as a string in "yyyyMMdd" format, you may use ToString
method.
string date = DateTime.ToString("yyyyMMdd");
In your case, assuming you don't want to handle scenario when date is different format or misssing, it would be most convenient to use ParseExact
:
string dateToParse = "20170506";
DateTime parsedDate = DateTime.ParseExact(dateToParse,
"yyyyMMdd",
CultureInfo.InvariantCulture);
Try to avoid globals, instead you can use something like this
class myClass() {
private $myNumber;
public function setNumber($number) {
$this->myNumber = $number;
}
}
Now you can call
$class = new myClass();
$class->setNumber('1234');
private void PDFExport(LocalReport report)
{
string[] streamids;
string minetype;
string encod;
string fextension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>EMF</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.25in</MarginTop>" +
" <MarginLeft>0.25in</MarginLeft>" +
" <MarginRight>0.25in</MarginRight>" +
" <MarginBottom>0.25in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
byte[] rpbybe = report.Render("PDF", deviceInfo, out minetype, out encod, out fextension, out streamids,
out warnings);
using(FileStream fs=new FileStream("E:\\newwwfg.pdf",FileMode.Create))
{
fs.Write(rpbybe , 0, rpbybe .Length);
}
}
First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:
global $db;
And I guess, when you wrote:
if($result->num_rows){
return (mysqli_result($query, 0) == 1) ? true : false;
what you really wanted was:
if ($result->num_rows==1) { return true; } else { return false; }
I have a slightly different solution based on the answer by user167517. In my function I'm using a variable for the id of the select box I'm targeting.
var vOptionSelect = "#productcodeSelect1";
The index is returned with:
$(vOptionSelect).find(":selected").index();
One example of usage for null
values is when using a HashMap
as a cache for results of an expensive operation (such as a call to an external web service) which may return null
.
Putting a null
value in the map then allows you to distinguish between the case where the operation has not been performed for a given key (cache.containsKey(someKey)
returns false
), and where the operation has been performed but returned a null
value (cache.containsKey(someKey)
returns true
, cache.get(someKey)
returns null
).
Without null
values, you would have to either put some special value in the cache to indicate a null
response, or simply not cache that response at all and perform the operation every time.
The following works as of now (tested in Chrome and Firefox):
<form onsubmit="event.preventDefault(); validateMyForm();">
Where validateMyForm() is a function that returns false
if validation fails. The key point is to use the name event
. We cannot use for e.g. e.preventDefault()
.
As I know you can't make array without size, but you can use
List<string> l = new List<string>()
and then l.ToArray()
.
First list all iptables rules with this command:
iptables -S
it lists like:
-A XYZ -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
Then copy the desired line, and just replace -A
with -D
to delete that:
iptables -D XYZ -p ...
Run Internet Explorer as Administrator. If you open IE in normal mode then favicon will not display on IE 11 (Win 7). I am not sure about the behavior on other version of browsers.
Quick fix. Create whole structure tr > td > button; then find button inside; attach event on it; end filtering of chain and at the and insert it into dom.
$("#myButton").click(function () {
var test = $('<tr><td><button>Test</button></td></tr>').find('button').click(function () {
alert('hi');
}).end();
$("#nodeAttributeHeader").attr('style', 'display: table-row;');
$("#addNodeTable tr:last").before(test);
});
If you use that forumla in the name manager you are creating a dynamic range which uses "this sheet" in place of a specific sheet.
As Jerry says, Sheet1!A1 refers to cell A1 on Sheet1. If you create a named range and omit the Sheet1 part you will reference cell A1 on the currently active sheet. (omitting the sheet reference and using it in a cell formula will error).
edit: my bad, I was using $A$1 which will lock it to the A1 cell as above, thanks pnuts :p
iOS 5 now supports HTML5 better. in your webapp do
<input type="date" name="date" />
Android as of 4.0 lacks this type of native menu support.
enum ServicePlatform {
UPLAY = "uplay",
PSN = "psn",
XBL = "xbl"
}
becomes:
{ UPLAY: 'uplay', PSN: 'psn', XBL: 'xbl' }
so
ServicePlatform.UPLAY in ServicePlatform // false
SOLUTION:
ServicePlatform.UPLAY.toUpperCase() in ServicePlatform // true
XmlTextWriter xmlw = new XmlTextWriter(@"C:\WINDOWS\Temp\exm.xml",System.Text.Encoding.UTF8);
xmlw.WriteStartDocument();
xmlw.WriteStartElement("examtimes");
xmlw.WriteStartElement("Starttime");
xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
xmlw.WriteEndElement();
xmlw.WriteStartElement("Changetime");
xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
xmlw.WriteEndElement();
xmlw.WriteStartElement("Endtime");
xmlw.WriteString(DateTime.Now.AddHours(1).ToString());
xmlw.WriteEndElement();
xmlw.WriteEndElement();
xmlw.WriteEndDocument();
xmlw.Close();
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\WINDOWS\Temp\exm.xml");
XmlNode root = doc.DocumentElement["Starttime"];
root.FirstChild.InnerText = "First";
XmlNode root1 = doc.DocumentElement["Changetime"];
root1.FirstChild.InnerText = "Second";
doc.Save(@"C:\WINDOWS\Temp\exm.xml");
Try this. It's C# code.
Tested and Verified Code
<script>
jQuery(document).ready(function(){
// Add smooth scrolling to all links
jQuery("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
jQuery('html, body').animate({
scrollTop: jQuery(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
</script>
Simply install Win64 OpenSSL v1.0.2a or Win32 OpenSSL v1.0.2a, you can download these from http://slproweb.com/products/Win32OpenSSL.html. Works out of the box, no configuration needed.
Long
is the Object
form of long
, and Integer
is the object form of int
.
The long
uses 64 bits. The int
uses 32 bits, and so can only hold numbers up to ±2 billion (-231 to +231-1).
You should use long
and int
, except where you need to make use of methods inherited from Object
, such as hashcode
. Java.util.collections
methods usually use the boxed (Object
-wrapped) versions, because they need to work for any Object
, and a primitive type, like int
or long
, is not an Object
.
Another difference is that long
and int
are pass-by-value, whereas Long
and Integer
are pass-by-reference value, like all non-primitive Java types. So if it were possible to modify a Long
or Integer
(it's not, they're immutable without using JNI code), there would be another reason to use one over the other.
A final difference is that a Long
or Integer
could be null
.
from tkinter import *
import time
tk=Tk()
def clock():
t=time.strftime('%I:%M:%S',time.localtime())
if t!='':
label1.config(text=t,font='times 25')
tk.after(100,clock)
label1=Label(tk,justify='center')
label1.pack()
clock()
tk.mainloop()
PowerShell 3 has the $PSScriptRoot
automatic variable:
Contains the directory from which a script is being run.
In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.
Don't be fooled by the poor wording. PSScriptRoot
is the directory of the current file.
In PowerShell 2, you can calculate the value of $PSScriptRoot
yourself:
# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
I would suggest not to use seaborn pointplot
for plotting. This makes things unnecessarily complicated.
Instead use matplotlib plot_date
. This allows to set labels to the plots and have them automatically put into a legend with ax.legend()
.
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
date = pd.date_range("2017-03", freq="M", periods=15)
count = np.random.rand(15,4)
df1 = pd.DataFrame({"date":date, "count" : count[:,0]})
df2 = pd.DataFrame({"date":date, "count" : count[:,1]+0.7})
df3 = pd.DataFrame({"date":date, "count" : count[:,2]+2})
f, ax = plt.subplots(1, 1)
x_col='date'
y_col = 'count'
ax.plot_date(df1.date, df1["count"], color="blue", label="A", linestyle="-")
ax.plot_date(df2.date, df2["count"], color="red", label="B", linestyle="-")
ax.plot_date(df3.date, df3["count"], color="green", label="C", linestyle="-")
ax.legend()
plt.gcf().autofmt_xdate()
plt.show()
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df1,color='blue')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df2,color='green')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df3,color='red')
ax.legend(handles=ax.lines[::len(df1)+1], labels=["A","B","C"])
ax.set_xticklabels([t.get_text().split("T")[0] for t in ax.get_xticklabels()])
plt.gcf().autofmt_xdate()
plt.show()
If I understand right, you've made a commit to changed_branch
and you want to copy that commit to other_branch
? Easy:
git checkout other_branch
git cherry-pick changed_branch
You can also use the following alternative realpath.
Create a file called path.php
Put the following code inside by specifying the name of the created file.
<?php
echo realpath('path.php');
?>
A php file that you can move to all your folders to always have the absolute path from where the executed file is located.
;-)
LSP concerns invariants.
The classic example is given by the following pseudo-code declaration (implementations omitted):
class Rectangle {
int getHeight()
void setHeight(int value) {
postcondition: width didn’t change
}
int getWidth()
void setWidth(int value) {
postcondition: height didn’t change
}
}
class Square extends Rectangle { }
Now we have a problem although the interface matches. The reason is that we have violated invariants stemming from the mathematical definition of squares and rectangles. The way getters and setters work, a Rectangle
should satisfy the following invariant:
void invariant(Rectangle r) {
r.setHeight(200)
r.setWidth(100)
assert(r.getHeight() == 200 and r.getWidth() == 100)
}
However, this invariant (as well as the explicit postconditions) must be violated by a correct implementation of Square
, therefore it is not a valid substitute of Rectangle
.
As some of my servers are on an old Ubuntu LTS versions, I can't easily upgrade git to the latest version (which supports the -C option as described in some answers).
This trick works well for me, especially because it does not have the side effect of some other answers that leave you in a different directory from where you started.
pushd /X/Y
git pull
popd
Or, doing it as a one-liner:
pushd /X/Y; git pull; popd
Both Linux and Windows have pushd and popd commands.
I found a bug in MySQL 5.1.72 when using the nested if() functions .... the value of column variables (e.g. qty_1) is blank inside the second if(), rendering it useless. Use the following construct instead:
case
when qty_1<='23' then price
when '23'>qty_1 && qty_2<='23' then price_2
when '23'>qty_2 && qty_3<='23' then price_3
when '23'>qty_3 then price_4
else 1
end
<?xml version="1.0" encoding="utf-8"?>
<gradient
android:angle="90"
android:startColor="@color/colorPrimary"
android:endColor="@color/colorPrimary"
android:centerColor="@color/white"
android:type="linear"/>
<corners android:bottomRightRadius="10dp"
android:bottomLeftRadius="10dp"
android:topRightRadius="10dp"
android:topLeftRadius="10dp"/>
The first answer is too complex, historic, and uninformative for my tastes.
It's actually rather simple. Docker provides for a functionality called multi-stage builds the basic idea here is to,
Let's start with the first. Very often with something like Debian you'll see.
RUN apt-get update \
&& apt-get dist-upgrade \
&& apt-get install <whatever> \
&& apt-get clean
We can explain all of this in terms of the above. The above command is chained together so it represents a single change with no intermediate Images required. If it was written like this,
RUN apt-get update ;
RUN apt-get dist-upgrade;
RUN apt-get install <whatever>;
RUN apt-get clean;
It would result in 3 more temporary intermediate Images. Having it reduced to one image, there is one remaining problem: apt-get clean
doesn't clean up artifacts used in the install. If a Debian maintainer includes in his install a script that modifies the system that modification will also be present in the final solution (see something like pepperflashplugin-nonfree
for an example of that).
By using a multi-stage build you get all the benefits of a single changed action, but it will require you to manually whitelist and copy over files that were introduced in the temporary image using the COPY --from
syntax documented here. Moreover, it's a great solution where there is no alternative (like an apt-get clean
), and you would otherwise have lots of un-needed files in your final image.
See also
If you have tomcat on the classpath, it's as simple as:
TomcatURLStreamHandlerFactory.register();
This will register handlers for "war" and "classpath" protocols.
Just a guess what does the variable json
contain after
var json = Sys.Serialization.JavaScriptSerializer.serialize(obj);?
If it is a valid json object like {'foo':'foovalue', 'bar':'barvalue'}
then jQuery might not send it as json data but instead serialize it to foor=foovalue&bar=barvalue
thus you get the error "Invalid JSON primitive: foo"
Try instead setting the data as string
$.ajax({
...
data: "{'foo':'foovalue', 'bar':'barvalue'}", //note the additional quotation marks
...
})
This way jQuery should leave the data alone and send the string as is to the server which should allow ASP.NET to parse the json server side.
I use Scitech's MemProfiler when I suspect a memory leak.
So far, I have found it to be very reliable and powerful. It has saved my bacon on at least one occasion.
The GC works very well in .NET IMO, but just like any other language or platform, if you write bad code, bad things happen.
Your problem stems from reading from and writing to the same file. Rather than opening fileToSearch
for writing, open an actual temporary file and then after you're done and have closed tempFile
, use os.rename
to move the new file over fileToSearch
.
WHERE AND SELECT Condition In Array Format Laravel
use DB;
$conditions = array(
array('email', '=', '[email protected]')
);
$selected = array('id','name','email','mobile','created');
$result = DB::table('users')->select($selected)->where($conditions)->get();
public static bool RegistryValueExists(string hive_HKLM_or_HKCU, string registryRoot, string valueName)
{
RegistryKey root;
switch (hive_HKLM_or_HKCU.ToUpper())
{
case "HKLM":
root = Registry.LocalMachine.OpenSubKey(registryRoot, false);
break;
case "HKCU":
root = Registry.CurrentUser.OpenSubKey(registryRoot, false);
break;
default:
throw new System.InvalidOperationException("parameter registryRoot must be either \"HKLM\" or \"HKCU\"");
}
return root.GetValue(valueName) != null;
}
This little and simple trick I just learnt may help someone trying to avoid :before or :after pseudo elements altogether (for whatever reason) in changing text on hover. You can add both texts in the HTML, but vary the CSS 'display' property based on hover. Assuming the second text 'Add' has a class named 'add-label'; here is a little modification:
span.add-label{
display:none;
}
.item:hover span.align{
display:none;
}
.item:hover span.add-label{
display:block;
}
Here is a demonstration on codepen: https://codepen.io/ifekt/pen/zBaEVJ
cat *.png | ffmpeg -f image2pipe -i - output.mp4
from wiki
A simple approach with no third party libraries using Java 7
String path = "your complete file path";
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(Files.readAllBytes(Paths.get(path)));
byte[] digest = md.digest();
If you need to print this byte array. Use as below
System.out.println(Arrays.toString(digest));
If you need hex string out of this digest. Use as below
String digestInHex = DatatypeConverter.printHexBinary(digest).toUpperCase();
System.out.println(digestInHex);
where DatatypeConverter is javax.xml.bind.DatatypeConverter
I was looking for something like a LinkedHashMap in Java. Neither Swift nor Objective-C have one if I'm not mistaken.
My initial thought was to wrap my dictionary in an Array. [[String: UIImage]]
but then I realized that grabbing the key from the dictionary was wacky with Array(dict)[index].key
so I went with Tuples. Now my array looks like [(String, UIImage)]
so I can retrieve it by tuple.0
. No more converting it to an Array. Just my 2 cents.
I modified rushidesai1's answer to include a working example.
import java.io.*;
import java.util.*;
public class JsonMarshaller<T> {
private static ClassLoader loader = JsonMarshaller.class.getClassLoader();
public static void main(String[] args) {
try {
JsonMarshallerUnmarshaller<Station> marshaller = new JsonMarshallerUnmarshaller<>(Station.class);
String jsonString = read(loader.getResourceAsStream("data.json"));
List<Station> stations = marshaller.unmarshal(jsonString);
stations.forEach(System.out::println);
System.out.println(marshaller.marshal(stations));
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("resource")
public static String read(InputStream ios) {
return new Scanner(ios).useDelimiter("\\A").next(); // Read the entire file
}
}
Station [id=123, title=my title, name=my name]
Station [id=456, title=my title 2, name=my name 2]
[{"id":123,"title":"my title","name":"my name"},{"id":456,"title":"my title 2","name":"my name 2"}]
import java.io.*;
import java.util.List;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
public class JsonMarshallerUnmarshaller<T> {
private ObjectMapper mapper;
private Class<T> targetClass;
public JsonMarshallerUnmarshaller(Class<T> targetClass) {
AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
mapper = new ObjectMapper();
mapper.getDeserializationConfig().with(introspector);
mapper.getSerializationConfig().with(introspector);
this.targetClass = targetClass;
}
public List<T> unmarshal(String jsonString) throws JsonParseException, JsonMappingException, IOException {
return parseList(jsonString, mapper, targetClass);
}
public String marshal(List<T> list) throws JsonProcessingException {
return mapper.writeValueAsString(list);
}
public static <E> List<E> parseList(String str, ObjectMapper mapper, Class<E> clazz)
throws JsonParseException, JsonMappingException, IOException {
return mapper.readValue(str, listType(mapper, clazz));
}
public static <E> List<E> parseList(InputStream is, ObjectMapper mapper, Class<E> clazz)
throws JsonParseException, JsonMappingException, IOException {
return mapper.readValue(is, listType(mapper, clazz));
}
public static <E> JavaType listType(ObjectMapper mapper, Class<E> clazz) {
return mapper.getTypeFactory().constructCollectionType(List.class, clazz);
}
}
public class Station {
private long id;
private String title;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return String.format("Station [id=%s, title=%s, name=%s]", id, title, name);
}
}
[{
"id": 123,
"title": "my title",
"name": "my name"
}, {
"id": 456,
"title": "my title 2",
"name": "my name 2"
}]
I hope my script help you.
<i class="mostrar-producto">mostrar...</i>
<div class="producto" style="display:none;position: absolute;">Producto</div>
My script
<script>
$(".mostrar-producto").mouseover(function(){
$(".producto").fadeIn();
});
$(".mostrar-producto").mouseleave(function(){
$(".producto").fadeOut();
});
</script>
ENGINE=MEMORY
is not supported when table contains BLOB
/TEXT
columns
Check the jQuery FAQ...
You can use the length property of the jQuery collection returned by your selector:
if ( $('#myDiv').length ){}
If you would like to check in PHP , then you should do something like :
$query_s =mysql_query("SELECT YOURROWNAME from `YOURTABLENAME` where name = $name");
$ertom=mysql_fetch_array($query_s);
if ('' !== $ertom['YOURROWNAME']) {
//do your action
echo "It was filled";
} else {
echo "it was empty!";
}
Execute the following on your terminal to get the latest stable version:
sudo gem install cocoapods
Add --pre
to get the latest pre release:
sudo gem install cocoapods --pre
If you originally installed the cocoapods gem using sudo
, you should use that command again.
Later on, when you're actively using CocoaPods by installing pods, you will be notified when new versions become available with a CocoaPods X.X.X is now available, please update message.
In python 3.x, use input()
instead of raw_input()
I agree with the points dnmckee mentions, plus:
As King King said, you must add the browser specific prefix. This should cover most browsers:
@keyframes flickerAnimation {_x000D_
0% { opacity:1; }_x000D_
50% { opacity:0; }_x000D_
100% { opacity:1; }_x000D_
}_x000D_
@-o-keyframes flickerAnimation{_x000D_
0% { opacity:1; }_x000D_
50% { opacity:0; }_x000D_
100% { opacity:1; }_x000D_
}_x000D_
@-moz-keyframes flickerAnimation{_x000D_
0% { opacity:1; }_x000D_
50% { opacity:0; }_x000D_
100% { opacity:1; }_x000D_
}_x000D_
@-webkit-keyframes flickerAnimation{_x000D_
0% { opacity:1; }_x000D_
50% { opacity:0; }_x000D_
100% { opacity:1; }_x000D_
}_x000D_
.animate-flicker {_x000D_
-webkit-animation: flickerAnimation 1s infinite;_x000D_
-moz-animation: flickerAnimation 1s infinite;_x000D_
-o-animation: flickerAnimation 1s infinite;_x000D_
animation: flickerAnimation 1s infinite;_x000D_
}
_x000D_
<div class="animate-flicker">Loading...</div>
_x000D_
Below is the code that read the data from the text file and sends it to the handler for processing and receive the response data from the handler and read it and store the data in the string builder class
//Get the data from text file that needs to be sent.
FileStream fileStream = new FileStream(@"G:\Papertest.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
byte[] buffer = new byte[fileStream.Length];
int count = fileStream.Read(buffer, 0, buffer.Length);
//This is a handler would recieve the data and process it and sends back response.
WebRequest myWebRequest = WebRequest.Create(@"http://localhost/Provider/ProcessorHandler.ashx");
myWebRequest.ContentLength = buffer.Length;
myWebRequest.ContentType = "application/octet-stream";
myWebRequest.Method = "POST";
// get the stream object that holds request stream.
Stream stream = myWebRequest.GetRequestStream();
stream.Write(buffer, 0, buffer.Length);
stream.Close();
//Sends a web request and wait for response.
try
{
WebResponse webResponse = myWebRequest.GetResponse();
//get Stream Data from the response
Stream respData = webResponse.GetResponseStream();
//read the response from stream.
StreamReader streamReader = new StreamReader(respData);
string name;
StringBuilder str = new StringBuilder();
while ((name = streamReader.ReadLine()) != null)
{
str.Append(name); // Add to stringbuider when response contains multple lines data
}
}
catch (Exception ex)
{
throw ex;
}
If you need to manipulate it on the client side, you can't use the Visible property on the server side. Instead, set its CSS display style to "none". For example:
<asp:Label runat="server" id="Label1" style="display: none;" />
Then, you could make it visible on the client side with:
document.getElementById('Label1').style.display = 'inherit';
You could make it hidden again with:
document.getElementById('Label1').style.display = 'none';
Keep in mind that there may be issues with the ClientID being more complex than "Label1" in practice. You'll need to use the ClientID with getElementById, not the server side ID, if they differ.
Although this is almost certainly not the OPs issue, you can also get Unable to establish SSL connection
from wget
if you're behind a proxy and don't have HTTP_PROXY
and HTTPS_PROXY
environment variables set correctly. Make sure to set HTTP_PROXY
and HTTPS_PROXY
to point to your proxy.
This is a common situation if you work for a large corporation.
You can take a look here for a longer list of screen sizes and respective media queries.
Or go for Bootstrap media queries:
/* Large desktop */
@media (min-width: 1200px) { ... }
/* Portrait tablet to landscape and desktop */
@media (min-width: 768px) and (max-width: 979px) { ... }
/* Landscape phone to portrait tablet */
@media (max-width: 767px) { ... }
/* Landscape phones and down */
@media (max-width: 480px) { ... }
Additionally you might wanty to take a look at Foundation's media queries with the following default settings:
// Media Queries
$screenSmall: 768px !default;
$screenMedium: 1279px !default;
$screenXlarge: 1441px !default;
I was looking for something and I found this post. I post this code that managed many-to-many relationships in case someone needs it.
var UserInRole = db.UsersInRoles.Include(u => u.UserProfile).Include(u => u.Roles)
.Select (m => new
{
UserName = u.UserProfile.UserName,
RoleName = u.Roles.RoleName
});
Other answers have suggested using TryParse
, which might fit your needs, but the safest way to provide the functionality of the IsNumeric
function is to reference the VB library and use the IsNumeric
function.
IsNumeric
is more flexible than TryParse
. For example, IsNumeric
returns true
for the string "$100"
, while the TryParse
methods all return false
.
To use IsNumeric
in C#, add a reference to Microsoft.VisualBasic.dll. The function is a static method of the Microsoft.VisualBasic.Information
class, so assuming you have using Microsoft.VisualBasic;
, you can do this:
if (Information.IsNumeric(txtMyText.Text.Trim())) //...
Or use the XmlSerializer class.
XmlSerializer xs = new XmlSerializer(objectType);
obj = xs.Deserialize(new StringReader(yourXmlString));
Updating Nuget packages fixed proglem for me.
function routeToRoom(userId, passw, cb) {
var roomId = 0;
var nStore = require('nstore/lib/nstore').extend(require('nstore/lib/nstore/query')());
var users = nStore.new('data/users.db', function() {
users.find({
user: userId,
pass: passw
}, function(err, results) {
if (err) {
roomId = -1;
} else {
roomId = results.creationix.room;
}
cb(roomId);
});
});
}
routeToRoom("alex", "123", function(id) {
console.log(id);
});
You need to use callbacks. That's how asynchronous IO works. Btw sys.puts
is deprecated
HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Compatibility Assistant\Persisted
The issue may happen while fetching dependencies from a remote repository. In my case, the repository did not need any authentication and it has been resolved by removing the servers section in the settings.xml file:
<servers>
<server>
<id>SomeRepo</id>
<username>SomeUN</username>
<password>SomePW</password>
</server>
</servers>
ps: I guess your target is mvn clean install instead of maven install clean
You can use the to_pydatetime method to be more explicit:
In [11]: ts = pd.Timestamp('2014-01-23 00:00:00', tz=None)
In [12]: ts.to_pydatetime()
Out[12]: datetime.datetime(2014, 1, 23, 0, 0)
It's also available on a DatetimeIndex:
In [13]: rng = pd.date_range('1/10/2011', periods=3, freq='D')
In [14]: rng.to_pydatetime()
Out[14]:
array([datetime.datetime(2011, 1, 10, 0, 0),
datetime.datetime(2011, 1, 11, 0, 0),
datetime.datetime(2011, 1, 12, 0, 0)], dtype=object)
This worked for me
<Text>{`Hi~\nthis is a test message.`}</Text>
(react-native 0.41.0)
Use Content Resolver ("content://sms/inbox") to read SMS which are in inbox.
// public static final String INBOX = "content://sms/inbox";
// public static final String SENT = "content://sms/sent";
// public static final String DRAFT = "content://sms/draft";
Cursor cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
if (cursor.moveToFirst()) { // must check the result to prevent exception
do {
String msgData = "";
for(int idx=0;idx<cursor.getColumnCount();idx++)
{
msgData += " " + cursor.getColumnName(idx) + ":" + cursor.getString(idx);
}
// use msgData
} while (cursor.moveToNext());
} else {
// empty box, no SMS
}
Please add READ_SMS permission.
I Hope it helps :)
You can use the cherry-pick to get the particular bug fix commit(s)
$ git checkout branch
$ git cherry-pick bugfix
If you're running with jQuery you can use the datepicker UI library's parseDate function to convert your string to a date:
var d = $.datepicker.parseDate("DD, MM dd, yy", "Sunday, February 28, 2010");
and then follow it up with the formatDate method to get it to the string format you want
var datestrInNewFormat = $.datepicker.formatDate( "mm/dd/yy", d);
If you're not running with jQuery of course its probably not the best plan given you'd need jQuery core as well as the datepicker UI module... best to go with the suggestion from Segfault above to use date.js.
HTH
Alternative solution is to use a hosting.json
in the root of the project.
{
"urls": "http://localhost:60000"
}
And then in Program.cs
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("hosting.json", true)
.Build();
var host = new WebHostBuilder()
.UseKestrel(options => options.AddServerHeader = false)
.UseConfiguration(config)
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
Here is an elegant way to do similar thing. But why do partly JSON unmarshal? That doesn't make sense.
Look below at the working code. Copy and paste it.
import (
"bytes"
"encoding/json" // Encoding and Decoding Package
"fmt"
)
var messeging = `{
"say":"Hello",
"sendMsg":{
"user":"ANisus",
"msg":"Trying to send a message"
}
}`
type SendMsg struct {
User string `json:"user"`
Msg string `json:"msg"`
}
type Chat struct {
Say string `json:"say"`
SendMsg *SendMsg `json:"sendMsg"`
}
func main() {
/** Clean way to solve Json Decoding in Go */
/** Excellent solution */
var chat Chat
r := bytes.NewReader([]byte(messeging))
chatErr := json.NewDecoder(r).Decode(&chat)
errHandler(chatErr)
fmt.Println(chat.Say)
fmt.Println(chat.SendMsg.User)
fmt.Println(chat.SendMsg.Msg)
}
func errHandler(err error) {
if err != nil {
fmt.Println(err)
return
}
}
I recommend you to checkout @angular-material-components/datetime-picker. This is a DatetimePicker like @angular/material Datepicker by adding support for choosing time.
You have #include "fun.cpp"
in mainfile.cpp
so compiling with:
g++ -o hw1 mainfile.cpp
will work, however if you compile by linking these together like
g++ -g -std=c++11 -Wall -pedantic -c -o fun.o fun.cpp
g++ -g -std=c++11 -Wall -pedantic -c -o mainfile.o mainfile.cpp
As they mention above, adding #include "fun.hpp"
will need to be done or it won't work. However, your case with the funct()
function is slightly different than my problem.
I had this issue when doing a HW assignment and the autograder compiled by the lower bash recipe, yet locally it worked using the upper bash.
Add a Dependency in
pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.4.3</version>
</dependency>
The solution you posted seems to work in stopping the zoom controls from appearing when the user drags, however there are situations where a user will pinch zoom and the zoom controls will appear. I've noticed that there are 2 ways that the webview will accept pinch zooming, and only one of them causes the zoom controls to appear despite your code:
User Pinch Zooms and controls appear:
ACTION_DOWN
getSettings().setBuiltInZoomControls(false); getSettings().setSupportZoom(false);
ACTION_POINTER_2_DOWN
getSettings().setBuiltInZoomControls(true); getSettings().setSupportZoom(true);
ACTION_MOVE (Repeat several times, as the user moves their fingers)
ACTION_POINTER_2_UP
ACTION_UP
User Pinch Zoom and Controls don't appear:
ACTION_DOWN
getSettings().setBuiltInZoomControls(false); getSettings().setSupportZoom(false);
ACTION_POINTER_2_DOWN
getSettings().setBuiltInZoomControls(true); getSettings().setSupportZoom(true);
ACTION_MOVE (Repeat several times, as the user moves their fingers)
ACTION_POINTER_1_UP
ACTION_POINTER_UP
ACTION_UP
Can you shed more light on your solution?
You could use the PECL extension
runkit_function_redefine
— Replace a function definition with a new implementation but that is bad practise in my opinion. You are using functions, but check out the Decorator design pattern. Can borrow the basic idea from it.
With JavaScript it is very difficult if not impossible(?). I would suggest using some sort of code-behind language such as PHP, C#, or Java. If you were to use PHP, you could, in the page your button posts to, do something like this:
<?php
header('Content-type: application/pdf');
header('Content-disposition: attachment; filename=filename.pdf');
readfile("http://manuals.info.apple.com/en/iphone_user_guide.pdf");
?>
This also seems to work for JS (from http://www.phpbuilder.com/board/showthread.php?t=10149735):
<body>
<script>
function downloadme(x){
myTempWindow = window.open(x,'','left=10000,screenX=10000');
myTempWindow.document.execCommand('SaveAs','null','download.pdf');
myTempWindow.close();
}
</script>
<a href=javascript:downloadme('http://manuals.info.apple.com/en/iphone_user_guide.pdf');>Download this pdf</a>
</body>
I prefer this syntaxis:
$query = "INSERT INTO myTable SET fname='Fname',lname='Lname',website='Website'";
Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000
or Access-Control-Allow-Origin: *
on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true
on the POST response as well.
Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept
to match the requested header.
pullFiles.sh
:#!/bin/bash
HOST_DIR=<pull-to>
DEVICE_DIR=/sdcard/<pull-from>
EXTENSION=".jpg"
for file in $(adb shell ls $DEVICE_DIR | grep $EXTENSION'$')
do
file=$(echo -e $file | tr -d "\r\n"); # EOL fix
adb pull $DEVICE_DIR/$file $HOST_DIR/$file;
done
Make it executable: chmod +x pullFiles.sh
Run it: ./pullFiles.sh
You could do a
mysqlimport --columns='head -n 1 $yourfile' --ignore-lines=1 dbname $yourfile`
That is, if your file is comma separated and is not semi-colon separated. Else you might need to sed
through it too.
The best way to check for a null values is
if ( testVar !== null )
{
// do action here
}
and for undefined
if ( testVar !== undefined )
{
// do action here
}
You can assign a avariable with undefined.
testVar = undefined;
//typeof(testVar) will be equal to undefined.
The @supports rule (92% browser support July 2017) rule can be used for conditional logic on css properties:
@supports (display: -webkit-box) {
.for_older_webkit_browser { display: -webkit-box }
}
@supports not (display: -webkit-box) {
.newer_browsers { display: flex }
}
This worked for me :
EDITOR="/usr/bin/vim"
export EDITOR
Add this to ~/.bash_profile or ~/.bashrc to enable this for current user.
let count=0;_x000D_
let text = document.getElementById('heading');_x000D_
let btn = document.getElementById('btn');_x000D_
btn.addEventListener('click', function(){_x000D_
if(count%2==0){_x000D_
text.style.opacity="0.1";_x000D_
unfade(text);_x000D_
text.innerText="Welcome to Javascript </>"; _x000D_
text.style.color="forestgreen";_x000D_
}//end of if_x000D_
else{ text.style.opacity="0.1";_x000D_
unfade(text);_x000D_
text.innerText="Hello javascript"; _x000D_
text.style.color="blueviolet";_x000D_
}//end of else_x000D_
count++;//for toggling the text_x000D_
});_x000D_
//function for fade effect--------_x000D_
function unfade(element) {_x000D_
var op = 0.1; // initial opacity_x000D_
element.style.display = 'block';_x000D_
var timer = setInterval(function () {_x000D_
if (op >= 1){_x000D_
clearInterval(timer);_x000D_
}_x000D_
element.style.opacity = op;_x000D_
element.style.filter = 'alpha(opacity=' + op * 100 + ")";_x000D_
op += op * 0.1;_x000D_
}, 30);_x000D_
}
_x000D_
<h1 style="color:blueviolet" id="heading">Hello javascript</h1>_x000D_
<button id="btn">Click me</button>
_x000D_
Help -> About Eclipse -> Installation Details -> tab Configuration
Look for -arch
, and below it you'll see either x86_64
(meaning 64bit) or x86
(meaning 32bit).
The werkzeug debugger already has an 'auto reload' function available that can be enabled by doing one of the following:
app.run(debug=True)
or
app.debug = True
You can also use a separate configuration file to manage all your setup if you need be. For example I use 'settings.py' with a 'DEBUG = True' option. Importing this file is easy too;
app.config.from_object('application.settings')
However this is not suitable for a production environment.
Personally I chose Nginx + uWSGI over Apache + mod_wsgi for a few performance reasons but also the configuration options. The touch-reload option allows you to specify a file/folder that will cause the uWSGI application to reload your newly deployed flask app.
For example, your update script pulls your newest changes down and touches 'reload_me.txt' file. Your uWSGI ini script (which is kept up by Supervisord - obviously) has this line in it somewhere:
touch-reload = '/opt/virtual_environments/application/reload_me.txt'
I hope this helps!
If you try joining C on a field from B before joining B, i.e.:
SELECT A.x,
A.y,
A.z
FROM A
INNER JOIN C
on B.x = C.x
INNER JOIN B
on A.x = B.x
your query will fail, so in this case the order matters.
For self-hiding you can use getCmdPID.bat and windowMode.bat:
@echo off
echo --- self hiding bat ----
pause
call getCmdPid.bat
set PID=%errorlevel%
call windowMode.bat -pid %PID% -mode hidden
Here's my collection of ways to achieve that - and even more - where it was possible I've tried to return also the PID of the started process (all linked scripts can be downloaded and saved with whatever name you find convenient):
Example usage:
call IEXPhidden.bat "cmd /c myBat.bat" "argument"
Example usage:
call SCHPhidden.bat "cmd /c myBat.bat" "argument"
Example usage (for more info print the help with '-h'):
call ShellRunJS.bat "notepad.exe" -style 0 -wait no
Example usage (for more info print the help with '-h'):
call win32process.bat "notepad" -arguments "/A openFile.txt" -showWindows 0 -title "notepad"
Example usage (for more info print the help with '-h'):
call ProcessStartJS.bat "notepad" -arguments "/A openFile.txt" -style Hidden -directory "." -title "notepad" -priority Normal
Local temporary tables: if you create local temporary tables and then open another connection and try the query , you will get the following error.
the temporary tables are only accessible within the session that created them.
Global temporary tables: Sometimes, you may want to create a temporary table that is accessible other connections. In this case, you can use global temporary tables.
Global temporary tables are only destroyed when all the sessions referring to it are closed.
Yes. It is true. .NET code is extremely easy to reverse engineer if the code is not obfuscated.
Obfuscation will add a layer of annoyance to people trying to reverse engineer your software. Depending on which version you get, you'll get different levels of protection.
Visual Studio includes a version of Dotfuscator. Since it's a bundled version, you're definitely not getting the strongest obfuscation possible. If you look at their feature lists, you'll see exactly what you're missing (and exactly what the application will do to make your code more secure).
There are a couple of other free or open source .NET obfuscators out there (but I can't comment on the quality or the various methods they use):
In the end, nothing is perfect. If somebody really wants to see how your software works, they will.
Thanks a bundle, guys. You are great.
I used Chuff's answer and modified it a little to do what I wanted.
I have 2 worksheets in the same workbook.
On 1st worksheet I have a list of SMS in 3 columns: phone number, date & time, message
Then I inserted a new blank column next to the phone number
On worksheet 2 I have two columns: phone number, name of person
Used the formula to check the cell on the left, and match against the range in worksheet 2, pick the name corresponding to the number and input it into the blank cell in worksheet 1.
Then just copy the formula down the whole column until last sms It worked beautifully.
=VLOOKUP(A3,Sheet2!$A$1:$B$31,2,0)
The way is correct, but can be improved a bit with the extended set-syntax.
set "var=xyz"
Sets the var to the content until the last quotation mark, this ensures that no "hidden" spaces are appended.
Your code would look like
set "var1=A"
set "var2=B"
set "AB=hi"
set "newvar=%var1%%var2%"
echo %newvar% is the concat of var1 and var2
echo !%newvar%! is the indirect content of newvar
Instead of parsing it manually it's better to use pathinfo function:
$path_parts = pathinfo($value);
$extension = strtolower($path_parts['extension']);
$fileName = $path_parts['filename'];
As far as I can tell,
hstore as it currently exists (in Postgresql 9.3) does not allow for nesting other objects and arrays as the values of its key/value pairs. however a future hstore patch will allow for nesting. this patch will not be in the 9.4 release and may not be included any time soon.
json as it currently exists does allow for nesting, but is text-based, and does not allow for indexing, thus it is "slow"
jsonb that will be released with 9.4 will have the current nesting capabilities of json, as well as the GIN/GIST indexing of hstore, so it will be fast
People working on postgresql 9.4 seem to be saying that the new, fast jsonb type will appeal to people who would have chosen to use a noSQL data store like MongoDB, but can now combine a relational database with query-able unstructured data under one roof
http://www.databasesoup.com/2014/02/why-hstore2jsonb-is-most-important.html
Benchmarks of postgresql 9.4 jsonb seem to be on par with or in some cases faster than MongoDB
http://texture.io/alphabetum/postgresql-incl-hstore-vs-mongodb
A char
is an integral type. When you write
char ch = 'A';
you're setting the value of ch
to whatever number your compiler uses to represent the character 'A'
. That's usually the ASCII code for 'A'
these days, but that's not required. You're almost certainly using a system that uses ASCII.
Like any numeric type, you can initialize it with an ordinary number:
char ch = 13;
If you want do do arithmetic on a char
value, just do it: ch = ch + 1;
etc.
However, in order to display the value you have to get around the assumption in the iostreams library that you want to display char
values as characters rather than numbers. There are a couple of ways to do that.
std::cout << +ch << '\n';
std::cout << int(ch) << '\n'
This code will work. The answer from samplebias is almost correct, but you need a third change:
int addNodeBottom(int val, node *head){
//create new node
node *newNode = (node*)malloc(sizeof(node));
if(newNode == NULL){
fprintf(stderr, "Unable to allocate memory for new node\n");
exit(-1);
}
newNode->value = val;
newNode->next = NULL; // Change 1
//check for first insertion
if(head->next == NULL){
head->next = newNode;
printf("added at beginning\n");
}
else
{
//else loop through the list and find the last
//node, insert next to it
node *current = head;
while (true) { // Change 2
if(current->next == NULL)
{
current->next = newNode;
printf("added later\n");
break; // Change 3
}
current = current->next;
};
}
return 0;
}
Change 1: newNode->next
must be set to NULL
so we don't insert invalid pointers at the end of the list.
Change 2/3: The loop is changed to an endless loop that will be jumped out with break;
when we found the last element. Note how while(current->next != NULL)
contradicted if(current->next == NULL)
before.
EDIT: Regarding the while loop, this way it is much better:
node *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
printf("added later\n");
Don't use multiple parameters in the function name just go with simple few args convention that will increase the readability of codes, for this you can do like -
// MultipartBody.Part.createFormData("partName", data)
Call<SomReponse> methodName(@Part MultiPartBody.Part part);
// RequestBody.create(MediaType.get("text/plain"), data)
Call<SomReponse> methodName(@Part(value = "partName") RequestBody part);
/* for single use or you can use by Part name with Request body */
// add multiple list of part as abstraction |ease of readability|
Call<SomReponse> methodName(@Part List<MultiPartBody.Part> parts);
Call<SomReponse> methodName(@PartMap Map<String, RequestBody> parts);
// this way you will save the abstraction of multiple parts.
There can be multiple exceptions that you may encounter while using Retrofit, all of the exceptions documented as code, have a walkthrough to retrofit2/RequestFactory.java
. you can able to two functions parseParameterAnnotation
and parseMethodAnnotation
where you can able to exception thrown, please go through this, it will save your much of time than googling/stackoverflow
I suggest tig
https://github.com/jonas/tig
, a much much better command line tool for git.
You can use homebrew to install tig on macOS:
$ brew install tig
$ tig
You must hide AppBarLayout
before scrollToPosition
if you are using him
For those that are using a .conf
file.
<VirtualHost *:443>
ServerName domain.com
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/domain.crt
SSLCertificateKeyFile /etc/apache2/ssl/domain.key
SSLCACertificateFile /etc/apache2/ssl/domain.crt
</VirtualHost>
That's because you're getting the numeric value associated with the class. For example if you have two classes cats and dogs, Keras will associate them numeric values 0 and 1. To get the mapping between your classes and their associated numeric value, you can use
>>> classes = train_generator.class_indices
>>> print(classes)
{'cats': 0, 'dogs': 1}
Now you know the mapping between your classes and indices. So now what you can do is
if classes[0][0] == 1:
prediction = 'dog'
else:
prediction = 'cat'
If you are using an in-memory collection as your filter, it's probably best to use the negation of Contains(). Note that this can fail if the list is too long, in which case you will need to choose another strategy (see below for using a strategy for a fully DB-oriented query).
var exceptionList = new List<string> { "exception1", "exception2" };
var query = myEntities.MyEntity
.Select(e => e.Name)
.Where(e => !exceptionList.Contains(e.Name));
If you're excluding based on another database query using Except
might be a better choice. (Here is a link to the supported Set extensions in LINQ to Entities)
var exceptionList = myEntities.MyOtherEntity
.Select(e => e.Name);
var query = myEntities.MyEntity
.Select(e => e.Name)
.Except(exceptionList);
This assumes a complex entity in which you are excluding certain ones depending some property of another table and want the names of the entities that are not excluded. If you wanted the entire entity, then you'd need to construct the exceptions as instances of the entity class such that they would satisfy the default equality operator (see docs).
Suppose a new build of an app is ready from the development phase.
We check if we are able to open the app without a crash. We login to the app. We check if the user is redirected to the proper URL and that the environment is stable. If the main aim of the app is to provide a "purchase" functionality to the user, check if the user's ID is redirected to the buying page.
After the smoke testing we confirm the build is in a testable form and is ready to go through sanity testing.
In this phase, we check the basic functionalities, like
LinkedHashMap
is precisely what you're looking for.
It is exactly like HashMap
, except that when you iterate over it, it presents the items in the insertion order.
You are right that greediness is an issue:
--A--Z--A--Z--
^^^^^^^^^^
A.*Z
If you want to match both A--Z
, you'd have to use A.*?Z
(the ?
makes the *
"reluctant", or lazy).
There are sometimes better ways to do this, though, e.g.
A[^Z]*+Z
This uses negated character class and possessive quantifier, to reduce backtracking, and is likely to be more efficient.
In your case, the regex would be:
/(\[[^\]]++\])/
Unfortunately Javascript regex doesn't support possessive quantifier, so you'd just have to do with:
/(\[[^\]]+\])/
* Zero or more, greedy
*? Zero or more, reluctant
*+ Zero or more, possessive
+ One or more, greedy
+? One or more, reluctant
++ One or more, possessive
? Zero or one, greedy
?? Zero or one, reluctant
?+ Zero or one, possessive
Note that the reluctant and possessive quantifiers are also applicable to the finite repetition {n,m}
constructs.
Examples in Java:
System.out.println("aAoZbAoZc".replaceAll("A.*Z", "!")); // prints "a!c"
System.out.println("aAoZbAoZc".replaceAll("A.*?Z", "!")); // prints "a!b!c"
System.out.println("xxxxxx".replaceAll("x{3,5}", "Y")); // prints "Yx"
System.out.println("xxxxxx".replaceAll("x{3,5}?", "Y")); // prints "YY"
You can use the FromStr
trait's from_str
method, which is implemented for i32
:
let my_num = i32::from_str("9").unwrap_or(0);
You haven't been very specific with your code, so I'll make up a scenario. Let's say you have 10 ajax calls and you want to accumulate the results from those 10 ajax calls and then when they have all completed you want to do something. You can do it like this by accumulating the data in an array and keeping track of when the last one has finished:
Manual Counter
var ajaxCallsRemaining = 10;
var returnedData = [];
for (var i = 0; i < 10; i++) {
doAjax(whatever, function(response) {
// success handler from the ajax call
// save response
returnedData.push(response);
// see if we're done with the last ajax call
--ajaxCallsRemaining;
if (ajaxCallsRemaining <= 0) {
// all data is here now
// look through the returnedData and do whatever processing
// you want on it right here
}
});
}
Note: error handling is important here (not shown because it's specific to how you're making your ajax calls). You will want to think about how you're going to handle the case when one ajax call never completes, either with an error or gets stuck for a long time or times out after a long time.
jQuery Promises
Adding to my answer in 2014. These days, promises are often used to solve this type of problem since jQuery's $.ajax()
already returns a promise and $.when()
will let you know when a group of promises are all resolved and will collect the return results for you:
var promises = [];
for (var i = 0; i < 10; i++) {
promises.push($.ajax(...));
}
$.when.apply($, promises).then(function() {
// returned data is in arguments[0][0], arguments[1][0], ... arguments[9][0]
// you can process it here
}, function() {
// error occurred
});
ES6 Standard Promises
As specified in kba's answer: if you have an environment with native promises built-in (modern browser or node.js or using babeljs transpile or using a promise polyfill), then you can use ES6-specified promises. See this table for browser support. Promises are supported in pretty much all current browsers, except IE.
If doAjax()
returns a promise, then you can do this:
var promises = [];
for (var i = 0; i < 10; i++) {
promises.push(doAjax(...));
}
Promise.all(promises).then(function() {
// returned data is in arguments[0], arguments[1], ... arguments[n]
// you can process it here
}, function(err) {
// error occurred
});
If you need to make a non-promise async operation into one that returns a promise, you can "promisify" it like this:
function doAjax(...) {
return new Promise(function(resolve, reject) {
someAsyncOperation(..., function(err, result) {
if (err) return reject(err);
resolve(result);
});
});
}
And, then use the pattern above:
var promises = [];
for (var i = 0; i < 10; i++) {
promises.push(doAjax(...));
}
Promise.all(promises).then(function() {
// returned data is in arguments[0], arguments[1], ... arguments[n]
// you can process it here
}, function(err) {
// error occurred
});
Bluebird Promises
If you use a more feature rich library such as the Bluebird promise library, then it has some additional functions built in to make this easier:
var doAjax = Promise.promisify(someAsync);
var someData = [...]
Promise.map(someData, doAjax).then(function(results) {
// all ajax results here
}, function(err) {
// some error here
});
In Swift:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.tableView.contentInset = UIEdgeInsets(top: 108, left: 0, bottom: 0, right: 0)
}
The below snippet examines EAX using GDB.
(gdb) info register eax
eax 0xaa55 43605
(gdb) info register ax
ax 0xaa55 -21931
(gdb) info register ah
ah 0xaa -86
(gdb) info register al
al 0x55 85
A bit late but this is a solution that worked for me. Perfect if your modal is inside the overlay tag. So, the modal will close when you click anywhere outside the modal content.
HTML
<div class="modal">
<div class="overlay">
<div class="modal-content">
<p>HELLO WORLD!</p>
</div>
</div>
</div>
JS
$(document).on("click", function(event) {
if ($(event.target).has(".modal-content").length) {
$(".modal").hide();
}
});
Here is a working example
NB: If using a windows service to host the webservice.
You have to insure that your webservice is using the right Log on account to connect to SQL Server.
In addition to slhck, this is what worked for me (mac).
To check where your sdk is located.
File -> Project Structure -> Sdk location
Copy the path.
Create the hidden .bash_profile
in your home.
vim
, or open -e
) with the following:export PATH=/Users/<Your session name>/Library/Android/sdk/platform-tools:/Users/<Your session name>/Library/Android/sdk/tools:$PATH
. ~/.bash_profile