Yes, you can solve it using the ElementName=Something
as suggested by Juve.
BUT!
If a child element (on which you use this kind of binding) is a user control which uses the same element name as you specify in the parent control, then the binding goes to the wrong object!!
I know this post is not a solution but I thought everyone who uses the ElementName in the binding should know this, since it's a possible runtime bug.
<UserControl x:Class="MyNiceControl"
x:Name="TheSameName">
the content ...
</UserControl>
<UserControl x:Class="AnotherUserControl">
<ListView x:Name="TheSameName">
<ListView.ItemTemplate>
<DataTemplate>
<MyNiceControl Width="{Binding DataContext.Width, ElementName=TheSameName}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</UserControl>
Don't forget TemplatedParent:
<Binding RelativeSource="{RelativeSource TemplatedParent}"/>
or
{Binding RelativeSource={RelativeSource TemplatedParent}}
TemplateBinding is a shorthand for Binding with TemplatedParent but it does not expose all the capabilities of the Binding class, for example you can't control Binding.Mode from TemplateBinding.
A DataFrame is equivalent to a table in RDBMS and can also be manipulated in similar ways to the "native" distributed collections in RDDs. Unlike RDDs, Dataframes keep track of the schema and support various relational operations that lead to more optimized execution. Each DataFrame object represents a logical plan but because of their "lazy" nature no execution occurs until the user calls a specific "output operation".
You can instantiate 2 Node.js servers - one for HTTP and HTTPS
You can also define a setup function that both servers will execute, so that you don't have to write much duplicated code.
Here's the way I did it: (using restify.js, but should work for express.js, or node itself too)
http://qugstart.com/blog/node-js/node-js-restify-server-with-both-http-and-https/
SDK developers prefer to define their own types using typedef. This allows changing underlying types only in one place, without changing all client code. It is important to follow this convention. DWORD is unlikely to be changed, but types like DWORD_PTR are different on different platforms, like Win32 and x64. So, if some function has DWORD parameter, use DWORD and not unsigned int, and your code will be compiled in all future windows headers versions.
SFTP is not FTP over SSH, it's a different protocol and being similar to SCP, it's offers more capabilities.
Try this
frame$twohouses <- ifelse(frame$data>1, 2, 1)
frame
data twohouses
1 0 1
2 1 1
3 2 2
4 3 2
5 4 2
6 2 2
7 3 2
8 1 1
9 4 2
10 3 2
11 2 2
12 4 2
13 0 1
14 1 1
15 2 2
16 0 1
17 2 2
18 1 1
19 2 2
20 0 1
21 4 2
from datetime import datetime, timedelta
yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%m%d%y')
This should unstage a <file> for you (without removing or otherwise modifying the file):
git reset <file>
Not sure about flexbox but you can do using the position property.
set parent div
position: relative
and child element which might be an <p>
or <h1>
etc.. set position: absolute
and bottom: 0
.
Example:
index.html
<div class="parent">
<p>Child</p>
</div>
style.css
.parent {
background: gray;
width: 10%;
height: 100px;
position: relative;
}
p {
position: absolute;
bottom: 0;
}
For my fellow Googlers out there, here's a very simple plug-and-play solution that worked for me after struggling with the more complex solutions for a while:
SELECT
distinct empName,
NewColumnName=STUFF((SELECT ','+ CONVERT(VARCHAR(10), projID )
FROM returns
WHERE empName=t.empName FOR XML PATH('')) , 1 , 1 , '' )
FROM
returns t
Notice that I had to convert the ID into a VARCHAR in order to concatenate it as a string. If you don't have to do that, here's an even simpler version:
SELECT
distinct empName,
NewColumnName=STUFF((SELECT ','+ projID
FROM returns
WHERE empName=t.empName FOR XML PATH('')) , 1 , 1 , '' )
FROM
returns t
All credit for this goes to here: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/9508abc2-46e7-4186-b57f-7f368374e084/replicating-groupconcat-function-of-mysql-in-sql-server?forum=transactsql
Build Settings > Enable Bitcode > No
When configuring an console_scripts entrypoint in setup.py I found this issue existed when the endpoint was a module or package rather than a function within the module.
Traceback (most recent call last):
File "/Users/ubuntu/.virtualenvs/virtualenv/bin/mycli", line 11, in <module>
load_entry_point('my-package', 'console_scripts', 'mycli')()
TypeError: 'module' object is not callable
For example
from setuptools import setup
setup (
# ...
entry_points = {
'console_scripts': [mycli=package.module.submodule]
},
# ...
)
Should have been
from setuptools import setup
setup (
# ...
entry_points = {
'console_scripts': [mycli=package.module.submodule:main]
},
# ...
)
So that it would refer to a callable function rather than the module itself. It seems to make no difference if the module has a if __name__ == '__main__':
block. This will not make the module callable.
It seems to me that CROSS APPLY can fill a certain gap when working with calculated fields in complex/nested queries, and make them simpler and more readable.
Simple example: you have a DoB and you want to present multiple age-related fields that will also rely on other data sources (such as employment), like Age, AgeGroup, AgeAtHiring, MinimumRetirementDate, etc. for use in your end-user application (Excel PivotTables, for example).
Options are limited and rarely elegant:
JOIN subqueries cannot introduce new values in the dataset based on data in the parent query (it must stand on its own).
UDFs are neat, but slow as they tend to prevent parallel operations. And being a separate entity can be a good (less code) or a bad (where is the code) thing.
Junction tables. Sometimes they can work, but soon enough you're joining subqueries with tons of UNIONs. Big mess.
Create yet another single-purpose view, assuming your calculations don't require data obtained mid-way through your main query.
Intermediary tables. Yes... that usually works, and often a good option as they can be indexed and fast, but performance can also drop due to to UPDATE statements not being parallel and not allowing to cascade formulas (reuse results) to update several fields within the same statement. And sometimes you'd just prefer to do things in one pass.
Nesting queries. Yes at any point you can put parenthesis on your entire query and use it as a subquery upon which you can manipulate source data and calculated fields alike. But you can only do this so much before it gets ugly. Very ugly.
Repeating code. What is the greatest value of 3 long (CASE...ELSE...END) statements? That's gonna be readable!
Did I miss something? Probably, so feel free to comment. But hey, CROSS APPLY is like a godsend in such situations: you just add a simple CROSS APPLY (select tbl.value + 1 as someFormula) as crossTbl
and voilà! Your new field is now ready for use practically like it had always been there in your source data.
Values introduced through CROSS APPLY can...
CROSS APPLY (select crossTbl.someFormula + 1 as someMoreFormula) as crossTbl2
Dang, there's nothing they can't do!
This is for all the people that cannot solve their problem with getters and actually really need a watcher, e.g. to talk to non-vue third party stuff (see Vue Watchers on when to use watchers).
Vue component's watchers and computed values both also work on computed values. So it's no different with vuex:
import { mapState } from 'vuex';
export default {
computed: {
...mapState(['somestate']),
someComputedLocalState() {
// is triggered whenever the store state changes
return this.somestate + ' works too';
}
},
watch: {
somestate(val, oldVal) {
// is triggered whenever the store state changes
console.log('do stuff', val, oldVal);
}
}
}
if it's only about combining local and global state, the mapState's doc also provides an example:
computed: {
...mapState({
// to access local state with `this`, a normal function must be used
countPlusLocalState (state) {
return state.count + this.localCount
}
}
})
One easy step:
$ npm i -g npm-check-updates && ncu -u && npm i
That is all. All of the package versions in package.json
will be the latest major versions.
Edit:
What is happening here?
Installing a package that checks updates for you.
Use this package to update all package versions in your
package.json
(-u is short for --updateAll).Install all of the new versions of the packages.
Use the built-in time
keyword:
$ help time time: time [-p] PIPELINE Execute PIPELINE and print a summary of the real time, user CPU time, and system CPU time spent executing PIPELINE when it terminates. The return status is the return status of PIPELINE. The `-p' option prints the timing summary in a slightly different format. This uses the value of the TIMEFORMAT variable as the output format.
Example:
$ time sleep 2
real 0m2.009s user 0m0.000s sys 0m0.004s
Try this one: http://www.pipsomania.com/best_php_obfuscator.do
Recently I wrote it in Java to obfuscate my PHP projects, because I didnt find any good and compatible ready written on the net, I decided to put it online as saas, so everyone use it free. It does not change variable names between different scripts for maximum compatibility, but is obfuscating them very good, with random logic, every instruction too. Strings... everything. I believe its much better then this buggy codeeclipse, that is by the way written in PHP and very slow :)
You'd need to use return values.
DECLARE @SelectedValue int
CREATE PROCEDURE GetMyInt (@MyIntField int OUTPUT)
AS
SELECT @MyIntField = MyIntField FROM MyTable WHERE MyPrimaryKeyField = 1
Then you call it like this:
EXEC GetMyInt OUTPUT @SelectedValue
The best and most accurate way to think of pass
is as a way to explicitly tell the interpreter to do nothing. In the same way the following code:
def foo(x,y):
return x+y
means "if I call the function foo(x, y), sum the two numbers the labels x and y represent and hand back the result",
def bar():
pass
means "If I call the function bar(), do absolutely nothing."
The other answers are quite correct, but it's also useful for a few things that don't involve place-holding.
For example, in a bit of code I worked on just recently, it was necessary to divide two variables, and it was possible for the divisor to be zero.
c = a / b
will, obviously, produce a ZeroDivisionError if b is zero. In this particular situation, leaving c as zero was the desired behavior in the case that b was zero, so I used the following code:
try:
c = a / b
except ZeroDivisionError:
pass
Another, less standard usage is as a handy place to put a breakpoint for your debugger. For example, I wanted a bit of code to break into the debugger on the 20th iteration of a for... in statement. So:
for t in range(25):
do_a_thing(t)
if t == 20:
pass
with the breakpoint on pass.
Here's a simple example to add two variables:
var1=4
var2=3
let var3=$var1+$var2
echo $var3
You can read up this property every few calls, Environment.StackTrace
, and if the stacktrace exceded a specific threshold that you preset, you can return the function.
You should also try to replace some recursive functions with loops.
Here is my function, uses binary search to find item and then inserts appropriately:
function binaryInsert(val, arr){_x000D_
let mid, _x000D_
len=arr.length,_x000D_
start=0,_x000D_
end=len-1;_x000D_
while(start <= end){_x000D_
mid = Math.floor((end + start)/2);_x000D_
if(val <= arr[mid]){_x000D_
if(val >= arr[mid-1]){_x000D_
arr.splice(mid,0,val);_x000D_
break;_x000D_
}_x000D_
end = mid-1;_x000D_
}else{_x000D_
if(val <= arr[mid+1]){_x000D_
arr.splice(mid+1,0,val);_x000D_
break;_x000D_
}_x000D_
start = mid+1;_x000D_
}_x000D_
}_x000D_
return arr;_x000D_
}_x000D_
_x000D_
console.log(binaryInsert(16, [_x000D_
5, 6, 14, 19, 23, 44,_x000D_
35, 51, 86, 68, 63, 71,_x000D_
87, 117_x000D_
]));
_x000D_
For full numbers (non-floats) in Angular you can use:
if (Number.isInteger(yourVariable)) {
...
}
If You are comparing only with the date vale, then converting it to date (not datetime) will work
select id,numbers_from,created_date,amount_numbers,SMS_text
from Test_Table
where
created_date <= convert(date,'2013-04-12',102)
This conversion is also applicable during using GetDate() function
None of the current answers including the accepted one will use Apple's San Francisco font on systems that don't have it installed as the system font. Since the question isn't "how do I use the OS X system font on a webpage" the correct solution is to use web fonts:
@font-face {
font-family: "San Francisco";
font-weight: 400;
src: url("https://applesocial.s3.amazonaws.com/assets/styles/fonts/sanfrancisco/sanfranciscodisplay-regular-webfont.woff");
}
You can also change the value of this database parameter for your session by using the ALTER SESSION command and use it as you wanted
ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MM-YYYY';
SELECT TO_DATE('05-12-2015') FROM dual;
05/12/2015
not Error:
JSONObject json1 = getJsonX();
Error:
JSONObject json2 = null;
if(x == y)
json2 = getJSONX();
Error: Local variable statement defined in an enclosing scope must be final or effectively final.
But you can write:
JSONObject json2 = (x == y) ? json2 = getJSONX() : null;
in your Product Web API controller:
[RoutePrefix("api/product")]
public class ProductController : ApiController
{
private readonly IProductRepository _repository;
public ProductController(IProductRepository repository)
{
this._repository = repository;
}
[HttpGet, Route("orders")]
public async Task<IHttpActionResult> GetProductPeriodOrders(string productCode, DateTime dateStart, DateTime dateEnd)
{
try
{
IList<Order> orders = await _repository.GetPeriodOrdersAsync(productCode, dateStart.ToUniversalTime(), dateEnd.ToUniversalTime());
return Ok(orders);
}
catch(Exception ex)
{
return NotFound();
}
}
}
test GetProductPeriodOrders method in Fiddler - Composer:
http://localhost:46017/api/product/orders?productCode=100&dateStart=2016-12-01T00:00:00&dateEnd=2016-12-31T23:59:59
DateTime format:
yyyy-MM-ddTHH:mm:ss
javascript pass parameter use moment.js
const dateStart = moment(startDate).format('YYYY-MM-DDTHH:mm:ss');
const dateEnd = moment(endDate).format('YYYY-MM-DDTHH:mm:ss');
All answers are great. Here is an example use case for multiple add address: The ability to add as many email you want on demand with a web form:
See it in action with jsfiddle here (except the php processor)
### Send unlimited email with a web form
# Form for continuously adding e-mails:
<button type="button" onclick="emailNext();">Click to Add Another Email.</button>
<div id="addEmail"></div>
<button type="submit">Send All Emails</button>
# Script function:
<script>
function emailNext() {
var nextEmail, inside_where;
nextEmail = document.createElement('input');
nextEmail.type = 'text';
nextEmail.name = 'emails[]';
nextEmail.className = 'class_for_styling';
nextEmail.style.display = 'block';
nextEmail.placeholder = 'Enter E-mail Here';
inside_where = document.getElementById('addEmail');
inside_where.appendChild(nextEmail);
return false;
}
</script>
# PHP Data Processor:
<?php
// ...
// Add the rest of your $mailer here...
if ($_POST[emails]){
foreach ($_POST[emails] AS $postEmail){
if ($postEmail){$mailer->AddAddress($postEmail);}
}
}
?>
So what it does basically is to generate a new input text box on every click with the name "emails[]".
The [] added at the end makes it an array when posted.
Then we go through each element of the array with "foreach" on PHP side adding the:
$mailer->AddAddress($postEmail);
Firstly this is a very good question.
e.g. The authorization header or content type header. Which is absolutely required by the server to understand the request. This can differ from server to server.
This is less severe than 400. The request has reached the server. The server has acknowledged the request has got the basic structure right. But the information in the request body can't be parsed or understood.
e.g. Content-Type: application/xml
when request body is JSON.
Here's an article listing status codes and its use in REST APIs. https://metamug.com/article/status-codes-for-rest-api.php
In your example the slice
argument of the Test
function receives a copy of the variable a
in the caller's scope.
Since a slice variable holds a "slice descriptor" which merely references an underlying array, in your Test
function you modify the slice descriptor held in the slice
variable several times in a row, but this does not affect the caller and its a
variable.
Inside the (Jeff Lee is correct about that it's not what really happens, so the updated version follows; as he correctly states, this answer is correct, if maybe a bit too terse.)Test
function, the first append
reallocates the backing array under the slice
variable, copies its original contents over, appends 100
to it, and that's what you're observing. Upon exiting from Test
, the slice
variable goes out of scope and so does the (new) underlying array that slice references.
Outside the Test
function, a slice of length 7 and capacity 8 is allocated, and its 7 elements filled.
Inside the Test
function, the first append
sees the that the slice's capacity is still one element larger than its length — in other words, there is room for one more element to add without reallocation.
So it "eats up" that remaining element and places 100
to it, after which it adjusts the length in the copy of the slice descriptor to become equal to the slice's capaticy.
This does not affect the slice descriptor's in the caller's scope.
And that's what you're observing. Upon exiting from Test
, the slice
variable goes out of scope and so does the (new) underlying array that slice references.
If you want to make Test
behave like append
, you have to return the new slice from it — just like append
does — and require the callers of Test
to use it in the same way they would use append
:
func Test(slice []int) []int {
slice = append(slice, 100)
fmt.Println(slice)
return slice
}
a = Test(a)
Please read this article thoroughly as it basically shows you how to implement append
by hand, after explaining how slices are working internally. Then read this.
This depends on the database server, but it is often called something like CEIL
or CEILING
. For example, in MySQL...
mysql> select ceil(10.5);
+------------+
| ceil(10.5) |
+------------+
| 11 |
+------------+
You can then do UPDATE PRODUCT SET price=CEIL(some_other_field);
because your jQuery code is wrong. Correctly would be:
var theParent = $(this).parent().get(0);
$(theParent).css('z-index', 3000);
Even cleaner would be to just put p#given img { float: right }
in the style sheet, or in the <head>
and wrapped in style
tags. Then, just use the markdown ![Alt text](/path/to/img.jpg)
.
You can use module clipboard
. Its simple and extremely easy to use. Works with Mac, Windows, & Linux.
Note: Its an alternative of pyperclip
After installing, import it:
import clipboard
Then you can copy like this:
clipboard.copy("This is copied")
You can also paste the copied text:
clipboard.paste()
I am using SQL Server 2016 and both myDate
and myTime
fields are strings. The below tsql statement worked in concatenating them into datetime
select cast((myDate + ' ' + myTime) as datetime) from myTable
adding this worked for me:
<link href="https://fortawesome.github.io/Font-Awesome/assets/font-awesome/css/font-awesome.css" rel="stylesheet">
so full example is:
<link href="https://github.com/FortAwesome/Font-Awesome/blob/master/web-fonts-with-css/css/fontawesome.css" rel="stylesheet">_x000D_
<a class="btn-cta-freequote" href="#">Compute <i class="fa fa-calculator"></i></a>
_x000D_
Based on the answer of cs95
map
is defined on Series ONLYapplymap
is defined on DataFrames ONLYapply
is defined on BOTHgive some examples
In [3]: frame = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'), index=['Utah', 'Ohio', 'Texas', 'Oregon'])
In [4]: frame
Out[4]:
b d e
Utah 0.129885 -0.475957 -0.207679
Ohio -2.978331 -1.015918 0.784675
Texas -0.256689 -0.226366 2.262588
Oregon 2.605526 1.139105 -0.927518
In [5]: myformat=lambda x: f'{x:.2f}'
In [6]: frame.d.map(myformat)
Out[6]:
Utah -0.48
Ohio -1.02
Texas -0.23
Oregon 1.14
Name: d, dtype: object
In [7]: frame.d.apply(myformat)
Out[7]:
Utah -0.48
Ohio -1.02
Texas -0.23
Oregon 1.14
Name: d, dtype: object
In [8]: frame.applymap(myformat)
Out[8]:
b d e
Utah 0.13 -0.48 -0.21
Ohio -2.98 -1.02 0.78
Texas -0.26 -0.23 2.26
Oregon 2.61 1.14 -0.93
In [9]: frame.apply(lambda x: x.apply(myformat))
Out[9]:
b d e
Utah 0.13 -0.48 -0.21
Ohio -2.98 -1.02 0.78
Texas -0.26 -0.23 2.26
Oregon 2.61 1.14 -0.93
In [10]: myfunc=lambda x: x**2
In [11]: frame.applymap(myfunc)
Out[11]:
b d e
Utah 0.016870 0.226535 0.043131
Ohio 8.870453 1.032089 0.615714
Texas 0.065889 0.051242 5.119305
Oregon 6.788766 1.297560 0.860289
In [12]: frame.apply(myfunc)
Out[12]:
b d e
Utah 0.016870 0.226535 0.043131
Ohio 8.870453 1.032089 0.615714
Texas 0.065889 0.051242 5.119305
Oregon 6.788766 1.297560 0.860289
// http headers for zip downloads
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filepath.$filename));
ob_end_flush();
@readfile($filepath.$filename);
I found this soludtion here and it work for me
You use EXECUTENONQUERY()
for INSERT
,UPDATE
and DELETE
.
But for SELECT
you must use EXECUTEREADER()
.........
1) The reason not to prefer a shape of (R, 1)
over (R,)
is that it unnecessarily complicates things. Besides, why would it be preferable to have shape (R, 1)
by default for a length-R vector instead of (1, R)
? It's better to keep it simple and be explicit when you require additional dimensions.
2) For your example, you are computing an outer product so you can do this without a reshape
call by using np.outer
:
np.outer(M[:,0], numpy.ones((1, R)))
You're using curvy-braces when you should be using parentheses.
A where statement is kept inside a scriptblock, which is defined using curvy baces { }
. To isolate/wrap you tests, you should use parentheses ()
.
I would also suggest trying to do the filtering on the remote computer. Try:
Invoke-Command -computername SERVERNAME {
Get-ChildItem -path E:\dfsroots\datastore2\public |
Where-Object { ($_.extension -eq "xls" -or $_.extension -eq "xlk") -and $_.creationtime -ge "06/01/2014" }
}
You are first setting opacity: 1;
and then you are ending it on 0
, so it starts from 0%
and ends on 100%
, so instead just set opacity to 0
at 50%
and the rest will take care of itself.
.blink_me {_x000D_
animation: blinker 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes blinker {_x000D_
50% {_x000D_
opacity: 0;_x000D_
}_x000D_
}
_x000D_
<div class="blink_me">BLINK ME</div>
_x000D_
Here, I am setting the animation duration to be 1 second
, and then I am setting the timing
to linear
. That means it will be constant throughout. Last, I am using infinite
. That means it will go on and on.
Note: If this doesn't work for you, use browser prefixes like
-webkit
,-moz
and so on as required foranimation
and@keyframes
. You can refer to my detailed code here
As commented, this won't work on older versions of Internet Explorer, and for that you need to use jQuery or JavaScript...
(function blink() {
$('.blink_me').fadeOut(500).fadeIn(500, blink);
})();
Thanks to Alnitak for suggesting a better approach.
Demo (Blinker using jQuery)
You can do that with the following:
Form3 formshow = new Form3();
formshow.ShowDialog();
I think your problem is your version numbers. Try making 8.1 --> 8.01, and so forth. That should put the points in the right order.
Alternatively, you could plot using X
, where X is the column number you want, instead of using 1:X
. That will plot those values on the y axis and integers on the x axis. Try:
plot "ls.dat" using 2 title 'Removed' with lines, \
"ls.dat" using 3 title 'Added' with lines, \
"ls.dat" using 4 title 'Modified' with lines
In my code, when I got the error, I checked the possible source, In a line, I had typed a beginning \[
and an ending \]
due to which the error of missing $
appeared though I tried using $
for both the brackets. Removing the brackets or using $[$
instead of $\[$
solved my problem. If you've something like that, try altering.
Try to press ALT-? (alt and question mark at the same time). Give it a second or two to build the list. It should work in bash.
From Database.
Blob blob = resultSet.getBlob("pictureBlob");
byte [] data = blob.getBytes( 1, ( int ) blob.length() );
BufferedImage img = null;
try {
img = ImageIO.read(new ByteArrayInputStream(data));
} catch (IOException e) {
e.printStackTrace();
}
drawPicture(img); // void drawPicture(Image img);
If you use Sublime Text on Windows or Mac to edit your scripts:
Click on View > Line Endings > Unix
and save the file again.
It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.
I've always used phpMailer's SMTP feature:
$mail->IsSMTP();
$mail->Host = "localhost";
And if you need debug info:
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
You can rewrite the code likes this:
#include<iostream>
#include<stdio.h>
using namespace std;
To get the actual scrollable height of the areas scrolled by the window scrollbar, I used $('body').prop('scrollHeight')
. This seems to be the simplest working solution, but I haven't checked extensively for compatibility. Emanuele Del Grande notes on another solution that this probably won't work for IE below 8.
Most of the other solutions work fine for scrollable elements, but this works for the whole window. Notably, I had the same issue as Michael for Ankit's solution, namely, that $(document).prop('scrollHeight')
is returning undefined
.
object-fit
may help you, if you're playing with<img>
tag
The below code will crop your image for you. You can play around with object-fit
img {
object-fit: cover;
width: 300px;
height: 337px;
}
Importing Jobs Manually: Alternate way
Upload the Jobs on to Git (Version Control) Basically upload config.xml of the Job.
If Linux Servers:
cd /var/lib/jenkins/jobs/<Job name>
Download the config.xml from Git
Restart the Jenkins
I like using RegEx in this occasion:
str = str.replace(/X/g, '');
where g means global so it will go through your whole string and replace all X with ''; if you want to replace both X and x, you simply say:
str = str.replace(/X|x/g, '');
(see my fiddle here: fiddle)
If you want to change MSSQL server language, you can use the following QUERY:
EXEC sp_configure 'default language', 'British English';
From near the beginning of the PIL Tutorial:
Once you have an instance of the Image class, you can use the methods defined by this class to process and manipulate the image. For example, let's display the image we just loaded:
>>> im.show()
Update:
Nowadays theImage.show()
method is formally documented in the Pillow fork of PIL along with an explanation of how it's implemented on different OSs.
Actually only setTimeout
is fine for that job and normally you cannot set exact delays with non determined methods as busy loops.
This line of code might not work in IE 8 because of native support problems.
$(".hidden").attr("placeholder", "Type here to search");
You can try importing a JQuery placeholder plugin for this task. Simply import it to your libraries and initiate from the sample code below.
$('input, textarea').placeholder();
For refreshing page with javascript, you can simply use:
location.reload();
If you need to change the path, add this after your .config in your app file.
Then you can do $location.path('/sampleurl', false);
to prevent reloading
app.run(['$route', '$rootScope', '$location', function ($route, $rootScope, $location) {
var original = $location.path;
$location.path = function (path, reload) {
if (reload === false) {
var lastRoute = $route.current;
var un = $rootScope.$on('$locationChangeSuccess', function () {
$route.current = lastRoute;
un();
});
}
return original.apply($location, [path]);
};
}])
Credit goes to https://www.consolelog.io/angularjs-change-path-without-reloading for the most elegant solution I've found.
I prefer to use this instead of TempData
public class Home1Controller : Controller
{
[HttpPost]
public ActionResult CheckBox(string date)
{
return RedirectToAction("ActionName", "Home2", new { Date =date });
}
}
and another controller Action
is
public class Home2Controller : Controller
{
[HttpPost]
Public ActionResult ActionName(string Date)
{
// do whatever with Date
return View();
}
}
it is too late but i hope to be helpful for any one in the future
echo "Subject: test" | /usr/sbin/sendmail [email protected]
This enables you to do it within one command line without having to echo a text file. This answer builds on top of @mti2935's answer. So credit goes there.
Yes. I updated my answer DEMO
table td {
border-top: thin solid;
border-bottom: thin solid;
}
table td:first-child {
border-left: thin solid;
}
table td:last-child {
border-right: thin solid;
}
If you want to style only one <tr>
you can do it with a class: Second DEMO
Per Phairoh: Use this in the Page/Component just in case the panel name changes
<script type="text/javascript">
<!--
//must be global to be called by ExternalInterface
function JSFunction() {
__doPostBack('<%= myUpdatePanel.ClientID %>', '');
}
-->
</script>
A crude work around is to set display: table
on the containing div.
This snippet might help in removing the xticks only.
from matplotlib import pyplot as plt
plt.xticks([])
This snippet might help in removing the xticks and yticks both.
from matplotlib import pyplot as plt
plt.xticks([]),plt.yticks([])
Actually I don't know you want to this.
try this
INSERT INTO my_table (my_column)
SELECT
(random() * 10) + 1
;
You are returning a reference to ret which is a variable on the stack.
>>> def contains(string, char):
... for i in xrange(len(string) - 1, -1, -1):
... if string[i] == char:
... return i
... raise ValueError("could not find %r in %r" % (char, string))
...
>>> contains('bababa', 'k')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in contains
ValueError: could not find 'k' in 'bababa'
>>> contains('bababa', 'a')
5
>>> contains('bababa', 'b')
4
>>> contains('xbababa', 'x')
0
>>>
The tabularx
package gives you
X
, all X
columns will grow to fill up the total width.For your example:
\usepackage{tabularx}
% ...
\begin{document}
% ...
\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF & simulation & jsp\\
\hline
\end{tabularx}
String test = "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);
mkoryak
is correct.
But, if events are bound to that DOM node using more modern methods (not using onclick
), then this method will fail.
If that is what you really want, check out this question, and its accepted answer.
Cheers!
I read your question again.
I'd like to tell you this: don't use onclick
, onkeypress
and the likes to bind events.
Using better methods like addEventListener()
will enable you to:
Instead of actually using addEventListener()
, you could use jQuery
wrappers like $('selector').click()
.
Cheers again!
In Laravel 5.5
I was trying to accomplish the same problem in Laravel 5.5. Instead of using Auth::routes()
in the web.php routes file, I only included the login/logout routes:
Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');
From the HTML 4 specification:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
A common mistake is to use an ID that starts with a digit.
NOTE: This answer addresses enterprise-class development in-the-large.
This is an RDBMS issue, not just SQL Server, and the behavior can be very interesting. For one, while it is common for primary keys to be automatically (uniquely) indexed, it is NOT absolute. There are times when it is essential that a primary key NOT be uniquely indexed.
In most RDBMSs, a unique index will automatically be created on a primary key if one does not already exist. Therefore, you can create your own index on the primary key column before declaring it as a primary key, then that index will be used (if acceptable) by the database engine when you apply the primary key declaration. Often, you can create the primary key and allow its default unique index to be created, then create your own alternate index on that column, then drop the default index.
Now for the fun part--when do you NOT want a unique primary key index? You don't want one, and can't tolerate one, when your table acquires enough data (rows) to make the maintenance of the index too expensive. This varies based on the hardware, the RDBMS engine, characteristics of the table and the database, and the system load. However, it typically begins to manifest once a table reaches a few million rows.
The essential issue is that each insert of a row or update of the primary key column results in an index scan to ensure uniqueness. That unique index scan (or its equivalent in whichever RDBMS) becomes much more expensive as the table grows, until it dominates the performance of the table.
I have dealt with this issue many times with tables as large as two billion rows, 8 TBs of storage, and forty million row inserts per day. I was tasked to redesign the system involved, which included dropping the unique primary key index practically as step one. Indeed, dropping that index was necessary in production simply to recover from an outage, before we even got close to a redesign. That redesign included finding other ways to ensure the uniqueness of the primary key and to provide quick access to the data.
Try this
#import <QuartzCore/QuartzCore.h> // not necessary for 10 years now :)
...
view.layer.cornerRadius = 5;
view.layer.masksToBounds = true;
Note: If you are trying to apply rounded corners to a UIViewController
's view, it should not be applied in the view controller's constructor, but rather in -viewDidLoad
, after view
is actually instantiated.
With Moment.js simply use:
var jsDate = moment(netDateTime).toDate();
Where netDateTime
is your DateTime variable serialized, something like "/Date(1456956000000+0200)/"
.
!pwd
import os
os.chdir('/content/drive/My Drive/Colab Notebooks/Data')
!pwd
view this answer for detailed explaination https://stackoverflow.com/a/61636734/11535267
You can use backslash to quote "funny" characters in your jQuery selectors:
$('#input\\[23\\]')
For attribute values, you can use quotes:
$('input[name="weirdName[23]"]')
Now, I'm a little confused by your example; what exactly does your HTML look like? Where does the string "inputName" show up, in particular?
edit fixed bogosity; thanks @Dancrumb
I had the same issue with weblogic 12c and maven I initially while deploying from eclipse (kepler) (deploying from the console gave no errors).
The other solutions given on this page didn't help.
I extracted the spring.tld spring-form.tld files of the spring-webmvc jar (which I found in my repository) in the web\WEB-INF folder of my war module;
I did a fresh build; deployed (from eclipse) into weblogic 12c, tested the application and the error was gone;
I removed the spring.tld spring-form.tld files again and after deleting; rebuilding and redeploying the application the error didn't show up again.
I double checked whether the files were gone in the war and they were indeed not present.
hope this helps others with a similar issue...
After you add some stuff... commit them and after all finished push it! BANG!! Start all problems... As you should notice there are some differences in the way both new and existent projects were defined. If some other person tries to add/commit/push same files, or content (git keep both as same objects), we will face the following error:
$ git push
Counting objects: 31, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (17/17), done.
Writing objects: 100% (21/21), 2.07 KiB | 0 bytes/s, done.
Total 21 (delta 12), reused 0 (delta 0)
remote: error: insufficient permission for adding an object to repository database ./objects remote: fatal: failed to write object
To solve this problem you have to have something in mind operational system's permissions system as you are restricted by it in this case. Tu understand better the problem, go ahead and check your git object's folder (.git/objects). You will probably see something like that:
<your user_name>@<the machine name> objects]$ ls -la
total 200
drwxr-xr-x 25 <your user_name> <group_name> 2048 Feb 10 09:28 .
drwxr-xr-x 3 <his user_name> <group_name> 1024 Feb 3 15:06 ..
drwxr-xr-x 2 <his user_name> <group_name> 1024 Jan 31 13:39 02
drwxr-xr-x 2 <his user_name> <group_name> 1024 Feb 3 13:24 08
*Note that those file's permissions were granted only for your users, no one will never can changed it... *
Level u g o
Permission rwx r-x ---
Binary 111 101 000
Octal 7 5 0
SOLVING THE PROBLEM
If you have super user permission, you can go forward and change all permissions by yourself using the step two, in any-other case you will need to ask all users with objects created with their users, use the following command to know who they are:
$ ls -la | awk '{print $3}' | sort -u
<your user_name>
<his user_name>
Now you and all file's owner users will have to change those files permission, doing:
$ chmod -R 774 .
After that you will need to add a new property that is equivalent to --shared=group done for the new repository, according to the documentation, this make the repository group-writable, do it executing:
$ git config core.sharedRepository group
Make sure you have this code on you component:
export class Component {
checked = true;
}
I think if I set a color for a:visited
it is not good: you must know the default color of tag a
and every time synchronize it with a:visited
.
I don't want know about the default color (it can be set in common.css
of your application, or you can using outside styles).
I think it's nice solution:
HTML
:
<body>
<a class="absolute">Test of URL</a>
<a class="unvisited absolute" target="_blank" href="google.ru">Test of URL</a>
</body>
CSS
:
.absolute{
position: absolute;
}
a.unvisited, a.unvisited:visited, a.unvisited:active{
text-decoration: none;
color: transparent;
}
Try the following code:
For PHP 5.4.0 and above:
$filename = basename(parse_url('http://learner.com/learningphp.php?lid=1348')['path']);
For PHP Version < 5.4.0
$parsed = parse_url('http://learner.com/learningphp.php?lid=1348');
$filename = basename($parsed['path']);
In laravel 5.3
I want to show the get param in my view
Step 1 : my route
Route::get('my_route/{myvalue}', 'myController@myfunction');
Step 2 : Write a function inside your controller
public function myfunction($myvalue)
{
return view('get')->with('myvalue', $myvalue);
}
Now you're returning the parameter that you passed to the view
Step 3 : Showing it in my View
Inside my view you i can simply echo it by using
{{ $myvalue }}
So If you have this in your url
http://127.0.0.1/yourproject/refral/[email protected]
Then it will print [email protected] in you view file
hope this helps someone.
You can just use the built-in R functions tapply
with length
tapply(myvec$order_no, myvec$name, FUN = function(x) length(unique(x)))
This seemed far harder to find than it needs to be for OSX. Too many conflicting posts
For MAC OSX Mavericks Java JDK 7, follow these steps to locate keytool
:
Firstly make sure to install Java JDK
:
http://docs.oracle.com/javase/7/docs/webnotes/install/mac/mac-jdk.html
Then type this into command prompt:
/usr/libexec/java_home -v 1.7
it will spit out something like:
/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home
keytool
is located in the same directory as javac
. ie:
/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/bin
From bin
directory you can use the keytool
.
in my case
my service has function to download Files
and this error only shown up on trying to download Big Files
so I found this answer to Increase maxRequestLength
to needed value in web.config
I know that's weird, but problem solved
if you don't make any upload or download operations maybe this answer will not help you
Actually, according to jsperf.com, The DOM operations are fastest, then $().prop() followed by $().is()!!
Here are the syntaxes :
var checkbox = $('#'+id);
/* OR var checkbox = $("input[name=checkbox1]"); whichever is best */
/* The DOM way - The fastest */
if(checkbox[0].checked == true)
alert('Checkbox is checked!!');
/* Using jQuery .prop() - The second fastest */
if(checkbox.prop('checked') == true)
alert('Checkbox is checked!!');
/* Using jQuery .is() - The slowest in the lot */
if(checkbox.is(':checked') == true)
alert('Checkbox is checked!!');
I personally prefer .prop()
. Unlike .is()
, It can also be used to set the value.
create table Table1
(
id varchar(2),
name varchar(2),
PRIMARY KEY (id)
)
Create table Table1_Addr
(
addid varchar(2),
Address varchar(2),
PRIMARY KEY (addid)
)
Create table Table1_sal
(
salid varchar(2),`enter code here`
addid varchar(2),
id varchar(2),
PRIMARY KEY (salid),
index(addid),
index(id),
FOREIGN KEY (addid) REFERENCES Table1_Addr(addid),
FOREIGN KEY (id) REFERENCES Table1(id)
)
list = [1, 2, 3, 4, 5]
for i in list[0:-1]:
print(i, end=', ')
print(list[-1])
do for loops really take that much longer to run?
was trying to make something that printed all str values in a list separated by commas, inserting "and" before the last entry and came up with this:
spam = ['apples', 'bananas', 'tofu', 'cats']
for i in spam[0:-1]:
print(i, end=', ')
print('and ' + spam[-1])
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
The main functionality of attr_accessor over the other ones is the capability of accessing data from other files.
So you usually would have attr_reader or attr_writer but the good news is that Ruby lets you combine these two together with attr_accessor. I think of it as my to go method because it is more well rounded or versatile.
Also, peep in mind that in Rails, this is eliminated because it does it for you in the back end. So in other words: you are better off using attr_acessor over the other two because you don't have to worry about being to specific, the accessor covers it all. I know this is more of a general explanation but it helped me as a beginner.
Hope this helped!
See the documentation events section
Depending on the version, one of the snippets below should give you the event you want, alternatively just replace "select2-selecting" with "change".
Version 4.0 +
Events are now in format: select2:selecting
(instead of select2-selecting
)
Thanks to snakey for the notification that this has changed as of 4.0
$('#yourselect').on("select2:selecting", function(e) {
// what you would like to happen
});
Version Before 4.0
$('#yourselect').on("select2-selecting", function(e) {
// what you would like to happen
});
Just to clarify, the documentation for select2-selecting
reads:
select2-selecting Fired when a choice is being selected in the dropdown, but before any modification has been made to the selection. This event is used to allow the user to reject selection by calling event.preventDefault()
whereas change has:
change Fired when selection is changed.
So change
may be more appropriate for your needs, depending on whether you want the selection to complete and then do your event, or potentially block the change.
<?php
$subject = "this is a subject";
$message = "testing a message";
$headers .= "Reply-To: The Sender <[email protected]>\r\n";
$headers .= "Return-Path: The Sender <[email protected]>\r\n";
$headers .= "From: The Sender <[email protected]>\r\n";
$headers .= "Organization: Sender Organization\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "X-Priority: 3\r\n";
$headers .= "X-Mailer: PHP". phpversion() ."\r\n" ;
mail("[email protected]", $subject, $message, $headers);
?>
It's not Twitter bootstrap specific, it is a normal HTML5 component and you can specify the range with the min
and max
attributes (in your case only the first attribute). For example:
<div> _x000D_
<input type="number" id="replyNumber" min="0" data-bind="value:replyNumber" />_x000D_
</div>
_x000D_
I'm not sure if only integers are allowed by default in the control or not, but else you can specify the step
attribute:
<div> _x000D_
<input type="number" id="replyNumber" min="0" step="1" data-bind="value:replyNumber" />_x000D_
</div>
_x000D_
Now only numbers higher (and equal to) zero can be used and there is a step of 1, which means the values are 0, 1, 2, 3, 4, ... .
BE AWARE: Not all browsers support the HTML5 features, so it's recommended to have some kind of JavaScript fallback (and in your back-end too) if you really want to use the constraints.
For a list of browsers that support it, you can look at caniuse.com.
Those are different APIs to access a MySQL backend
So it depends on what kind of code you want to produce. If you prefer object-oriented layers or plain functions...
My advice would be
Also my feeling, the mysql API would probably being deleted in future releases of PHP
.
There are also DRM behaviors that incorporate multiple steps to the process. One of the most well known examples is one of Adobe's methods for verifying an installation of their Creative Suite. The traditional CD Key method discussed here is used, then Adobe's support line is called. The CD key is given to the Adobe representative and they give back an activation number to be used by the user.
However, despite being broken up into steps, this falls prey to the same methods of cracking used for the normal process. The process used to create an activation key that is checked against the original CD key was quickly discovered, and generators that incorporate both of the keys were made.
However, this method still exists as a way for users with no internet connection to verify the product. Going forward, it's easy to see how these methods would be eliminated as internet access becomes ubiquitous.
There are automatic backup under %systemdrive%\inetpub\history but it may not help much if you already made lots of changes.
http://blogs.iis.net/bills/archive/2008/03/24/how-to-backup-restore-iis7-configuration.aspx
You will have to regularly back up manually using appcmd.
If you try to reinstall IIS, please first uninstall IIS and WAS via Add/Remove Programs, and then delete all existing files under C:\inetpub and C:\Windows\system32\inetsrv directories. Then you can install again cleanly.
WARN: beginners on IIS are not recommended to execute the steps above without a full backup of the system. The steps should be executed with caution and good understanding of IIS. If you are not capable of or you have doubt, make sure you open a support case with Microsoft via http://support.microsoft.com and consult.
You JSON is not a valid string as P. Galbraith has told you above.
and here is the solution for it.
<?php
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$data = json_decode($json);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
Use this code it will work for you.
I'm going to provide a functional (immutable) way of doing it.
The standard and easy way of doing it is to use slicing:
index_to_remove = 3
data = [*range(5)]
new_data = data[:index_to_remove] + data[index_to_remove + 1:]
print(f"data: {data}, new_data: {new_data}")
Output:
data: [0, 1, 2, 3, 4], new_data: [0, 1, 2, 4]
Use list comprehension:
data = [*range(5)]
new_data = [v for i, v in enumerate(data) if i != index_to_remove]
print(f"data: {data}, new_data: {new_data}")
Output:
data: [0, 1, 2, 3, 4], new_data: [0, 1, 2, 4]
Use filter function:
index_to_remove = 3
data = [*range(5)]
new_data = [*filter(lambda i: i != index_to_remove, data)]
Output:
data: [0, 1, 2, 3, 4], new_data: [0, 1, 2, 4]
Using masking. Masking is provided by itertools.compress function in the standard library:
from itertools import compress
index_to_remove = 3
data = [*range(5)]
mask = [1] * len(data)
mask[index_to_remove] = 0
new_data = [*compress(data, mask)]
print(f"data: {data}, mask: {mask}, new_data: {new_data}")
Output:
data: [0, 1, 2, 3, 4], mask: [1, 1, 1, 0, 1], new_data: [0, 1, 2, 4]
Use itertools.filterfalse function from Python standard library
from itertools import filterfalse
index_to_remove = 3
data = [*range(5)]
new_data = [*filterfalse(lambda i: i == index_to_remove, data)]
print(f"data: {data}, new_data: {new_data}")
Output:
data: [0, 1, 2, 3, 4], new_data: [0, 1, 2, 4]
No, only using LIKE
will not work. LIKE
searches values matching exactly your given pattern. In this case LIKE
would find only the text 'sOmeVal' and not 'someval'.
A pracitcable solution is using the LCASE()
function. LCASE('sOmeVal')
gets the lowercase string of your text: 'someval'. If you use this function for both sides of your comparison, it works:
SELECT * FROM myTable WHERE LCASE(myField) LIKE LCASE('sOmeVal')
The statement compares two lowercase strings, so that your 'sOmeVal' will match every other notation of 'someval' (e.g. 'Someval', 'sOMEVAl' etc.).
The await
inside your asynchronous method is trying to come back to the UI thread.
Since the UI thread is busy waiting for the entire task to complete, you have a deadlock.
Moving the async call to Task.Run()
solves the issue.
Because the async call is now running on a thread pool thread, it doesn't try to come back to the UI thread, and everything therefore works.
Alternatively, you could call StartAsTask().ConfigureAwait(false)
before awaiting the inner operation to make it come back to the thread pool rather than the UI thread, avoiding the deadlock entirely.
This happened to me when I deleted a folder and then copy-pasted it back to the project.
Right-click project folder -> Rebuild
worked for me.
Converting millis to datetime (UTC):
import datetime
time_in_millis = 1596542285000
dt = datetime.datetime.fromtimestamp(time_in_millis / 1000.0, tz=datetime.timezone.utc)
Converting datetime to string following the RFC3339 standard (used by Open API specification):
from rfc3339 import rfc3339
converted_to_str = rfc3339(dt, utc=True, use_system_timezone=False)
# 2020-08-04T11:58:05Z
Matlab allows you to return multiple values as well as receive them inline.
When you call it, receive individual variables inline:
[array, listp, freep] = initialize(size)
AddSingleton() creates a single instance of the service when it is first requested and reuses that same instance in all the places where that service is needed.
In a scoped service, with every HTTP request, we get a new instance. However, within the same HTTP request, if the service is required in multiple places, like in the view and in the controller, then the same instance is provided for the entire scope of that HTTP request. But every new HTTP request will get a new instance of the service.
With a transient service, a new instance is provided every time a service instance is requested whether it is in the scope of the same HTTP request or across different HTTP requests.
Unfortunately it seems to be a issue with MySql usage of "NOT IN" clause, the screen-shoot below shows the sub-query option returning wrong results:
mysql> show variables like '%version%';
+-------------------------+------------------------------+
| Variable_name | Value |
+-------------------------+------------------------------+
| innodb_version | 1.1.8 |
| protocol_version | 10 |
| slave_type_conversions | |
| version | 5.5.21 |
| version_comment | MySQL Community Server (GPL) |
| version_compile_machine | x86_64 |
| version_compile_os | Linux |
+-------------------------+------------------------------+
7 rows in set (0.07 sec)
mysql> select count(*) from TABLE_A where TABLE_A.Pkey not in (select distinct TABLE_B.Fkey from TABLE_B );
+----------+
| count(*) |
+----------+
| 0 |
+----------+
1 row in set (0.07 sec)
mysql> select count(*) from TABLE_A left join TABLE_B on TABLE_A.Pkey = TABLE_B.Fkey where TABLE_B.Pkey is null;
+----------+
| count(*) |
+----------+
| 139 |
+----------+
1 row in set (0.06 sec)
mysql> select count(*) from TABLE_A where NOT EXISTS (select * FROM TABLE_B WHERE TABLE_B.Fkey = TABLE_A.Pkey );
+----------+
| count(*) |
+----------+
| 139 |
+----------+
1 row in set (0.06 sec)
mysql>
If non of the answers worked
For me was .Net Framework version compatibility issue of the one i'm using was older then what is referencing
From properties => Application then target framework
Another way for single item in center, which fill half of screen:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<View
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="1"
android:visibility="invisible" />
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2" />
<View
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="1"
android:visibility="invisible" />
</LinearLayout>
//My Form
<form id="someform">
<div class="input-group">
<textarea placeholder="Post your Comment Here ..." name="post" class="form-control custom-control" rows="3" style="resize:none"></textarea>
<span class="input-group-addon">
<button type="submit" name="post_comment" class="btn btn-primary">
Post
</button>
</span>
</div>
</form>
//your text area get value to URL
<?php
if(isset($_POST['post_comment']))
{
echo htmlspecialchars($_POST['post']);
}
?>
//print the value using get
echo $_GET['post'];
//url must be like this
http://localhost/blog/home.php?post=asdasdsad&post_comment=
//post value has asdasdsad so it will print to your page
Yes, you can use jQuery's attribute selector for that.
var linksToGoogle = $('a[href="http://google.com"]');
Alternatively, if your interest is rather links starting with a certain URL, use the attribute-starts-with selector:
var allLinksToGoogle = $('a[href^="http://google.com"]');
Updated answer, from Peter in comments :
This is de "old terminology", use directally the WSDL2 "endepoint" definition (WSDL2 translated "port" to "endpoint").
Maybe you find an answer in this document : http://www.w3.org/TR/wsdl.html
A WSDL document defines services as collections of network endpoints, or ports. In WSDL, the abstract definition of endpoints and messages is separated from their concrete network deployment or data format bindings. This allows the reuse of abstract definitions: messages, which are abstract descriptions of the data being exchanged, and port types which are abstract collections of operations. The concrete protocol and data format specifications for a particular port type constitutes a reusable binding. A port is defined by associating a network address with a reusable binding, and a collection of ports define a service. Hence, a WSDL document uses the following elements in the definition of network services:
- Types– a container for data type definitions using some type system (such as XSD).
- Message– an abstract, typed definition of the data being communicated.
- Operation– an abstract description of an action supported by the service.
- Port Type–an abstract set of operations supported by one or more endpoints.
- Binding– a concrete protocol and data format specification for a particular port type.
- Port– a single endpoint defined as a combination of a binding and a network address.
- Service– a collection of related endpoints.
http://www.ehow.com/info_12212371_definition-service-endpoint.html
The endpoint is a connection point where HTML files or active server pages are exposed. Endpoints provide information needed to address a Web service endpoint. The endpoint provides a reference or specification that is used to define a group or family of message addressing properties and give end-to-end message characteristics, such as references for the source and destination of endpoints, and the identity of messages to allow for uniform addressing of "independent" messages. The endpoint can be a PC, PDA, or point-of-sale terminal.
It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.
Let's say you have something like this in your code:
$str = "test";
echo($str{0});
since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:
$str = "test";
echo($str[0]);
Fixing the code in the question will look something like this:
public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
$records = $this->listRecords($zoneID, $type, $name);
if (isset($records->result[0]->id)) {
return $records->result[0]->id;
}
return false;
}
As an addendum to @xmechanix's answer, I noticed through writing the contents to a file:
echo | set /p dummyName=Hello World > somefile.txt
That this will add an extra space at the end of the printed string, which can be inconvenient, specially since we're trying to avoid adding a new line (another whitespace character) to the end of the string.
Fortunately, quoting the string to be printed, i.e. using:
echo | set /p dummyName="Hello World" > somefile.txt
Will print the string without any newline or space character at the end.
Here is the shortest version (Java 1.5+ required):
repeated = new String(new char[n]).replace("\0", s);
Where n
is the number of times you want to repeat the string and s
is the string to repeat.
No imports or libraries needed.
I found out I made a mistake. There's no need to call toObject() or toJSON() at all. The __proto__ in the question came from jquery, not mongoose. Here's my test:
UserModel.find({}, function (err, users) {
console.log(users.save); // { [Function] numAsyncPres: 0 }
var json = JSON.stringify(users);
users = users.map(function (user) {
return user.toObject();
}
console.log(user.save); // undefined
console.log(json == JSON.stringify(users)); // true
}
doc.toObject() removes doc.prototype from a doc. But it makes no difference in JSON.stringify(doc). And it's not needed in this case.
To search the whole computer:
gdr -PSProvider 'FileSystem' | %{ ls -r $_.root} 2>$null | where { $_.name -eq "httpd.exe" }
EDIT: yes I agree this is not a correct MVVM approach and I am now using something similar to what is suggested by blindmeis.
One of the way you could to this is
In your Main View Model (where you open the modal):
void OpenModal()
{
ModalWindowViewModel mwvm = new ModalWindowViewModel();
Window mw = new Window();
mw.content = mwvm;
mw.ShowDialog()
if(mw.DialogResult == true)
{
// Your Code, you can access property in mwvm if you need.
}
}
And in your Modal Window View/ViewModel:
XAML:
<Button Name="okButton" Command="{Binding OkCommand}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}">OK</Button>
<Button Margin="2" VerticalAlignment="Center" Name="cancelButton" IsCancel="True">Cancel</Button>
ViewModel:
public ICommand OkCommand
{
get
{
if (_okCommand == null)
{
_okCommand = new ActionCommand<Window>(DoOk, CanDoOk);
}
return _okCommand ;
}
}
void DoOk(Window win)
{
<!--Your Code-->
win.DialogResult = true;
win.Close();
}
bool CanDoOk(Window win) { return true; }
or similar to what is posted here WPF MVVM: How to close a window
you have to do like this in your project level gradle file
allprojects {
repositories {
jcenter()
maven { url "http://dl.appnext.com/" }
maven { url "https://maven.google.com" }
}
}
Reg file
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Console]
"CodePage"=dword:fde9
Command Prompt
REG ADD HKCU\Console /v CodePage /t REG_DWORD /d 0xfde9
PowerShell
sp -t d HKCU:\Console CodePage 0xfde9
Cygwin
regtool set /user/Console/CodePage 0xfde9
You can simply use json_encode function of php and save file with file handling functions such as fopen and fwrite.
This didn't exist when the question was asked, but ES2015 introduced array destructuring, allowing you to write it as follows:
let a = 1, b = 2;
// a: 1, b: 2
[a, b] = [b, a];
// a: 2, b: 1
It will be written on a new line if you examine the source code of the page. If you want it to appear on a new line when it is rendered in the browser, you'll have use a <br />
tag instead.
I had the same question. While there are good answers here I decided to create a table-valued function. With a table (or scalar) valued function you don't have to change your stored proc. I simply did a select from the table-valued function. Note that the parameter (MyParameter is optional).
CREATE FUNCTION [dbo].[MyDateFunction]
(@MyParameter varchar(max))
RETURNS TABLE
AS
RETURN
(
--- Query your table or view or whatever and select the results.
SELECT DateValue FROM MyTable WHERE ID = @MyParameter;
)
To assign to your variable you simply can do something like:
Declare @MyDate datetime;
SET @MyDate = (SELECT DateValue FROM MyDateFunction(@MyParameter));
You can also use a scalar valued function:
CREATE FUNCTION TestDateFunction()
RETURNS datetime
BEGIN
RETURN (SELECT GetDate());
END
Then you can simply do
Declare @MyDate datetime;
SET @MyDate = (Select dbo.TestDateFunction());
SELECT @MyDate;
I had the same error code but different issue
Error: /Users/danieloram/desktop/CordovaProject/platforms/android/gradlew: Command failed with exit code 1 Error output:
Exception in thread "main" java.lang.UnsupportedClassVersionError: com/android/dx/command/Main : Unsupported major.minor version 52.0
To resolve this issue I opened the Android SDK Manager, uninstalled the latest Android SDK build-tools that I had (24.0.3) and installed version 23.0.3 of the build-tools.
My cordova app then proceeded to build successfully for android.
I didn't want to wrap my *ngFor
into another div
with *ngIf
or use [ngClass]
, so I created a pipe named show
:
show.pipe.ts
export class ShowPipe implements PipeTransform {
transform(values: any[], show: boolean): any[] {
if (!show) {
return[];
}
return values;
}
}
any.page.html
<table>
<tr *ngFor="let arr of anyArray | show : ngIfCondition">
<td>{{arr.label}}</td>
</tr>
</table>
Similar to unutbu above, you could also use applymap
as follows:
import pandas as pd
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
index=['foo','bar','baz','quux'],
columns=['cost'])
df = df.applymap("${0:.2f}".format)
The quickest way to echo all json values is using loop in loop, the first loop is going to get all the objects and the second one the values...
foreach($data as $object) {
foreach($object as $value) {
echo $value;
}
}
I used the
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
and works perfectly
You can also use these ways:
EXEC sp_helpdb
and:
SELECT name FROM sys.sysdatabases
Recommended Read:
Don't forget to have a look at sysdatabases VS sys.sysdatabases
A similar thread.
I found your question because I was also fighting with NSAttributedString.
For me, the beginEditing
and endEditing
methods did the trick, like stated in Changing an Attributed String.
Apart from that, the lineSpacing is set with setLineSpacing
on the paragraphStyle.
So you might want to try changing your code to:
NSString *string = @" Hello \n world";
attrString = [[NSMutableAttributedString alloc] initWithString:string];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
[paragraphStyle setLineSpacing:20] // Or whatever (positive) value you like...
[attrSting beginEditing];
[attrString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:20] range:NSMakeRange(0, string.length)];
[attrString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, string.length)];
[attrString endEditing];
mainTextView.attributedText = attrString;
Didn't test this exact code though, btw, but mine looks nearly the same.
Meanwhile, I've tested it, and, correct me if I'm wrong, the - beginEditing
and - endEditing
calls seem to be of quite an importance.
You want win.Sleep(milliseconds)
, methinks.
Yeah, you definitely don't want to do a busy-wait like you describe.
This will give you the current element name (tag name)
<xsl:value-of select ="name(.)"/>
OP-Edit: This will also do the trick:
<xsl:value-of select ="local-name()"/>
As an extension method:
public static class Extensions
{
public static string AsString(this XmlDocument xmlDoc)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter tx = new XmlTextWriter(sw))
{
xmlDoc.WriteTo(tx);
string strXmlText = sw.ToString();
return strXmlText;
}
}
}
}
Now to use simply:
yourXmlDoc.AsString()
You could use wmic with the /locale option
call wmic /locale:ms_409 service where (name="wsearch") get state /value | findstr State=Running
if %ErrorLevel% EQU 0 (
echo Running
) else (
echo Not running
)
Setting the build active architectures only to No fixed this problem for me.
The value of a button element isn't the displayed text, contrary to what happens to input
elements of type button.
You can do this :
b.appendChild(document.createTextNode('test value'));
Jquery later allowed you to to find the parents with the .parents()
method.
Hence I recommend using:
var $div = $('#divid').parents('div[class^="div-a"]');
This gives all parent nodes matching the selector. To get the first parent matching the selector use:
var $div = $('#divid').parents('div[class^="div-a"]').eq(0);
For other such DOM traversal queries, check out the documentation on traversing the DOM.
I had this issue and the problem was that Navicat was connected to my local Postgres db. Once I disconnected Navicat the problem disappeared.
EDIT:
Also, as an absolute last resort you can back up your data then run this command:
sudo kill -15 `ps -u postgres -o pid`
... which will kill everything that the postgres user is accessing. Avoid doing this on a production machine but you shouldn't have a problem with a development environment. It is vital that you ensure every postgres
process has really terminated before attempting to restart PostgreSQL after this.
EDIT 2:
Due to this unix.SE post I've changed from kill -9
to kill -15
.
To center the canvas element horizontally, you must specify it as a block level and leave its left and right margin properties to the browser:
canvas{
margin-right: auto;
margin-left: auto;
display: block;
}
If you wanted to center it vertically, the canvas element needs to be absolutely positioned:
canvas{
position: absolute;
top: 50%;
transform: translate(0, -50%);
}
If you wanted to center it horizontally and vertically, do:
canvas{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
For more info visit: https://www.w3.org/Style/Examples/007/center.en.html
The below code this will help you
public class TextProperty {
private int heigt; //???????
private String []context = new String[1024]; //???????
/*
*@parameter wordNum
*
*/
public TextProperty(int wordNum ,InputStreamReader in) throws Exception {
int i=0;
BufferedReader br = new BufferedReader(in);
String s;
while((s=br.readLine())!=null){
if(s.length()>wordNum){
int k=0;
while(k+wordNum<=s.length()){
context[i++] = s.substring(k, k+wordNum);
k=k+wordNum;
}
context[i++] = s.substring(k,s.length());
}
else{
context[i++]=s;
}
}
this.heigt = i;
in.close();
br.close();
}
public int getHeigt() {
return heigt;
}
public String[] getContext() {
return context;
}
}
public class MainActivity extends AppCompatActivity {
private Button btn;
private ImageView iv;
private final int WORDNUM = 35; //?????? ???????
private final int WIDTH = 450; //???????
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.imageView);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int x=5,y=10;
try {
TextProperty tp = new TextProperty(WORDNUM, new InputStreamReader(getResources().getAssets().open("1.txt")));
Bitmap bitmap = Bitmap.createBitmap(WIDTH, 20*tp.getHeigt(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextAlign(Paint.Align.LEFT);
paint.setTextSize(20f);
String [] ss = tp.getContext();
for(int i=0;i<tp.getHeigt();i++){
canvas.drawText(ss[i], x, y, paint);
y=y+20;
}
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
String path = Environment.getExternalStorageDirectory() + "/image.png";
System.out.println(path);
FileOutputStream os = new FileOutputStream(new File(path));
bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
//Display the image on ImageView.
iv.setImageBitmap(bitmap);
iv.setBackgroundColor(Color.BLUE);
os.flush();
os.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}```
Here is another approach using read
. I am using this for brute search of a file by its name fragment, ignoring the "permission denied" messages.
alias loc0='{ IFS= read -r x; find . -iname "*" -print 2>/dev/null | grep $x;} <<<'
A simple example:
$ { IFS= read -r x; echo "1 $x 2 ";} <<< "a b"
1 a b 2
Note, that this converts the argument as a string into variable(s). One could use several parameters within quotes for this, space separated:
$ { read -r x0 x1; echo "1 ${x0} 2 ${x1} 3 ";} <<< "a b"
1 a 2 b 3
I also had the similar problem while registering myinfo.dll file in windows 7. Following work for me: Create a short cut on your desktop C:\Windows\System32\regsvr32.exe c:\windows\system32\myinfo.dll right click on the short cut just created and select as Run as administrator.
show alert box with use variable with message
<script>
$(document).ready(function() {
var total = 30 ;
alert("your total is :"+ total +"rs");
});
</script>
It looks like you're trying to deserialize to a raw object. You could create a Class that represents the object that you're converting to. This would be most useful in cases where you're dealing with larger objects or JSON Strings.
For instance:
class Test {
String test;
String getTest() { return test; }
void setTest(String test) { this.test = test; }
}
Then your deserialization code would be:
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
Test routes_list =
(Test)json_serializer.DeserializeObject("{ \"test\":\"some data\" }");
More information can be found in this tutorial: http://www.codeproject.com/Tips/79435/Deserialize-JSON-with-Csharp.aspx
The example you are using is wrong. See the man page for easy_setopt. In the example write_data uses its own FILE, *outfile, and not the fp that was specified in CURLOPT_WRITEDATA. That's why closing fp causes problems - it's not even opened.
This is more or less what it should look like (no libcurl available here to test)
#include <stdio.h>
#include <curl/curl.h>
/* For older cURL versions you will also need
#include <curl/types.h>
#include <curl/easy.h>
*/
#include <string>
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
int main(void) {
CURL *curl;
FILE *fp;
CURLcode res;
char *url = "http://localhost/aaa.txt";
char outfilename[FILENAME_MAX] = "C:\\bbb.txt";
curl = curl_easy_init();
if (curl) {
fp = fopen(outfilename,"wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
fclose(fp);
}
return 0;
}
Updated: as suggested by @rsethc types.h
and easy.h
aren't present in current cURL versions anymore.
for multiple scripts, use this
var loadScript = function(src) {
var tag = document.createElement('script');
tag.async = false;
tag.src = src;
document.getElementsByTagName('body').appendChild(tag);
}
loadScript('//cdnjs.com/some/library.js')
loadScript('//cdnjs.com/some/other/library.js')
If you mean the screen where you have that interpreter prompt >>>
you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do
import os
os.system('cls') # on windows
or
os.system('clear') # on linux / os x
This code will store the image in database.
$('#image').change(function(){
// FileReader function for read the file.
let reader = new FileReader();
var base64;
reader.readAsDataURL(this.files[0]);
//Read File
let filereader = new FileReader();
var selectedFile = this.files[0];
// Onload of file read the file content
filereader.onload = function(fileLoadedEvent) {
base64 = fileLoadedEvent.target.result;
$("#pimage").val(JSON.stringify(base64));
};
filereader.readAsDataURL(selectedFile);
});
HTML content should be like this.
<div class="col-xs-12 col-sm-4 col-md-4 user_frm form-group">
<input id="image" type="file" class="inputMaterial" name="image">
<input type="hidden" id="pimage" name="pimage" value="">
<span class="bar"></span>
</div>
Store image data in database like this:
//property_image longtext(database field type)
$data= array(
'property_image' => trim($request->get('pimage'),'"')
);
Display image:
<img src="{{$result->property_image}}" >
I used the below code to redirect to new page
$window.location.href = '/foldername/page.html';
and injected $window object in my controller function.
And, in my case, I mistakenly define my two different columns as identities on DbContext configurations like below,
builder.HasKey(e => e.HistoryId).HasName("HistoryId");
builder.Property(e => e.Id).UseSqlServerIdentityColumn(); //History Id should use identity column in this example
When I correct it like below,
builder.HasKey(e => e.HistoryId).HasName("HistoryId");
builder.Property(e => e.HistoryId).UseSqlServerIdentityColumn();
I have also got rid of this error.
Working with a dictionary ->level2 above comes from a dictionary in my case (just in case anybody will find it useful) Trying the first example I stumbled over this error: "This document already has a 'DocumentElement' node." I was inspired by the answer here
and edited my code: (xmlDoc.DocumentElement.AppendChild(body))
//a dictionary:
Dictionary<string, string> Level2Data
{
{"level2", "text"},
{"level2", "other text"},
{"same_level2", "more text"}
}
//xml Decalration:
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDoc.DocumentElement;
xmlDoc.InsertBefore(xmlDeclaration, root);
// add body
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.AppendChild(body);
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.DocumentElement.AppendChild(body); //without DocumentElement ->ERR
foreach (KeyValuePair<string, string> entry in Level2Data)
{
//write to xml: - it works version 1.
XmlNode keyNode = xmlDoc.CreateElement(entry.Key); //open TAB
keyNode.InnerText = entry.Value;
body.AppendChild(keyNode); //close TAB
//Write to xmml verdion 2: (uncomment the next 4 lines and comment the above 3 - version 1
//XmlElement key = xmlDoc.CreateElement(string.Empty, entry.Key, string.Empty);
//XmlText value = xmlDoc.CreateTextNode(entry.Value);
//key.AppendChild(value);
//body.AppendChild(key);
}
Both versions (1 and 2 inside foreach loop) give the output:
<?xml version="1.0" encoding="UTF-8"?>
<body>
<level1>
<level2>text</level2>
<level2>ther text</level2>
<same_level2>more text</same_level2>
</level1>
</body>
(Note: third line "same level2" in dictionary can be also level2 as the others but I wanted to ilustrate the advantage of the dictionary - in my case I needed level2 with different names.
https://github.com/koffsyrup/FileSaver.js#examples
Saving text(All Browsers)
saveTextAs("Hi,This,is,a,CSV,File", "test.csv");
saveTextAs("<div>Hello, world!</div>", "test.html");
Saving text(HTML 5)
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");
The easiest way I found
Dialog dialog=new Dialog(this,android.R.style.Theme_Black_NoTitleBar_Fullscreen);
dialog.setContentView(R.layout.frame_help);
dialog.show();
Here are two ways :
const array = [ 'My', 'name', 'Hamza' ];_x000D_
_x000D_
array.splice(2, 0, 'is');_x000D_
_x000D_
console.log("Method 1 : ", array.join(" "));
_x000D_
OR
Array.prototype.insert = function ( index, item ) {_x000D_
this.splice( index, 0, item );_x000D_
};_x000D_
_x000D_
const array = [ 'My', 'name', 'Hamza' ];_x000D_
array.insert(2, 'is');_x000D_
_x000D_
console.log("Method 2 : ", array.join(" "));
_x000D_
Well,
Just worked it out. While having both installations we have two ORACLE_HOME directories and both have SQAORA32.dll files. While looking up for ORACLE_HOMe my app was getting confused..I just removed the Client oracle home entry as oracle client is by default present in oracle DB Now its working...Thanks!!
It depends how many times you're going to want to find this information, if more than once:
Set<Boolean> flags = new HashSet<Boolean>(myArray);
flags.contains(false);
Otherwise a short circuited loop:
for (i = 0; i < myArray.length; i++) {
if (!myArray[i]) return false;
}
return true;
webView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
return super.onJsAlert(view, url, message, result);
}
});
@echo off
rem The * at the end of the destination file is to avoid File/Directory Internal Question.
rem You can do this for each especific file. (Make sure you already have permissions to the path)
xcopy /Y "\\Oldeserver\storage\data\MyFile01.txt" "\\New server\storage\data\MyFile01.txt"*
pause
rem You can use "copy" instead of "xcopy "for this example.
The following should work. Keep single connection open all time, and just create new commands and execute them.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command1 = new SqlCommand(commandText1, connection))
{
}
using (SqlCommand command2 = new SqlCommand(commandText2, connection))
{
}
// etc
}
Just for reference, I am using Angular 7.1.4, TypeScript 3.1.6, and the only thing I need to do is to add this line in tsconfig.json
:
"types": ["node"], // within compilerOptions
date('Y-m-d H:i:s')
. See the manual for more.
I've been trying different variants of this for days, and I thought for a day I had it re-launching the app in the background, even when the user swiped to kill, but no I can't replicate that behavior.
It's unfortunate that the behavior is quite different than before. On iOS 6, if you killed the app from the jiggling icons, it would still get re-awoken on SLC triggers. Now, if you kill by swiping, that doesn't happen.
It's a different behavior, and the user, who would continue to get useful information from our app if they had killed it on iOS 6, now will not.
We need to nudge our users to re-open the app now if they have swiped to kill it and are still expecting some of the notification behavior that we used to give them. I'm worried this won't be obvious to users when they swipe an app away. They may, after all, be basically cleaning up or wanting to rearrange the apps that are shown minimized.
To reference an element by id, you need to use the #
qualifier.
Try:
alert($("#link1").text());
To replace it, you could use:
$("#link1").text('New text');
The .html()
function would work in this case too.
You can use dummynet ofcourse, There is extension of dummynet called KauNet. which can provide even more precise control of network conditions. It can drop/delay/re-order specific packets (that way you can perform more in-depth analysis of dropping key packets like TCP handshake to see how your web pages digest it). It also works in time domain. Usually most the emulators are tuned to work in data domain. In time domain you can specify from what time to what time you can alter the network conditions.
If your local installation is running XAMPP on Windows , That's enough : you can open the file "\xampp\php\php.ini" to activate the php exstension by removing the beginning semicolon at the line ";extension=php_imap.dll". It should be:
;extension=php_imap.dll
to
extension=php_imap.dll
You cannot do using JDBC as it does not support . Work around would be including iBatis iBATIS is a persistence framework and call the Scriptrunner
constructor as shown in iBatis documentation .
Its not good to include a heavy weight persistence framework like ibatis in order to run a simple sql scripts any ways which you can do using command line
$ mysql -u root -p db_name < test.sql
I've used this to solve my similar problem ... displaying an image counter (from an external provider). It did not refresh always correctly. And after a random parameter was added, all works fine :)
I've appended a date string to ensure refresh at least every minute.
sample code (PHP):
$output .= "<img src=\"http://xy.somecounter.com/?id=1234567890&".date(ymdHi)."\" alt=\"somecounter.com\" style=\"border:none;\">";
That results in a src
link like:
http://xy.somecounter.com/?id=1234567890&1207241014
I think the below rules are recommended for a default wordpress site:
For folders inside wp-content, set 0755 permissions:
chmod -R 0755 plugins
chmod -R 0755 uploads
chmod -R 0755 upgrade
Let apache user be the owner for the above directories of wp-content:
chown apache uploads
chown apache upgrade
chown apache plugins
Use the @ViewChildren decorator combined with QueryList. Both of these are from "@angular/core"
@ViewChildren(CustomComponent) customComponentChildren: QueryList<CustomComponent>;
Doing something with each child looks like:
this.customComponentChildren.forEach((child) => { child.stuff = 'y' })
There is further documentation to be had at angular.io, specifically: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts=Parent%20calls%20a%20ViewChild
Use the CONCAT
function to avoid conversion errors:
DECLARE @StudentID VARCHAR(1000)
SELECT @StudentID = CONCAT(COALESCE(@StudentID + ',', ''), StudentID)
FROM Student
WHERE StudentID IS NOT NULL and Condition='XYZ'
select @StudentID
Can you pick the appropriate char set in the Constructor:
new InputStreamReader(new FileInputStream(in), "ISO8859_1");
I've created an example to show how to. Updated state
definition would be:
$stateProvider
.state('home', {
url: '/:foo?bar',
views: {
'': {
templateUrl: 'tpl.home.html',
controller: 'MainRootCtrl'
},
...
}
And this would be the controller:
.controller('MainRootCtrl', function($scope, $state, $stateParams) {
//..
var foo = $stateParams.foo; //getting fooVal
var bar = $stateParams.bar; //getting barVal
//..
$scope.state = $state.current
$scope.params = $stateParams;
})
What we can see is that the state home now has url defined as:
url: '/:foo?bar',
which means, that the params in url are expected as
/fooVal?bar=barValue
These two links will correctly pass arguments into the controller:
<a ui-sref="home({foo: 'fooVal1', bar: 'barVal1'})">
<a ui-sref="home({foo: 'fooVal2', bar: 'barVal2'})">
Also, the controller does consume $stateParams
instead of $stateParam
.
Link to doc:
You can check it here
params : {}
There is also new, more granular setting params : {}
. As we've already seen, we can declare parameters as part of url
. But with params : {}
configuration - we can extend this definition or even introduce paramters which are not part of the url:
.state('other', {
url: '/other/:foo?bar',
params: {
// here we define default value for foo
// we also set squash to false, to force injecting
// even the default value into url
foo: {
value: 'defaultValue',
squash: false,
},
// this parameter is now array
// we can pass more items, and expect them as []
bar : {
array : true,
},
// this param is not part of url
// it could be passed with $state.go or ui-sref
hiddenParam: 'YES',
},
...
Settings available for params are described in the documentation of the $stateProvider
Below is just an extract
We can call these params this way:
// hidden param cannot be passed via url
<a href="#/other/fooVal?bar=1&bar=2">
// default foo is skipped
<a ui-sref="other({bar: [4,5]})">
Check it in action here
I wrote a little script based on Florian's answer that uses nano (my favorite editor):
#!/bin/sh
if [ "$#" -ne 3 ]; then
echo "Usage: $0 hugeFilePath startLine endLine" >&2
exit 1
fi
sed -n -e $2','$3'p' -e $3'q' $1 > hfnano_temporary_file
nano hfnano_temporary_file
(head -n `expr $2 - 1` $1; cat hfnano_temporary_file; sed -e '1,'$3'd' $1) > hfnano_temporary_file2
cat hfnano_temporary_file2 > $1
rm hfnano_temporary_file hfnano_temporary_file2
Use it like this:
sh hfnano yourHugeFile 3 8
In that example, nano will open up lines 3 through 8, you can edit them, and when you save and quit, those lines in the hugefile will automatically be overwritten with your saved lines.
You can write bash in your package.json:
# package.json
{
"name": ...,
"version": ...,
"scripts": {
"build": "NODE_ENV=production npm run webpack && cp -v <this> <that> && echo ok",
...
}
}
Swift 3
This code has the re-entry ability and can work with Asynchronous function calls. In this code, after someAsyncFunc() is called, another function closure on the serial queue will process but be blocked by semaphore.wait() until signal() is called. internalQueue.sync shouldn't be used as it will block the main thread if I'm not mistaken.
let internalQueue = DispatchQueue(label: "serialQueue")
let semaphore = DispatchSemaphore(value: 1)
internalQueue.async {
self.semaphore.wait()
// Critical section
someAsyncFunc() {
// Do some work here
self.semaphore.signal()
}
}
objc_sync_enter/objc_sync_exit isn't a good idea without error handling.
this is how I do it
JAVASCRIPT:
var module = angular.module('yourModuleName', ['ui.router']);
module.run( ['$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
]);
HTML:
<pre id="uiRouterInfo">
$state = {{$state.current.name}}
$stateParams = {{$stateParams}}
$state full url = {{ $state.$current.url.source }}
</pre>
EXAMPLE
The Original Question
Why is one loop so much slower than two loops?
Conclusion:
Case 1 is a classic interpolation problem that happens to be an inefficient one. I also think that this was one of the leading reasons why many machine architectures and developers ended up building and designing multi-core systems with the ability to do multi-threaded applications as well as parallel programming.
Looking at it from this kind of an approach without involving how the hardware, OS, and compiler(s) work together to do heap allocations that involve working with RAM, cache, page files, etc.; the mathematics that is at the foundation of these algorithms shows us which of these two is the better solution.
We can use an analogy of a Boss
being a Summation
that will represent a For Loop
that has to travel between workers A
& B
.
We can easily see that Case 2 is at least half as fast if not a little more than Case 1 due to the difference in the distance that is needed to travel and the time taken between the workers. This math lines up almost virtually and perfectly with both the benchmark times as well as the number of differences in assembly instructions.
I will now begin to explain how all of this works below.
Assessing The Problem
The OP's code:
const int n=100000;
for(int j=0;j<n;j++){
a1[j] += b1[j];
c1[j] += d1[j];
}
And
for(int j=0;j<n;j++){
a1[j] += b1[j];
}
for(int j=0;j<n;j++){
c1[j] += d1[j];
}
The Consideration
Considering the OP's original question about the two variants of the for
loops and his amended question towards the behavior of caches along with many of the other excellent answers and useful comments; I'd like to try and do something different here by taking a different approach about this situation and problem.
The Approach
Considering the two loops and all of the discussion about cache and page filing I'd like to take another approach as to looking at this from a different perspective. One that doesn't involve the cache and page files nor the executions to allocate memory, in fact, this approach doesn't even concern the actual hardware or the software at all.
The Perspective
After looking at the code for a while it became quite apparent what the problem is and what is generating it. Let's break this down into an algorithmic problem and look at it from the perspective of using mathematical notations then apply an analogy to the math problems as well as to the algorithms.
What We Do Know
We know is that this loop will run 100,000 times. We also know that a1
, b1
, c1
& d1
are pointers on a 64-bit architecture. Within C++ on a 32-bit machine, all pointers are 4 bytes and on a 64-bit machine, they are 8 bytes in size since pointers are of a fixed length.
We know that we have 32 bytes in which to allocate for in both cases. The only difference is we are allocating 32 bytes or two sets of 2-8 bytes on each iteration wherein the second case we are allocating 16 bytes for each iteration for both of the independent loops.
Both loops still equal 32 bytes in total allocations. With this information let's now go ahead and show the general math, algorithms, and analogy of these concepts.
We do know the number of times that the same set or group of operations that will have to be performed in both cases. We do know the amount of memory that needs to be allocated in both cases. We can assess that the overall workload of the allocations between both cases will be approximately the same.
What We Don't Know
We do not know how long it will take for each case unless if we set a counter and run a benchmark test. However, the benchmarks were already included from the original question and from some of the answers and comments as well; and we can see a significant difference between the two and this is the whole reasoning for this proposal to this problem.
Let's Investigate
It is already apparent that many have already done this by looking at the heap allocations, benchmark tests, looking at RAM, cache, and page files. Looking at specific data points and specific iteration indices were also included and the various conversations about this specific problem have many people starting to question other related things about it. How do we begin to look at this problem by using mathematical algorithms and applying an analogy to it? We start off by making a couple of assertions! Then we build out our algorithm from there.
Our Assertions:
F1()
, F2()
, f(a)
, f(b)
, f(c)
and f(d)
.The Algorithms:
1st Case: - Only one summation but two independent function calls.
Sum n=1 : [1,100000] = F1(), F2();
F1() = { f(a) = f(a) + f(b); }
F2() = { f(c) = f(c) + f(d); }
2nd Case: - Two summations but each has its own function call.
Sum1 n=1 : [1,100000] = F1();
F1() = { f(a) = f(a) + f(b); }
Sum2 n=1 : [1,100000] = F1();
F1() = { f(c) = f(c) + f(d); }
If you noticed F2()
only exists in Sum
from Case1
where F1()
is contained in Sum
from Case1
and in both Sum1
and Sum2
from Case2
. This will be evident later on when we begin to conclude that there is an optimization that is happening within the second algorithm.
The iterations through the first case Sum
calls f(a)
that will add to its self f(b)
then it calls f(c)
that will do the same but add f(d)
to itself for each 100000
iterations. In the second case, we have Sum1
and Sum2
that both act the same as if they were the same function being called twice in a row.
In this case we can treat Sum1
and Sum2
as just plain old Sum
where Sum
in this case looks like this: Sum n=1 : [1,100000] { f(a) = f(a) + f(b); }
and now this looks like an optimization where we can just consider it to be the same function.
Summary with Analogy
With what we have seen in the second case it almost appears as if there is optimization since both for loops have the same exact signature, but this isn't the real issue. The issue isn't the work that is being done by f(a)
, f(b)
, f(c)
, and f(d)
. In both cases and the comparison between the two, it is the difference in the distance that the Summation has to travel in each case that gives you the difference in execution time.
Think of the for
loops as being the summations that does the iterations as being a Boss
that is giving orders to two people A
& B
and that their jobs are to meat C
& D
respectively and to pick up some package from them and return it. In this analogy, the for loops or summation iterations and condition checks themselves don't actually represent the Boss
. What actually represents the Boss
is not from the actual mathematical algorithms directly but from the actual concept of Scope
and Code Block
within a routine or subroutine, method, function, translation unit, etc. The first algorithm has one scope where the second algorithm has two consecutive scopes.
Within the first case on each call slip, the Boss
goes to A
and gives the order and A
goes off to fetch B's
package then the Boss
goes to C
and gives the orders to do the same and receive the package from D
on each iteration.
Within the second case, the Boss
works directly with A
to go and fetch B's
package until all packages are received. Then the Boss
works with C
to do the same for getting all of D's
packages.
Since we are working with an 8-byte pointer and dealing with heap allocation let's consider the following problem. Let's say that the Boss
is 100 feet from A
and that A
is 500 feet from C
. We don't need to worry about how far the Boss
is initially from C
because of the order of executions. In both cases, the Boss
initially travels from A
first then to B
. This analogy isn't to say that this distance is exact; it is just a useful test case scenario to show the workings of the algorithms.
In many cases when doing heap allocations and working with the cache and page files, these distances between address locations may not vary that much or they can vary significantly depending on the nature of the data types and the array sizes.
The Test Cases:
First Case: On first iteration the Boss
has to initially go 100 feet to give the order slip to A
and A
goes off and does his thing, but then the Boss
has to travel 500 feet to C
to give him his order slip. Then on the next iteration and every other iteration after the Boss
has to go back and forth 500 feet between the two.
Second Case: The Boss
has to travel 100 feet on the first iteration to A
, but after that, he is already there and just waits for A
to get back until all slips are filled. Then the Boss
has to travel 500 feet on the first iteration to C
because C
is 500 feet from A
. Since this Boss( Summation, For Loop )
is being called right after working with A
he then just waits there as he did with A
until all of C's
order slips are done.
The Difference In Distances Traveled
const n = 100000
distTraveledOfFirst = (100 + 500) + ((n-1)*(500 + 500);
// Simplify
distTraveledOfFirst = 600 + (99999*100);
distTraveledOfFirst = 600 + 9999900;
distTraveledOfFirst = 10000500;
// Distance Traveled On First Algorithm = 10,000,500ft
distTraveledOfSecond = 100 + 500 = 600;
// Distance Traveled On Second Algorithm = 600ft;
The Comparison of Arbitrary Values
We can easily see that 600 is far less than 10 million. Now, this isn't exact, because we don't know the actual difference in distance between which address of RAM or from which cache or page file each call on each iteration is going to be due to many other unseen variables. This is just an assessment of the situation to be aware of and looking at it from the worst-case scenario.
From these numbers it would almost appear as if algorithm one should be 99%
slower than algorithm two; however, this is only the Boss's
part or responsibility of the algorithms and it doesn't account for the actual workers A
, B
, C
, & D
and what they have to do on each and every iteration of the Loop. So the boss's job only accounts for about 15 - 40% of the total work being done. The bulk of the work that is done through the workers has a slightly bigger impact towards keeping the ratio of the speed rate differences to about 50-70%
The Observation: - The differences between the two algorithms
In this situation, it is the structure of the process of the work being done. It goes to show that Case 2 is more efficient from both the partial optimization of having a similar function declaration and definition where it is only the variables that differ by name and the distance traveled.
We also see that the total distance traveled in Case 1 is much farther than it is in Case 2 and we can consider this distance traveled our Time Factor between the two algorithms. Case 1 has considerable more work to do than Case 2 does.
This is observable from the evidence of the assembly instructions that were shown in both cases. Along with what was already stated about these cases, this doesn't account for the fact that in Case 1 the boss will have to wait for both A
& C
to get back before he can go back to A
again for each iteration. It also doesn't account for the fact that if A
or B
is taking an extremely long time then both the Boss
and the other worker(s) are idle waiting to be executed.
In Case 2 the only one being idle is the Boss
until the worker gets back. So even this has an impact on the algorithm.
The OP's Amended Question(s)
EDIT: The question turned out to be of no relevance, as the behavior severely depends on the sizes of the arrays (n) and the CPU cache. So if there is further interest, I rephrase the question:
Could you provide some solid insight into the details that lead to the different cache behaviors as illustrated by the five regions on the following graph?
It might also be interesting to point out the differences between CPU/cache architectures, by providing a similar graph for these CPUs.
Regarding These Questions
As I have demonstrated without a doubt, there is an underlying issue even before the Hardware and Software becomes involved.
Now as for the management of memory and caching along with page files, etc. which all work together in an integrated set of systems between the following:
We can already see that there is a bottleneck that is happening within the first algorithm before we even apply it to any machine with any arbitrary architecture, OS, and programmable language compared to the second algorithm. There already existed a problem before involving the intrinsics of a modern computer.
The Ending Results
However; it is not to say that these new questions are not of importance because they themselves are and they do play a role after all. They do impact the procedures and the overall performance and that is evident with the various graphs and assessments from many who have given their answer(s) and or comment(s).
If you paid attention to the analogy of the Boss
and the two workers A
& B
who had to go and retrieve packages from C
& D
respectively and considering the mathematical notations of the two algorithms in question; you can see without the involvement of the computer hardware and software Case 2
is approximately 60%
faster than Case 1
.
When you look at the graphs and charts after these algorithms have been applied to some source code, compiled, optimized, and executed through the OS to perform their operations on a given piece of hardware, you can even see a little more degradation between the differences in these algorithms.
If the Data
set is fairly small it may not seem all that bad of a difference at first. However, since Case 1
is about 60 - 70%
slower than Case 2
we can look at the growth of this function in terms of the differences in time executions:
DeltaTimeDifference approximately = Loop1(time) - Loop2(time)
//where
Loop1(time) = Loop2(time) + (Loop2(time)*[0.6,0.7]) // approximately
// So when we substitute this back into the difference equation we end up with
DeltaTimeDifference approximately = (Loop2(time) + (Loop2(time)*[0.6,0.7])) - Loop2(time)
// And finally we can simplify this to
DeltaTimeDifference approximately = [0.6,0.7]*Loop2(time)
This approximation is the average difference between these two loops both algorithmically and machine operations involving software optimizations and machine instructions.
When the data set grows linearly, so does the difference in time between the two. Algorithm 1 has more fetches than algorithm 2 which is evident when the Boss
has to travel back and forth the maximum distance between A
& C
for every iteration after the first iteration while algorithm 2 the Boss
has to travel to A
once and then after being done with A
he has to travel a maximum distance only one time when going from A
to C
.
Trying to have the Boss
focusing on doing two similar things at once and juggling them back and forth instead of focusing on similar consecutive tasks is going to make him quite angry by the end of the day since he had to travel and work twice as much. Therefore do not lose the scope of the situation by letting your boss getting into an interpolated bottleneck because the boss's spouse and children wouldn't appreciate it.
Amendment: Software Engineering Design Principles
-- The difference between local Stack and heap allocated computations within iterative for loops and the difference between their usages, their efficiencies, and effectiveness --
The mathematical algorithm that I proposed above mainly applies to loops that perform operations on data that is allocated on the heap.
So when you are working with data that needs to be on the heap and you are traversing through them in loops, it is more efficient to keep each data set and its corresponding algorithms within its own single loop. You will get better optimizations compared to trying to factor out consecutive loops by putting multiple operations of different data sets that are on the heap into a single loop.
It is okay to do this with data that is on the stack since they are frequently cached, but not for data that has to have its memory address queried every iteration.
This is where software engineering and software architecture design comes into play. It is the ability to know how to organize your data, knowing when to cache your data, knowing when to allocate your data on the heap, knowing how to design and implement your algorithms, and knowing when and where to call them.
You might have the same algorithm that pertains to the same data set, but you might want one implementation design for its stack variant and another for its heap-allocated variant just because of the above issue that is seen from its O(n)
complexity of the algorithm when working with the heap.
From what I've noticed over the years, many people do not take this fact into consideration. They will tend to design one algorithm that works on a particular data set and they will use it regardless of the data set being locally cached on the stack or if it was allocated on the heap.
If you want true optimization, yes it might seem like code duplication, but to generalize it would be more efficient to have two variants of the same algorithm. One for stack operations, and the other for heap operations that are performed in iterative loops!
Here's a pseudo example: Two simple structs, one algorithm.
struct A {
int data;
A() : data{0}{}
A(int a) : data{a}{}
};
struct B {
int data;
B() : data{0}{}
A(int b) : data{b}{}
}
template<typename T>
void Foo( T& t ) {
// Do something with t
}
// Some looping operation: first stack then heap.
// Stack data:
A dataSetA[10] = {};
B dataSetB[10] = {};
// For stack operations this is okay and efficient
for (int i = 0; i < 10; i++ ) {
Foo(dataSetA[i]);
Foo(dataSetB[i]);
}
// If the above two were on the heap then performing
// the same algorithm to both within the same loop
// will create that bottleneck
A* dataSetA = new [] A();
B* dataSetB = new [] B();
for ( int i = 0; i < 10; i++ ) {
Foo(dataSetA[i]); // dataSetA is on the heap here
Foo(dataSetB[i]); // dataSetB is on the heap here
} // this will be inefficient.
// To improve the efficiency above, put them into separate loops...
for (int i = 0; i < 10; i++ ) {
Foo(dataSetA[i]);
}
for (int i = 0; i < 10; i++ ) {
Foo(dataSetB[i]);
}
// This will be much more efficient than above.
// The code isn't perfect syntax, it's only psuedo code
// to illustrate a point.
This is what I was referring to by having separate implementations for stack variants versus heap variants. The algorithms themselves don't matter too much, it's the looping structures that you will use them in that do.
Add line:
import java.util.Scanner;
Then create an object of Scanner
class:
Scanner s = new Scanner(System.in);
Now you can call any time:
int a = Integer.parseInt(s.nextLine());
This will store integer
value from your keyboard.
There is a nice gem especially for uploading files : carrierwave. If the wiki does not help , there is a nice RailsCast about the best way to use it . Summarizing , there is a field type file
in Rails forms , which invokes the file upload dialog. You can use it , but the 'magic' is done by carrierwave
gem .
I don't know what do you mean with "how to write to a file" , but I hope this is a nice start.
path_src=./folder1
path_dst=./folder2
date=$(date +"%m%d%y")
for file_src in $path_src/*; do
file_dst="$path_dst/$(basename $file_src | \
sed "s/^\(.*\)\.\(.*\)/\1$date.\2/")"
echo mv "$file_src" "$file_dst"
done
I also realise this thread is old but I had a unique problem where, while converting the soon-to-be deprecated mysql driver to the PDO driver I had to make a function which could build, dynamically, both normal params and INs from the same param array. So I quickly built this:
/**
* mysql::pdo_query('SELECT * FROM TBL_WHOOP WHERE type_of_whoop IN :param AND siz_of_whoop = :size', array(':param' => array(1,2,3), ':size' => 3))
*
* @param $query
* @param $params
*/
function pdo_query($query, $params = array()){
if(!$query)
trigger_error('Could not query nothing');
// Lets get our IN fields first
$in_fields = array();
foreach($params as $field => $value){
if(is_array($value)){
for($i=0,$size=sizeof($value);$i<$size;$i++)
$in_array[] = $field.$i;
$query = str_replace($field, "(".implode(',', $in_array).")", $query); // Lets replace the position in the query string with the full version
$in_fields[$field] = $value; // Lets add this field to an array for use later
unset($params[$field]); // Lets unset so we don't bind the param later down the line
}
}
$query_obj = $this->pdo_link->prepare($query);
$query_obj->setFetchMode(PDO::FETCH_ASSOC);
// Now lets bind normal params.
foreach($params as $field => $value) $query_obj->bindValue($field, $value);
// Now lets bind the IN params
foreach($in_fields as $field => $value){
for($i=0,$size=sizeof($value);$i<$size;$i++)
$query_obj->bindValue($field.$i, $value[$i]); // Both the named param index and this index are based off the array index which has not changed...hopefully
}
$query_obj->execute();
if($query_obj->rowCount() <= 0)
return null;
return $query_obj;
}
It is still untested however the logic seems to be there.
Hope it helps someone in the same position,
Edit: After some testing I found out:
Code edited to working version.
Here is what needs to go in D1: =VLOOKUP(C1, $A$1:$B$4, 2, FALSE)
You should then be able to copy this down to the rest of column D.
You can create enums to deal with errors :)
enum RikhError: Error {
case unknownError
case connectionError
case invalidCredentials
case invalidRequest
case notFound
case invalidResponse
case serverError
case serverUnavailable
case timeOut
case unsuppotedURL
}
and then create a method inside enum to receive the http response code and return the corresponding error in return :)
static func checkErrorCode(_ errorCode: Int) -> RikhError {
switch errorCode {
case 400:
return .invalidRequest
case 401:
return .invalidCredentials
case 404:
return .notFound
//bla bla bla
default:
return .unknownError
}
}
Finally update your failure block to accept single parameter of type RikhError :)
I have a detailed tutorial on how to restructure traditional Objective - C based Object Oriented network model to modern Protocol Oriented model using Swift3 here https://learnwithmehere.blogspot.in Have a look :)
Hope it helps :)
I have a similar problem and the solution I am currently using uses Go 1.11 modules. I have the following structure
- projects
- go.mod
- go.sum
- project1
- main.go
- project2
- main.go
- package1
- lib.go
- package2
- lib.go
And I am able to import package1 and package2 from project1 and project2 by using
import (
"projects/package1"
"projects/package2"
)
After running go mod init projects
. I can use go build
from project1 and project2 directories or I can do go build -o project1/exe project1/*.go
from the projects directory.
The downside of this method is that all your projects end up sharing the same dependency list in go.mod. I am still looking for a solution to this problem, but it looks like it might be fundamental.
Installing the Chrome extension IE Tab did the job for me.
It has the ability to auto-detect URLs so whenever I browse to our SharePoint it emulates Internet Explorer. Finally I can open Office documents directly from Chrome.
You can install IETab for FireFox too.
This function checks for other types of whitespace, not just space (tab, carriage return, etc.)
import some from 'lodash/fp/some'
const whitespaceCharacters = [' ', ' ',
'\b', '\t', '\n', '\v', '\f', '\r', `\"`, `\'`, `\\`,
'\u0008', '\u0009', '\u000A', '\u000B', '\u000C',
'\u000D', '\u0020','\u0022', '\u0027', '\u005C',
'\u00A0', '\u2028', '\u2029', '\uFEFF']
const hasWhitespace = char => some(
w => char.indexOf(w) > -1,
whitespaceCharacters
)
console.log(hasWhitespace('a')); // a, false
console.log(hasWhitespace(' ')); // space, true
console.log(hasWhitespace(' ')); // tab, true
console.log(hasWhitespace('\r')); // carriage return, true
If you don't want to use Lodash, then here is a simple some
implementation with 2 s
:
const ssome = (predicate, list) =>
{
const len = list.length;
for(const i = 0; i<len; i++)
{
if(predicate(list[i]) === true) {
return true;
}
}
return false;
};
Then just replace some
with ssome
.
const hasWhitespace = char => some(
w => char.indexOf(w) > -1,
whitespaceCharacters
)
For those in Node, use:
const { some } = require('lodash/fp');
I faced the same problem and solve it by this method. html :
<div id="parentDiv">
<div id="childDiv">
AAA
</div>
BBBB
</div>
JS:
$(document).ready(function(){
$("#parentDiv").click(function(e){
if(e.target.id=="childDiv"){
childEvent();
} else {
parentEvent();
}
});
});
function childEvent(){
alert("child event");
}
function parentEvent(){
alert("paren event");
}
HTML 5 allows summary tag, details element. That can be used to view or hide (collapse/expand) a section. Link
getPath()
returns the path used to create the File
object. This return value is not changed based on the location it is run (results below are for windows, separators are obviously different elsewhere)
File f1 = new File("/some/path");
String path = f1.getPath(); // will return "\some\path"
File dir = new File("/basedir");
File f2 = new File(dir, "/some/path");
path = f2.getPath(); // will return "\basedir\some\path"
File f3 = new File("./some/path");
path = f3.getPath(); // will return ".\some\path"
getAbsolutePath()
will resolve the path based on the execution location or drive. So if run from c:\test
:
path = f1.getAbsolutePath(); // will return "c:\some\path"
path = f2.getAbsolutePath(); // will return "c:\basedir\some\path"
path = f3.getAbsolutePath(); // will return "c:\test\.\basedir\some\path"
getCanonicalPath()
is system dependent. It will resolve the unique location the path represents. So if you have any "."s in the path they will typically be removed.
As to when to use them. It depends on what you are trying to achieve. getPath()
is useful for portability. getAbsolutePath()
is useful to find the file system location, and getCanonicalPath()
is particularly useful to check if two files are the same.
First you need to think off when you want to swap. For example you could switch everytime when its a div tag thats loaded. In my example i just used a extra data field "background" and whenever its set the image is applied as a background image.
Then you just have to load the Data with the created image tag. And not overwrite the img tag instead apply a css background image.
Here is a example of the code change:
if (settings.appear) {
var elements_left = elements.length;
settings.appear.call(self, elements_left, settings);
}
var loadImgUri;
if($self.data("background"))
loadImgUri = $self.data("background");
else
loadImgUri = $self.data(settings.data_attribute);
$("<img />")
.bind("load", function() {
$self
.hide();
if($self.data("background")){
$self.css('backgroundImage', 'url('+$self.data("background")+')');
}else
$self.attr("src", $self.data(settings.data_attribute))
$self[settings.effect](settings.effect_speed);
self.loaded = true;
/* Remove image from array so it is not looped next time. */
var temp = $.grep(elements, function(element) {
return !element.loaded;
});
elements = $(temp);
if (settings.load) {
var elements_left = elements.length;
settings.load.call(self, elements_left, settings);
}
})
.attr("src", loadImgUri );
}
the loading stays the same
$("#divToLoad").lazyload();
and in this example you need to modify the html code like this:
<div data-background="http://apod.nasa.gov/apod/image/9712/orionfull_jcc_big.jpg" id="divToLoad" />?
but it would also work if you change the switch to div tags and then you you could work with the "data-original" attribute.
Here's an fiddle example: http://jsfiddle.net/dtm3k/1/
I had exactly the same issue and it was not cross domain but the same domain. I just added this line to the php file which was handling the ajax request.
<?php header('Access-Control-Allow-Origin: *'); ?>
It worked like a charm. Thanks to the poster
You may find that using the `group' aes will help you get the result you want. For example:
tu <- expand.grid(Land = gl(2, 1, labels = c("DE", "BB")),
Altersgr = gl(5, 1, labels = letters[1:5]),
Geschlecht = gl(2, 1, labels = c('m', 'w')),
Jahr = 2000:2009)
set.seed(42)
tu$Wert <- unclass(tu$Altersgr) * 200 + rnorm(200, 0, 10)
ggplot(tu, aes(x = Jahr, y = Wert, color = Altersgr, group = Altersgr)) +
geom_point() + geom_line() +
facet_grid(Geschlecht ~ Land)
Which produces the plot found here:
You can also use jQuery('.class-name').attr("href")
, in my case it works better.
Here more information: "jQuery(...)" instead of "$(...)"
Once you have a reference to your image, you can set its height and width like so:
var yourImg = document.getElementById('yourImgId');
if(yourImg && yourImg.style) {
yourImg.style.height = '100px';
yourImg.style.width = '200px';
}
In the html, it would look like this:
<img src="src/to/your/img.jpg" id="yourImgId" alt="alt tags are key!"/>
You can iterate DataTable
like this:
private void button1_Click(object sender, EventArgs e)
{
for(int i = 0; i< dt.Rows.Count;i++)
for (int j = 0; j <dt.Columns.Count ; j++)
{
object o = dt.Rows[i].ItemArray[j];
//if you want to get the string
//string s = o = dt.Rows[i].ItemArray[j].ToString();
}
}
Depending on the type of the data in the DataTable
cell, you can cast the object to whatever you want.