You can get this issue if Apple update their terms. Simply log into your dev account and accept any updated terms and you should be good (you will need to goto Xcode -> project->signing and capabilities and retry the certificate check. This should get you going if terms are the issue.
Another fix for Ionic 3 devs is to create build-extras.gradle inside platforms/android and put following
configurations.all {
resolutionStrategy {
force 'com.android.support:support-v4:27.1.0'
}
}
Note that build-extras.gradle is not the same as build.gradle
I was facing same issue and it is resolved by removing error from resource files like style, colors files in values folder. In my case, error in style colors as below:
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
<item name="android:textColorPrimary">**@color/colorPrimary**</item>
<item name="android:textColorSecondary">**@color/colorPrimaryDark**</item>
</style>
Used below code to set driver type based on need of Headless / Head for both Firefox and chrome:
// Can pass browser type
if brower.lower() == 'chrome':
driver = webdriver.Chrome('..\drivers\chromedriver')
elif brower.lower() == 'headless chrome':
ch_Options = Options()
ch_Options.add_argument('--headless')
ch_Options.add_argument("--disable-gpu")
driver = webdriver.Chrome('..\drivers\chromedriver',options=ch_Options)
elif brower.lower() == 'firefox':
driver = webdriver.Firefox(executable_path=r'..\drivers\geckodriver.exe')
elif brower.lower() == 'headless firefox':
ff_option = FFOption()
ff_option.add_argument('--headless')
ff_option.add_argument("--disable-gpu")
driver = webdriver.Firefox(executable_path=r'..\drivers\geckodriver.exe', options=ff_option)
elif brower.lower() == 'ie':
driver = webdriver.Ie('..\drivers\IEDriverServer')
else:
raise Exception('Invalid Browser Type')
The transform method signature changed somewhere in an RC of Angular 2. Try something more like this:
export class FilterPipe implements PipeTransform {
transform(items: any[], filterBy: string): any {
return items.filter(item => item.id.indexOf(filterBy) !== -1);
}
}
And if you want to handle nulls and make the filter case insensitive, you may want to do something more like the one I have here:
export class ProductFilterPipe implements PipeTransform {
transform(value: IProduct[], filterBy: string): IProduct[] {
filterBy = filterBy ? filterBy.toLocaleLowerCase() : null;
return filterBy ? value.filter((product: IProduct) =>
product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1) : value;
}
}
And NOTE: Sorting and filtering in pipes is a big issue with performance and they are NOT recommended. See the docs here for more info: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe
I had the same problem and this saved me from the problem in second:
write in console this:
npm i --save bluebird
npm i --save-dev @types/bluebird @types/[email protected]
in the file where the problem is copy paste this:
import * as Promise from 'bluebird';
In react-router-v4 you don't nest <Routes />
. Instead, you put them inside another <Component />
.
For instance
<Route path='/topics' component={Topics}>
<Route path='/topics/:topicId' component={Topic} />
</Route>
should become
<Route path='/topics' component={Topics} />
with
const Topics = ({ match }) => (
<div>
<h2>Topics</h2>
<Link to={`${match.url}/exampleTopicId`}>
Example topic
</Link>
<Route path={`${match.path}/:topicId`} component={Topic}/>
</div>
)
Here is a basic example straight from the react-router documentation.
Use localhost
instead of 127.0.0.1
(in your .env file), then run command:
php artisan config:cache
I want to mention that in some win 10 systems, Microsoft pre-installed a python. Thus, in order to invoke the python installed in the anaconda, you should adjust the order of the environment variable to ensure that the anaconda has a higher priority.
The changelog is sloppily worded. from __future__ import absolute_import
does not care about whether something is part of the standard library, and import string
will not always give you the standard-library module with absolute imports on.
from __future__ import absolute_import
means that if you import string
, Python will always look for a top-level string
module, rather than current_package.string
. However, it does not affect the logic Python uses to decide what file is the string
module. When you do
python pkg/script.py
pkg/script.py
doesn't look like part of a package to Python. Following the normal procedures, the pkg
directory is added to the path, and all .py
files in the pkg
directory look like top-level modules. import string
finds pkg/string.py
not because it's doing a relative import, but because pkg/string.py
appears to be the top-level module string
. The fact that this isn't the standard-library string
module doesn't come up.
To run the file as part of the pkg
package, you could do
python -m pkg.script
In this case, the pkg
directory will not be added to the path. However, the current directory will be added to the path.
You can also add some boilerplate to pkg/script.py
to make Python treat it as part of the pkg
package even when run as a file:
if __name__ == '__main__' and __package__ is None:
__package__ = 'pkg'
However, this won't affect sys.path
. You'll need some additional handling to remove the pkg
directory from the path, and if pkg
's parent directory isn't on the path, you'll need to stick that on the path too.
In my case, just using flex-shrink: 0
didn't work. But adding flex-grow: 1
to it worked.
.item {
flex-shrink: 0;
flex-grow: 1;
}
mydata$sCode
is a vector, it's why nrow output is NULL.mydata[mydata$sCode == 'CA',]
returns data.frame
where sCode == 'CA'
. sCode includes character. That's why sum
gives you the error.subset(mydata, sCode='CA', select=c(sCode))
, you should use sCode=='CA'
instead sCode='CA'
. Then subset returns you vector where sCode equals CA, so you should use
length(subset(na.omit(mydata), sCode='CA', select=c(sCode)))
Or you can try this: sum(na.omit(mydata$sCode) == "CA")
Just go to the folder path and type cmd on it. Then press ENTER enter image description here
For those who use Mac, edit this file:
/Applications/SQLDeveloper.app/Contents/MacOS/sqldeveloper.sh
Mine had:
export JAVA_HOME=`/usr/libexec/java_home -v 1.7`
and I changed it to 1.8 and it stopped complaining about java version.
Try this one, it works fine for me.
In CSS:
::-webkit-scrollbar
{
width: 0px;
}
::-webkit-scrollbar-track-piece
{
background-color: transparent;
-webkit-border-radius: 6px;
}
and here is the working demo: https://jsfiddle.net/qpvnecz5/
df.dropna(subset=['columnName1', 'columnName2'])
Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:
json: cannot unmarshal object into Go struct field Comment.author of type string
var data = {_x000D_
"items": [{_x000D_
"id": 1,_x000D_
"category": "cat1"_x000D_
}, {_x000D_
"id": 2,_x000D_
"category": "cat2"_x000D_
}, {_x000D_
"id": 3,_x000D_
"category": "cat1"_x000D_
}, {_x000D_
"id": 4,_x000D_
"category": "cat2"_x000D_
}, {_x000D_
"id": 5,_x000D_
"category": "cat1"_x000D_
}]_x000D_
};_x000D_
//Filters an array of numbers to include only numbers bigger then zero._x000D_
//Exact Data you want..._x000D_
var returnedData = $.grep(data.items, function(element) {_x000D_
return element.category === "cat1" && element.id === 3;_x000D_
}, false);_x000D_
console.log(returnedData);_x000D_
$('#id').text('Id is:-' + returnedData[0].id)_x000D_
$('#category').text('Category is:-' + returnedData[0].category)_x000D_
//Filter an array of numbers to include numbers that are not bigger than zero._x000D_
//Exact Data you don't want..._x000D_
var returnedOppositeData = $.grep(data.items, function(element) {_x000D_
return element.category === "cat1";_x000D_
}, true);_x000D_
console.log(returnedOppositeData);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<p id='id'></p>_x000D_
<p id='category'></p>
_x000D_
The $.grep()
method eliminates items from an array as necessary so that only remaining items carry a given search. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.
If I move
CreateUser.py
to the main user_management directory, I can easily use:import Modules.LDAPManager
to importLDAPManager.py
--- this works.
Please, don't. In this way the LDAPManager
module used by CreateUser
will not be the same as the one imported via other imports. This can create problems when you have some global state in the module or during pickling/unpickling. Avoid imports that work only because the module happens to be in the same directory.
When you have a package structure you should either:
Use relative imports, i.e if the CreateUser.py
is in Scripts/
:
from ..Modules import LDAPManager
Note that this was (note the past tense) discouraged by PEP 8 only because old versions of python didn't support them very well, but this problem was solved years ago. The current version of PEP 8 does suggest them as an acceptable alternative to absolute imports. I actually like them inside packages.
Use absolute imports using the whole package name(CreateUser.py
in Scripts/
):
from user_management.Modules import LDAPManager
In order for the second one to work the package user_management
should be installed inside the PYTHONPATH
. During development you can configure the IDE so that this happens, without having to manually add calls to sys.path.append
anywhere.
Also I find it odd that Scripts/
is a subpackage. Because in a real installation the user_management
module would be installed under the site-packages
found in the lib/
directory (whichever directory is used to install libraries in your OS), while the scripts should be installed under a bin/
directory (whichever contains executables for your OS).
In fact I believe Script/
shouldn't even be under user_management
. It should be at the same level of user_management
.
In this way you do not have to use -m
, but you simply have to make sure the package can be found (this again is a matter of configuring the IDE, installing the package correctly or using PYTHONPATH=. python Scripts/CreateUser.py
to launch the scripts with the correct path).
In summary, the hierarchy I would use is:
user_management (package)
|
|------- __init__.py
|
|------- Modules/
| |
| |----- __init__.py
| |----- LDAPManager.py
| |----- PasswordManager.py
|
Scripts/ (*not* a package)
|
|----- CreateUser.py
|----- FindUser.py
Then the code of CreateUser.py
and FindUser.py
should use absolute imports to import the modules:
from user_management.Modules import LDAPManager
During installation you make sure that user_management
ends up somewhere in the PYTHONPATH
, and the scripts inside the directory for executables so that they are able to find the modules. During development you either rely on IDE configuration, or you launch CreateUser.py
adding the Scripts/
parent directory to the PYTHONPATH
(I mean the directory that contains both user_management
and Scripts
):
PYTHONPATH=/the/parent/directory python Scripts/CreateUser.py
Or you can modify the PYTHONPATH
globally so that you don't have to specify this each time. On unix OSes (linux, Mac OS X etc.) you can modify one of the shell scripts to define the PYTHONPATH
external variable, on Windows you have to change the environmental variables settings.
Addendum I believe, if you are using python2, it's better to make sure to avoid implicit relative imports by putting:
from __future__ import absolute_import
at the top of your modules. In this way import X
always means to import the toplevel module X
and will never try to import the X.py
file that's in the same directory (if that directory isn't in the PYTHONPATH
). In this way the only way to do a relative import is to use the explicit syntax (the from . import X
), which is better (explicit is better than implicit).
This will make sure you never happen to use the "bogus" implicit relative imports, since these would raise an ImportError
clearly signalling that something is wrong. Otherwise you could use a module that's not what you think it is.
When installing make sure that under Tcl/Tk
you select Will be installed on hard drive
. If it is installing with a cross at the left then Tkinter will not be installed.
The same goes for Python 3:
It looks like this issue has to do with the difference between the Content-Type
and Accept
headers. In HTTP, Content-Type
is used in request and response payloads to convey the media type of the current payload. Accept
is used in request payloads to say what media types the server may use in the response payload.
So, having a Content-Type
in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type
does matter.
If a server is not able to process the Content-Type
of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept
header, it will return a 406 error.)
In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.
You could fix this in one of two ways:
Include the DataServiceVersion header in the request and set it be less than v3. For example:
DataServiceVersion: 2.0;
(Option 2 assumes that you aren't using any v3 features in your request payload.)
You could also make the ajax call more generic, reusable, so you can call it from different CRUD(create, read, update, delete) tasks for example and treat the success cases from those calls.
makePostCall = function (url, data) { // here the data and url are not hardcoded anymore
var json_data = JSON.stringify(data);
return $.ajax({
type: "POST",
url: url,
data: json_data,
dataType: "json",
contentType: "application/json;charset=utf-8"
});
}
// and here a call example
makePostCall("index.php?action=READUSERS", {'city' : 'Tokio'})
.success(function(data){
// treat the READUSERS data returned
})
.fail(function(sender, message, details){
alert("Sorry, something went wrong!");
});
Have you used the variable sum
anywhere else? That would explain it.
>>> sum = 1
>>> numbers = [1, 2, 3]
>>> numsum = (sum(numbers))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
The name sum
doesn't point to the function anymore now, it points to an integer.
Solution: Don't call your variable sum
, call it total
or something similar.
I am surprised the code answer is not posted already, it's a one liner.
You could just {{ categeory_id | getVariations }}
It's a one-liner:
$twig->addFilter('getVariations', new Twig_Filter_Function('getVariations'));
Just want to share with what I used so far to save your time.
Here are examples of hard-coded headers and dynamic headers (in case if don't care about data structure). In both cases I wrote some simple directive: customSort
customSort
.directive("customSort", function() {
return {
restrict: 'A',
transclude: true,
scope: {
order: '=',
sort: '='
},
template :
' <a ng-click="sort_by(order)" style="color: #555555;">'+
' <span ng-transclude></span>'+
' <i ng-class="selectedCls(order)"></i>'+
'</a>',
link: function(scope) {
// change sorting order
scope.sort_by = function(newSortingOrder) {
var sort = scope.sort;
if (sort.sortingOrder == newSortingOrder){
sort.reverse = !sort.reverse;
}
sort.sortingOrder = newSortingOrder;
};
scope.selectedCls = function(column) {
if(column == scope.sort.sortingOrder){
return ('icon-chevron-' + ((scope.sort.reverse) ? 'down' : 'up'));
}
else{
return'icon-sort'
}
};
}// end link
}
});
I used single ng-repeat
This is a good example in Fiddle (Notice, there is no jQuery library!)
<tbody>
<tr ng-repeat="item in pagedItems[currentPage] | orderBy:sortingOrder:reverse">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.description}}</td>
<td>{{item.field3}}</td>
<td>{{item.field4}}</td>
<td>{{item.field5}}</td>
</tr>
</tbody>
Demo 2: Fiddle
HTML
<table class="table table-striped table-condensed table-hover">
<thead>
<tr>
<th ng-repeat="header in table_headers"
class="{{header.name}}" custom-sort order="header.name" sort="sort"
>{{ header.name }}
</th>
</tr>
</thead>
<tfoot>
<td colspan="6">
<div class="pagination pull-right">
<ul>
<li ng-class="{disabled: currentPage == 0}">
<a href ng-click="prevPage()">« Prev</a>
</li>
<li ng-repeat="n in range(pagedItems.length, currentPage, currentPage + gap) "
ng-class="{active: n == currentPage}"
ng-click="setPage()">
<a href ng-bind="n + 1">1</a>
</li>
<li ng-class="{disabled: (currentPage) == pagedItems.length - 1}">
<a href ng-click="nextPage()">Next »</a>
</li>
</ul>
</div>
</td>
</tfoot>
<pre>pagedItems.length: {{pagedItems.length|json}}</pre>
<pre>currentPage: {{currentPage|json}}</pre>
<pre>currentPage: {{sort|json}}</pre>
<tbody>
<tr ng-repeat="item in pagedItems[currentPage] | orderBy:sort.sortingOrder:sort.reverse">
<td ng-repeat="val in item" ng-bind-html-unsafe="item[table_headers[$index].name]"></td>
</tr>
</tbody>
</table>
As a side note:
The ng-bind-html-unsafe
is deprecated, so I used it only for Demo (2nd example). You welcome to edit.
Try this:
find . -name "*.pdf" -type f -exec cp {} ./pdfsfolder \;
ok i spent some frustrating time with this problem too. My little guide.
Open desktop for example. If you didnt switch your disc in cmd, type:
cd desktop
Now if you want to display subfolders:
cd, make 1 spacebar, and press tab 2 times
Now if you want to enter directory/file with SPACE IN NAME. Lets open some file name f.g., to open it we need to type:
cd file\ name
p.s. notice this space after slash :)
You have to use GROUP BY
so you will have multiple records returned,
SELECT COUNT(*) TotalCount,
b.category_id,
b.category_name
FROM table1 a
INNER JOIN table2 b
ON a.category_id = b.category_id
WHERE a.colour <> 'red'
GROUP BY b.category_id, b.category_name
As Robert pointed out, quotation marks might do the trick for you:
git stash pop stash@"{1}"
Try this
COALESCE(NULLIF(Address.COUNTRY,''), 'United States')
timestamp=$(awk 'BEGIN {srand(); print srand()}')
srand without a value uses the current timestamp with most Awk implementations.
Abstraction and Encapsulation are confusing terms and dependent on each other. Let's take it by an example:
public class Person
{
private int Id { get; set; }
private string Name { get; set; }
private string CustomName()
{
return "Name:- " + Name + " and Id is:- " + Id;
}
}
When you created Person class, you did encapsulation by writing properties and functions together(Id, Name, CustomName). You perform abstraction when you expose this class to client as
Person p = new Person();
p.CustomName();
Your client doesn't know anything about Id and Name in this function. Now if, your client wants to know the last name as well without disturbing the function call. You do encapsulation by adding one more property into Person class like this.
public class Person
{
private int Id { get; set; }
private string Name { get; set; }
private string LastName {get; set;}
public string CustomName()
{
return "Name:- " + Name + " and Id is:- " + Id + "last name:- " + LastName;
}
}
Look, even after addding an extra property in class, your client doesn't know what you did to your code. This is where you did abstraction.
You should try the IE 5 quirks compatibility mod (is the default IE10 compatibility view)
<meta http-equiv="X-UA-Compatible" content="IE=5">
important: set in the top of your iframe structure (if you use iframe structure)
For the original issue, I would request you to apply below logic:
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPostRequest = new HttpPost();
Leave your email.php code the same, but replace this JavaScript code:
var name = $("#form_name").val();
var email = $("#form_email").val();
var text = $("#msg_text").val();
var dataString = 'name='+ name + '&email=' + email + '&text=' + text;
$.ajax({
type: "POST",
url: "email.php",
data: dataString,
success: function(){
$('.success').fadeIn(1000);
}
});
with this:
$.ajax({
type: "POST",
url: "email.php",
data: $(form).serialize(),
success: function(){
$('.success').fadeIn(1000);
}
});
So that your form input names match up.
THIS DOESN'T USE PIPEs, but requires a single tempfile
I used this to put simplified timestamps into a lowtech daily maintenance batfile
We have already Short-formatted our System-Time to HHmm, (which is 2245 for 10:45PM)
I direct output of Maint-Routines to logfiles with a $DATE%@%TIME% timestamp;
. . . but %TIME% is a long ugly string (ex. 224513.56, for down to the hundredths of a sec)
SOLUTION OVERVIEW:
1. Use redirection (">") to send the command "TIME /T" everytime to OVERWRITE a temp-file in the %TEMP% DIRECTORY
2. Then use that tempfile as the input to set a new variable (I called it NOW)
3. Replace
echo $DATE%@%TIME% blah-blah-blah >> %logfile%with
echo $DATE%@%NOW% blah-blah-blah >> %logfile%
SUCCESSFUL TIMESYNCH [email protected]AFTER:
SUCCESSFUL TIMESYNCH 29Dec14@2252
ACTUAL CODE:
TIME /T > %TEMP%\DailyTemp.txt SET /p NOW=<%TEMP%\DailyTemp.txt echo $DATE%@%NOW% blah-blah-blah >> %logfile%
AFTERMATH:
All that remains afterwards is the appended logfile, and constantly overwritten tempfile. And if the Tempfile is ever deleted, it will be re-created as necessary.
- Line Feed and Carriage Return
These HTML entities will insert a new line or carriage return inside a text area.
In relative layout you need specify textview height:
android:layout_height="100dp"
Or specify lines attribute:
android:lines="3"
Adding on to the one mentioned by @abarnert
a better one is to catch the exception
import subprocess
try:
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'],stderr= subprocess.STDOUT)
#print('py2 said:', py2output)
print "here"
except subprocess.CalledProcessError as e:
print "Calledprocerr"
this stderr= subprocess.STDOUT is for making sure you dont get the filenotfound error in stderr- which cant be usually caught in filenotfoundexception, else you would end up getting
python: can't open file 'py2.py': [Errno 2] No such file or directory
Infact a better solution to this might be to check, whether the file/scripts exist and then to run the file/script
An alternative way would be to create a new temporary table with same structure.
CREATE TABLE temp_table AS SELECT * FROM original_table LIMIT 0
Then create the primary key in the table.
ALTER TABLE temp_table ADD PRIMARY KEY (primary-key-field)
Finally copy all records from the original table while ignoring the duplicate records.
INSERT IGNORE INTO temp_table AS SELECT * FROM original_table
Now you can delete the original table and rename the new table.
DROP TABLE original_table
RENAME TABLE temp_table TO original_table
Also remember you can include custom indices to the array sent to the server like this
<form method='post' id='userform' action='thisform.php'>
<tr>
<td>Trouble Type</td>
<td>
<input type='checkbox' name='checkboxvar[4]' value='Option One'>4<br>
<input type='checkbox' name='checkboxvar[6]' value='Option Two'>6<br>
<input type='checkbox' name='checkboxvar[9]' value='Option Three'>9
</td>
</tr>
<input type='submit' class='buttons'>
</form>
This is particularly useful when you want to use the id
of individual objects in a server array accounts
(for instance) to send data back to the server and recognize same at server
<form method='post' id='userform' action='thisform.php'>
<tr>
<td>Trouble Type</td>
<td>
<?php foreach($accounts as $account) { ?>
<input type='checkbox' name='accounts[<?php echo $account->id ?>]' value='<?php echo $account->name ?>'>
<?php echo $account->name ?>
<br>
<?php } ?>
</td>
</tr>
<input type='submit' class='buttons'>
</form>
<?php
if (isset($_POST['accounts']))
{
print_r($_POST['accounts']);
}
?>
<ng-include src="'views/sidepanel.html'"></ng-include>
OR
<div ng-include="'views/sidepanel.html'"></div>
OR
<div ng-include src="'views/sidepanel.html'"></div>
Points To Remember:
--> No spaces in src
--> Remember to use single quotation in double quotation for src
Does this work for you?
eval repo forall -c '....$variable'
This should fulfill your requirements.
ABC:\s*(\(\D+\)\s*.*?)\\n
Here it is with some tests http://www.regexplanet.com/cookbook/ahJzfnJlZ2V4cGxhbmV0LWhyZHNyDgsSBlJlY2lwZRiEjiUM/index.html
Futher reading on regular expressions: http://www.regular-expressions.info/characters.html
This is based on Jim's answer,
SELECT
@field_text + SPACE(@pad_length - LEN(@field_text)) AS RightPad
,SPACE(@pad_length - LEN(@field_text)) + @field_text AS LeftPad
Advantages
Disadvantages
This is how I'm getting the N max rows per group in mysql
SELECT co.id, co.person, co.country
FROM person co
WHERE (
SELECT COUNT(*)
FROM person ci
WHERE co.country = ci.country AND co.id < ci.id
) < 1
;
how it works:
co.country = ci.country
) < 1
so for 3 elements - ) < 3co.id < ci.id
Full example here:
My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany
which explains how to do this with a @JoinColumn
annotation. In your case, i think you would want:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;
I've used a Set
rather than a List
, because the data itself is not ordered.
The above is using a defaulted referencedColumnName
, unlike the example in the wikibook. If that doesn't work, try an explicit one:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;
Answer : I found this and wants to share it with you.
Sub Copier4()
Dim x As Integer
For x = 1 To ActiveWorkbook.Sheets.Count
'Loop through each of the sheets in the workbook
'by using x as the sheet index number.
ActiveWorkbook.Sheets(x).Copy _
After:=ActiveWorkbook.Sheets(ActiveWorkbook.Sheets.Count)
'Puts all copies after the last existing sheet.
Next
End Sub
But the question, can we use it with following code to rename the sheets, if yes, how can we do so?
Sub CreateSheetsFromAList()
Dim MyCell As Range, MyRange As Range
Set MyRange = Sheets("Summary").Range("A10")
Set MyRange = Range(MyRange, MyRange.End(xlDown))
For Each MyCell In MyRange
Sheets.Add After:=Sheets(Sheets.Count) 'creates a new worksheet
Sheets(Sheets.Count).Name = MyCell.Value ' renames the new worksheet
Next MyCell
End Sub
create trigger doct_trigger
after delete on doctor
for each row
delete from patient where patient.PrimaryDoctor_SSN=doctor.SSN ;
You need to name the entity that holds the association to User. For example,
... INNER JOIN ug.user u ...
That's the "path" the error message is complaining about -- path from UserGroup to User entity.
Hibernate relies on declarative JOINs, for which the join condition is declared in the mapping metadata. This is why it is impossible to construct the native SQL query without having the path.
Try:
//category[@name='Sport' and ./author/text()='James Small']
Answer 1 worked perfectly for me. I tested it on a new MID 10' tablet. Here are the lines I added in the .inf file and it installed without a problem:
;Google MID
%SingleAdbInterface% = USB_INSTALL, USB\Vid_18d1&Pid_0003&MI_01
%CompositeAdbInterface% = USB_INSTALL, USB\Vid_18d1&Pid_0003&Rev_0230&MI_01
Are you trying to pass the command line arguments to the program AS you launch it? I am working on something right now that does exactly this, and it was a lot simpler than I thought. If I go into the command line, and type
C:\folder\app.exe/xC:\folder\file.txt
then my application launches, and creates a file in the specified directory with the specified name.
I wanted to do this through a Powershell script on a remote machine, and figured out that all I needed to do was put
$s = New-PSSession -computername NAME -credential LOGIN
Invoke-Command -session $s -scriptblock {C:\folder\app.exe /xC:\folder\file.txt}
Remove-PSSession $s
(I have a bunch more similar commands inside the session, this is just the minimum it requires to run) notice the space between the executable, and the command line arguments. It works for me, but I am not sure exactly how your application works, or if that is even how you pass arguments to it.
*I can also have my application push the file back to my own local computer by changing the script-block to
C:\folder\app.exe /x"\\LocalPC\DATA (C)\localfolder\localfile.txt"
You need the quotes if your file-path has a space in it.
EDIT: actually, this brought up some silly problems with Powershell launching the application as a service or something, so I did some searching, and figured out that you can call CMD to execute commands for you on the remote computer. This way, the command is carried out EXACTLY as if you had just typed it into a CMD window on the remote machine. Put the command in the scriptblock into double quotes, and then put a cmd.exe /C before it. like this:
cmd.exe /C "C:\folder\app.exe/xC:\folder\file.txt"
this solved all of the problems that I have been having recently.
EDIT EDIT: Had more problems, and found a much better way to do it.
start-process -filepath C:\folder\app.exe -argumentlist "/xC:\folder\file.txt"
and this doesn't hang up your terminal window waiting for the remote process to end. Just make sure you have a way to terminate the process if it doesn't do that on it's own. (mine doesn't, required the coding of another argument)
I think you can reset the invocations using Mockito.reset(mockLog). You should call this before every test, so inside @Before would be a good place.
Following document published by W3C also describes the differences between SOAP 1.1 and 1.2:
you can try this way in Colab
!git clone https://github.com/UKPLab/sentence-transformers.git
!pip install -e /content/sentence-transformers
import sentence_transformers
font-family:'Open Sans' , sans-serif;
For light:
font-weight : 100;
Or
font-weight : lighter;
For normal:
font-weight : 500;
Or
font-weight : normal;
For bold:
font-weight : 700;
Or
font-weight : bold;
For more bolder:
font-weight : 900;
Or
font-weight : bolder;
In the W3 wiki page about structuring HTML5, it says:
<section>
: Used to either group different articles into different purposes or subjects, or to define the different sections of a single article.
And then displays an image that I cleaned up:
It's also important to know how to use the <article>
tag (from the same W3 link above):
<article>
is related to<section>
, but is distinctly different. Whereas<section>
is for grouping distinct sections of content or functionality,<article>
is for containing related individual standalone pieces of content, such as individual blog posts, videos, images or news items. Think of it this way - if you have a number of items of content, each of which would be suitable for reading on their own, and would make sense to syndicate as separate items in an RSS feed, then<article>
is suitable for marking them up.In our example,
<section id="main">
contains blog entries. Each blog entry would be suitable for syndicating as an item in an RSS feed, and would make sense when read on its own, out of context, therefore<article>
is perfect for them:
<section id="main">
<article>
<!-- first blog post -->
</article>
<article>
<!-- second blog post -->
</article>
<article>
<!-- third blog post -->
</article>
</section>
Simple huh? Be aware though that you can also nest sections inside articles, where it makes sense to do so. For example, if each one of these blog posts has a consistent structure of distinct sections, then you could put sections inside your articles as well. It could look something like this:
<article>
<section id="introduction">
</section>
<section id="content">
</section>
<section id="summary">
</section>
</article>
If intake_date is some common date format you can use date()
and strtotime()
$mysqlDate = date('Y-m-d H:i:s', strtotime($_POST['intake_date']));
However, this will only work if the date format is accepted by strtotime()
. See it's doc page for supported formats.
Python 3.8 added functools.singledispatchmethod
Transform a method into a single-dispatch generic function.
To define a generic method, decorate it with the @singledispatchmethod decorator. Note that the dispatch happens on the type of the first non-self or non-cls argument, create your function accordingly:
from functools import singledispatchmethod
class Negator:
@singledispatchmethod
def neg(self, arg):
raise NotImplementedError("Cannot negate a")
@neg.register
def _(self, arg: int):
return -arg
@neg.register
def _(self, arg: bool):
return not arg
negator = Negator()
for v in [42, True, "Overloading"]:
neg = negator.neg(v)
print(f"{v=}, {neg=}")
Output
v=42, neg=-42
v=True, neg=False
NotImplementedError: Cannot negate a
@singledispatchmethod supports nesting with other decorators such as @classmethod. Note that to allow for dispatcher.register, singledispatchmethod must be the outer most decorator. Here is the Negator class with the neg methods being class bound:
from functools import singledispatchmethod
class Negator:
@singledispatchmethod
@staticmethod
def neg(arg):
raise NotImplementedError("Cannot negate a")
@neg.register
def _(arg: int) -> int:
return -arg
@neg.register
def _(arg: bool) -> bool:
return not arg
for v in [42, True, "Overloading"]:
neg = Negator.neg(v)
print(f"{v=}, {neg=}")
Output:
v=42, neg=-42
v=True, neg=False
NotImplementedError: Cannot negate a
The same pattern can be used for other similar decorators: staticmethod, abstractmethod, and others.
js-graph.it supports this use case, as seen by its getting started guide, supporting dragging elements without connection overlaps. Doesn't seem like it supports editing/creating connections. Doesn't seem it is maintained anymore.
TLDR:
CREATE TABLE MyTable(
a int NOT NULL
,b smallint NOT NULL index IX_indexName nonclustered
,c smallint NOT NULL
,d smallint NOT NULL
,e smallint NOT NULL
)
Details
As per T-SQL CREATE TABLE documentation, in 2014 the column definition supports defining an index:
<column_definition> ::=
column_name <data_type>
...
[ <column_index> ]
and <column_index> grammar is defined as:
<column_index> ::=
INDEX index_name [ CLUSTERED | NONCLUSTERED ]
[ WITH ( <index_option> [ ,... n ] ) ]
[ ON { partition_scheme_name (column_name )
| filegroup_name
| default
}
]
[ FILESTREAM_ON { filestream_filegroup_name | partition_scheme_name | "NULL" } ]
So a lot of what you can do as a separate statement can be done inline. I noticed include
is not an option in this grammar so some things are not possible.
CREATE TABLE MyTable(
a int NOT NULL
,b smallint NOT NULL index IX_indexName nonclustered
,c smallint NOT NULL
,d smallint NOT NULL
,e smallint NOT NULL
)
You can also have inline indexes defined as another line after columns, but within the create table statement, and this allows multiple columns in the index, but still no include
clause:
< table_index > ::=
{
{
INDEX index_name [ CLUSTERED | NONCLUSTERED ]
(column_name [ ASC | DESC ] [ ,... n ] )
| INDEX index_name CLUSTERED COLUMNSTORE
| INDEX index_name [ NONCLUSTERED ] COLUMNSTORE (column_name [ ,... n ] )
}
[ WITH ( <index_option> [ ,... n ] ) ]
[ ON { partition_scheme_name (column_name )
| filegroup_name
| default
}
]
[ FILESTREAM_ON { filestream_filegroup_name | partition_scheme_name | "NULL" } ]
}
For example here we add an index on both columns c and d:
CREATE TABLE MyTable(
a int NOT NULL
,b smallint NOT NULL index IX_MyTable_b nonclustered
,c smallint NOT NULL
,d smallint NOT NULL
,e smallint NOT NULL
,index IX_MyTable_c_d nonclustered (c,d)
)
After writing
header('HTTP/1.0 404 Not Found');
add one more header for any inexisting page on your site. It works, for sure.
header("Location: http://yoursite/nowhere");
die;
'HTTP_USER_AGENT' Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Among other things, you can use this value with get_browser() to tailor your page's output to the capabilities of the user agent.
So I assume you'll be able to get the browser name/id from the $_SERVER["HTTP_USER_AGENT"] variable.
To elaborate on @Marc B's answer,
$ passwd
$ while [ $? -ne 0 ]; do !!; done
Is nice way of doing the same thing that's not command specific.
Simple Override onBackPressed Method:
@Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
Try: Console.WriteLine
(type out
for a Visual Studio snippet)
Console.WriteLine(stuff);
Another way is to use System.Diagnostics.Debug.WriteLine
:
System.Diagnostics.Debug.WriteLine(stuff);
Debug.WriteLine
may suit better for Output window in IDE because it will be rendered for both Console and Windows applications. Whereas Console.WriteLine
won't be rendered in Output window but only in the Console itself in case of Console Application type.
Another difference is that Debug.WriteLine
will not print anything in Release configuration.
See: https://blogs.oracle.com/darcy/project-coin:-the-final-five-or-so (specifically "Elvis and other null safe operators").
The result is that this feature was considered for Java 7, but was not included.
Starting from Pylint v. 0.25.3, you can use the symbolic names for disabling warnings instead of having to remember all those code numbers. E.g.:
# pylint: disable=locally-disabled, multiple-statements, fixme, line-too-long
This style is more instructive than cryptic error codes, and also more practical since newer versions of Pylint only output the symbolic name, not the error code.
The correspondence between symbolic names and codes can be found here.
A disable comment can be inserted on its own line, applying the disable to everything that comes after in the same block. Alternatively, it can be inserted at the end of the line for which it is meant to apply.
If Pylint outputs "Locally disabling
" messages, you can get rid of them by including the disable locally-disabled
first as in the example above.
The "echo" command in PHP sends the output to the browser as raw html so even if in double quotes the browser will not parse it into two lines because a newline character in HTML means nothing. That's why you need to either use:
echo [output text]."<br>";
when using "echo", or instead use fwrite...
fwrite([output text]."\n");
This will output HTML newline in place of "\n".
Use alter session set current_schema = <username>
, in your case as an execute immediate.
See Oracle's documentation for further information.
In your case, that would probably boil down to (untested)
DECLARE
CURSOR client_cur IS
SELECT distinct username
from all_users
where length(username) = 3;
-- client cursor
CURSOR emails_cur IS
SELECT id, name
FROM org;
BEGIN
FOR client IN client_cur LOOP
-- ****
execute immediate
'alter session set current_schema = ' || client.username;
-- ****
FOR email_rec in client_cur LOOP
dbms_output.put_line(
'Org id is ' || email_rec.id ||
' org nam ' || email_rec.name);
END LOOP;
END LOOP;
END;
/
From your ant buildfile, I assume that what you want is to create a single JAR archive that will contain not only your application classes, but also the contents of other JARs required by your application.
However your build-jar
file is just putting required JARs inside your own JAR; this will not work as explained here (see note).
Try to modify this:
<jar destfile="${jar.file}"
basedir="${build.dir}"
manifest="${manifest.file}">
<fileset dir="${classes.dir}" includes="**/*.class" />
<fileset dir="${lib.dir}" includes="**/*.jar" />
</jar>
to this:
<jar destfile="${jar.file}"
basedir="${build.dir}"
manifest="${manifest.file}">
<fileset dir="${classes.dir}" includes="**/*.class" />
<zipgroupfileset dir="${lib.dir}" includes="**/*.jar" />
</jar>
More flexible and powerful solutions are the JarJar or One-Jar projects. Have a look into those if the above does not satisfy your requirements.
Your fundamental problem is that grep
works one line at a time - so it cannot find a SELECT statement spread across lines.
Your second problem is that the regex you are using doesn't deal with the complexity of what can appear between SELECT and FROM - in particular, it omits commas, full stops (periods) and blanks, but also quotes and anything that can be inside a quoted string.
I would likely go with a Perl-based solution, having Perl read 'paragraphs' at a time and applying a regex to that. The downside is having to deal with the recursive search - there are modules to do that, of course, including the core module File::Find.
In outline, for a single file:
$/ = "\n\n"; # Paragraphs
while (<>)
{
if ($_ =~ m/SELECT.*customerName.*FROM/mi)
{
printf file name
go to next file
}
}
That needs to be wrapped into a sub that is then invoked by the methods of File::Find.
@Bill Karwin describes three inheritance models in his SQL Antipatterns book, when proposing solutions to the SQL Entity-Attribute-Value antipattern. This is a brief overview:
Using a single table as in your first option is probably the simplest design. As you mentioned, many attributes that are subtype-specific will have to be given a NULL
value on rows where these attributes do not apply. With this model, you would have one policies table, which would look something like this:
+------+---------------------+----------+----------------+------------------+
| id | date_issued | type | vehicle_reg_no | property_address |
+------+---------------------+----------+----------------+------------------+
| 1 | 2010-08-20 12:00:00 | MOTOR | 01-A-04004 | NULL |
| 2 | 2010-08-20 13:00:00 | MOTOR | 02-B-01010 | NULL |
| 3 | 2010-08-20 14:00:00 | PROPERTY | NULL | Oxford Street |
| 4 | 2010-08-20 15:00:00 | MOTOR | 03-C-02020 | NULL |
+------+---------------------+----------+----------------+------------------+
\------ COMMON FIELDS -------/ \----- SUBTYPE SPECIFIC FIELDS -----/
Keeping the design simple is a plus, but the main problems with this approach are the following:
When it comes to adding new subtypes, you would have to alter the table to accommodate the attributes that describe these new objects. This can quickly become problematic when you have many subtypes, or if you plan to add subtypes on a regular basis.
The database will not be able to enforce which attributes apply and which don't, since there is no metadata to define which attributes belong to which subtypes.
You also cannot enforce NOT NULL
on attributes of a subtype that should be mandatory. You would have to handle this in your application, which in general is not ideal.
Another approach to tackle inheritance is to create a new table for each subtype, repeating all the common attributes in each table. For example:
--// Table: policies_motor
+------+---------------------+----------------+
| id | date_issued | vehicle_reg_no |
+------+---------------------+----------------+
| 1 | 2010-08-20 12:00:00 | 01-A-04004 |
| 2 | 2010-08-20 13:00:00 | 02-B-01010 |
| 3 | 2010-08-20 15:00:00 | 03-C-02020 |
+------+---------------------+----------------+
--// Table: policies_property
+------+---------------------+------------------+
| id | date_issued | property_address |
+------+---------------------+------------------+
| 1 | 2010-08-20 14:00:00 | Oxford Street |
+------+---------------------+------------------+
This design will basically solve the problems identified for the single table method:
Mandatory attributes can now be enforced with NOT NULL
.
Adding a new subtype requires adding a new table instead of adding columns to an existing one.
There is also no risk that an inappropriate attribute is set for a particular subtype, such as the vehicle_reg_no
field for a property policy.
There is no need for the type
attribute as in the single table method. The type is now defined by the metadata: the table name.
However this model also comes with a few disadvantages:
The common attributes are mixed with the subtype specific attributes, and there is no easy way to identify them. The database will not know either.
When defining the tables, you would have to repeat the common attributes for each subtype table. That's definitely not DRY.
Searching for all the policies regardless of the subtype becomes difficult, and would require a bunch of UNION
s.
This is how you would have to query all the policies regardless of the type:
SELECT date_issued, other_common_fields, 'MOTOR' AS type
FROM policies_motor
UNION ALL
SELECT date_issued, other_common_fields, 'PROPERTY' AS type
FROM policies_property;
Note how adding new subtypes would require the above query to be modified with an additional UNION ALL
for each subtype. This can easily lead to bugs in your application if this operation is forgotten.
This is the solution that @David mentions in the other answer. You create a single table for your base class, which includes all the common attributes. Then you would create specific tables for each subtype, whose primary key also serves as a foreign key to the base table. Example:
CREATE TABLE policies (
policy_id int,
date_issued datetime,
-- // other common attributes ...
);
CREATE TABLE policy_motor (
policy_id int,
vehicle_reg_no varchar(20),
-- // other attributes specific to motor insurance ...
FOREIGN KEY (policy_id) REFERENCES policies (policy_id)
);
CREATE TABLE policy_property (
policy_id int,
property_address varchar(20),
-- // other attributes specific to property insurance ...
FOREIGN KEY (policy_id) REFERENCES policies (policy_id)
);
This solution solves the problems identified in the other two designs:
Mandatory attributes can be enforced with NOT NULL
.
Adding a new subtype requires adding a new table instead of adding columns to an existing one.
No risk that an inappropriate attribute is set for a particular subtype.
No need for the type
attribute.
Now the common attributes are not mixed with the subtype specific attributes anymore.
We can stay DRY, finally. There is no need to repeat the common attributes for each subtype table when creating the tables.
Managing an auto incrementing id
for the policies becomes easier, because this can be handled by the base table, instead of each subtype table generating them independently.
Searching for all the policies regardless of the subtype now becomes very easy: No UNION
s needed - just a SELECT * FROM policies
.
I consider the class table approach as the most suitable in most situations.
The names of these three models come from Martin Fowler's book Patterns of Enterprise Application Architecture.
Your query should work for synonyms as well as the tables. However, you seem to expect indexes on views where there are not. Maybe is it materialized views ?
binascii methodes are easier by the way
>>> import binascii
>>> x=b'test'
>>> x=binascii.hexlify(x)
>>> x
b'74657374'
>>> y=str(x,'ascii')
>>> y
'74657374'
>>> x=binascii.unhexlify(x)
>>> x
b'test'
>>> y=str(x,'ascii')
>>> y
'test'
Hope it helps. :)
Try this code :
View view = LayoutInflater.from(context).inflate(R.layout.your_xml_layout,null); // Code for inflating xml layout_x000D_
RelativeLayout item = view.findViewById(R.id.item);
_x000D_
LinearLayout parent = findViewById(R.id.container); //parent layout._x000D_
View view = LayoutInflater.from(context).inflate(R.layout.your_xml_layout,parent,false); _x000D_
RelativeLayout item = view.findViewById(R.id.item); //initialize layout & By this you can also perform any event._x000D_
parent.addView(view); //adding your inflated layout in parent layout.
_x000D_
First you need to make sure that jQuery script is loaded. This could be from a CDN or local on your website. If you don't load this first before trying to use jQuery it will tell you that jQuery is not defined.
<script src="jquery.min.js"></script>
This could be in the HEAD or in the footer of the page, just make sure you load it before you try to call any other jQuery stuff.
Then you need to use one of the two solutions below
(function($){
// your standard jquery code goes here with $ prefix
// best used inside a page with inline code,
// or outside the document ready, enter code here
})(jQuery);
or
jQuery(document).ready(function($){
// standard on load code goes here with $ prefix
// note: the $ is setup inside the anonymous function of the ready command
});
please be aware that many times $(document).ready(function(){//code here}); will not work.
It is not possible to write exception-safe code under the assumption that "any line can throw". The design of exception-safe code relies critically on certain contracts/guarantees that you are supposed to expect, observe, follow and implement in your code. It is absolutely necessary to have code that is guaranteed to never throw. There are other kinds of exception guarantees out there.
In other words, creating exception-safe code is to a large degree a matter of program design not just a matter of plain coding.
Each node is named uniquely and knows who it is connected to. The List of connections allows for a Node to be connected to an arbitrary number of other nodes.
public class Node {
public String name;
public List<Edge> connections;
}
Each connection is directed, has a start and an end, and is weighted.
public class Edge {
public Node start;
public Node end;
public double weight;
}
A graph is just your collection of nodes. Instead of List<Node>
consider Map<String, Node>
for fast lookup by name.
public class Graph {
List<Node> nodes;
}
Even then however, getting a user's real IP address is going to be unreliable. All they need to do is use an anonymous proxy server (one that doesn't honor the headers for http_x_forwarded_for
, http_forwarded
, etc) and all you get is their proxy server's IP address.
You can then see if there is a list of proxy server IP addresses that are anonymous, but there is no way to be sure that is 100% accurate as well and the most it'd do is let you know it is a proxy server. And if someone is being clever, they can spoof headers for HTTP forwards.
Let's say I don't like the local college. I figure out what IP addresses they registered, and get their IP address banned on your site by doing bad things, because I figure out you honor the HTTP forwards. The list is endless.
Then there is, as you guessed, internal IP addresses such as the college network I metioned before. A lot use a 10.x.x.x format. So all you would know is that it was forwarded for a shared network.
Then I won't start much into it, but dynamic IP addresses are the way of broadband anymore. So. Even if you get a user IP address, expect it to change in 2 - 3 months, at the longest.
The problem with "converting" arbitrary Unicode to ASCII is that the meaning of a character is culture-dependent. For example, “ß” to a German-speaking person should be converted to "ss" while an English-speaker would probably convert it to “B”.
Add to that the fact that Unicode has multiple code points for the same glyphs.
The upshot is that the only way to do this is create a massive table with each Unicode character and the ASCII character you want to convert it to. You can take a shortcut by normalizing characters with accents to normalization form KD, but not all characters normalize to ASCII. In addition, Unicode does not define which parts of a glyph are "accents".
Here is a tiny excerpt from an app that does this:
switch (c)
{
case 'A':
case '\u00C0': // À LATIN CAPITAL LETTER A WITH GRAVE
case '\u00C1': // Á LATIN CAPITAL LETTER A WITH ACUTE
case '\u00C2': // Â LATIN CAPITAL LETTER A WITH CIRCUMFLEX
// and so on for about 20 lines...
return "A";
break;
case '\u00C6':// Æ LATIN CAPITAL LIGATURE AE
return "AE";
break;
// And so on for pages...
}
jQuery (1.4.2) gets confused if you have any form elements named "action". You can get around this by using the DOM attribute methods or simply avoid having form elements named "action".
<form action="foo">
<button name="action" value="bar">Go</button>
</form>
<script type="text/javascript">
$('form').attr('action', 'baz'); //this fails silently
$('form').get(0).setAttribute('action', 'baz'); //this works
</script>
If each file only has one sequence of aminoacids, I wouldn't use regular expressions at all. Just something like this:
def read_amino_acid_sequence(path):
with open(path) as sequence_file:
title = sequence_file.readline() # read 1st line
aminoacid_sequence = sequence_file.read() # read the rest
# some cleanup, if necessary
title = title.strip() # remove trailing white spaces and newline
aminoacid_sequence = aminoacid_sequence.replace(" ","").replace("\n","")
return title, aminoacid_sequence
I just thought I'd share this solution that I found to be working just fine.
I call it the Dummy Field (though I haven't invented this so don't credit me).
In short: you just have to insert this into your <form>
and check for it to be empty at when validating:
<input type="text" name="email" style="display:none" />
The trick is to fool a bot into thinking it has to insert data into a required field, that's why I named the input "email". If you already have a field called email that you're using you should try naming the dummy field something else like "company", "phone" or "emailaddress". Just pick something you know you don't need and what sounds like something people would normally find logical to fill in into a web form. Now hide the input
field using CSS or JavaScript/jQuery - whatever fits you best - just don't set the input type
to hidden
or else the bot won't fall for it.
When you are validating the form (either client or server side) check if your dummy field has been filled to determine if it was sent by a human or a bot.
Example:
In case of a human: The user will not see the dummy field (in my case named "email") and will not attempt to fill it. So the value of the dummy field should still be empty when the form has been sent.
In case of a bot: The bot will see a field whose type is text
and a name email
(or whatever it is you called it) and will logically attempt to fill it with appropriate data. It doesn't care if you styled the input form with some fancy CSS, web-developers do it all the time. Whatever the value in the dummy field is, we don't care as long as it's larger than 0
characters.
I used this method on a guestbook in combination with CAPTCHA, and I haven't seen a single spam post since. I had used a CAPTCHA-only solution before, but eventually, it resulted in about five spam posts every hour. Adding the dummy field in the form has stopped (at least until now) all the spam from appearing.
I believe this can also be used just fine with a login/authentication form.
Warning: Of course this method is not 100% foolproof. Bots can be programmed to ignore input fields with the style display:none
applied to it. You also have to think about people who use some form of auto-completion (like most browsers have built-in!) to auto-fill all form fields for them. They might just as well pick up a dummy field.
You can also vary this up a little by leaving the dummy field visible but outside the boundaries of the screen, but this is totally up to you.
Be creative!
Check the installation directories (typically C:\Program Files (x86)
or C:\Program Files
) for the java folder. If it contains the JRE you have java installed.
Ubuntu:
$ sudo vi /etc/default/locale
Add below setting at the end of file.
LC_ALL = en_US.UTF-8
Why not just use .show()/.hide()
instead?
$("#menu").hover(function(){
$('.flyout').show();
},function(){
$('.flyout').hide();
});
You could also set the default format for float :
pd.options.display.float_format = '{:.2%}'.format
Use '{:.2%}' instead of '{:.2f}%' - The former converts 0.41 to 41.00% (correctly), the latter to 0.41% (incorrectly)
<div class="container-fluid">
<div class="row">
<h3 class="one">Text</h3>
<button class="btn btn-secondary ml-auto">Button</button>
</div>
</div>
.ml-auto
is Bootstraph 4's non-flexbox way of aligning things.
It looks like you did not add a MySQL database to your application, OR you added it after you installed laravel. In that case, you need to stop & start (not restart) your application so that it will pick up your environment variables. (rhc app stop , rhc app start ). If you did not add a database yet, you will need to add one of the mysql cartridges, and then stop & start your application using the previously shown commands.
The const with the int on either sides will make pointer to constant int:
const int *ptr=&i;
or:
int const *ptr=&i;
const
after *
will make constant pointer to int:
int *const ptr=&i;
In this case all of these are pointer to constant integer, but none of these are constant pointer:
const int *ptr1=&i, *ptr2=&j;
In this case all are pointer to constant integer and ptr2 is constant pointer to constant integer. But ptr1 is not constant pointer:
int const *ptr1=&i, *const ptr2=&j;
The RemoveAll()
methods accept a Predicate<T>
delegate (until here nothing new). A predicate points to a method that simply returns true or false. Of course, the RemoveAll
will remove from the collection all the T
instances that return True with the predicate applied.
C# 3.0 lets the developer use several methods to pass a predicate to the RemoveAll
method (and not only this one…). You can use:
Lambda expressions
vehicles.RemoveAll(vehicle => vehicle.EnquiryID == 123);
Anonymous methods
vehicles.RemoveAll(delegate(Vehicle v) {
return v.EnquiryID == 123;
});
Normal methods
vehicles.RemoveAll(VehicleCustomPredicate);
private static bool
VehicleCustomPredicate (Vehicle v) {
return v.EnquiryID == 123;
}
You can use generic methods to replace any char with any char.
public static void removeWithAnyChar(String str, char replceChar,
char replaceWith) {
char chrs[] = str.toCharArray();
int i = 0;
while (i < chrs.length) {
if (chrs[i] == replceChar) {
chrs[i] = replaceWith;
}
i++;
}
}
I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int?
There isn't.
In my case, heredoc caused the issue. There is no problem with PHP version 7.3 up. Howerver, it error with PHP 7.0.33 if you use heredoc with space.
My example code
$rexpenditure = <<<Expenditure
<tr>
<td>$row->payment_referencenumber</td>
<td>$row->payment_requestdate</td>
<td>$row->payment_description</td>
<td>$row->payment_fundingsource</td>
<td>$row->payment_agencyulo</td>
<td>$row->payment_agencyproject</td>
<td>$$row->payment_disbustment</td>
<td>$row->payment_payeename</td>
<td>$row->payment_processpayment</td>
</tr>
Expenditure;
It will error if there is a space on PHP 7.0.33.
You need to redefine the unnamed struct during &Configuration{}
package main
import "fmt"
type Configuration struct {
Val string
Proxy struct {
Address string
Port string
}
}
func main() {
c := &Configuration{
Val: "test",
Proxy: struct {
Address string
Port string
}{
Address: "127.0.0.1",
Port: "8080",
},
}
fmt.Println(c)
}
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for item in my_list:
if (item.find('abc')) != -1:
print ('Found at ', item)
Maybe something like this?
var d = new Date();_x000D_
var v = new Date();_x000D_
v.setMinutes(d.getMinutes()+30);_x000D_
_x000D_
console.log(v)
_x000D_
Output on Windows 7 (64-bit)
SpecialFolder.CommonApplicationData: C:\ProgramData
SpecialFolder.CommonDesktopDirectory: C:\Users\Public\Desktop
SpecialFolder.CommonStartMenu: C:\ProgramData\Microsoft\Windows\Start Menu
SpecialFolder.CommonPrograms: C:\ProgramData\Microsoft\Windows\Start Menu\Programs
SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files
SpecialFolder.CommonProgramFilesX86: C:\Program Files (x86)\Common Files
SpecialFolder.CommonStartup: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
SpecialFolder.ProgramFiles: C:\Program Files
SpecialFolder.ProgramFilesX86: C:\Program Files (x86)
SpecialFolder.System: C:\Windows\system32
SpecialFolder.SystemX86: C:\Windows\SysWOW64
Output on Windows XP
SpecialFolder.CommonApplicationData: C:\Documents and Settings\All Users\Application Data
SpecialFolder.CommonDesktopDirectory: C:\Documents and Settings\All Users\Desktop
SpecialFolder.CommonPrograms: C:\Documents and Settings\All Users\Start Menu\Programs
SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files
SpecialFolder.CommonProgramFilesX86:
SpecialFolder.CommonStartMenu: C:\Documents and Settings\All Users\Start Menu
SpecialFolder.CommonStartup: C:\Documents and Settings\All Users\Start Menu\Programs\Startup
SpecialFolder.ProgramFiles: C:\Program Files
SpecialFolder.ProgramFilesX86:
SpecialFolder.System: C:\WINDOWS\system32
SpecialFolder.SystemX86: C:\WINDOWS\system32
Using the Func as mentioned above works but there are also delegates that do the same task and also define intent within the naming:
public delegate double MyFunction(double x);
public double Diff(double x, MyFunction f)
{
double h = 0.0000001;
return (f(x + h) - f(x)) / h;
}
public double MyFunctionMethod(double x)
{
// Can add more complicated logic here
return x + 10;
}
public void Client()
{
double result = Diff(1.234, x => x * 456.1234);
double secondResult = Diff(2.345, MyFunctionMethod);
}
Michael Kropats solution in VB.net
Private Function RandomString(ByVal length As Integer, Optional ByVal allowedChars As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") As String
If length < 0 Then Throw New ArgumentOutOfRangeException("length", "length cannot be less than zero.")
If String.IsNullOrEmpty(allowedChars) Then Throw New ArgumentException("allowedChars may not be empty.")
Dim byteSize As Integer = 256
Dim hash As HashSet(Of Char) = New HashSet(Of Char)(allowedChars)
'Dim hash As HashSet(Of String) = New HashSet(Of String)(allowedChars)
Dim allowedCharSet() = hash.ToArray
If byteSize < allowedCharSet.Length Then Throw New ArgumentException(String.Format("allowedChars may contain no more than {0} characters.", byteSize))
' Guid.NewGuid and System.Random are not particularly random. By using a
' cryptographically-secure random number generator, the caller is always
' protected, regardless of use.
Dim rng = New System.Security.Cryptography.RNGCryptoServiceProvider()
Dim result = New System.Text.StringBuilder()
Dim buf = New Byte(128) {}
While result.Length < length
rng.GetBytes(buf)
Dim i
For i = 0 To buf.Length - 1 Step +1
If result.Length >= length Then Exit For
' Divide the byte into allowedCharSet-sized groups. If the
' random value falls into the last group and the last group is
' too small to choose from the entire allowedCharSet, ignore
' the value in order to avoid biasing the result.
Dim outOfRangeStart = byteSize - (byteSize Mod allowedCharSet.Length)
If outOfRangeStart <= buf(i) Then
Continue For
End If
result.Append(allowedCharSet(buf(i) Mod allowedCharSet.Length))
Next
End While
Return result.ToString()
End Function
Great question!
There are many websites and free web apps implemented in PHP that run on Apache, lots of people use it so you can mash up something pretty easy and besides, its a no-brainer way of serving static content. Node is fast, powerful, elegant, and a sexy tool with the raw power of V8 and a flat stack with no in-built dependencies.
I also want the ease/flexibility of Apache and yet the grunt and elegance of Node.JS, why can't I have both?
Fortunately with the ProxyPass directive in the Apache httpd.conf
its not too hard to pipe all requests on a particular URL to your Node.JS application.
ProxyPass /node http://localhost:8000
Also, make sure the following lines are NOT commented out so you get the right proxy and submodule to reroute http requests:
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
Then run your Node app on port 8000!
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Apache!\n');
}).listen(8000, '127.0.0.1');
Then you can access all Node.JS logic using the /node/
path on your url, the rest of the website can be left to Apache to host your existing PHP pages:
Now the only thing left is convincing your hosting company let your run with this configuration!!!
Mine is using LOCATE
in mysql:
LOCATE(substr,str), LOCATE(substr,str,pos)
This function is multi-byte safe, and is case-sensitive only if at least one argument is a binary string.
In your case:
mysql_query("
SELECT * FROM `table`
WHERE LOCATE('{$needle}','column') > 0
");
for clarification open console application, just copy below code and paste it in static void Main(string[] args)
method, I hope you can understand
public class Program
{
static void Main(string[] args)
{
int result;
bool status;
string s1 = "12345";
Console.WriteLine("input1:12345");
string s2 = "1234.45";
Console.WriteLine("input2:1234.45");
string s3 = null;
Console.WriteLine("input3:null");
string s4 = "1234567899012345677890123456789012345667890";
Console.WriteLine("input4:1234567899012345677890123456789012345667890");
string s5 = string.Empty;
Console.WriteLine("input5:String.Empty");
Console.WriteLine();
Console.WriteLine("--------Int.Parse Methods Outputs-------------");
try
{
result = int.Parse(s1);
Console.WriteLine("OutPut1:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut1:"+ee.Message);
}
try
{
result = int.Parse(s2);
Console.WriteLine("OutPut2:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut2:" + ee.Message);
}
try
{
result = int.Parse(s3);
Console.WriteLine("OutPut3:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut3:" + ee.Message);
}
try
{
result = int.Parse(s4);
Console.WriteLine("OutPut4:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut4:" + ee.Message);
}
try
{
result = int.Parse(s5);
Console.WriteLine("OutPut5:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut5:" + ee.Message);
}
Console.WriteLine();
Console.WriteLine("--------Convert.To.Int32 Method Outputs-------------");
try
{
result= Convert.ToInt32(s1);
Console.WriteLine("OutPut1:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut1:" + ee.Message);
}
try
{
result = Convert.ToInt32(s2);
Console.WriteLine("OutPut2:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut2:" + ee.Message);
}
try
{
result = Convert.ToInt32(s3);
Console.WriteLine("OutPut3:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut3:" + ee.Message);
}
try
{
result = Convert.ToInt32(s4);
Console.WriteLine("OutPut4:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut4:" + ee.Message);
}
try
{
result = Convert.ToInt32(s5);
Console.WriteLine("OutPut5:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut5:" + ee.Message);
}
Console.WriteLine();
Console.WriteLine("--------TryParse Methods Outputs-------------");
try
{
status = int.TryParse(s1, out result);
Console.WriteLine("OutPut1:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut1:" + ee.Message);
}
try
{
status = int.TryParse(s2, out result);
Console.WriteLine("OutPut2:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut2:" + ee.Message);
}
try
{
status = int.TryParse(s3, out result);
Console.WriteLine("OutPut3:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut3:" + ee.Message);
}
try
{
status = int.TryParse(s4, out result);
Console.WriteLine("OutPut4:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut4:" + ee.Message);
}
try
{
status = int.TryParse(s5, out result);
Console.WriteLine("OutPut5:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut5:" + ee.Message);
}
Console.Read();
}
}
If all above point not work. Then try this one. I tried it. It's working for me.
UPDATE 2017
For new versions of apache the file is called apache2.conf
So to access the file, type sudo nano /etc/apache2/apache2.conf and change the correspondent line inside block <Directory /var/www >
if you check only null or empty then you can use the with default option for this:
<c:out default="var1 is empty or null." value="${var1}"/>
Some JavaScript engines can parse that format directly, which makes the task pretty easy:
function convertDate(inputFormat) {_x000D_
function pad(s) { return (s < 10) ? '0' + s : s; }_x000D_
var d = new Date(inputFormat)_x000D_
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')_x000D_
}_x000D_
_x000D_
console.log(convertDate('Mon Nov 19 13:29:40 2012')) // => "19/11/2012"
_x000D_
You may be victim of a garbage collection problem.
When your application requires memory and it's getting low on what it's configured to use the garbage collector will run often which consume a lot of CPU cycles. If it can't collect anything your memory will stay low so it will be run again and again. When you redeploy your application the memory is cleared and the garbage collection won't happen more than required so the CPU utilization stays low until it's full again.
You should check that there is no possible memory leak in your application and that it's well configured for memory (check the -Xmx
parameter, see What does Java option -Xmx stand for?)
Also, what are you using as web framework? JSF relies a lot on sessions and consumes a lot of memory, consider being stateless at most!
I would do this:
data["list"].append({'b':'2'})
so simply you are adding an object to the list that is present in "data"
The first parameter to the iterator in forEach
is the value and second is the key of the object.
angular.forEach(objectToIterate, function(value, key) {
/* do something for all key: value pairs */
});
In your example, the outer forEach is actually:
angular.forEach($scope.filters, function(filterObj , filterKey)
If you code your x axis text categories, list them in a single column, then in adjacent columns list plot points for respective variables against relevant text category code and just leave blank cells against non-relevant text category code, you can scatter plot and get the displayed result. Any questions let me know.
WebConfigurationManager.ConnectionStrings["YourConnectionString"].ProviderName;
Chrome did change their menus since this question was asked. This solution was tested with Chrome 47.0.2526.73 to 72.0.3626.109.
If you are using Chrome right now, you can check your version with : chrome://version
OLDER VERSIONS:
Scroll down to the bottom of the page and click on "Show advanced settings..." to show more settings.
OLDER VERSIONS:
In the "Network" section, click on "Change proxy settings...".
That's it.
I found that these instructions were not enough. I also had to search through the code files for models, controllers, and views as well as the AppStart files to change the namespace.
Since I was copying my project not just renaming it, I also had to go into the applicationhost.config for IIS express and recreate the bindings using different port numbers and change the physical directory as well.
we can use different types of system fonts like below
myButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
myButton.titleLabel?.font = UIFont.italicSystemFont(ofSize:UIFont.smallSystemFontSize)
myButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: UIFont.buttonFontSize)
and your custom font like below
myButton.titleLabel?.font = UIFont(name: "Helvetica", size:12)
I use numpy.insert(arr, i, the_object_to_be_added, axis)
in order to insert object_to_be_added
at the i'th row(axis=0)
or column(axis=1)
import numpy as np
a = np.array([[1, 2, 3], [5, 4, 6]])
# array([[1, 2, 3],
# [5, 4, 6]])
np.insert(a, 1, [55, 66], axis=1)
# array([[ 1, 55, 2, 3],
# [ 5, 66, 4, 6]])
np.insert(a, 2, [50, 60, 70], axis=0)
# array([[ 1, 2, 3],
# [ 5, 4, 6],
# [50, 60, 70]])
Too old discussion, but I hope it helps someone.
The straight answer was already given: Use !!
.
However newbies often tend to overuse this operator, which is expensive in Haskell (because you work on single linked lists, not on arrays). There are several useful techniques to avoid this, the easiest one is using zip. If you write zip ["foo","bar","baz"] [0..]
, you get a new list with the indices "attached" to each element in a pair: [("foo",0),("bar",1),("baz",2)]
, which is often exactly what you need.
Could not get IE9 to center the dialog.
Fixed it by adding this to the css:
.ui-dialog {
left:1%;
right:1%;
}
Percent doesn't matter. Any small number worked.
Step 1: Build a checked/unchecked selector:
selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/yellow" android:state_checked="true" />
<item android:color="@color/white" android:state_checked="false" />
</selector>
Step 2: use the xml attribute app:itemTextColor
within NavigationView
widget for selecting the text color.
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/navigation_header_layout"
app:itemTextColor="@drawable/selector"
app:menu="@menu/navigation_menu" />
Step 3:
For some reason when you hit an item from the NavigationView
menu, it doesn't consider this as a button check. So you need to manually get the selected item checked and clear the previously selected item. Use below listener to do that
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
// remove all colors of the items to the `unchecked` state of the selector
removeColor(mNavigationView);
// check the selected item to change its color set by the `checked` state of the selector
item.setChecked(true);
switch (item.getItemId()) {
case R.id.dashboard:
...
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
private void removeColor(NavigationView view) {
for (int i = 0; i < view.getMenu().size(); i++) {
MenuItem item = view.getMenu().getItem(i);
item.setChecked(false);
}
}
Step 4:
To change icon color, use the app:iconTint
attribute in the NavigationView
menu items, and set to the same selector.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/nav_account"
android:checked="true"
android:icon="@drawable/ic_person_black_24dp"
android:title="My Account"
app:iconTint="@drawable/selector" />
<item
android:id="@+id/nav_settings"
android:icon="@drawable/ic_settings_black_24dp"
android:title="Settings"
app:iconTint="@drawable/selector" />
<item
android:id="@+id/nav_logout"
android:icon="@drawable/logout"
android:title="Log Out"
app:iconTint="@drawable/selector" />
</menu>
Result:
HttpBasicAuth works for me with smaller changes
I use maven dependency
<dependency>
<groupId>net.iharder</groupId>
<artifactId>base64</artifactId>
<version>2.3.8</version>
</dependency>
Smaller change
String encoding = Base64.encodeBytes ((user + ":" + passwd).getBytes());
context.deleteDatabase("database_name.db");
This might help someone. You have to mention the extension otherwise, it will not work.
I see that you’re trying to export SQL data to Excel to avoid copy-pasting your very large data set into Excel.
You might be interested in learning how to export SQL data to Excel and update the export automatically (with any SQL database: MySQL, Microsoft SQL Server, PostgreSQL).
?
I find answer. Thanks all but right answer next:
$("#myModal").on("hidden", function () {
$('#result').html('yes,result');
});
Events here http://bootstrap-ru.com/javascript.php#modals
UPD
For Bootstrap 3.x need use hidden.bs.modal:
$("#myModal").on("hidden.bs.modal", function () {
$('#result').html('yes,result');
});
Let's say that you have:
#include <iostream>
double foo(double x)
{
asm("# MyTag BEGIN"); // <- asm comment,
// used later to locate piece of code
double y = 2 * x + 1;
asm("# MyTag END");
return y;
}
int main()
{
std::cout << foo(2);
}
To get assembly code using gcc you can do:
g++ prog.cpp -c -S -o - -masm=intel | c++filt | grep -vE '\s+\.'
c++filt
demangles symbols
grep -vE '\s+\.'
removes some useless information
Now if you want to visualize the tagged part, simply use:
g++ prog.cpp -c -S -o - -masm=intel | c++filt | grep -vE '\s+\.' | grep "MyTag BEGIN" -A 20
With my computer I get:
# MyTag BEGIN
# 0 "" 2
#NO_APP
movsd xmm0, QWORD PTR -24[rbp]
movapd xmm1, xmm0
addsd xmm1, xmm0
addsd xmm0, xmm1
movsd QWORD PTR -8[rbp], xmm0
#APP
# 9 "poub.cpp" 1
# MyTag END
# 0 "" 2
#NO_APP
movsd xmm0, QWORD PTR -8[rbp]
pop rbp
ret
.LFE1814:
main:
.LFB1815:
push rbp
mov rbp, rsp
A more friendly approach is to use: Compiler Explorer
In Android Studio 4.0.1, Help -> About shows the details of the Java version used by the studio, in my case:
Android Studio 4.0.1
Build #AI-193.6911.18.40.6626763, built on June 25, 2020
Runtime version: 1.8.0_242-release-1644-b01 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0
GC: ParNew, ConcurrentMarkSweep
Memory: 1237M
Cores: 8
Registry: ide.new.welcome.screen.force=true
Non-Bundled Plugins: com.google.services.firebase
use this for open pdf file in webview
NSString *path = [[NSBundle mainBundle] pathForResource:@"mypdf" ofType:@"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
UIWebView *webView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
[[webView scrollView] setContentOffset:CGPointMake(0,500) animated:YES];
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.scrollTo(0.0, 50.0)"]];
[webView loadRequest:request];
[self.view addSubview:webView];
[webView release];
For Ubuntu:
sudo apt-get install ca-certificates
Hit this problem trying to curl things as ROOT inside of Dockerfile
This works for me:
window.onload = function() {
// short timeout
setTimeout(function() {
$(document.body).scrollTop(0);
}, 15);
};
Uses a short setTimeout
inside the onload
to give the browser a chance to do the scroll.
var handle = setInterval(changeIframe, 30000);
var sites = ["google.com", "yahoo.com"];
var index = 0;
function changeIframe() {
$('#frame')[0].src = sites[index++];
index = index >= sites.length ? 0 : index;
}
RandomStringUtils
from Apache commons-lang might help:
RandomStringUtils.randomAlphanumeric(17).toUpperCase()
2017 update: RandomStringUtils
has been deprecated, you should now use RandomStringGenerator.
Why is $observe different than $watch?
The watchExpression is evaluated and compared to the previous value each digest() cycle, if there's a change in the watchExpression value, the watch function is called.
$observe is specific to watching for interpolated values. If a directive's attribute value is interpolated, eg dir-attr="{{ scopeVar }}"
, the observe function will only be called when the interpolated value is set (and therefore when $digest has already determined updates need to be made). Basically there's already a watcher for the interpolation, and the $observe function piggybacks off that.
See $observe & $set in compile.js
You can also check using a environment variable:
echo $HOSTTYPE
Result:
i386
-> 32 bits
x86_64
-> 64 bits
Extracted from: http://www.sysadmit.com/2016/02/linux-como-saber-si-es-32-o-64-bits.html
addToCart(docId: string, prodId: string): Promise<void> {
return this.baseAngularFirestore.collection('carts').doc(docId).update({
products:
firestore.FieldValue.arrayUnion({
productId: prodId,
qty: 1
}),
});
}
I recently got this message, too, after I switched the data center location of a web application sending through Google SMTP.
The URL that apparently Google means is: https://support.google.com/mail/answer/78754. At that link, one of the steps is to reset your password. Not coincidentally, I also received an email from google with a subject of "Suspicious sign in prevented" that instructed me to change my password.
After resetting my password, I was back to using Google SMTP as usual.
func simpleIndex(ofDate: Date) -> Int {
// index here just means today 0, yesterday -1, tomorrow 1 etc.
let c = Calendar.current
let todayRightNow = Date()
let d = c.date(bySetting: .hour, value: 13, of: ofDate)
let t = c.date(bySetting: .hour, value: 13, of: todayRightNow)
if d == nil || today == nil {
print("weird problem simpleIndex#ofDate")
return 0
}
let r = c.dateComponents([.day], from: today!, to: d!)
// yesterday is negative one, tomorrow is one
if let o = r.value(for: .day) {
return o
}
else {
print("another weird problem simpleIndex#ofDate")
return 0
}
}
The answer above covers everything in great detail, apart from a couple of things.
First, if there are no styles, then the (Context context, AttributeSet attrs)
method signature will be used to instantiate the preference. In this case just use context.obtainStyledAttributes(attrs, R.styleable.MyCustomView)
to get the TypedArray.
Secondly it does not cover how to deal with plaurals resources (quantity strings). These cannot be dealt with using TypedArray. Here is a code snippet from my SeekBarPreference that sets the summary of the preference formatting its value according to the value of the preference. If the xml for the preference sets android:summary to a text string or a string resouce the value of the preference is formatted into the string (it should have %d in it, to pick up the value). If android:summary is set to a plaurals resource, then that is used to format the result.
// Use your own name space if not using an android resource.
final static private String ANDROID_NS =
"http://schemas.android.com/apk/res/android";
private int pluralResource;
private Resources resources;
private String summary;
public SeekBarPreference(Context context, AttributeSet attrs) {
// ...
TypedArray attributes = context.obtainStyledAttributes(
attrs, R.styleable.SeekBarPreference);
pluralResource = attrs.getAttributeResourceValue(ANDROID_NS, "summary", 0);
if (pluralResource != 0) {
if (! resources.getResourceTypeName(pluralResource).equals("plurals")) {
pluralResource = 0;
}
}
if (pluralResource == 0) {
summary = attributes.getString(
R.styleable.SeekBarPreference_android_summary);
}
attributes.recycle();
}
@Override
public CharSequence getSummary() {
int value = getPersistedInt(defaultValue);
if (pluralResource != 0) {
return resources.getQuantityString(pluralResource, value, value);
}
return (summary == null) ? null : String.format(summary, value);
}
notifyChanged()
in the preference's onDialogClosed
method.If you have a component with multiple elements inside of the root element you can use this It just works™ solution with a boolean.
<template>
<div @click="clickInside"></div>
<template>
<script>
export default {
name: "MyComponent",
methods: {
clickInside() {
this.inside = true;
setTimeout(() => (this.inside = false), 0);
},
clickOutside() {
if (this.inside) return;
// handle outside state from here
}
},
created() {
this.__handlerRef__ = this.clickOutside.bind(this);
document.body.addEventListener("click", this.__handlerRef__);
},
destroyed() {
document.body.removeEventListener("click", this.__handlerRef__);
},
};
</script>
Because you want to set it when the form loads, you have to first .Show() the form before you can call the .Focus() method. The form cannot take focus in the Load event until you show the form
Private Sub RibbonForm1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.Show()
TextBox1.Select()
End Sub
Via css. Put this inside the <head>
tag.
<style type="text/css" media="screen">
table{
border-collapse:collapse;
border:1px solid #FF0000;
}
table td{
border:1px solid #FF0000;
}
</style>
It depends. You could
string.match(/^abc$/)
But that would not match the following string: 'the first 3 letters of the alphabet are abc. not abc123'
I think you would want to use \b
(word boundaries):
var str = 'the first 3 letters of the alphabet are abc. not abc123';_x000D_
var pat = /\b(abc)\b/g;_x000D_
console.log(str.match(pat));
_x000D_
Live example: http://jsfiddle.net/uu5VJ/
If the former solution works for you, I would advise against using it.
That means you may have something like the following:
var strs = ['abc', 'abc1', 'abc2']
for (var i = 0; i < strs.length; i++) {
if (strs[i] == 'abc') {
//do something
}
else {
//do something else
}
}
While you could use
if (str[i].match(/^abc$/g)) {
//do something
}
It would be considerably more resource-intensive. For me, a general rule of thumb is for a simple string comparison use a conditional expression, for a more dynamic pattern use a regular expression.
More on JavaScript regexes: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
This is a optimized version of the function which removes dependency on BitConverter function and makes it compatible with NETMF (.NET Micro Framework)
public static DateTime GetNetworkTime()
{
const string ntpServer = "pool.ntp.org";
var ntpData = new byte[48];
ntpData[0] = 0x1B; //LeapIndicator = 0 (no warning), VersionNum = 3 (IPv4 only), Mode = 3 (Client Mode)
var addresses = Dns.GetHostEntry(ntpServer).AddressList;
var ipEndPoint = new IPEndPoint(addresses[0], 123);
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Connect(ipEndPoint);
socket.Send(ntpData);
socket.Receive(ntpData);
socket.Close();
ulong intPart = (ulong)ntpData[40] << 24 | (ulong)ntpData[41] << 16 | (ulong)ntpData[42] << 8 | (ulong)ntpData[43];
ulong fractPart = (ulong)ntpData[44] << 24 | (ulong)ntpData[45] << 16 | (ulong)ntpData[46] << 8 | (ulong)ntpData[47];
var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
var networkDateTime = (new DateTime(1900, 1, 1)).AddMilliseconds((long)milliseconds);
return networkDateTime;
}
I don't think there is a way to do that out-of-the-box. A possibly cleaner solution would be:
Stream.of(objects)
.filter(c -> c instanceof Client)
.map(c -> (Client) c)
.map(Client::getID)
.forEach(System.out::println);
or, as suggested in the comments, you could use the cast
method - the former may be easier to read though:
Stream.of(objects)
.filter(Client.class::isInstance)
.map(Client.class::cast)
.map(Client::getID)
.forEach(System.out::println);
As of Rails 5.0.0.beta4 you can use the new String#upcase_first
method or ActiveSupport::Inflector#upcase_first
to do it. Check this blog post for more info.
Reference article: Show red color border for invalid input fields angualrjs
I used ng-class on all input fields.like below
<input type="text" ng-class="{submitted:newEmployee.submitted}" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/>
when I click on save button I am changing newEmployee.submitted value to true(you can check it in my question). So when I click on save, a class named submitted gets added to all input fields(there are some other classes initially added by angularjs).
So now my input field contains classes like this
class="ng-pristine ng-invalid submitted"
now I am using below css code to show red border on all invalid input fields(after submitting the form)
input.submitted.ng-invalid
{
border:1px solid #f00;
}
Thank you !!
Update:
We can add the ng-class at the form element instead of applying it to all input elements. So if the form is submitted, a new class(submitted) gets added to the form element. Then we can select all the invalid input fields using the below selector
form.submitted .ng-invalid
{
border:1px solid #f00;
}
Here is another method of forcing a file to view in the browser in PHP:
$extension = pathinfo($file_name, PATHINFO_EXTENSION);
$url = 'uploads/'.$file_name;
echo '<html>'
.header('Content-Type: application/'.$extension).'<br>'
.header('Content-Disposition: inline; filename="'.$file_name.'"').'<br>'
.'<body>'
.'<object style="overflow: hidden; height: 100%;
width: 100%; position: absolute;" height="100%" width="100%" data="'.$url.'" type="application/'.$extension.'">
<embed src="'.$url.'" type="application/'.$extension.'" />
</object>'
.'</body>'
. '</html>';
simple way to use modals is with eModal!
Ex from github:
<script src="//rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>
var options = {_x000D_
message: "The famouse question?",_x000D_
title: 'Header title',_x000D_
size: 'sm',_x000D_
callback: function(result) { result ? doActionTrue(result) : doActionFalse(); },_x000D_
subtitle: 'smaller text header',_x000D_
label: "True" // use the possitive lable as key_x000D_
//..._x000D_
};_x000D_
_x000D_
eModal.confirm(options);
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>_x000D_
<script src="//rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>
_x000D_
Tip: You can use change the default label name! { label: 'Yes' | 'True'| 'OK' }
Can be done with in jquery-
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#dialog" ).dialog();
});
</script>
<div id="dialog" title="Basic dialog">
//your form layout
</div>
It depends on the likelihood of a semicolon ending up near your &
, causing it to display something quite different.
For example, when dealing with input from users (say, if you include the user-provided subject of a forum post in your title tags), you never know where they might be putting random semicolons, and it might randomly display strange entities. So always escape in that situation.
For your own static html, sure, you could skip it, but it's so trivial to include proper escaping, that there's no good reason to avoid it.
You need to use the fitBounds()
method.
var markers = [];//some array
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i]);
}
map.fitBounds(bounds);
Documentation from developers.google.com/maps/documentation/javascript:
fitBounds(bounds[, padding])
Parameters:
`bounds`: [`LatLngBounds`][1]|[`LatLngBoundsLiteral`][1] `padding` (optional): number|[`Padding`][1]
Return Value: None
Sets the viewport to contain the given bounds.
Note: When the map is set todisplay: none
, thefitBounds
function reads the map's size as0x0
, and therefore does not do anything. To change the viewport while the map is hidden, set the map tovisibility: hidden
, thereby ensuring the map div has an actual size.
Structure and class are user defied data types
By default, structure is a public whereas class is private
Class implements the principal of encapsulation
Objects of a class are created on the heap memory
Class is used for re usability whereas structure is used for grouping the data in the same structure
Structure data members cannot be initialized directly but they can be assigned by the outside the structure
Class data members can be initialized directly by the parameter less constructor and assigned by the parameterized constructor
require 'json'
out=JSON.parse(input)
This will return a Hash
Timeit has two big flaws: it doesn't return the return value of the function, and it uses eval, which requires passing in extra setup code for imports. This solves both problems simply and elegantly:
def timed(f):
start = time.time()
ret = f()
elapsed = time.time() - start
return ret, elapsed
timed(lambda: database.foo.execute('select count(*) from source.apachelog'))
(<sqlalchemy.engine.result.ResultProxy object at 0x7fd6c20fc690>, 4.07547402381897)
First try to understand how Entity Framework Connection string works then you will get idea of what is wrong.
Another alternative is, you can create your own constructor for your context and pass your own connection string and you can write some if condition etc to load defaults from web.config
Better thing would be to do is, leave connection strings as it is, give your application pool an identity that will have access to your database server and do not include username and password inside connection string.
What's wrong with your code? I find it to be quite elegant and simple. The only problem is that if the file doesn't end in a newline, the last line returned won't have a '\n'
as the last character, and therefore doing line = line[:-1]
would incorrectly strip off the last character of the line.
The most elegant way to solve this problem would be to define a generator which took the lines of the file and removed the last character from each line only if that character is a newline:
def strip_trailing_newlines(file):
for line in file:
if line[-1] == '\n':
yield line[:-1]
else:
yield line
f = open("myFile.txt", "r")
for line in strip_trailing_newlines(f):
# do something with line
Best practice: one form per product is definitely the way to go.
Benefits:
In your specific situation
If you only ever intend to have one form element, in this case a submit
button, one form for all should work just fine.
My recommendation Do one form per product, and change your markup to something like:
<form method="post" action="">
<input type="hidden" name="product_id" value="123">
<button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>
This will give you a much cleaner and usable POST
. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).
Note: There's no technical benefit to using
<button>
vs.<input>
, but as a programmer I find it cooler to work withaction=='add_to_cart'
thanaction=='Add to Cart'
. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.
JPEG will have poor quality around sharp edges etc. and for this reason it is unsuitable for most web graphics. It excels at photographs.
Compared to GIF, PNG offers better compression, larger pallette and more features, including transparency. And it is lossless.
`CREATE TRIGGER `category_before_ins_tr` BEFORE INSERT ON `category`
FOR EACH ROW
BEGIN
**SET @tableId= (SELECT id FROM dummy LIMIT 1);**
END;`;
my datagridview is editonEnter mode . so it refresh only after i leave cell or after i revisit and exit cell twice.
to trigger this iimedately . i unfocus from datagridview . then refocus it.
this.SelectNextControl(dgv1,true,true,false,true);
Application.DoEvents(); //this does magic
dgv1.Focus();
mp3 files sometimes throw strange mime types as per this answer: https://stackoverflow.com/a/2755288/14482130
If you are doing some user validation do not allow 'application/octet-stream' or 'application/x-zip-compressed' as suggested above since they can contain be .exe or other potentially dangerous files.
In order to validate when mime type gives a false negative you can use fleep as per this answer https://stackoverflow.com/a/52570299/14482130 to finish the validation.
I would suggest having a look at Alex Shevchuk's tutorial. He explains "major upgrade" through WiX with a good hands-on example at From MSI to WiX, Part 8 - Major Upgrade.
It's not the angular way, remove the function from html body and use it in controller, or use
angular.element(document).ready
More details are available here: https://stackoverflow.com/a/18646795/4301583
This one line of code in writeToParcel(Parcel dest, int flags) method helped me to get rid of TransactionTooLargeException.
dest=Parcel.obtain();
After this code only i am writing all data to the parcel object i.e dest.writeInt() etc.
Sets new value for backgroundPosition
on the carousel
div when a li in the submenu
div is hovered. Removes the backgroundPosition
when hovering ends and resets backgroundPosition
to old value.
$('#submenu li').hover(function() {
if ($('#carousel').data('oldbackgroundPosition')==undefined) {
$('#carousel').data('oldbackgroundPosition', $('#carousel').css('backgroundPosition'));
}
$('#carousel').css('backgroundPosition', [enternewvaluehere]);
},
function() {
var reset = '';
if ($('#carousel').data('oldbackgroundPosition') != undefined) {
reset = $('#carousel').data('oldbackgroundPosition');
$('#carousel').removeData('oldbackgroundPosition');
}
$('#carousel').css('backgroundPosition', reset);
});
set scrolling="no"
attribute in your iframe.
Complete Dynamic Function I jumped here for associative array sorting and found this amazing function on http://php.net/manual/en/function.sort.php. This function is very dynamic that sort in ascending and descending order with specified key.
Simple function to sort an array by a specific key. Maintains index association
<?php
function array_sort($array, $on, $order=SORT_ASC)
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
$people = array(
12345 => array(
'id' => 12345,
'first_name' => 'Joe',
'surname' => 'Bloggs',
'age' => 23,
'sex' => 'm'
),
12346 => array(
'id' => 12346,
'first_name' => 'Adam',
'surname' => 'Smith',
'age' => 18,
'sex' => 'm'
),
12347 => array(
'id' => 12347,
'first_name' => 'Amy',
'surname' => 'Jones',
'age' => 21,
'sex' => 'f'
)
);
print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname
Template
<span date-now="MM/dd/yyyy"></span>
Directive
.directive('dateNow', ['$filter', function($filter) {
return {
link: function( $scope, $element, $attrs) {
$element.text($filter('date')(new Date(), $attrs.dateNow));
}
};
}])
Because you can't access the Date
object direcly in a template (for an inline solution), I opteted for this Directive. It also keeps your Controllers clean and is reusable.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_id:
//Your Code....
item.setEnabled(false);
break;
}
return super.onOptionsItemSelected(item);
}
Be careful with that.
But you can use the rebase command
git rebase -i HEAD~2
A vi
will open and all you have to do is delete the line with the commit. Also can read instructions that were shown in proper edition @ vi
. A couple of things can be performed on this mode.
Simply, to enforce JAVA version to Ant in Eclipse:
Use RunAs option on Ant file then select External Tool Configuration in JRE tab define your JDK/JRE version you want to use.
Above one has some syntax error, Please use following on oracle:
SELECT ROUND (totalSeconds / (24 * 60 * 60), 1) TotalTimeSpendIn_DAYS,
ROUND (totalSeconds / (60 * 60), 0) TotalTimeSpendIn_HOURS,
ROUND (totalSeconds / 60) TotalTimeSpendIn_MINUTES,
ROUND (totalSeconds) TotalTimeSpendIn_SECONDS
FROM
(SELECT ROUND ( EXTRACT (DAY FROM timeDiff) * 24 * 60 * 60 + EXTRACT (HOUR FROM timeDiff) * 60 * 60 + EXTRACT (MINUTE FROM timeDiff) * 60 + EXTRACT (SECOND FROM timeDiff)) totalSeconds
FROM
(SELECT TO_TIMESTAMP(TO_CHAR( date2 , 'yyyy-mm-dd HH24:mi:ss'), 'yyyy-mm-dd HH24:mi:ss') - TO_TIMESTAMP(TO_CHAR(date1, 'yyyy-mm-dd HH24:mi:ss'),'yyyy-mm-dd HH24:mi:ss') timeDiff
FROM TABLENAME
)
);
Update 2018-01-07 with Spring Boot 1.5.8.RELEASE
If you want to know how to config it, how to use it, and how to control transaction. I may have answers for you.
You can see the runnable example and some explanation in https://www.surasint.com/spring-boot-with-multiple-databases-example/
I copied some code here.
First you have to set application.properties like this
#Database
database1.datasource.url=jdbc:mysql://localhost/testdb
database1.datasource.username=root
database1.datasource.password=root
database1.datasource.driver-class-name=com.mysql.jdbc.Driver
database2.datasource.url=jdbc:mysql://localhost/testdb2
database2.datasource.username=root
database2.datasource.password=root
database2.datasource.driver-class-name=com.mysql.jdbc.Driver
Then define them as providers (@Bean) like this:
@Bean(name = "datasource1")
@ConfigurationProperties("database1.datasource")
@Primary
public DataSource dataSource(){
return DataSourceBuilder.create().build();
}
@Bean(name = "datasource2")
@ConfigurationProperties("database2.datasource")
public DataSource dataSource2(){
return DataSourceBuilder.create().build();
}
Note that I have @Bean(name="datasource1") and @Bean(name="datasource2"), then you can use it when we need datasource as @Qualifier("datasource1") and @Qualifier("datasource2") , for example
@Qualifier("datasource1")
@Autowired
private DataSource dataSource;
If you do care about transaction, you have to define DataSourceTransactionManager for both of them, like this:
@Bean(name="tm1")
@Autowired
@Primary
DataSourceTransactionManager tm1(@Qualifier ("datasource1") DataSource datasource) {
DataSourceTransactionManager txm = new DataSourceTransactionManager(datasource);
return txm;
}
@Bean(name="tm2")
@Autowired
DataSourceTransactionManager tm2(@Qualifier ("datasource2") DataSource datasource) {
DataSourceTransactionManager txm = new DataSourceTransactionManager(datasource);
return txm;
}
Then you can use it like
@Transactional //this will use the first datasource because it is @primary
or
@Transactional("tm2")
This should be enough. See example and detail in the link above.
Constructor typically is Method.
When we create object of a class new operator use then we invoked a special kind of method called constructor.
Constructor used to perform initialization of instance variable.
public class Diff{
public Diff() { //same as class name so constructor
String A = "Local variable A in Constructor:";
System.out.println(A+ "Contructor Print me");
}
public void Print(){
String B = "Local variable B in Method";
System.out.println(B+ "Method print me");
}
public static void main(String args[]){
Diff ob = new Diff();
}
}
`
Output:
Local variable A in Constructor:Contructor Print me
So,only show here Constructor method Diff() statement because we create Diff class object. In that case constructor always come first to instantiate Class here class Diff().
typically,
Constructor is set up feature.
Everything start with here, when we call ob object in the main method constructor takes this class and create copy and it's load into the " Java Virtual Machine Class loader " .
This class loader takes this copy and load into memory,so we can now use it by referencing.
Constructor done its work then Method are come and done its real implementation.
In this program when we call
ob.print();
then method will coming.
Thanks
Arindam
Reset and sync local repository with remote branch
The command: Remember to replace origin and master with the remote and branch that you want to synchronize with.
git fetch origin && git reset --hard origin/master && git clean -f -d
Or step-by-step:
git fetch origin
git reset --hard origin/master
git clean -f -d
Your local branch is now an exact copy (commits and all) of the remote branch.
Command output:
Here is an example of running the command on a local clone of the Forge a git repository.
sharkbook:forge lbaxter$ git fetch origin && git reset --hard origin/master && git clean -f -d
HEAD is now at 356cd85 FORGE-680
Removing forge-example-plugin/
Removing plugin-container-api/
Removing plugin-container/
Removing shell/.forge_settings
sharkbook:forge lbaxter$
You can use StringBuffer
StringBuffer text = new StringBuffer("Hello World");
text.replace( StartIndex ,EndIndex ,String);
I am able to achieve subfolders by following the top answer to this question.
However, as the project grows bigger, you will have many sub-folders:
sourceSets {
main {
res.srcDirs =
[
'src/main/res/layouts/somethingA',
'src/main/res/layouts/somethingB',
'src/main/res/layouts/somethingC',
'src/main/res/layouts/somethingD',
'src/main/res/layouts/somethingE',
'src/main/res/layouts/somethingF',
'src/main/res/layouts/somethingG',
'src/main/res/layouts/somethingH',
'src/main/res/layouts/...many more',
'src/main/res'
]
}
}
Not a big problem, but:
app/build.gradle
everytime you add a new folder.So I wrote a simple Groovy method to grab all nested folders:
def getLayoutList(path) {
File file = new File(path)
def throwAway = file.path.split("/")[0]
def newPath = file.path.substring(throwAway.length() + 1)
def array = file.list().collect {
"${newPath}/${it}"
}
array.push("src/main/res");
return array
}
Paste this method outside of the android {...}
block in your app/build.gradle
.
For a structure like this:
<project root>
+-- app <---------- TAKE NOTE
+-- build
+-- build.gradle
+-- gradle
+-- gradle.properties
+-- gradlew
+-- gradlew.bat
+-- local.properties
+-- settings.gradle
Use it like this:
android {
sourceSets {
main {
res.srcDirs = getLayoutList("app/src/main/res/layouts/")
}
}
}
If you have a structure like this:
<project root>
+-- my_special_app_name <---------- TAKE NOTE
+-- build
+-- build.gradle
+-- gradle
+-- gradle.properties
+-- gradlew
+-- gradlew.bat
+-- local.properties
+-- settings.gradle
You will use it like this:
android {
sourceSets {
main {
res.srcDirs = getLayoutList("my_special_app_name/src/main/res/layouts/")
}
}
}
getLayoutList()
takes a relative path
as an argument. The relative path
is relative to the root of the project. So when we input "app/src/main/res/layouts/"
, it will return all the subfolders' name as an array, which will be exactly the same as:
[
'src/main/res/layouts/somethingA',
'src/main/res/layouts/somethingB',
'src/main/res/layouts/somethingC',
'src/main/res/layouts/somethingD',
'src/main/res/layouts/somethingE',
'src/main/res/layouts/somethingF',
'src/main/res/layouts/somethingG',
'src/main/res/layouts/somethingH',
'src/main/res/layouts/...many more',
'src/main/res'
]
Here's the script with comments for understanding:
def getLayoutList(path) {
// let's say path = "app/src/main/res/layouts/
File file = new File(path)
def throwAway = file.path.split("/")[0]
// throwAway = 'app'
def newPath = file.path.substring(throwAway.length() + 1) // +1 is for '/'
// newPath = src/main/res/layouts/
def array = file.list().collect {
// println "filename: ${it}" // uncomment for debugging
"${newPath}/${it}"
}
array.push("src/main/res");
// println "result: ${array}" // uncomment for debugging
return array
}
Hope it helps!
Updated June 2020
It is no longer possible... allegedly. If you have a Facebook or Instagram dedicated contact (because you work in either a big agency or with a big client) it may potentially be possible depending on your use case, but it's highly discouraged.
Before December 2019:
It is now "possible":
https://developers.facebook.com/docs/instagram-api/content-publishing
The Content Publishing API is a subset of Instagram Graph API endpoints that allow you to publish media objects. Publishing media objects with this API is a two step process — you first create a media object container, then publish the container on your Business Account.
Its worth noting that "The Content Publishing API is in closed beta with Facebook Marketing Partners and Instagram Partners only. We are not accepting new applicants at this time." from https://stackoverflow.com/a/49677468/445887
Since none of the answers are up to date with the last version of Pandas, I am writing another solution for this problem:
In [1]:
import pandas as pd
# Set exemple
df2 = pd.DataFrame({'X' : ['X1', 'X1', 'X1', 'X1'], 'Y' : ['Y2','Y1','Y1','Y1'], 'Z' : ['Z3','Z1','Z1','Z2']})
# Pivot
pd.crosstab(index=df2['Y'], columns=df2['Z'], values=df2['X'], aggfunc=pd.Series.nunique)
Out [1]:
Z Z1 Z2 Z3
Y
Y1 1.0 1.0 NaN
Y2 NaN NaN 1.0
If you want help debugging a problem like this you need to provide the make rule or at least the tar command you invoked. How can we see what's wrong with the command if there's no command to see?
However, 99% of the time an error like this means that you're creating the tar file inside a directory that you're trying to put into the tar file. So, when tar tries to read the directory it finds the tar file as a member of the directory, starts to read it and write it out to the tar file, and so between the time it starts to read the tar file and when it finishes reading the tar file, the tar file has changed.
So for example something like:
tar cf ./foo.tar .
There's no way to "stop" this, because it's not wrong. Just put your tar file somewhere else when you create it, or find another way (using --exclude
or whatever) to omit the tar file.
One way to do it would be like this:
param(
[Parameter(Position=0)][String]$Vlan,
[Parameter(ValueFromRemainingArguments=$true)][String[]]$Hosts
) ...
This would allow multiple hosts to be entered with spaces.
have a look at mysql_insert_id()
here the documentation: http://in.php.net/manual/en/function.mysql-insert-id.php
<gradient android:startColor="#ffdd00"
android:endColor="@color/colorPrimary"
android:centerColor="#ffff" />
<corners android:radius="33dp"/>
<padding
android:bottom="7dp"
android:left="7dp"
android:right="7dp"
android:top="7dp"
/>
There is a reason you cannot do this. (despite all the attempted answers)
You'll need to dump all object types in that database, create the newly named one and then import the dump. If this is a live system you'll need to take it down. If you cannot, then you will need to setup replication from this database to the new one.
If you want to see the commands that could do this, @satishD has the details, which conveys some of the challenges around which you'll need to build a strategy that matches your target database.
You can use down-stepping to achieve better results. Most browsers seem to use linear interpolation rather than bi-cubic when resizing images.
(Update There has been added a quality property to the specs, imageSmoothingQuality
which is currently available in Chrome only.)
Unless one chooses no smoothing or nearest neighbor the browser will always interpolate the image after down-scaling it as this function as a low-pass filter to avoid aliasing.
Bi-linear uses 2x2 pixels to do the interpolation while bi-cubic uses 4x4 so by doing it in steps you can get close to bi-cubic result while using bi-linear interpolation as seen in the resulting images.
var canvas = document.getElementById("canvas");_x000D_
var ctx = canvas.getContext("2d");_x000D_
var img = new Image();_x000D_
_x000D_
img.onload = function () {_x000D_
_x000D_
// set size proportional to image_x000D_
canvas.height = canvas.width * (img.height / img.width);_x000D_
_x000D_
// step 1 - resize to 50%_x000D_
var oc = document.createElement('canvas'),_x000D_
octx = oc.getContext('2d');_x000D_
_x000D_
oc.width = img.width * 0.5;_x000D_
oc.height = img.height * 0.5;_x000D_
octx.drawImage(img, 0, 0, oc.width, oc.height);_x000D_
_x000D_
// step 2_x000D_
octx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5);_x000D_
_x000D_
// step 3, resize to final size_x000D_
ctx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5,_x000D_
0, 0, canvas.width, canvas.height);_x000D_
}_x000D_
img.src = "//i.imgur.com/SHo6Fub.jpg";
_x000D_
<img src="//i.imgur.com/SHo6Fub.jpg" width="300" height="234">_x000D_
<canvas id="canvas" width=300></canvas>
_x000D_
Depending on how drastic your resize is you can might skip step 2 if the difference is less.
In the demo you can see the new result is now much similar to the image element.
Call nrow
passing as argument the name of the dataset:
nrow(dataset)
Well, the only thing I can make it work is like so:
servers: >
dev.example.com,
another.example.com
@Value("${servers}")
private String[] array;
And dont forget the @Configuration above your class....
Without the "," separation, no such luck...
Works too (boot 1.5.8 versie)
servers:
dev.example.com,
another.example.com
In a Python interpreter or script, you can do
import site
site.getsitepackages() # List of global package locations
and
site.getusersitepackages() # String for user-specific package location
For locations third-party packages (those not in the core Python distribution) are installed to.
On my Homebrew-installed Python on macOS, the former outputs
['/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages']
,
which canonicalizes to the same path output by pip show
, as mentioned in a previous answer:
$ readlink -f /usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages
/usr/local/lib/python3.7/site-packages
Reference: https://docs.python.org/3/library/site.html#site.getsitepackages
Zach is correct about the direct answer to the question.
An interesting side note is that the following two loops do not execute the same:
for i=1:10000
% do something
end
for i=[1:10000]
% do something
end
The first loop creates a variable i
that is a scalar and it iterates it like a C for loop. Note that if you modify i
in the loop body, the modified value will be ignored, as Zach says. In the second case, Matlab creates a 10k-element array, then it walks all elements of the array.
What this means is that
for i=1:inf
% do something
end
works, but
for i=[1:inf]
% do something
end
does not (because this one would require allocating infinite memory). See Loren's blog for details.
Also note that you can iterate over cell arrays.
Others have mentioned that lib32z-dev solves the problem, but in general the required packages can be found here:
http://source.android.com/source/initializing.html See "Installing required packages"
Karl answered your search-path question, but as far as the "source of the files" goes, one thing to be aware of is that if you install the libfoo
package and want to do some development with it (i.e., use its headers), you will also need to install libfoo-dev
. The standard library header files are already in /usr/include
, as you saw.
Note that some libraries with a lot of headers will install them to a subdirectory, e.g., /usr/include/openssl
. To include one of those, just provide the path without the /usr/include
part, for example:
#include <openssl/aes.h>
This works too. It seems shortest working notation:
!$('#selector:checked')
In case the formatting needs to be done on Crystal Report side.
Simple way.
Crystal Report Design Window->Right click on the date field->format Field->Customize the date format per your need.
Works effectively.
I'd aditionally recommend putting the output of var_dump() or printr into a pre tag when outputting to a browser.
print "<pre>";
print_r($dataset);
print "</pre>";
Will give a more readable result.
To make your formula more readable, you could assign a Name to cell A0, and then use that name in the formula.
The easiest way to define a Name is to highlight the cell or range, then click on the Name box in the formula bar.
Then, if you named A0 "Rate" you can use that name like this:
=(B0+4)/(Rate)
See, much easier to read.
If you want to find Rate, click F5 and it appears in the GoTo list.
Easily get KERAS and TENSORFLOW version number --> Run this command in terminal:
[username@usrnm:~] python3
>>import keras; print(keras.__version__)
Using TensorFlow backend.
2.2.4
>>import tensorflow as tf; print(tf.__version__)
1.12.0
Assume that we want to get a list of certain images from a PHP server using the POST method.
You have to provide two parameters in the form for the POST method. Here is how you are going to do.
app.controller('gallery-item', function ($scope, $http) {
var url = 'service.php';
var data = new FormData();
data.append("function", 'getImageList');
data.append('dir', 'all');
$http.post(url, data, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function (response) {
// This function handles success
console.log('angular:', response);
}, function (response) {
// this function handles error
});
});
I have tested it on my system and it works.
Because the TOP 1
from the ordered sub-query does not have profile_id = 'u162231993'
Remove where u.id = 'u162231993'
and see results then.
Run the sub-query separately to understand what's going on.
A solution using recursion:
def brute(string, length, charset):
if len(string) == length:
return
for char in charset:
temp = string + char
print(temp)
brute(temp, length, charset)
Usage:
brute("", 4, "rce")
If using Angular CLI v7+, the webpack version is printed in the output of ng version
:
-> ng version
_ _ ____ _ ___
/ \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|
/ ? \ | '_ \ / _` | | | | |/ _` | '__| | | | | | |
/ ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | |
/_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___|
|___/
Angular CLI: 7.0.6
Node: 11.0.0
OS: darwin x64
Angular: 7.1.0
... animations, cdk, common, compiler, compiler-cli, core, forms
... http, language-service, material, platform-browser
... platform-browser-dynamic, router
Package Version
-----------------------------------------------------------
@angular-devkit/architect 0.10.6
@angular-devkit/build-angular 0.10.6
@angular-devkit/build-optimizer 0.10.6
@angular-devkit/build-webpack 0.10.6
@angular-devkit/core 7.0.6
@angular-devkit/schematics 7.0.6
@angular/cli 7.0.6
@ngtools/webpack 7.0.6
@schematics/angular 7.0.6
@schematics/update 0.10.6
rxjs 6.3.3
typescript 3.1.6
webpack 4.19.1
This has support for both title and image.
For iOS 11 and afterwards:
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let action = UIContextualAction(
style: .normal,
title: "My Title",
handler: { (action, view, completion) in
//do what you want here
completion(true)
})
action.image = UIImage(named: "My Image")
action.backgroundColor = .red
let configuration = UISwipeActionsConfiguration(actions: [action])
configuration.performsFirstActionWithFullSwipe = false
return configuration
}
Also, similar method is available for leadingSwipeActions
Source:
https://developer.apple.com/videos/play/wwdc2017/201/ (Talks about this at around 16 mins time) https://developer.apple.com/videos/play/wwdc2017/204/ (Talks about this at around 23 mins time)
If you are making cross domain call the Use Jsonp. else the error is not returned.
Do not use classpath. This may cause problems with different ClassLoaders (container vs. application). WEB-INF is always the better choice.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml</param-value>
</context-param>
and
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>/WEB-INF/social.properties</value>
</property>
</bean>
You can simply do :-
{{"<li>Something</li>".repeat(5)}}
You can use Scanner class like this:
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner scan= new Scanner(System.in);
//For string
String text= scan.nextLine();
System.out.println(text);
//for int
int num= scan.nextInt();
System.out.println(num);
}
}
You could store your JSON inside of an array and then insert the JSON data into the array with push
Check this out https://jsfiddle.net/cx2rk40e/2/
$(document).ready(function(){
// using jQuery just to load function but will work without library.
$( "button" ).on( "click", go );
// Array of JSON we will append too.
var jsonTest = [{
"colour": "blue",
"link": "http1"
}]
// Appends JSON to array with push. Then displays the data in alert.
function go() {
jsonTest.push({"colour":"red", "link":"http2"});
alert(JSON.stringify(jsonTest));
}
});
Result of JSON.stringify(jsonTest)
[{"colour":"blue","link":"http1"},{"colour":"red","link":"http2"}]
This answer maybe useful to users who wish to emulate a similar result.
When you run the code
listoflists.append((list, list[0]))
You are not (as I think you expect) adding a copy of list
to the end of listoflists
. What you are doing is adding a reference to list
to the end of listoflists
. Thus, every time you update list
, it updates every reference to list
, which in this case, is every item in listoflists
What you could do instead is something like this:
listoflists = []
for i in range(1, 10):
listoflists.append((range(i), 0))
For my issue, I didn't want my images scaled to 100% when they weren't intended to be as large as the container.
For my xs container (<768px as .container), not having a fixed width drove the issue, so I put one back on to it (less the 15px col padding).
// Helps bootstrap 3.0 keep images constrained to container width when width isn't set a fixed value (below 768px), while avoiding all images at 100% width.
// NOTE: proper function relies on there being no inline styling on the element being given a defined width ( '.container' )
function setWidth() {
width_val = $( window ).width();
if( width_val < 768 ) {
$( '.container' ).width( width_val - 30 );
} else {
$( '.container' ).removeAttr( 'style' );
}
}
setWidth();
$( window ).resize( setWidth );
If you want to find the last populated cell in a particular column, the best method is:
Range("A" & Rows.Count).End(xlUp).Row
This code uses the very last cell in the entire column (65536 for Excel 2003, 1048576 in later versions), and then find the first populated cell above it. This has the ability to ignore "breaks" in your data and find the true last row.
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.
You can add the application folder to your path from a command prompt using:
setx PATH "%PATH%;c:\MinGW\bin"
Note that you will probably need to open a new command window for the modified path setting to go into effect.
Sometimes dict()
is a good choice:
a=dict(zip(['Mon','Tue','Wed','Thu','Fri'], [x for x in range(1, 6)]))
mydict=dict(zip(['mon','tue','wed','thu','fri','sat','sun'],
[random.randint(0,100) for x in range(0,7)]))
Following solution worked for me.
.algncenterdiv {
display: block;
margin-left: auto;
margin-right: auto;
}
Download it from here:
http://www.iis.net/downloads/microsoft/url-rewrite
or if you already have Web Platform Installer on your machine you can install it from there.
I disagree with the advice given here - even the reference for the accepted answer concludes:
You can of course use query string parameters with HTTPS, but don’t use them for anything that could present a security problem. For example, you could safely use them to identity part numbers or types of display like ‘accountview’ or ‘printpage’, but don’t use them for passwords, credit card numbers or other pieces of information that should not be publicly available.
So, no they aren't really safe...!
Have you tried binding the list to the datagridview directly? If not, try that first because it will save you lots of pain. If you have tried it already, please tell us what went wrong so we can better advise you. Data binding gives you different behaviour depending on what interfaces your data object implements. For example, if your data object only implements IEnumerable
(e.g. List
), you will get very basic one-way binding, but if it implements IBindingList
as well (e.g. BindingList
, DataView
), then you get two-way binding.
How did you try it? Maybe you are working with \
and omit proper escaping.
Instead of
open('\\HOST\share\path\to\file')
use either Johnsyweb's solution with the /
s, or try one of
open(r'\\HOST\share\path\to\file')
or
open('\\\\HOST\\share\\path\\to\\file')
.
An old school approach:
fh = open(file_name, 'rt')
line = fh.readline()
while line:
# do stuff with line
line = fh.readline()
fh.close()
How about this
let numbers = [1,2,3,4,5]
numbers.forEach((number, index) => console.log(`${index}:${number}`))
Where array.forEach
this method has an index
parameter which is the index of the current element being processed in the array.
In my case, I had a OneToOne relation which I was using with @Column
by mistake. I changed it to @JoinColumn
and added @OneToOne
annotation and it fixed the exception.
A small addition to previous answers, since I couldn't find a solution for a problem, which is not worth opening a new question, but led me here.
Here is a small code snippet, which combines lists
, zip()
and *args
, to provide a wrapper that can deal with an unknown amount of functions with an unknown amount of arguments.
def f1(var1, var2, var3):
print(var1+var2+var3)
def f2(var1, var2):
print(var1*var2)
def f3():
print('f3, empty')
def wrapper(a,b, func_list, arg_list):
print(a)
for f,var in zip(func_list,arg_list):
f(*var)
print(b)
f_list = [f1, f2, f3]
a_list = [[1,2,3], [4,5], []]
wrapper('begin', 'end', f_list, a_list)
Keep in mind, that zip()
does not provide a safety check for lists of unequal length, see zip iterators asserting for equal length in python.
out
or ref
(since that changes the reference, not the object). A programmer therefore knows that if string x = "abc"
at the start of a method, and that doesn't change in the body of the method, then x == "abc"
at the end of the method."abc" == "ab" + "c"
. While this doesn't require immutability, the fact that a reference to such a string will always equal "abc" throughout its lifetime (which does require immutability) makes uses as keys where maintaining equality to previous values is vital, much easier to ensure correctness of (strings are indeed commonly used as keys).Christmas.AddMonths(1)
produces a new DateTime
rather than changing a mutable one. (Another example, if I as a mutable object change my name, what has changed is which name I am using, "Jon" remains immutable and other Jons will be unaffected.return this
. Since the copy can't be changed anyway, pretending something is its own copy is safe.In all, for objects which don't have undergoing change as part of their purpose, there can be many advantages in being immutable. The main disadvantage is in requiring extra constructions, though even here it's often overstated (remember, you have to do several appends before StringBuilder becomes more efficient than the equivalent series of concatenations, with their inherent construction).
It would be a disadvantage if mutability was part of the purpose of an object (who'd want to be modeled by an Employee object whose salary could never ever change) though sometimes even then it can be useful (in a many web and other stateless applications, code doing read operations is separate from that doing updates, and using different objects may be natural - I wouldn't make an object immutable and then force that pattern, but if I already had that pattern I might make my "read" objects immutable for the performance and correctness-guarantee gain).
Copy-on-write is a middle ground. Here the "real" class holds a reference to a "state" class. State classes are shared on copy operations, but if you change the state, a new copy of the state class is created. This is more often used with C++ than C#, which is why it's std:string enjoys some, but not all, of the advantages of immutable types, while remaining mutable.
This solution will give you the Network parameters. Check out this solution
You can use this simple awk script:
#!/bin/gawk -f
{ print strftime("%c", $0); }
Sample usage:
$ echo '1098181096' | ./a.awk
Tue 19 Oct 2004 03:18:16 AM PDT
$
Is your SQL Server in 'mixed mode authentication' ? This is necessary to login with a SQL server account instead of a Windows login.
You can verify this by checking the properties of the server and then SECURITY, it should be in 'SQL Server and Windows Authentication Mode'
This problem occurs if the user tries to log in with credentials that cannot be validated. This problem can occur in the following scenarios:
Scenario 1: The login may be a SQL Server login but the server only accepts Windows Authentication.
Scenario 2: You are trying to connect by using SQL Server Authentication but the login used does not exist on SQL Server.
Scenario 3: The login may use Windows Authentication but the login is an unrecognized Windows principal. An unrecognized Windows principal means that Windows can't verify the login. This might be because the Windows login is from an untrusted domain.
It's also possible the user put in incorrect information.
The documentation for focusout says (emphasis mine):
The
focusout
event is sent to an element when it, or any element inside of it, loses focus. This is distinct from theblur
event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).
The same distinction exists between the focusin and focus events.
foo.instance_of? String
or
foo.kind_of? String
if you you only care if it is derrived from String
somewhere up its inheritance chain
I developed a jQuery plugin that allows you to call any core PHP function or even user defined PHP functions as methods of the plugin: jquery.php
After including jquery and jquery.php in the head of our document and placing request_handler.php on our server we would start using the plugin in the manner described below.
For ease of use reference the function in a simple manner:
var P = $.fn.php;
Then initialize the plugin:
P('init',
{
// The path to our function request handler is absolutely required
'path': 'http://www.YourDomain.com/jqueryphp/request_handler.php',
// Synchronous requests are required for method chaining functionality
'async': false,
// List any user defined functions in the manner prescribed here
// There must be user defined functions with these same names in your PHP
'userFunctions': {
languageFunctions: 'someFunc1 someFunc2'
}
});
And now some usage scenarios:
// Suspend callback mode so we don't work with the DOM
P.callback(false);
// Both .end() and .data return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
Demonstrating PHP function chaining:
var data1 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).data();
var data2 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).end();
console.log( data1, data2 );
Demonstrating sending a JSON block of PHP pseudo-code:
var data1 =
P.block({
$str: "Let's use PHP's file_get_contents()!",
$opts:
[
{
http: {
method: "GET",
header: "Accept-language: en\r\n" +
"Cookie: foo=bar\r\n"
}
}
],
$context:
{
stream_context_create: ['$opts']
},
$contents:
{
file_get_contents: ['http://www.github.com/', false, '$context']
},
$html:
{
htmlentities: ['$contents']
}
}).data();
console.log( data1 );
The backend configuration provides a whitelist so you can restrict which functions can be called. There are a few other patterns for working with PHP described by the plugin as well.
I think you want to cast your dt
to a date
and fix the format of your date literal:
SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD
Or the standard version:
SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD
The extract
function doesn't understand "date" and it returns a number.
I could not restart IIexpress. This is the solution that worked for me
This feature is called XML Inclusions (XInclude). Some examples:
For tensorflow 2.0, it is as simple as
# Save the model model.save('path_to_my_model.h5')
To restore:
new_model = tensorflow.keras.models.load_model('path_to_my_model.h5')
this worked for me:
ssh-keygen -R <server_IP>
to delete the old keys stored on the workstation also works with instead of
then doing the same ssh again it worked:
ssh -v -i <your_pem_file> ubuntu@<server_IP>
on ubuntu instances the username is: ubuntu on Amazon Linux AMI the username is: ec2-user
I didn't have to re-create the instance from an image.
Recently I had to recover my pictures with the extension .jpg. I ran photorec and recovered 4579 directories 2.2 million files within, having tremendous variety of extensions.With the script below I was able to select 50133 files havin .jpg extension within minutes:
#!/usr/binenv python2.7
import glob
import shutil
import os
src_dir = "/home/mustafa/Masaüstü/yedek"
dst_dir = "/home/mustafa/Genel/media"
for mediafile in glob.iglob(os.path.join(src_dir, "*", "*.jpg")): #"*" is for subdirectory
shutil.copy(mediafile, dst_dir)
$ file=${$(basename $file_path)%.*}
You may use it with like the following.
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="15dp">
<Space
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"/>
<Space
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset"/>
<Space
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="cancel"/>
<Space
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
</LinearLayout>
Try an if statement ...
if @value is null
insert into t (value) values (default)
else
insert into t (value) values (@value)
What if the incoming changes are the ones you want? I'm unable to run svn resolve --accept theirs-full
svn resolve --accept base
The <NAME>
you use in multer's upload.single(<NAME>)
function must be the same as the one you use in <input type="file" name="<NAME>" ...>
.
So you need to change
var type = upload.single('file')
to
var type = upload.single('recfile')
in you app.js
Hope this helps.
You can use list.sort
with its optional key
parameter and a lambda
expression:
>>> lst = [
... ['John',2],
... ['Jim',9],
... ['Jason',1]
... ]
>>> lst.sort(key=lambda x:x[1])
>>> lst
[['Jason', 1], ['John', 2], ['Jim', 9]]
>>>
This will sort the list in-place.
Note that for large lists, it will be faster to use operator.itemgetter
instead of a lambda
:
>>> from operator import itemgetter
>>> lst = [
... ['John',2],
... ['Jim',9],
... ['Jason',1]
... ]
>>> lst.sort(key=itemgetter(1))
>>> lst
[['Jason', 1], ['John', 2], ['Jim', 9]]
>>>
See if your script is running GPU in Task manager. If not, suspect your CUDA version is right one for the tensorflow version you are using, as the other answers suggested already.
Additionally, a proper CUDA DNN library for the CUDA version is required to run GPU with tensorflow. Download/extract it from here and put the DLL (e.g., cudnn64_7.dll) into CUDA bin folder (e.g., C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin).
Easy way to convert base64 image into file and save as some random id or name.
// to create some random id or name for your image name
const imgname = new Date().getTime().toString();
// to declare some path to store your converted image
const path = yourpath.png
// image takes from body which you uploaded
const imgdata = req.body.image;
// to convert base64 format into random filename
const base64Data = imgdata.replace(/^data:([A-Za-z-+/]+);base64,/, '');
fs.writeFile(path, base64Data, 'base64', (err) => {
console.log(err);
});
// assigning converted image into your database
req.body.coverImage = imgname
I use ubuntu 16.04 and because I already had openJDK installed, this command have solved the problem. Don't forget that JavaFX is part of OpenJDK.
sudo apt-get install openjfx
Create FUNCTION [dbo].[fnSplitString]
(
@string NVARCHAR(200),
@delimiter CHAR(1)
)
RETURNS @output TABLE(splitdata NVARCHAR(10)
)
BEGIN
DECLARE @start INT, @end INT
SELECT @start = 1, @end = CHARINDEX(@delimiter, @string)
WHILE @start < LEN(@string) + 1 BEGIN
IF @end = 0
SET @end = LEN(@string) + 1
INSERT INTO @output (splitdata)
VALUES(SUBSTRING(@string, @start, @end - @start))
SET @start = @end + 1
SET @end = CHARINDEX(@delimiter, @string, @start)
END
RETURN
END**strong text**
As well as the already mentioned @Html.Raw(string) approach, if you output an MvcHtmlString it will not be encoded. This can be useful when adding your own extensions to the HtmlHelper, or when returning a value from your view model that you know may contain html.
For example, if your view model was:
public class SampleViewModel
{
public string SampleString { get; set; }
public MvcHtmlString SampleHtmlString { get; set; }
}
For Core 1.0+ (and MVC 5+) use HtmlString
public class SampleViewModel
{
public string SampleString { get; set; }
public HtmlString SampleHtmlString { get; set; }
}
then
<!-- this will be encoded -->
<div>@Model.SampleString</div>
<!-- this will not be encoded -->
<div>@Html.Raw(Model.SampleString)</div>
<!-- this will not be encoded either -->
<div>@Model.SampleHtmlString</div>
SELECT
T.NAME AS 'TABLE NAME',
P.[ROWS] AS 'NO OF ROWS'
FROM SYS.TABLES T
INNER JOIN SYS.PARTITIONS P ON T.OBJECT_ID=P.OBJECT_ID;
For some applications may be better:
string.Join(",", arr1) == string.Join(",", arr2)
With [email protected] or later you can install types with npm install
npm install --save-dev @types/jasmine
then import the types automatically using the typeRoots option in tsconfig.json.
"typeRoots": [
"node_modules/@types"
],
This solution does not require import {} from 'jasmine'; in each spec file.
If you have several threads executing the methods m1 and m2 in the code below:
class SomeClass {
private int i = 0;
public void m1() { i = 5; }
public int m2() { return i; }
}
you have the guarantee that any thread calling m2
will either read 0 or 5.
On the other hand, with this code (where i
is a long):
class SomeClass {
private long i = 0;
public void m1() { i = 1234567890L; }
public long m2() { return i; }
}
a thread calling m2
could read 0, 1234567890L, or some other random value because the statement i = 1234567890L
is not guaranteed to be atomic for a long
(a JVM could write the first 32 bits and the last 32 bits in two operations and a thread might observe i
in between).
The simplest choice I found to solve this problem was using the python lib called networkx
.
It implements the Johnson's algorithm mentioned in the best answer of this question but it makes quite simple to execute.
In short you need the following:
import networkx as nx
import matplotlib.pyplot as plt
# Create Directed Graph
G=nx.DiGraph()
# Add a list of nodes:
G.add_nodes_from(["a","b","c","d","e"])
# Add a list of edges:
G.add_edges_from([("a","b"),("b","c"), ("c","a"), ("b","d"), ("d","e"), ("e","a")])
#Return a list of cycles described as a list o nodes
list(nx.simple_cycles(G))
Answer: [['a', 'b', 'd', 'e'], ['a', 'b', 'c']]
If you want to change the size of plot the use arg figsize
df.groupby(['NFF', 'ABUSE']).size().unstack()
.plot(kind='bar', stacked=True, figsize=(15, 5))
If you're looking for a way to immutably change the collection (as I was when I found your question), you might take a look at immutability-helper, a library forked from the original React util. In your case, you would accomplish what you mentioned via the following:
var update = require('immutability-helper')
var arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}]
var newArray = update(arr, { 0: { name: { $set: 'New Name' } } })
//=> [{id: 1, name: "New Name"}, {id:2, name:"Person 2"}]
The lifetime of function static
variables begins the first time[0] the program flow encounters the declaration and it ends at program termination. This means that the run-time must perform some book keeping in order to destruct it only if it was actually constructed.
Additionally, since the standard says that the destructors of static objects must run in the reverse order of the completion of their construction[1], and the order of construction may depend on the specific program run, the order of construction must be taken into account.
Example
struct emitter {
string str;
emitter(const string& s) : str(s) { cout << "Created " << str << endl; }
~emitter() { cout << "Destroyed " << str << endl; }
};
void foo(bool skip_first)
{
if (!skip_first)
static emitter a("in if");
static emitter b("in foo");
}
int main(int argc, char*[])
{
foo(argc != 2);
if (argc == 3)
foo(false);
}
Output:
C:>sample.exe
Created in foo
Destroyed in fooC:>sample.exe 1
Created in if
Created in foo
Destroyed in foo
Destroyed in ifC:>sample.exe 1 2
Created in foo
Created in if
Destroyed in if
Destroyed in foo
[0]
Since C++98[2] has no reference to multiple threads how this will be behave in a multi-threaded environment is unspecified, and can be problematic as Roddy mentions.
[1]
C++98 section 3.6.3.1
[basic.start.term]
[2]
In C++11 statics are initialized in a thread safe way, this is also known as Magic Statics.
I had this problem. I'll share my ride on the learning curve.
First, I couldn't find how to reject the binary but remembered seeing it earlier today in the iTunesConnect App. So using the App I rejected the binary.
If you "mouse over" the rejected binary under the "Build" section you'll notice that a red circle icon with a - (i.e. a delete button) appears. Tap on this and then hit the save button at the top of the screen. Submitted binary is now gone.
You should now get all the notifications for the app being in state "Prepare for Upload" (email, App notification etc).
Xcode organiser was still giving me "Redundant Binary". After a bit of research I now understand the difference between "Version" & "Build". Version is what iTunes displays and the user sees. Build is just the internal tracking number. I had both at 2.3.0, I changed build to 2.3.0.1 and re-Archive. Now it validates and I can upload the new binary and re-submit. Hope that helps others!
When you are appending data into div by id using any service or database, first try it empty, like this:
var json = jsonParse(data.d);
$('#divname').empty();
An extra pair of rabbits' ears should do the trick.
start "" "C:\Program...
START
regards the first quoted parameter as the window-title, unless it's the only parameter - and any switches up until the executable name are regarded as START
switches.
I'm using VS 2019.
if your solution has more than one project / class libraries etc, then you may not see the Web tab when clicking on Solution explorer properties.
Clicking on the MVC project and then checking properties will reveal the web tab where you can change the port.
set your property using below code at the time of model creation i think your problem will be solved..and the time are not appear in database.you dont need to add any annotation.
private DateTime? dob;
public DateTime? DOB
{
get
{
if (dob != null)
{
return dob.Value.Date;
}
else
{
return null;
}
}
set { dob = value; }
}
I like Aptana Studio and Redcar for rails programming.
You can get good Time Series graphs in Excel, the way you want, but you have to work with a few quirks.
Be sure to select "Scatter Graph" (with a line option). This is needed if you have non-uniform time stamps, and will scale the X-axis accordingly.
In your data, you need to add a column with the mid-point. Here's what I did with your sample data. (This trick ensures that the data gets plotted at the mid-point, like you desire.)
You can format the x-axis options with this menu. (Chart->Design->Layout)
Select "Axes" and go to Primary Horizontal Axis, and then select "More Primary Horizontal Axis Options"
Set up the options you wish. (Fix the starting and ending points.)
And you will get a graph such as the one below.
You can then tweak many of the options, label the axes better etc, but this should get you started.
Hope this helps you move forward.
I am working with Visual studio 2010, if you would like to split your files to .h and .cpp, include your cpp header at the end of the .h file
For me, the problem occurs when I've downloaded macOS Compressed Archive
which underlying directory contains
jdk-11.0.8.jdk
- Contents
- Home
- bin
- ...
- MacOS
- _CodeSignature
So, to solve the problem, JAVA_HOME should be pointed directly to /Path-to-JDK/Contents/Home.
Use getDeclaredMethod()
to get a private Method object and then use method.setAccessible()
to allow to actually call it.
To keep the promise chain going, you can't use setTimeout()
the way you did because you aren't returning a promise from the .then()
handler - you're returning it from the setTimeout()
callback which does you no good.
Instead, you can make a simple little delay function like this:
function delay(t, v) {
return new Promise(function(resolve) {
setTimeout(resolve.bind(null, v), t)
});
}
And, then use it like this:
getLinks('links.txt').then(function(links){
let all_links = (JSON.parse(links));
globalObj=all_links;
return getLinks(globalObj["one"]+".txt");
}).then(function(topic){
writeToBody(topic);
// return a promise here that will be chained to prior promise
return delay(1000).then(function() {
return getLinks(globalObj["two"]+".txt");
});
});
Here you're returning a promise from the .then()
handler and thus it is chained appropriately.
You can also add a delay method to the Promise object and then directly use a .delay(x)
method on your promises like this:
function delay(t, v) {_x000D_
return new Promise(function(resolve) { _x000D_
setTimeout(resolve.bind(null, v), t)_x000D_
});_x000D_
}_x000D_
_x000D_
Promise.prototype.delay = function(t) {_x000D_
return this.then(function(v) {_x000D_
return delay(t, v);_x000D_
});_x000D_
}_x000D_
_x000D_
_x000D_
Promise.resolve("hello").delay(500).then(function(v) {_x000D_
console.log(v);_x000D_
});
_x000D_
Or, use the Bluebird promise library which already has the .delay()
method built-in.
I think your problem is that the :after psuedo-element requires the content: property set inside it. You need to tell it to insert something. You could even just have it insert the image directly:
ul li:after {
content: url('../images/small_triangle.png');
}
Use performance.now()
:
<script>
var a = performance.now();
alert('do something...');
var b = performance.now();
alert('It took ' + (b - a) + ' ms.');
</script>
It works on:
IE 10 ++
FireFox 15 ++
Chrome 24 ++
Safari 8 ++
Opera 15 ++
Android 4.4 ++
console.time
may be viable for you, but it's non-standard §:
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
Besides browser support, performance.now
seems to have the potential to provide more accurate timings as it appears to be the bare-bones version of console.time
.
<rant> Also, DON'T EVER use Date
for anything because it's affected by changes in "system time". Which means we will get invalid results —like "negative timing"— when the user doesn't have an accurate system time:
On Oct 2014, my system clock went haywire and guess what.... I opened Gmail and saw all of my day's emails "sent 0 minutes ago". And I'd thought Gmail is supposed to be built by world-class engineers from Google.......
(Set your system clock to one year ago and go to Gmail so we can all have a good laugh. Perhaps someday we will have a Hall of Shame for JS Date
.)
Google Spreadsheet's now()
function also suffers from this problem.
The only time you'll be using Date
is when you want to show the user his system clock time. Not when you want to get the time or to measure anything.
You can use Object.prototype.hasOwnProperty()
var findInEnum,_x000D_
colorEnum = {_x000D_
red : 0,_x000D_
green : 1,_x000D_
blue : 2_x000D_
};_x000D_
_x000D_
// later on_x000D_
_x000D_
findInEnum = function (enumKey) {_x000D_
if (colorEnum.hasOwnProperty(enumKey)) {_x000D_
return enumKey+' Value: ' + colorEnum[enumKey]_x000D_
}_x000D_
}_x000D_
_x000D_
alert(findInEnum("blue"))
_x000D_
If you mean you want the background image itself to be offset by 50 pixels from the top, like a background margin, then just switch out the top
for 50px
and you're set.
#thedivstatus {
background-image: url("imagestatus.gif");
background-position: right 50px;
background-repeat: no-repeat;
}
As of January 2020 and Xcode 11.3.1 -
Xcode will automatically create an Apple Distribution certificate, install it in Keychain Access, and update Xcode's signing information
(Note: the single Apple Distribution certificate is now provided instead of the previous iOS Distribution certificate and equivalents.)
You can use ancestor
. I find that this is easier to read because the element you are actually selecting is at the end of the path.
//span[contains(text(),'someText')]/ancestor::div[contains(@class, 'measure-tab')]
If you try to decrypt PKCS5-padded data with the wrong key, and then unpad it (which is done by the Cipher class automatically), you most likely will get the BadPaddingException (with probably of slightly less than 255/256, around 99.61%), because the padding has a special structure which is validated during unpad and very few keys would produce a valid padding.
So, if you get this exception, catch it and treat it as "wrong key".
This also can happen when you provide a wrong password, which then is used to get the key from a keystore, or which is converted into a key using a key generation function.
Of course, bad padding can also happen if your data is corrupted in transport.
That said, there are some security remarks about your scheme:
For password-based encryption, you should use a SecretKeyFactory and PBEKeySpec instead of using a SecureRandom with KeyGenerator. The reason is that the SecureRandom could be a different algorithm on each Java implementation, giving you a different key. The SecretKeyFactory does the key derivation in a defined manner (and a manner which is deemed secure, if you select the right algorithm).
Don't use ECB-mode. It encrypts each block independently, which means that identical plain text blocks also give always identical ciphertext blocks.
Preferably use a secure mode of operation, like CBC (Cipher block chaining) or CTR (Counter). Alternatively, use a mode which also includes authentication, like GCM (Galois-Counter mode) or CCM (Counter with CBC-MAC), see next point.
You normally don't want only confidentiality, but also authentication, which makes sure the message is not tampered with. (This also prevents chosen-ciphertext attacks on your cipher, i.e. helps for confidentiality.) So, add a MAC (message authentication code) to your message, or use a cipher mode which includes authentication (see previous point).
DES has an effective key size of only 56 bits. This key space is quite small, it can be brute-forced in some hours by a dedicated attacker. If you generate your key by a password, this will get even faster. Also, DES has a block size of only 64 bits, which adds some more weaknesses in chaining modes. Use a modern algorithm like AES instead, which has a block size of 128 bits, and a key size of 128 bits (for the standard variant).
For the record, that margin and padding resetting didn't do the trick for me, but this quote from one of the comments above turned out to be crucial and solved the issue for me: "If i put the divs on the same line it margin disappears."
Basically the two styles, are like Yin and Yang. One is organized, while the other chaotic. There are situations when Functional programming is the obvious choice, and other situations were Procedural programming is the better choice. This is why there are at least two languages that have recently come out with a new version, that embraces both programming styles. ( Perl 6 and D 2 )
#Procedural:#
##Perl 6 ##
sub factorial ( UInt:D $n is copy ) returns UInt {
# modify "outside" state
state $call-count++;
# in this case it is rather pointless as
# it can't even be accessed from outside
my $result = 1;
loop ( ; $n > 0 ; $n-- ){
$result *= $n;
}
return $result;
}
##D 2##
int factorial( int n ){
int result = 1;
for( ; n > 0 ; n-- ){
result *= n;
}
return result;
}
#Functional:#
##Haskell## ( copied from Wikipedia );
fac :: Integer -> Integer
fac 0 = 1
fac n | n > 0 = n * fac (n-1)
or in one line:
fac n = if n > 0 then n * fac (n-1) else 1
##Perl 6 ##
proto sub factorial ( UInt:D $n ) returns UInt {*}
multi sub factorial ( 0 ) { 1 }
multi sub factorial ( $n ) { $n * samewith $n-1 } # { $n * factorial $n-1 }
##D 2##
pure int factorial( invariant int n ){
if( n <= 1 ){
return 1;
}else{
return n * factorial( n-1 );
}
}
#Side note:#
Factorial is actually a common example to show how easy it is to create new operators in Perl 6 the same way you would create a subroutine. This feature is so ingrained into Perl 6 that most operators in the Rakudo implementation are defined this way. It also allows you to add your own multi candidates to existing operators.
sub postfix:< ! > ( UInt:D $n --> UInt )
is tighter(&infix:<*>)
{ [*] 2 .. $n }
say 5!; # 120?
This example also shows range creation (2..$n
) and the list reduction meta-operator ([ OPERATOR ] LIST
) combined with the numeric infix multiplication operator. (*
)
It also shows that you can put --> UInt
in the signature instead of returns UInt
after it.
( You can get away with starting the range with 2
as the multiply "operator" will return 1
when called without any arguments )
Instead of passing functions or querying it on the controller, I think what you need is relationships on models since these are related tables on your database.
If based on your structure, input_details and products are related you should put relationship definition on your models like this:
public class InputDetail(){
protected $table = "input_details";
....//other code
public function product(){
return $this->hasOne('App\Product');
}
}
then in your view you'll just have to say:
<p>{{ $input_details->product->name }}</p>
More simpler that way. It is also the best practice that controllers should only do business logic for the current resource. For more info on how to do this just go to the docs: https://laravel.com/docs/5.0/eloquent#relationships
1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,
2) AbstractTableModel should be useful, where is in the JTable
required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel
,
3) consider using DefaultTableModel
, (if you are not sure about how to works) instead of AbstractTableModel
,
could be generated from simple code:
import javax.swing.*;
import javax.swing.table.*;
public class TableCheckBox extends JFrame {
private static final long serialVersionUID = 1L;
private JTable table;
public TableCheckBox() {
Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
Object[][] data = {
{"Buy", "IBM", new Integer(1000), new Double(80.50), false},
{"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
{"Sell", "Apple", new Integer(3000), new Double(7.35), true},
{"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model) {
private static final long serialVersionUID = 1L;
/*@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}*/
@Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Integer.class;
case 3:
return Double.class;
default:
return Boolean.class;
}
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TableCheckBox frame = new TableCheckBox();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
});
}
}
Here is 2018 updated solution as described in the Mozilla Development Resources
TO ENCODE FROM UNICODE TO B64
function b64EncodeUnicode(str) {
// first we use encodeURIComponent to get percent-encoded UTF-8,
// then we convert the percent encodings into raw bytes which
// can be fed into btoa.
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
function toSolidBytes(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
b64EncodeUnicode('? à la mode'); // "4pyTIMOgIGxhIG1vZGU="
b64EncodeUnicode('\n'); // "Cg=="
TO DECODE FROM B64 TO UNICODE
function b64DecodeUnicode(str) {
// Going backwards: from bytestream, to percent-encoding, to original string.
return decodeURIComponent(atob(str).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
b64DecodeUnicode('4pyTIMOgIGxhIG1vZGU='); // "? à la mode"
b64DecodeUnicode('Cg=='); // "\n"
It depends on what you mean by "dropped". For TCP sockets, if the other end closes the connection either through close() or the process terminating, you'll find out by reading an end of file, or getting a read error, usually the errno being set to whatever 'connection reset by peer' is by your operating system. For python, you'll read a zero length string, or a socket.error will be thrown when you try to read or write from the socket.
This site has a working workaround, same effect, uses some javascript to set the first child div to total height of viewport. http://webapp-net.com/Demo/Index.html
<p style="color:black">Shop our collection of beautiful women's <br> <span> wedding ring in classic & modern design.</span></p>
Remove <br>
effect using CSS.
<style> p br{ display:none; } </style>
If you use a browser released in the last year or so then it most likely supports JavaScript Strict mode. Only older browsers around before ECMAScript 5 became the current standard don't support it.
The quotes around the command make sure that the code will still work in older browsers as well (although the things that generate a syntax error in strict mode will generally just cause the script to malfunction in some hard to detect way in those older browsers).
I've been using IE Tester (good) but didn't know I could simply switch versions in IE. It's nice to know the browser voted "Most likely to be the bain of your existence" has the tool built in to look at previous versions.
The down side to IE Tester is it does not support javascript well, and also doesn't always do a great job with iframes. (Yes, I still use them.)
I decided that since Google and Facebook no longer support IE7, I won't either. I have a lot less funding than they do.
I know this doesn't fix the need to use VM for MAC users, but there should be ways around that too. With an 8 core processor PC computer, you can VM MAC with 4 cores, same for PC, and run 4 displays, two for each OS. Expensive, but this is our business. In most business models, it is not uncommon to spend tens of thousands of dollars on equipment. We shouldn't think of ourselves any differently. Invest in your success.