Make sure you have python in path,if not,win key + r, type in "%appdata%"(without the qotes) open local directory, then go to Programs directory ,open python and then select your python version directory. Click on file tab and select copy path and close file explorer.
Then do win key + r again, type control and hit enter. search for environment variables. click on the result, you will get a window. In the bottom right corner click on environmental variables. In the system side find path, select it and click on edit. In the new window, click on new and paste the path in there. Click ok and then apply in the first window. Restart your PC. Then do win + r for the last time, type cmd and do ctrl + shift + enter. Grant the previliges and open file explorer, goto your script and copy its path. Go back into cmd , type in "python" and paste the path and hit enter. Done
This problem mostly occurs because there could be another istance of the code running, from some previous tests you did most probably. Find out and close any other instance or if it is ok, try restarting the server.
I received the exact same error message. Except that my error message said "Could not load file or assembly 'EntityFramework, Version=6.0.0.0...", because I installed EF 6.1.1. Here's what I did to resolve the problem.
1) I started NuGet Manager Console by clicking on Tools > NuGet Package Manager > Package Manager Console 2) I uninstalled the installed EntityFramework 6.1.1 by typing the following command:
Uninstall-package EntityFramework
3) Once I received confirmation that the package has been uninstalled successfully, I installed the 5.0.0 version by typing the following command:
Install-Package EntityFramework -version 5.0.0
The problem is resolved.
I encountered the same problem to configure Git on a collaborative development platform that I have to manage.
To solve it :
I've Updated the release of Curl installed on the server. Download the last version on the website Download page of curland follow the installation proceedings Installation proceedings of curl
Get back the certificate of the authority which delivers the certificate for the server.
Add this certificate to the CAcert file used by curl. On my server it is located in /etc/pki/tls/certs/ca-bundle.crt
.
Configure git to use this certificate file by editing the .gitconfig file and set the sslcainfo path. sslcainfo= /etc/pki/tls/certs/ca-bundle.crt
On the client machine you must get the certificate and configure the .gitconfig file too.
I hope this will help some of you.
You could do this:
int x = 0x12345678;
x = ( x >> 24 ) | (( x << 8) & 0x00ff0000 )| ((x >> 8) & 0x0000ff00) | ( x << 24) ;
printf("value = %x", x); // x will be printed as 0x78563412
You could do that with services or factories. They are essentially the same apart for some core differences. I found this explanation on thinkster.io to be the easiest to follow. Simple, to the point and effective.
Extract jar file for ex. with winrar and use CAVAJ:
Cavaj Java Decompiler is a graphical freeware utility that reconstructs Java source code from CLASS files.
here is video tutorial if you need: https://www.youtube.com/watch?v=ByLUeem7680
import re
url = '<p>Hello World</p><a href="http://example.com">More Examples</a><a href="http://example2.com">Even More Examples</a>'
urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', url)
>>> print urls
['http://example.com', 'http://example2.com']
You do not need to use the while True:
loop in this case. There is a much simpler way to use the time condition directly:
import time
# timeout variable can be omitted, if you use specific value in the while condition
timeout = 300 # [seconds]
timeout_start = time.time()
while time.time() < timeout_start + timeout:
test = 0
if test == 5:
break
test -= 1
You have a few options other than using public key authentication:
If you decide to give sshpass a chance here is a working script snippet to do so:
export SSHPASS=your-password-here
sshpass -e sftp -oBatchMode=no -b - sftp-user@remote-host << !
cd incoming
put your-log-file.log
bye
!
You need to use delegates and protocols. Here is a site with an example http://iosdevelopertips.com/objective-c/the-basics-of-protocols-and-delegates.html
I know that this question has been answered, And all the answers are nice. But I wanted to add my two cents to this question for people who have similar (but not exactly the same) problem.
In a more general way, we can do something like this:
$('body').click(function(evt){
if(!$(evt.target).is('#menu_content')) {
//event handling code
}
});
This way we can handle not only events fired by anything except element with id menu_content
but also events that are fired by anything except any element that we can select using CSS selectors.
For instance in the following code snippet I am getting events fired by any element except all <li>
elements which are descendants of div element with id myNavbar
.
$('body').click(function(evt){
if(!$(evt.target).is('div#myNavbar li')) {
//event handling code
}
});
You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:
([0-9]+)\s+((\bseconds\b)|(\bminutes\b))
Without those you were either matching a number followed by seconds OR just the word minutes
begin transaction
// execute SQL code here
rollback transaction
If you've already executed the query and want to roll it back, unfortunately your only real option is to restore a database backup. If you're using Full backups, then you should be able to restore the database to a specific point in time.
If Postgres was downloaded and installed, running this should fix the issue:
sudo mkdir -p /etc/paths.d &&
echo /Applications/Postgres.app/Contents/Versions/latest/bin | sudo tee
/etc/paths.d/postgresapp
Restart the terminal and you'll be able to use psql
command.
consider two list L1 ans L2
Using Java8 we can easily find it out
L1.stream().filter(L2::contains).collect(Collectors.toList())
Join like this:
ON a.userid = b.sourceid AND a.listid = b.destinationid;
The following script set the sequence to a desired value:
Given a freshly created sequence named PCS_PROJ_KEY_SEQ and table PCS_PROJ:
BEGIN
DECLARE
PROJ_KEY_MAX NUMBER := 0;
PROJ_KEY_CURRVAL NUMBER := 0;
BEGIN
SELECT MAX (PROJ_KEY) INTO PROJ_KEY_MAX FROM PCS_PROJ;
EXECUTE IMMEDIATE 'ALTER SEQUENCE PCS_PROJ_KEY_SEQ INCREMENT BY ' || PROJ_KEY_MAX;
SELECT PCS_PROJ_KEY_SEQ.NEXTVAL INTO PROJ_KEY_CURRVAL FROM DUAL;
EXECUTE IMMEDIATE 'ALTER SEQUENCE PCS_PROJ_KEY_SEQ INCREMENT BY 1';
END;
END;
/
You are assigning a numeric value to a text field. You have to convert the numeric value to a string with:
String.valueOf(variable)
You can include JQuery using any of the following:
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
- http://code.jquery.com/jquery-latest.min.js (never use this link on production server)
Your code placement can look something like this
```
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
$('input[type=radio]').change(function() {
$('input[type=radio]').each(function(index) {
$(this).closest('tr').removeClass('selected');
});
$(this).closest('tr').addClass('selected');
});
});
</script>
```
In addition to @ImportanceOfBeingErnest's post, I use the following line to add a legend at an absolute position in a plot.
plt.legend(bbox_to_anchor=(1.0,1.0),\
bbox_transform=plt.gcf().transFigure)
For unknown reasons, bbox_transform=fig.transFigure
does not work with me.
To add to the answers above, the App Domain is required for security reasons. For example, your app has been sending the browser to "www.example.com/PAGE_NAME_HERE"
, but suddenly a third party application (or something else) sends the user to "www.supposedlymaliciouswebsite.com/PAGE_HERE"
, then a 191 error is thrown saying that this wasn't part of the app domains you listed in your Facebook application settings.
For me it worked like the code below. I made a difference between RouterModule.forRoot
and RouterModule.forChild
. Then in the child define the parent path and in the children array the childs.
parent-routing.module.ts
RouterModule.forRoot([
{
path: 'parent', //parent path, define the component that you imported earlier..
component: ParentComponent,
}
]),
RouterModule.forChild([
{
path: 'parent', //parent path
children: [
{
path: '',
redirectTo: '/parent/childs', //full child path
pathMatch: 'full'
},
{
path: 'childs',
component: ParentChildsComponent,
},
]
}
])
Hope this helps.
I would use inspect.currentframe().f_back.f_code.co_name
. Its use hasn't been covered in any of the prior answers which are mainly of one of three types:
inspect.stack
but it's known to be too slow.sys._getframe
which is an internal private function given its leading underscore, and so its use is implicitly discouraged.inspect.getouterframes(inspect.currentframe(), 2)[1][3]
but it's entirely unclear what [1][3]
is accessing.import inspect
from types import FrameType
from typing import cast
def caller_name() -> str:
"""Return the calling function's name."""
# Ref: https://stackoverflow.com/a/57712700/
return cast(FrameType, cast(FrameType, inspect.currentframe()).f_back).f_code.co_name
if __name__ == '__main__':
def _test_caller_name() -> None:
assert caller_name() == '_test_caller_name'
_test_caller_name()
Note that cast(FrameType, frame)
is used to satisfy mypy
.
Acknowlegement: comment by 1313e for an answer.
I know this is an old thread but I just stumbled across.
So heres how I would do it, with your local template variable on the input field you can set the value of the input like below
<input mdInput placeholder="Name" #filterName name="filterName" >
@ViewChild() input: ElementRef
public clear() {
this.input.NativeElement.value = '';
}
Pretty sure this will not set the form back to pristine but you can then reset this in the same function using the markAsPristine()
function
This should work:
if (!string.IsNullOrWhiteSpace(dateTimeEnd))
eventCustom.DateTimeEnd = DateTime.Parse(dateTimeEnd);
else
eventCustom.DateTimeEnd = null;
Note that this will throw an exception if the string is not in the correct format.
This can be solved also by izip
ping the dataframe (iterator) with an offset version of itself.
Of course the indexing error cannot be reproduced this way.
Check this out
import pandas as pd
from itertools import izip
df = pd.DataFrame(['AA', 'BB', 'CC'], columns = ['value'])
for id1, id2 in izip(df.iterrows(),df.ix[1:].iterrows()):
print id1[1]['value']
print id2[1]['value']
which gives
AA
BB
BB
CC
It looks like SyndFeed
is not using generics.
You could either have an unsafe cast and a warning suppression:
@SuppressWarnings("unchecked")
List<SyndEntry> entries = (List<SyndEntry>) sf.getEntries();
or call Collections.checkedList - although you'll still need to suppress the warning:
@SuppressWarnings("unchecked")
List<SyndEntry> entries = Collections.checkedList(sf.getEntries(), SyndEntry.class);
Tomcat is not running. Your search is showing you the grep process, which is searching for tomcat. Of course, by the time you see that output, grep is no longer running, so the pid is no longer valid.
You can add the collapse
component to the links like this..
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#home" data-toggle="collapse" data-target=".navbar-collapse.show">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#about-us" data-toggle="collapse" data-target=".navbar-collapse.show">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#pricing" data-toggle="collapse" data-target=".navbar-collapse.show">Pricing</a>
</li>
</ul>
BS3 demo using 'data-toggle' method
Or, (perhaps a better way) use jQuery like this..
$('.navbar-nav>li>a').on('click', function(){
$('.navbar-collapse').collapse('hide');
});
Update 2019 - Bootstrap 4
The navbar has changed, but the "close after click" method is still the same:
BS4 demo jQuery method
BS4 demo data-toggle
method
Update 2021 - Bootstrap 5 (beta)
Use javascript to add a click event listener on the menu items to close the Collapse navbar..
const navLinks = document.querySelectorAll('.nav-item')
const menuToggle = document.getElementById('navbarSupportedContent')
const bsCollapse = new bootstrap.Collapse(menuToggle)
navLinks.forEach((l) => {
l.addEventListener('click', () => { bsCollapse.toggle() })
})
Or, Use the data-bs-toggle
and data-bs-target
data attributes in the markup on each link to toggle the Collapse navbar...
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto">
<li class="nav-item active">
<a class="nav-link" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Disabled</a>
</li>
</ul>
<form class="d-flex my-2 my-lg-0">
<input class="form-control me-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</div>
</nav>
From $http.get
docs, the second parameter is a configuration object:
get(url, [config]);
Shortcut method to perform
GET
request.
You may change your code to:
$http.get('accept.php', {
params: {
source: link,
category_id: category
}
});
Or:
$http({
url: 'accept.php',
method: 'GET',
params: {
source: link,
category_id: category
}
});
As a side note, since Angular 1.6: .success
should not be used anymore, use .then
instead:
$http.get('/url', config).then(successCallback, errorCallback);
You can return an object of a Class in Java.
If you are returning more than 1 value that are related, then it makes sense to encapsulate them into a class and then return an object of that class.
If you want to return unrelated values, then you can use Java's built-in container classes like Map, List, Set etc. Check the java.util package's JavaDoc for more details.
If you're using windows, the command is:
type %userprofile%\.ssh\id_rsa.pub
_x000D_
it should print the key (if you have one). You should copy the entire result. If none is present, then do:
ssh-keygen -t rsa -C "[email protected]" -b 4096
_x000D_
I modified rushidesai1's answer to include a working example.
import java.io.*;
import java.util.*;
public class JsonMarshaller<T> {
private static ClassLoader loader = JsonMarshaller.class.getClassLoader();
public static void main(String[] args) {
try {
JsonMarshallerUnmarshaller<Station> marshaller = new JsonMarshallerUnmarshaller<>(Station.class);
String jsonString = read(loader.getResourceAsStream("data.json"));
List<Station> stations = marshaller.unmarshal(jsonString);
stations.forEach(System.out::println);
System.out.println(marshaller.marshal(stations));
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("resource")
public static String read(InputStream ios) {
return new Scanner(ios).useDelimiter("\\A").next(); // Read the entire file
}
}
Station [id=123, title=my title, name=my name]
Station [id=456, title=my title 2, name=my name 2]
[{"id":123,"title":"my title","name":"my name"},{"id":456,"title":"my title 2","name":"my name 2"}]
import java.io.*;
import java.util.List;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
public class JsonMarshallerUnmarshaller<T> {
private ObjectMapper mapper;
private Class<T> targetClass;
public JsonMarshallerUnmarshaller(Class<T> targetClass) {
AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
mapper = new ObjectMapper();
mapper.getDeserializationConfig().with(introspector);
mapper.getSerializationConfig().with(introspector);
this.targetClass = targetClass;
}
public List<T> unmarshal(String jsonString) throws JsonParseException, JsonMappingException, IOException {
return parseList(jsonString, mapper, targetClass);
}
public String marshal(List<T> list) throws JsonProcessingException {
return mapper.writeValueAsString(list);
}
public static <E> List<E> parseList(String str, ObjectMapper mapper, Class<E> clazz)
throws JsonParseException, JsonMappingException, IOException {
return mapper.readValue(str, listType(mapper, clazz));
}
public static <E> List<E> parseList(InputStream is, ObjectMapper mapper, Class<E> clazz)
throws JsonParseException, JsonMappingException, IOException {
return mapper.readValue(is, listType(mapper, clazz));
}
public static <E> JavaType listType(ObjectMapper mapper, Class<E> clazz) {
return mapper.getTypeFactory().constructCollectionType(List.class, clazz);
}
}
public class Station {
private long id;
private String title;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return String.format("Station [id=%s, title=%s, name=%s]", id, title, name);
}
}
[{
"id": 123,
"title": "my title",
"name": "my name"
}, {
"id": 456,
"title": "my title 2",
"name": "my name 2"
}]
This is a good description of its uses and shortcomings. You essentially use it whenever you need to do fast low-level I/O. If you were going to implement a TCP/IP protocol or if you were writing a database (DBMS) this class would come in handy.
If you want them to be displayed side by side, why is sideContent the child of mainContent? make them siblings then use:
float:left; display:inline; width: 49%;
on both of them.
#mainContent, #sideContent {float:left; display:inline; width: 49%;}
$("#closeLink").click(closeIt);
Let's say you want to call your function passing some args to it i.e., closeIt(1, false)
. Then, you should build an anonymous function and call closeIt
from it.
$("#closeLink").click(function() {
closeIt(1, false);
});
I had a similar problem with my tests and found somewhere in the Web, that you have to go to Build Path in your project's properties and move Maven Dependencies above JRE System Library. That seems to have worked for me.
I don't think there is a way to tell which program to use from just the .db extension. It could even be an encrypted database which can't be opened. You can MS Access, or a sqlite manager.
Edit: Try to rename the file to .txt and open it with a text editor. The first couple of words in the file could tell you the DB Type.
If it is a SQLite database, it will start with "SQLite format 3"
12000 elements is nothing in Python... and actually the number of elements can go as far as the Python interpreter has memory on your system.
var model = {"Id": "xx", "Name":"Ravi"};
$.ajax({ url: 'test/set',
type: "POST",
data: model,
success: function (res) {
if (res != null) {
alert("done.");
}
},
error: function (res) {
}
});
I'm not aware of a CSS-only solution.
As you mentioned, filters are the canonical approach to creating drop shadow effects in SVG. The SVG specification includes an example of this.
inner join with scala
val joinedDataFrame = PersonDf.join(ProfileDf ,"personId")
joinedDataFrame.show
I saw the answers here, and it is answering the question of sharing data between controllers, but what should I do if I want one controller to notify the other about the fact that the data has been changed (without using broadcast)? EASY! Just using the famous visitor pattern:
myApp.service('myService', function() {
var visitors = [];
var registerVisitor = function (visitor) {
visitors.push(visitor);
}
var notifyAll = function() {
for (var index = 0; index < visitors.length; ++index)
visitors[index].visit();
}
var myData = ["some", "list", "of", "data"];
var setData = function (newData) {
myData = newData;
notifyAll();
}
var getData = function () {
return myData;
}
return {
registerVisitor: registerVisitor,
setData: setData,
getData: getData
};
}
myApp.controller('firstController', ['$scope', 'myService',
function firstController($scope, myService) {
var setData = function (data) {
myService.setData(data);
}
}
]);
myApp.controller('secondController', ['$scope', 'myService',
function secondController($scope, myService) {
myService.registerVisitor(this);
this.visit = function () {
$scope.data = myService.getData();
}
$scope.data = myService.getData();
}
]);
In this simple manner, one controller can update another controller that some data has been updated.
The traditional for loop in Objective-C is inherited from standard C and takes the following form:
for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
// Do something.
}
For example, to print the numbers from 1 to 10, you could use the for loop:
for (int i = 1; i <= 10; i++)
{
NSLog(@"%d", i);
}
On the other hand, the for in loop was introduced in Objective-C 2.0, and is used to loop through objects in a collection, such as an NSArray instance. For example, to loop through a collection of NSString objects in an NSArray and print them all out, you could use the following format.
for (NSString* currentString in myArrayOfStrings)
{
NSLog(@"%@", currentString);
}
This is logically equivilant to the following traditional for loop:
for (int i = 0; i < [myArrayOfStrings count]; i++)
{
NSLog(@"%@", [myArrayOfStrings objectAtIndex:i]);
}
The advantage of using the for in loop is firstly that it's a lot cleaner code to look at. Secondly, the Objective-C compiler can optimize the for in loop so as the code runs faster than doing the same thing with a traditional for loop.
Hope this helps.
If you want to prevent all caching (e.g. force a reload when using the back button) you need:
no-cache for IE
no-store for Firefox
There's my information about this here:
http://blog.httpwatch.com/2008/10/15/two-important-differences-between-firefox-and-ie-caching/
If you are looking to do an exact match, use the following syntax:
(param)?
.
Eg.
<Route path={`my/(exact)?/path`} component={MyComponent} />
The nice thing about this is that you'll have props.match
to play with, and you don't need to worry about checking the value of the optional parameter:
{ props: { match: { "0": "exact" } } }
You gave the best answer to yourself in the OP: Hash[h.sort]
If you crave for more possibilities, here is in-place modification of the original hash to make it sorted:
h.keys.sort.each { |k| h[k] = h.delete k }
I was creating a JSON-LD to create a site review script.
**DECLARE @json VARCHAR(MAX);**
The actual JSON is about 94K.
I got this to work by using the CAST('' AS VARCHAR(MAX)) + @json, as explained by other contributors:-
so **SET @json = CAST('' AS VARCHAR(MAX)) + (SELECT .....**
2/ I also had to change the Query Options:- Query Options -> 'results' -> 'grid' -> 'Maximum Characters received' -> 'non-XML Data' SET to 2000000. (I left the 'results' -> 'text' -> 'Maximum number of characters displayed in each column' as the default)
A solution for Nuget 3.2 on Visual Studio 2015 is:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<config>
<add key="repositoryPath" value="../lib" />
</config>
</configuration>
Using forward slash for parent folder. Save above file (nuget.config) in solution folder.
Reference is available here
You can use show innodb status
(or show engine innodb status
for newer versions of mysql) to get a list of all the actions currently pending inside the InnoDB engine. Buried in the wall of output will be the transactions, and what internal process ID they're running under.
You won't be able to force a commit or rollback of those transactions, but you CAN kill the MySQL process running them, which does essentially boil down to a rollback. It kills the processes' connection and causes MySQL to clean up the mess its left.
Here's what you'd want to look for:
------------
TRANSACTIONS
------------
Trx id counter 0 140151
Purge done for trx's n:o < 0 134992 undo n:o < 0 0
History list length 10
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 0 0, not started, process no 17004, OS thread id 140621902116624
MySQL thread id 10594, query id 10269885 localhost marc
show innodb status
In this case, there's just one connection to the InnoDB engine right now (my login, running the show
query). If that line were an actual connection/stuck transaction you'd want to terminate, you'd then do a kill 10594
.
Here is the TextWatcher
that allow only n number of digits after decimal point.
TextWatcher
private static boolean flag;
public static TextWatcher getTextWatcherAllowAfterDeci(final int allowAfterDecimal){
TextWatcher watcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
String str = s.toString();
int index = str.indexOf ( "." );
if(index>=0){
if((index+1)<str.length()){
String numberD = str.substring(index+1);
if (numberD.length()!=allowAfterDecimal) {
flag=true;
}else{
flag=false;
}
}else{
flag = false;
}
}else{
flag=false;
}
if(flag)
s.delete(s.length() - 1,
s.length());
}
};
return watcher;
}
How to use
yourEditText.addTextChangedListener(getTextWatcherAllowAfterDeci(1));
In SQL Server 2008 you can use Change Data Capture for this. Details of how to set it up on a table are here http://msdn.microsoft.com/en-us/library/cc627369.aspx
This is the most flexible/reusable way to reset all select boxes in your form.
var $form = $('form') // Replace with your form selector
$('select', $form).each(function() {
$(this).val($(this).prop('defaultSelected'));
});
In C Pi is defined in math.h: #define M_PI 3.14159265358979323846
Use this code, it will surely work:
<script type="text/javascript">_x000D_
$(document).ready(function () {_x000D_
setTimeout(function(){_x000D_
downloadImage();_x000D_
},1000)_x000D_
});_x000D_
_x000D_
function downloadImage(){_x000D_
html2canvas(document.querySelector("#dvContainer")).then(canvas => {_x000D_
a = document.createElement('a'); _x000D_
document.body.appendChild(a); _x000D_
a.download = "test.png"; _x000D_
a.href = canvas.toDataURL();_x000D_
a.click();_x000D_
}); _x000D_
}_x000D_
</script>
_x000D_
Just do not forget to include Html2CanvasJS file in your program. https://html2canvas.hertzen.com/dist/html2canvas.js
A .sql file is a set of commands that can be executed against the SQL server.
Sometimes the .sql file will specify the database, other times you may need to specify this.
You should talk to your DBA or whoever is responsible for maintaining your databases. They will probably want to give the file a quick look. .sql files can do a lot of harm, even inadvertantly.
See the other answers if you want to plunge ahead.
Here is a slightly concised edition of what Jason suggested:
DateTime? d; DateTime dt;
d = DateTime.TryParse(DateTime.Now.ToString(), out dt)? dt : (DateTime?)null;
In computer programming, a callback is executable code that is passed as an argument to other code.
C# has delegates for that purpose. They are heavily used with events, as an event can automatically invoke a number of attached delegates (event handlers).
You will need to know if the REST API you are calling supports GET
or POST
, or both methods. The code below is something that works for me, I'm calling my own web service API, so I already know what the API takes and what it will return. It supports both GET
and POST
methods, so the less sensitive info goes into the URL (GET)
, and the info like username and password is submitted as POST
variables. Also, everything goes over the HTTPS
connection.
Inside the API code, I encode an array I want to return into json format, then simply use PHP command echo $my_json_variable
to make that json string availabe to the client.
So as you can see, my API returns json data, but you need to know (or look at the returned data to find out) what format the response from the API is in.
This is how I connect to the API from the client side:
$processed = FALSE;
$ERROR_MESSAGE = '';
// ************* Call API:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.myapi.com/api.php?format=json&action=subscribe&email=" . $email_to_subscribe);
curl_setopt($ch, CURLOPT_POST, 1);// set post data to true
curl_setopt($ch, CURLOPT_POSTFIELDS,"username=myname&password=mypass"); // post data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close ($ch);
// returned json string will look like this: {"code":1,"data":"OK"}
// "code" may contain an error code and "data" may contain error string instead of "OK"
$obj = json_decode($json);
if ($obj->{'code'} == '1')
{
$processed = TRUE;
}else{
$ERROR_MESSAGE = $obj->{'data'};
}
...
if (!$processed && $ERROR_MESSAGE != '') {
echo $ERROR_MESSAGE;
}
BTW, I also tried to use file_get_contents()
method as some of the users here suggested, but that din't work well for me. I found out the curl
method to be faster and more reliable.
Did some quick tests, and perhaps unsurprisingly the built-in version using dataframe.columns.values.tolist()
is the fastest:
In [1]: %timeit [column for column in df]
1000 loops, best of 3: 81.6 µs per loop
In [2]: %timeit df.columns.values.tolist()
10000 loops, best of 3: 16.1 µs per loop
In [3]: %timeit list(df)
10000 loops, best of 3: 44.9 µs per loop
In [4]: % timeit list(df.columns.values)
10000 loops, best of 3: 38.4 µs per loop
(I still really like the list(dataframe)
though, so thanks EdChum!)
On Telegram Desktop for macOS, the shortcuts differ. You can right-click a highlighted text, then hover over Transformations
to see the available options:
You should define a key name while storing data to local storage which should be a string and value should be a string
localStorage.setItem('dataSource', this.dataSource.length);
and to print, you should use getItem
console.log(localStorage.getItem('dataSource'));
If you'd rather transform your array, then the iterator
parameter of underscore's map
function is also passed the index as a second argument. So:
_.map([1, 4, 2, 66, 444, 9], function(value, index){ return index + ':' + value; });
... returns:
["0:1", "1:4", "2:2", "3:66", "4:444", "5:9"]
CSS:
.auto { cursor: auto; }
.default { cursor: default; }
.none { cursor: none; }
.context-menu { cursor: context-menu; }
.help { cursor: help; }
.pointer { cursor: pointer; }
.progress { cursor: progress; }
.wait { cursor: wait; }
.cell { cursor: cell; }
.crosshair { cursor: crosshair; }
.text { cursor: text; }
.vertical-text { cursor: vertical-text; }
.alias { cursor: alias; }
.copy { cursor: copy; }
.move { cursor: move; }
.no-drop { cursor: no-drop; }
.not-allowed { cursor: not-allowed; }
.all-scroll { cursor: all-scroll; }
.col-resize { cursor: col-resize; }
.row-resize { cursor: row-resize; }
.n-resize { cursor: n-resize; }
.e-resize { cursor: e-resize; }
.s-resize { cursor: s-resize; }
.w-resize { cursor: w-resize; }
.ns-resize { cursor: ns-resize; }
.ew-resize { cursor: ew-resize; }
.ne-resize { cursor: ne-resize; }
.nw-resize { cursor: nw-resize; }
.se-resize { cursor: se-resize; }
.sw-resize { cursor: sw-resize; }
.nesw-resize { cursor: nesw-resize; }
.nwse-resize { cursor: nwse-resize; }
You can also have the cursor be an image:
.img-cur {
cursor: url(images/cursor.png), auto;
}
I got this error when attempting to build with Xcode 10. It appears to be a bug in the Swift compiler. Building with Whole Module Optimization
on, resolves the issue: https://forums.swift.org/t/illegal-instruction-4-when-trying-to-compile-project/16118
This is not an ideal solution, I will continue to use Xcode 9.4.1 until this issue is resolved.
A very simple solution considering you have object A and B:
foreach($objB AS $var=>$value){
$objA->$var = $value;
}
That's all. You now have objA with all values from objB.
The advantage comes into account when the operations can be executed in parallel. (See http://java.dzone.com/articles/devoxx-2012-java-8-lambda-and - the section about internal and external iteration)
The main advantage from my point of view is that the implementation of what is to be done within the loop can be defined without having to decide if it will be executed in parallel or sequential
If you want your loop to be executed in parallel you could simply write
joins.parallelStream().forEach(join -> mIrc.join(mSession, join));
You will have to write some extra code for thread handling etc.
Note: For my answer I assumed joins implementing the java.util.Stream
interface. If joins implements only the java.util.Iterable
interface this is no longer true.
The correct answer is increasing fastcgi_read_timeout in your Nginx configuration.
Simple as that!
Selenium provides a convenient Select
class to work with select -> option
constructs:
from selenium import webdriver
from selenium.webdriver.support.ui import Select
driver = webdriver.Firefox()
driver.get('url')
select = Select(driver.find_element_by_id('fruits01'))
# select by visible text
select.select_by_visible_text('Banana')
# select by value
select.select_by_value('1')
See also:
This answer is just as good the top plugin-management answer above (which is to say, it's terrible).
Just delete all the offending xml code in the pom.
Done. Problem solved (except you just broke your maven config...).
Devs should be very careful they understand plugin-management tags before doing any of these solutions. Just slapping plugin-management around your plugins are random is likely to break the maven build for everyone else just to get eclipse to work.
Check Keyboard Commands given in the Android Studio Tips & Trick documentation:
You'd use font-weight: bold
.
Do you want to make the entire document bold? Or just parts of it?
Everytime the size of the string is undetermined at compile time you have to allocate memory with malloc (or some equiviallent method). In your case you know the size of your strings at compile time (sizeof("something") and sizeof("something else")).
The closest equivalent to Java's toString
is to implement __str__
for your class. Put this in your class definition:
def __str__(self):
return "foo"
You may also want to implement __repr__
to aid in debugging.
See here for more information:
A comparison between the different Visual Studio Express editions can be found at Visual Studio Express (archive.org link). The difference between Windows and Windows Desktop is that with the Windows edition you can build Windows Store Apps (using .NET, WPF/XAML) while the Windows Desktop edition allows you to write classic Windows Desktop applications. It is possible to install both products on the same machine.
Visual Studio Express 2010 allows you to build Windows Desktop applications. Writing Windows Store applications is not possible with this product.
For learning I would suggest Notepad and the command line. While an IDE provides significant productivity enhancements to professionals, it can be intimidating to a beginner. If you want to use an IDE nevertheless I would recommend Visual Studio Express 2013 for Windows Desktop.
More on gdoron's answer, it can also be done this way:
$(window).on("click", "#filter", function() {
alert('clicked!');
});
without the need to place them all into $(function(){...})
Is it a replacement for XML based configuration?
Not completely, but confguration that corresponds closely to code structures (such as JPA mappings or dependency injection in Spring) can often be replaced with annotations, and is then usually much less verbose, annoying and painful. Pretty much all notable frameworks have made this switch, though the old XML configuration usually remains as an option.
This is only true if you're iterating through an array; what if you were iterating through a different kind of collection that has no notion of accessing by index? In the array case, the easiest way to retain the index is to simply use a vanilla for loop.
Run command rndc querylog on
or add querylog yes;
to options{};
section in named.conf
to activate that channel.
Also make sure you’re checking correct directory if your bind is chrooted.
Although this is an old question, I had the same question when using the Standard console version. The answer can be found in the Debian Live manual under the section 10.1 Customizing the live user. It says:
It is also possible to change the default username "user" and the default password "live".
I tried the username user
and password live
and it did work. If you want to run commands as root you can preface each command with sudo
I spent a lot of time trying different answers all around the internet, and I suspect the reasons why one thing works for some people and not for others is due to very small weird differences in application. For context, I needed to read in file names from a csv file that had strange and/or unmappable unicode characters and write them to a new csv file. For what it's worth, here's what worked for me:
s = '\u00e7\u00a3\u0085\u00e5\u008d\u0095' # csv freaks if you try to write this
s = repr(s.encode('utf-8', 'ignore'))[2:-1]
Personally, I like to add meaning to long if-statements. I would have to search through code to find an appropriate example, but here's the first example that comes to mind: let's say I happen to run into some quirky logic where I want to display a certain page depending on many variables.
English: "If the logged-in user is NOT an administrator teacher, but is just a regular teacher, and is not a student themselves..."
if not user.isAdmin() and user.isTeacher() and not user.isStudent():
doSomething()
Sure this might look fine, but reading those if statements is a lot of work. How about we assign the logic to label that makes sense. The "label" is actually the variable name:
displayTeacherPanel = not user.isAdmin() and user.isTeacher() and not user.isStudent()
if displayTeacherPanel:
showTeacherPanel()
This may seem silly, but you might have yet another condition where you ONLY want to display another item if, and only if, you're displaying the teacher panel OR if the user has access to that other specific panel by default:
if displayTeacherPanel or user.canSeeSpecialPanel():
showSpecialPanel()
Try writing the above condition without using variables to store and label your logic, and not only do you end up with a very messy, hard-to-read logical statement, but you also just repeated yourself. While there are reasonable exceptions, remember: Don't Repeat Yourself (DRY).
for Chrome, Firefox, Edge (and other evergreen browsers)
Simply position: sticky; top: 0;
your th
elements:
/* Fix table head */
.tableFixHead { overflow-y: auto; height: 100px; }
.tableFixHead th { position: sticky; top: 0; }
/* Just common table stuff. */
table { border-collapse: collapse; width: 100%; }
th, td { padding: 8px 16px; }
th { background:#eee; }
_x000D_
<div class="tableFixHead">
<table>
<thead>
<tr><th>TH 1</th><th>TH 2</th></tr>
</thead>
<tbody>
<tr><td>A1</td><td>A2</td></tr>
<tr><td>B1</td><td>B2</td></tr>
<tr><td>C1</td><td>C2</td></tr>
<tr><td>D1</td><td>D2</td></tr>
<tr><td>E1</td><td>E2</td></tr>
</tbody>
</table>
</div>
_x000D_
PS: if you need borders for TH elements th {box-shadow: 1px 1px 0 #000; border-top: 0;}
will help (since the default borders are not painted correctly on scroll).
For a variant of the above that uses just a bit of JS in order to accommodate for IE11 see this answer Table fixed header and scrollable body
in "String.xml" you can notice any String or value you want to use, here are two examples:
<string name="app_name">My Calculator App
</string>
<color name="color_menu_home">#ffcccccc</color>
Used for the layout.xml: android:text="@string/app_name"
The advantage: you can use them as often you want, you only need to link them in your Layout-xml, and you can change the String-Content easily in the strings.xml, without searching in your source-code for the right position. Important for changing language, you only need to replace the strings.xml - file
Vanilla 1-liner for IE8+:
parent !== child && parent.contains(child);
Here, how it works:
function contains(parent, child) {_x000D_
return parent !== child && parent.contains(child);_x000D_
}_x000D_
_x000D_
var parentEl = document.querySelector('#parent'),_x000D_
childEl = document.querySelector('#child')_x000D_
_x000D_
if (contains(parentEl, childEl)) {_x000D_
document.querySelector('#result').innerText = 'I confirm, that child is within parent el';_x000D_
}_x000D_
_x000D_
if (!contains(childEl, parentEl)) {_x000D_
document.querySelector('#result').innerText += ' and parent is not within child';_x000D_
}
_x000D_
<div id="parent">_x000D_
<div>_x000D_
<table>_x000D_
<tr>_x000D_
<td><span id="child"></span></td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
</div>_x000D_
<div id="result"></div>
_x000D_
The resolution is 480 dpi, the launcher icon is 144*144px all is scaled 3x respect to mdpi (so called "base", "baseline" or "normal") sizes.
Here's an example of how you'd use filter
within your AngularJS JavaScript (rather than in an HTML element).
In this example, we have an array of Country records, each containing a name and a 3-character ISO code.
We want to write a function which will search through this list for a record which matches a specific 3-character code.
Here's how we'd do it without using filter
:
$scope.FindCountryByCode = function (CountryCode) {
// Search through an array of Country records for one containing a particular 3-character country-code.
// Returns either a record, or NULL, if the country couldn't be found.
for (var i = 0; i < $scope.CountryList.length; i++) {
if ($scope.CountryList[i].IsoAlpha3 == CountryCode) {
return $scope.CountryList[i];
};
};
return null;
};
Yup, nothing wrong with that.
But here's how the same function would look, using filter
:
$scope.FindCountryByCode = function (CountryCode) {
// Search through an array of Country records for one containing a particular 3-character country-code.
// Returns either a record, or NULL, if the country couldn't be found.
var matches = $scope.CountryList.filter(function (el) { return el.IsoAlpha3 == CountryCode; })
// If 'filter' didn't find any matching records, its result will be an array of 0 records.
if (matches.length == 0)
return null;
// Otherwise, it should've found just one matching record
return matches[0];
};
Much neater.
Remember that filter
returns an array as a result (a list of matching records), so in this example, we'll either want to return 1 record, or NULL.
Hope this helps.
We also log old and new values and the column they are from as well as the primary key of the table being audited in an audit detail table. Think what you need the audit table for? Not only do you want to know who made a change and when, but when a bad change happens, you want a fast way to put the data back.
While you are designing, you should write the code to recover data. When you need to recover, it is usually in a hurry, best to already be prepared.
To Access the element you need to get an iterator . But Iterator does not guarantee in a particular order unless it is some Exceptional case. so it is not sure to get the first Element.
All other answers, and mainly about list comprehension, are great. But just to explain your error:
strip_list = []
for lengths in range(1,20):
strip_list.append(0) #longest word in the text file is 20 characters long
for a in lines:
strip_list.append(lines[a].strip())
a
is a member of your list, not an index. What you could write is this:
[...]
for a in lines:
strip_list.append(a.strip())
Another important comment: you can create an empty list this way:
strip_list = [0] * 20
But this is not so useful, as .append
appends stuff to your list. In your case, it's not useful to create a list with defaut values, as you'll build it item per item when appending stripped strings.
So your code should be like:
strip_list = []
for a in lines:
strip_list.append(a.strip())
But, for sure, the best one is this one, as this is exactly the same thing:
stripped = [line.strip() for line in lines]
In case you have something more complicated than just a .strip
, put this in a function, and do the same. That's the most readable way to work with lists.
Hope it help. :)
const unsigned attribName = getname();
const unsigned attribVal = getvalue();
const char *attrName=NULL, *attrVal=NULL;
attrName = (const char*) attribName;
attrVal = (const char*) attribVal;
here's what I'd do
2.2.1 :015 > class String; def remove!(start_index, end_index) (end_index - start_index + 1).times{ self.slice! start_index }; self end; end;
2.2.1 :016 > "idliketodeleteHEREallthewaytoHEREplease".remove! 14, 32
=> "idliketodeleteplease"
2.2.1 :017 > ":)".remove! 1,1
=> ":"
2.2.1 :018 > "ohnoe!".remove! 2,4
=> "oh!"
Formatted on multiple lines:
class String
def remove!(start_index, end_index)
(end_index - start_index + 1).times{ self.slice! start_index }
self
end
end
You are creating three lists, instead of using one (you don't use the return value of DirSearch(d)
). You can use a list as a parameter to save the state:
static void Main(string[] args)
{
var list = new List<string>();
DirSearch(list, ".");
foreach (var file in list)
{
Console.WriteLine(file);
}
}
public static void DirSearch(List<string> files, string startDirectory)
{
try
{
foreach (string file in Directory.GetFiles(startDirectory, "*.*"))
{
string extension = Path.GetExtension(file);
if (extension != null)
{
files.Add(file);
}
}
foreach (string directory in Directory.GetDirectories(startDirectory))
{
DirSearch(files, directory);
}
}
catch (System.Exception e)
{
Console.WriteLine(e.Message);
}
}
From LDAP, there is not a query method to determine an empty string.
The best practice would be to scrub your data inputs to LDAP as an empty or null value in LDAP is no value at all.
To determine this you would need to query for all with a value (manager=*) and then use code to determine the ones that were a "space" or null value.
And as Terry said, storing an empty or null value in an attribute of DN syntax is wrong.
Some LDAP server implementations will not permit entering a DN where the DN entry does not exist.
Perhaps, you could, if your DN's are consistent, use something like:
(&(!(manager=cn*))(manager=*))
This should return any value of manager where there was a value for manager and it did not start with "cn".
However, some LDAP implementations will not allow sub-string searches on DN syntax attributes.
-jim
Please change your code as follows:
<script>
var button = document.getElementById("reactionTester");
var start = document.getElementById("start");
function init() {
var startInterval/*in milliseconds*/ = Math.floor(Math.random()*30)*1000;
setTimeout(startTimer,startInterval);
}
function startTimer(){
document.write("hey");
}
</script>
See if that helps. Basically, the difference is references the 'startTimer' function instead of executing it.
Use above annotation if someone is facing :--org.hibernate.jpa.HibernatePersistenceProvider persistence provider when it attempted to create the container entity manager factory for the paymentenginePU persistence unit. The following error occurred: [PersistenceUnit: paymentenginePU] Unable to build Hibernate SessionFactory ** This is a solution if you are using Audit table.@Audit
Use:- @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) on superclass.
As of version 2.4 of the Maven Dependency Plugin, you can also define a target destination for the artifact by using the -Ddest flag. It should point to a filename (not a directory) for the destination artifact. See the parameter page for additional parameters that can be used
mvn org.apache.maven.plugins:maven-dependency-plugin:2.4:get \
-DremoteRepositories=http://download.java.net/maven/2 \
-Dartifact=robo-guice:robo-guice:0.4-SNAPSHOT \
-Ddest=c:\temp\robo-guice.jar
$_SERVER['HTTP_REFERER']
is the answer
Steps to debug:-
In case you face any issue in kubernetes, first step is to check if kubernetes self applications are running fine or not.
Command to check:- kubectl get pods -n kube-system
If you see any pod is crashing, check it's logs
if getting NotReady
state error, verify network pod logs.
if not able to resolve with above, follow below steps:-
kubectl get nodes
# Check which node is not in ready state
kubectl describe node nodename
#nodename which is not in readystate
ssh to that node
execute systemctl status kubelet
# Make sure kubelet is running
systemctl status docker
# Make sure docker service is running
journalctl -u kubelet
# To Check logs in depth
Most probably you will get to know about error here, After fixing it reset kubelet with below commands:-
systemctl daemon-reload
systemctl restart kubelet
In case you still didn't get the root cause, check below things:-
Make sure your node has enough space and memory. Check for /var
directory space especially.
command to check: -df
-kh
, free -m
Verify cpu utilization with top command. and make sure any process is not taking an unexpected memory.
My first suggestion would be to learn a little about symbols first. Rails isn't the smallest framework ever, and while there's definitely lots to learn, most of it will start to make sense if you have at least a little bit of understanding what makes it different ("special") from other languages. As pointed out, there's no exact analog in any of the major languages, but they're heavily used by Rails, in order to make things read straightforwardly and perform well, which is the reason I brought it up. My very first exposure to Rails was also my first time looking at Ruby (well before 2.0), and the first thing that caught my eye was the goofy :things
they were passing around, and I asked, "WTF is that?"
Also, check out RubyQuiz, and read other peoples' answers on that site.
Create the script tag with a specific ID and then check if that ID exists?
Alternatively, loop through script tags checking for the script 'src' and make sure those are not already loaded with the same value as the one you want to avoid ?
Edit: following feedback that a code example would be useful:
(function(){
var desiredSource = 'https://sitename.com/js/script.js';
var scripts = document.getElementsByTagName('script');
var alreadyLoaded = false;
if(scripts.length){
for(var scriptIndex in scripts) {
if(!alreadyLoaded && desiredSource === scripts[scriptIndex].src) {
alreadyLoaded = true;
}
}
}
if(!alreadyLoaded){
// Run your code in this block?
}
})();
As mentioned in the comments (https://stackoverflow.com/users/1358777/alwin-kesler), this may be an alternative (not benchmarked):
(function(){
var desiredSource = 'https://sitename.com/js/script.js';
var scripts = document.getElementsByTagName('script');
var alreadyLoaded = false;
for(var scriptIndex in document.scripts) {
if(!alreadyLoaded && desiredSource === scripts[scriptIndex].src) {
alreadyLoaded = true;
}
}
if(!alreadyLoaded){
// Run your code in this block?
}
})();
Main Example
The example below will run myfile.sql on database mydatabase using schema myschema.
psql "dbname=mydatabase options=--search_path=myschema" -a -f myfile.sql
The way this works is the first argument to the psql command is the dbname argument. The docs mention a connection string can be provided.
If this parameter contains an = sign or starts with a valid URI prefix (postgresql:// or postgres://), it is treated as a conninfo string
The dbname keyword specifies the database to connect to and the options keyword lets you specify command-line options to send to the server at connection startup. Those options are detailed in the server configuration chapter. The option we are using to select the schema is search_path.
Another Example
The example below will connect to host myhost on database mydatabase using schema myschema. The =
special character must be url escaped with the escape sequence %3D
.
psql postgres://myuser@myhost?options=--search_path%3Dmyschema
Decode it.
>>> b'a string'.decode('ascii')
'a string'
To get bytes from string, encode it.
>>> 'a string'.encode('ascii')
b'a string'
You can mimic the Ping command.
Use Ajax to request a timestamp to your own server, define a timer using setTimeout to 5 seconds, if theres no response it try again.
If there's no response in 4 attempts, you can suppose that internet is down.
So you can check using this routine in regular intervals like 1 or 3 minutes.
That seems a good and clean solution for me.
The best way I've found is:
<script type="text/javascript">
$(document).ready(function() {
$.fancybox(
$("#WRAPPER_FOR_hidden_div_with_content_to_show").html(), //fancybox works perfect with hidden divs
{
//fancybox options
}
);
});
</script>
The key difference: NSMutableDictionary can be modified in place, NSDictionary cannot. This is true for all the other NSMutable* classes in Cocoa. NSMutableDictionary is a subclass of NSDictionary, so everything you can do with NSDictionary you can do with both. However, NSMutableDictionary also adds complementary methods to modify things in place, such as the method setObject:forKey:
.
You can convert between the two like this:
NSMutableDictionary *mutable = [[dict mutableCopy] autorelease];
NSDictionary *dict = [[mutable copy] autorelease];
Presumably you want to store data by writing it to a file. NSDictionary has a method to do this (which also works with NSMutableDictionary):
BOOL success = [dict writeToFile:@"/file/path" atomically:YES];
To read a dictionary from a file, there's a corresponding method:
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"/file/path"];
If you want to read the file as an NSMutableDictionary, simply use:
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/file/path"];
You can do this In the parent component declare:
get self(): ParenComponentClass {
return this;
}
In the child component,after include the import of ParenComponentClass, declare:
private _parent: ParenComponentClass ;
@Input() set parent(value: ParenComponentClass ) {
this._parent = value;
}
get parent(): ParenComponentClass {
return this._parent;
}
Then in the template of the parent you can do
<childselector [parent]="self"></childselector>
Now from the child you can access public properties and methods of parent using
this.parent
Wes McKinney (pandas' author) in Python for Data Analysis provides the following recipe:
groups = dict(list(gb))
which returns a dictionary whose keys are your group labels and whose values are DataFrames, i.e.
groups['foo']
will yield what you are looking for:
A B C
0 foo 1.624345 5
2 foo -0.528172 11
4 foo 0.865408 14
In case anyone had the same problem: check this as @PravinS suggested. I used the exact same code as shown there and it worked for me perfectly.
This is the relevant part of the server code that helped:
if (isset($_POST['btnUpload']))
{
$url = "URL_PATH of upload.php"; // e.g. http://localhost/myuploader/upload.php // request URL
$filename = $_FILES['file']['name'];
$filedata = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
if ($filedata != '')
{
$headers = array("Content-Type:multipart/form-data"); // cURL headers for file uploading
$postfields = array("filedata" => "@$filedata", "filename" => $filename);
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => true,
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $postfields,
CURLOPT_INFILESIZE => $filesize,
CURLOPT_RETURNTRANSFER => true
); // cURL options
curl_setopt_array($ch, $options);
curl_exec($ch);
if(!curl_errno($ch))
{
$info = curl_getinfo($ch);
if ($info['http_code'] == 200)
$errmsg = "File uploaded successfully";
}
else
{
$errmsg = curl_error($ch);
}
curl_close($ch);
}
else
{
$errmsg = "Please select the file";
}
}
html form should look something like:
<form action="uploadpost.php" method="post" name="frmUpload" enctype="multipart/form-data">
<tr>
<td>Upload</td>
<td align="center">:</td>
<td><input name="file" type="file" id="file"/></td>
</tr>
<tr>
<td> </td>
<td align="center"> </td>
<td><input name="btnUpload" type="submit" value="Upload" /></td>
</tr>
You can also use LINQ extensions:
string id = "hello";
MyClass result = list.Where(m => m.GetId() == id).First();
finalName is created as:
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
</build>
One of the solutions is to add own property:
<properties>
<finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
<finalName>${finalName}</finalName>
</build>
And now try:
mvn -DfinalName=build clean package
Use either COUNT(field)
or COUNT(*)
, and stick with it consistently, and if your database allows COUNT(tableHere)
or COUNT(tableHere.*)
, use that.
In short, don't use COUNT(1)
for anything. It's a one-trick pony, which rarely does what you want, and in those rare cases is equivalent to count(*)
count(*)
for countingUse *
for all your queries that need to count everything, even for joins, use *
SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
But don't use COUNT(*)
for LEFT joins, as that will return 1 even if the subordinate table doesn't match anything from parent table
SELECT boss.boss_id, COUNT(*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
Don't be fooled by those advising that when using *
in COUNT, it fetches entire row from your table, saying that *
is slow. The *
on SELECT COUNT(*)
and SELECT *
has no bearing to each other, they are entirely different thing, they just share a common token, i.e. *
.
In fact, if it is not permitted to name a field as same as its table name, RDBMS language designer could give COUNT(tableNameHere)
the same semantics as COUNT(*)
. Example:
For counting rows we could have this:
SELECT COUNT(emp) FROM emp
And they could make it simpler:
SELECT COUNT() FROM emp
And for LEFT JOINs, we could have this:
SELECT boss.boss_id, COUNT(subordinate)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
But they cannot do that (COUNT(tableNameHere)
) since SQL standard permits naming a field with the same name as its table name:
CREATE TABLE fruit -- ORM-friendly name
(
fruit_id int NOT NULL,
fruit varchar(50), /* same name as table name,
and let's say, someone forgot to put NOT NULL */
shape varchar(50) NOT NULL,
color varchar(50) NOT NULL
)
And also, it is not a good practice to make a field nullable if its name matches the table name. Say you have values 'Banana', 'Apple', NULL, 'Pears' on fruit
field. This will not count all rows, it will only yield 3, not 4
SELECT count(fruit) FROM fruit
Though some RDBMS do that sort of principle (for counting the table's rows, it accepts table name as COUNT's parameter), this will work in Postgresql (if there is no subordinate
field in any of the two tables below, i.e. as long as there is no name conflict between field name and table name):
SELECT boss.boss_id, COUNT(subordinate)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
But that could cause confusion later if we will add a subordinate
field in the table, as it will count the field(which could be nullable), not the table rows.
So to be on the safe side, use:
SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
count(1)
: The one-trick ponyIn particular to COUNT(1)
, it is a one-trick pony, it works well only on one table query:
SELECT COUNT(1) FROM tbl
But when you use joins, that trick won't work on multi-table queries without its semantics being confused, and in particular you cannot write:
-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.1)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
So what's the meaning of COUNT(1) here?
SELECT boss.boss_id, COUNT(1)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
Is it this...?
-- counting all the subordinates only
SELECT boss.boss_id, COUNT(subordinate.boss_id)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
Or this...?
-- or is that COUNT(1) will also count 1 for boss regardless if boss has a subordinate
SELECT boss.boss_id, COUNT(*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
By careful thought, you can infer that COUNT(1)
is the same as COUNT(*)
, regardless of type of join. But for LEFT JOINs result, we cannot mold COUNT(1)
to work as: COUNT(subordinate.boss_id)
, COUNT(subordinate.*)
So just use either of the following:
-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.boss_id)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
Works on Postgresql, it's clear that you want to count the cardinality of the set
-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
Another way to count the cardinality of the set, very English-like (just don't make a column with a name same as its table name) : http://www.sqlfiddle.com/#!1/98515/7
select boss.boss_name, count(subordinate)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name
You cannot do this: http://www.sqlfiddle.com/#!1/98515/8
select boss.boss_name, count(subordinate.1)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name
You can do this, but this produces wrong result: http://www.sqlfiddle.com/#!1/98515/9
select boss.boss_name, count(1)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name
Use Shell "program file path file path you want to open"
.
Example:
Shell "c:\windows\system32\mspaint.exe c:users\admin\x.jpg"
import java.util.*; public class Mult {
public static int[][] C;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter Row of Matrix A");
int Rowa = s.nextInt();
System.out.println("Enter Column of Matrix A");
int Cola = s.nextInt();
System.out.println("Enter Row of Matrix B");
int Rowb = s.nextInt();
System.out.println("Enter Column of Matrix B");
int Colb = s.nextInt();
int[][] A = new int[Rowa][Cola];
int[][] B = new int[Rowb][Colb];
C= new int[Rowa][Colb];
//int[][] C = new int;
System.out.println("Enter Values of Matrix A");
for(int i =0 ; i< A.length ; i++) {
for(int j = 0 ; j<A.length;j++) {
A[i][j] = s.nextInt();
}
}
System.out.println("Enter Values of Matrix B");
for(int i =0 ; i< B.length ; i++) {
for(int j = 0 ; j<B.length;j++) {
B[i][j] = s.nextInt();
}
}
if(Cola==Rowb) {
for(int i = 0;i < A.length;i++){
for(int j = 0;j < A.length;j++){
C[i][j]=0;
for(int k = 0;k < B.length;k++){
C[i][j] += A[i][k] * B[k][j];
}
}
}
}
else {
System.out.println("Cannot multiply");
}
// Printing matrix A
/*
for(int i =0 ; i< A.length ; i++) {
for(int j = 0 ; j<A.length;j++) {
System.out.print(A[i][j]+ "\t");
}
System.out.println();
}
*/
for(int i =0 ; i< A.length ; i++) {
for(int j = 0 ; j<A.length;j++) {
System.out.print(C[i][j]+ "\t");
}
System.out.println();
}
}
}
There's better support for this now through conda-env
. You can, for example, now do:
name: sample_env
channels:
dependencies:
- requests
- bokeh>=0.10.0
- pip:
- "--editable=git+https://github.com/pythonforfacebook/facebook-sdk.git@8c0d34291aaafec00e02eaa71cc2a242790a0fcc#egg=facebook_sdk-master"
It's still calling pip under the covers, but you can now unify your conda and pip package specifications in a single environment.yml
file.
If you wanted to update your root environment with this file, you would need to save this to a file (for example, environment.yml
), then run the command: conda env update -f environment.yml
.
It's more likely that you would want to create a new environment:
conda env create -f environment.yml
(changed as supposed in the comments)
window.location.replace('http://sidanmor.com');
It's better than using window.location.href = 'http://sidanmor.com';
Using replace()
is better because it does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.
If you want to simulate someone clicking on a link, use
window.location.href
If you want to simulate an HTTP redirect, use
window.location.replace
For example:
// similar behavior as an HTTP redirect
window.location.replace("http://sidanmor.com");
// similar behavior as clicking on a link
window.location.href = "http://sidanmor.com";
Taken from here: How to redirect to another page in jQuery?
Is this role attribute necessary?
Answer: Yes.
It provides you:
It is not quite as baked-in in Java, so you don't get this for free. It is done with convention rather than language constructs. In all data transfer classes (and maybe even in all classes you write...), you should implement a sensible toString
method. So here you need to override toString()
in your Person
class and return the desired state.
There are utilities available that help with writing a good toString method, or most IDEs have an automatic toString()
writing shortcut.
Rounds a double-precision floating-point value to the nearest integral value.
Turn the axes off with:
plt.axis('off')
And gridlines with:
plt.grid(b=None)
Option 1
You didn't say much about your environment, but assuming you have it available you could use a PowerShell script; one example is here. The essence of this is:
$smtp = New-Object Net.Mail.SmtpClient("ho-ex2010-caht1.exchangeserverpro.net")
$smtp.Send("[email protected]","[email protected]","Test Email","This is a test")
You could then launch the script from the command line as per this example:
powershell.exe -noexit c:\scripts\test.ps1
Note that PowerShell 2.0, which is installed by default on Windows 7 and Windows Server 2008R2, includes a simpler Send-MailMessage
command, making things easier.
Option 2
If you're prepared to use third-party software, is something line this SendEmail command-line tool. It depends on your target environment, though; if you're deploying your batch file to multiple machines, that will obviously require inclusion (but not formal installation) each time.
Option 3
You could drive Outlook directly from a VBA script, which in turn you would trigger from a batch file; this would let you send an email using Outlook itself, which looks to be closest to what you're wanting. There are two parts to this; first, figure out the VBA scripting required to send an email. There are lots of examples for this online, including from Microsoft here. Essence of this is:
Sub SendMessage(DisplayMsg As Boolean, Optional AttachmentPath)
Dim objOutlook As Outlook.Application
Dim objOutlookMsg As Outlook.MailItem
Dim objOutlookRecip As Outlook.Recipient
Dim objOutlookAttach As Outlook.Attachment
Set objOutlook = CreateObject("Outlook.Application")
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
With objOutlookMsg
Set objOutlookRecip = .Recipients.Add("Nancy Davolio")
objOutlookRecip.Type = olTo
' Set the Subject, Body, and Importance of the message.
.Subject = "This is an Automation test with Microsoft Outlook"
.Body = "This is the body of the message." &vbCrLf & vbCrLf
.Importance = olImportanceHigh 'High importance
If Not IsMissing(AttachmentPath) Then
Set objOutlookAttach = .Attachments.Add(AttachmentPath)
End If
For Each ObjOutlookRecip In .Recipients
objOutlookRecip.Resolve
Next
.Save
.Send
End With
Set objOutlook = Nothing
End Sub
Then, launch Outlook from the command line with the /autorun
parameter, as per this answer (alter path/macroname as necessary):
C:\Program Files\Microsoft Office\Office11\Outlook.exe" /autorun macroname
Option 4
You could use the same approach as option 3, but move the Outlook VBA into a PowerShell script (which you would run from a command line). Example here. This is probably the tidiest solution, IMO.
Since I went on about it in the comments for @Rocket's answer, I may as well provide an example that uses no libraries. This requires two new prototype functions, contains
and unique
Array.prototype.contains = function(v) {_x000D_
for (var i = 0; i < this.length; i++) {_x000D_
if (this[i] === v) return true;_x000D_
}_x000D_
return false;_x000D_
};_x000D_
_x000D_
Array.prototype.unique = function() {_x000D_
var arr = [];_x000D_
for (var i = 0; i < this.length; i++) {_x000D_
if (!arr.contains(this[i])) {_x000D_
arr.push(this[i]);_x000D_
}_x000D_
}_x000D_
return arr;_x000D_
}_x000D_
_x000D_
var duplicates = [1, 3, 4, 2, 1, 2, 3, 8];_x000D_
var uniques = duplicates.unique(); // result = [1,3,4,2,8]_x000D_
_x000D_
console.log(uniques);
_x000D_
For more reliability, you can replace contains
with MDN's indexOf
shim and check if each element's indexOf
is equal to -1: documentation
Chromedriver is a WebDriver. WebDriver is an open-source tool for automated testing of web apps across many browsers. It provides capabilities for navigating to web pages, user input, JavaScript execution, and more. When you run this driver, it will enable your scripts to access this and run commands on Google Chrome.
This can be done via scripts running in the local network (Only local connections are allowed.
) or via scripts running on outside networks (All remote connections are allowed.
). It is always safer to use the Local Connection option. By default your Chromedriver is accessible via port 9515
.
To answer the question, it is just an informational message. You don't have to worry about it.
Given below are both options.
$ chromedriver
Starting ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103@{#416}) on port 9515
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
This is by whitelisting all IPs.
$ chromedriver --whitelisted-ips=""
Starting ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103@{#416}) on port 9515
All remote connections are allowed. Use a whitelist instead!
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
I've used the queuing approach, and it works well as you can defer that processing until your server load is idle, letting you manage your load quite effectively if you can partition off "tasks which aren't urgent" easily.
Rolling your own isn't too tricky, here's a few other options to check out:
Another, perhaps simpler, approach is to use ignore_user_abort - once you've sent the page to the user, you can do your final processing without fear of premature termination, though this does have the effect of appearing to prolong the page load from the user perspective.
You can use an anonymous function to pass the matches to your function:
$result = preg_replace_callback(
"/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
$result
);
Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e
would convert a double quote "
into \"
.
Use clearRect method by passing x,y co-ordinates and height and width of canvas. ClearRect will clear whole canvas as :
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
using std::string;
string string_replace( string src, string const& target, string const& repl)
{
// handle error situations/trivial cases
if (target.length() == 0) {
// searching for a match to the empty string will result in
// an infinite loop
// it might make sense to throw an exception for this case
return src;
}
if (src.length() == 0) {
return src; // nothing to match against
}
size_t idx = 0;
for (;;) {
idx = src.find( target, idx);
if (idx == string::npos) break;
src.replace( idx, target.length(), repl);
idx += repl.length();
}
return src;
}
Since it's not a member of the string
class, it doesn't allow quite as nice a syntax as in your example, but the following will do the equivalent:
test = string_replace( string_replace( test, "abc", "hij"), "def", "klm")
Example: Inside myWindow() on line 3 is the code you need to set the window in the center of the screen.
JFrame window;
public myWindow() {
window = new JFrame();
window.setSize(1200,800);
window.setLocationRelativeTo(null); // this line set the window in the center of thr screen
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setBackground(Color.BLACK);
window.setLayout(null); // disable the default layout to use custom one.
window.setVisible(true); // to show the window on the screen.
}
I think if I set a color for a:visited
it is not good: you must know the default color of tag a
and every time synchronize it with a:visited
.
I don't want know about the default color (it can be set in common.css
of your application, or you can using outside styles).
I think it's nice solution:
HTML
:
<body>
<a class="absolute">Test of URL</a>
<a class="unvisited absolute" target="_blank" href="google.ru">Test of URL</a>
</body>
CSS
:
.absolute{
position: absolute;
}
a.unvisited, a.unvisited:visited, a.unvisited:active{
text-decoration: none;
color: transparent;
}
Batch files are processed row by row and terminate whenever you call an executable directly.
- To make the batch file wait for the process to terminate and continue, put call
in front of it.
- To make the batch file continue without waiting, put start ""
in front of it.
I recommend using this single line script to accomplish your goal:
@call cscript "%~dp0necdaily.vbs"
(because this is a single line, you can use @ instead of @echo off)
If you believe your script can only be called from the SysWOW64 versions of cmd.exe, you might try:
@%WINDIR%\SysWOW64\cmd.exe /c call cscript "%~dp0necdaily.vbs"
If you need the window to remain, you can replace /c with /k
You're looking for Action<T>
, which takes a parameter.
array = array.uniq
uniq
removes all duplicate elements and retains all unique elements in the array.
This is one of many beauties of the Ruby language.
you can do this with jdk >= 8
getComboBox().addItemListener(this::comboBoxitemStateChanged);
so
public void comboBoxitemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
YourObject selectedItem = (YourObject) e.getItem();
//TODO your actitons
}
}
For SQL Sever:
Decimal Type is 128 bit signed number Float is a 64 bit signed number.
The real answer is Float, I was incorrect about decimal.
The reason is if you use a decimal you will never fill 64 bit of the decimal type.
Although decimal won't give you an error if you try to use a int type.
Here is a nice reference chart of the types.
For auto-completion triggers in Eclipse like IntelliJ, follow these steps,
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._@
Thanks.
You can add:
#div2{
background-image:url(http://s7.static.hootsuite.com/3-0-48/images/themes/classic/streams/message-gradient.png);
background-size: 100% 100%;
height:180px;
width:200px;
border: 1px solid red;
}
You can read more about it here: css3 background-size
You can also use a call to SCOPE_IDENTITY in SQL Server.
This fixed it for me Fixing npm On Mac OS X for Homebrew Users. And it does not require too many steps.
Just go to the solution part if you don't care about the why.
Here is the relevant part for convenience:
This solution fixes the error caused by trying to run npm update npm -g
. Once you're finished, you also won't need to use sudo
to install npm modules globally.
Before you start, make a note of any globally installed npm packages. These instructions will have you remove all of those packages. After you're finished you'll need to re-install them.
Run the following commands to remove all existing global npm modules, uninstall node & npm, re-install node with the correct defaults, configure the location for global npm modules to be installed, and then install npm as its own pacakge.
rm -rf /usr/local/lib/node_modules
brew uninstall node
brew install node --without-npm
echo prefix=~/.npm-packages >> ~/.npmrc
curl -L https://www.npmjs.com/install.sh | sh
Node and npm should be correctly installed at this point. The final step is to add ~/.npm-packages/bin
to your PATH
so npm and global npm packages are usable. To do this, add the following line to your ~/.bash_profile
:
export PATH="$HOME/.npm-packages/bin:$PATH"
Now you can re-install any global npm packages you need without any problems.
function enter_comment(super_id) {
if (!(document.getElementById(super_id).checked)) {
alert('selected checkbox is unchecked now')
} else {
alert('selected checkbox is checked now');
}
}
<input type="checkbox" name="a" id="1" value="1" onclick="enter_comment(this.value)" />
<input type="checkbox" name="b" id="2" value="2" onclick="enter_comment(this.value)" />
TF v2.0 supports Eager mode vis-a-vis Graph mode of v1.0. Hence, tf.session() is not supported on v2.0. Hence, would suggest you to rewrite your code to work in Eager mode.
One way to check for the installed Office version would be to check the InstallRoot
registry keys for the Office applications of interest.
For example, if you would like to check whether Word 2007 is installed you should check for the presence of the following Registry key:
HKLM\Software\Microsoft\Office\12.0\Word\InstallRoot::Path
This entry contains the path to the executable.
Replace 12.0 (for Office 2007) with the corresponding version number:
Office 97 - 7.0 Office 98 - 8.0 Office 2000 - 9.0 Office XP - 10.0 Office 2003 - 11.0 Office 2007 - 12.0 Office 2010 - 14.0 (sic!) Office 2013 - 15.0 Office 2016 - 16.0 Office 2019 - 16.0 (sic!)
The other applications have similar keys:
HKLM\Software\Microsoft\Office\12.0\Excel\InstallRoot::Path
HKLM\Software\Microsoft\Office\12.0\PowerPoint\InstallRoot::Path
Or you can check the common root path of all applications:
HKLM\Software\Microsoft\Office\12.0\Common\InstallRoot::Path
Another option, without using specific Registry keys would be to query the MSI database using the MSIEnumProducts
API as described here.
As an aside, parallel installations of different Office versions are not officially supported by Microsoft. They do somewhat work, but you might get undesired effects and inconsistencies.
Update: Office 2019 and Office 365
As of Office 2019, MSI-based setup are no longer available, Click-To-Run is the only way to deploy Office now. Together with this change towards the regularly updated Office 365, also the major/minor version numbers of Office are no longer updated (at least for the time being). That means that – even for Office 2019 – the value used in Registry keys and the value returned by Application.Version
(e.g. in Word) still is 16.0
.
For the time being, there is no documented way to distinguish the Office 2016 from Office 2019. A clue might be the file version of the winword.exe; however, this version is also incremented for patched Office 2016 versions (see the comment by @antonio below).
If you need to distinguish somehow between Office versions, e.g. to make sure that a certain feature is present or that a minimum version of Office is installed, probably the best way it to look at the file version of one of the main Office applications:
// Using the file path to winword.exe
// Retrieve the path e.g. from the InstallRoot Registry key
var fileVersionInfo = FileVersionInfo.GetVersionInfo(@"C:\Program Files (x86)\Microsoft Office\root\Office16\WINWORD.EXE");
var version = new Version(fileVersionInfo.FileVersion);
// On a running instance using the `Process` class
var process = Process.GetProcessesByName("winword").First();
string fileVersionInfo = process.MainModule.FileVersionInfo.FileVersion;
var version = Version(fileVersionInfo);
The file version of Office 2019 is 16.0.10730.20102, so if you see anything greater than that you are dealing with Office 2019 or a current Office 365 version.
You must select range of the table first before using ActiveSheet.ShowAllData
Another simple solution:
var forbiddenChars = @"@,.;'".ToCharArray();
var dirty = "My name @is ,Wan.;'; Wan";
var clean = new string(dirty.Where(c => !forbiddenChars.Contains(c)).ToArray());
I can't believe how overcomplicated some of these answers are... (no offence!)
Here's a single-line function that will get the job done:
Function getFName(pf)As String:getFName=Mid(pf,InStrRev(pf,"\")+1):End Function
Function getPath(pf)As String:getPath=Left(pf,InStrRev(pf,"\")):End Function
I faced the same issue and resolved it with following commands:
sudo apt-get install libpq-dev
pip install psycopg2
public static void main(String[] args) {
java.util.Scanner scan = new java.util.Scanner(System.in);
long decimalValue = 0;
System.out.println("Please enter a positive binary number.(Only 1s and 0s)");
//This reads the input as a String and splits each symbol into
//array list
String element = scan.nextLine();
String[] array = element.split("");
//This assigns the length to integer arrys based on actual number of
//symbols entered
int[] numberSplit = new int[array.length];
int position = array.length - 1; //set beginning position to the end of array
//This turns String array into Integer array
for (int i = 0; i < array.length; i++) {
numberSplit[i] = Integer.parseInt(array[i]);
}
//This loop goes from last to first position of an array making
//calculation where power of 2 is the current loop instance number
for (int i = 0; i < array.length; i++) {
if (numberSplit[position] == 1) {
decimalValue = decimalValue + (long) Math.pow(2, i);
}
position--;
}
System.out.println(decimalValue);
main(null);
}
None of the above answers helped me. I suppose all the answers are for older OS X
For OS X Yosemite 10.10, follow these steps
Use your favorite text editor to open: ~/.bash_profile
//This command will open the file using vim
$ vim ~/.bash_profile
Add the following line in the file and save it ( : followed by "x" for vim):
export JAVA_HOME=$(/usr/libexec/java_home)
Then in the terminal type the following two commands to see output:
$ source ~/.bash_profile
$ echo $JAVA_HOME
In the second line, you are updating the contents of .bash_profile
file.
*
master = Tk()
entryb1 = StringVar
Label(master, text="Input: ").grid(row=0, sticky=W)
Entry(master, textvariable=entryb1).grid(row=1, column=1)
b1 = Button(master, text="continue", command=print_content)
b1.grid(row=2, column=1)
def print_content():
global entryb1
content = entryb1.get()
print(content)
master.mainloop()
What you did wrong was not put it inside a Define function then you hadn't used the .get
function with the textvariable you had set.
Use the isActivity variable to check if activity is alive or not.
private boolean activityState = true;
@Override
protected void onDestroy() {
super.onDestroy();
activityState = false;
}
Then check
if(activityState){
//add your code
}
From the standard
7.5.2 Element identifiers: the id and class attributes
Attribute definitions
id = name [CS]
This attribute assigns a name to an element. This name must be unique in a document.class = cdata-list [CS]
This attribute assigns a class name or set of class names to an element. Any number of elements may be assigned the same class name or names. Multiple class names must be separated by white space characters.
Yes, just put a space between them.
<article class="column wrapper">
Of course, there are many things you can do with CSS inheritance. Here is an article for further reading.
Following explanation actually explains how wait() and signal() of monitor differ from P and V of semaphore.
The wait() and signal() operations on condition variables in a monitor are similar to P and V operations on counting semaphores.
A wait statement can block a process's execution, while a signal statement can cause another process to be unblocked. However, there are some differences between them. When a process executes a P operation, it does not necessarily block that process because the counting semaphore may be greater than zero. In contrast, when a wait statement is executed, it always blocks the process. When a task executes a V operation on a semaphore, it either unblocks a task waiting on that semaphore or increments the semaphore counter if there is no task to unlock. On the other hand, if a process executes a signal statement when there is no other process to unblock, there is no effect on the condition variable. Another difference between semaphores and monitors is that users awaken by a V operation can resume execution without delay. Contrarily, users awaken by a signal operation are restarted only when the monitor is unlocked. In addition, a monitor solution is more structured than the one with semaphores because the data and procedures are encapsulated in a single module and that the mutual exclusion is provided automatically by the implementation.
Link: here for further reading. Hope it helps.
Just use this script to dynamically backup all databases on the server. Then create batch file according to the article. It is usefull to create two batch files, one for full backup a and one for diff backup. Then Create two tasks in Task Scheduler, one for full and one for diff.
-- // Copyright © Microsoft Corporation. All Rights Reserved.
-- // This code released under the terms of the
-- // Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
USE [master]
GO
/****** Object: StoredProcedure [dbo].[sp_BackupDatabases] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Microsoft
-- Create date: 2010-02-06
-- Description: Backup Databases for SQLExpress
-- Parameter1: databaseName
-- Parameter2: backupType F=full, D=differential, L=log
-- Parameter3: backup file location
-- =============================================
CREATE PROCEDURE [dbo].[sp_BackupDatabases]
@databaseName sysname = null,
@backupType CHAR(1),
@backupLocation nvarchar(200)
AS
SET NOCOUNT ON;
DECLARE @DBs TABLE
(
ID int IDENTITY PRIMARY KEY,
DBNAME nvarchar(500)
)
-- Pick out only databases which are online in case ALL databases are chosen to be backed up
-- If specific database is chosen to be backed up only pick that out from @DBs
INSERT INTO @DBs (DBNAME)
SELECT Name FROM master.sys.databases
where state=0
AND name=@DatabaseName
OR @DatabaseName IS NULL
ORDER BY Name
-- Filter out databases which do not need to backed up
IF @backupType='F'
BEGIN
DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','AdventureWorks')
END
ELSE IF @backupType='D'
BEGIN
DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')
END
ELSE IF @backupType='L'
BEGIN
DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')
END
ELSE
BEGIN
RETURN
END
-- Declare variables
DECLARE @BackupName varchar(100)
DECLARE @BackupFile varchar(100)
DECLARE @DBNAME varchar(300)
DECLARE @sqlCommand NVARCHAR(1000)
DECLARE @dateTime NVARCHAR(20)
DECLARE @Loop int
-- Loop through the databases one by one
SELECT @Loop = min(ID) FROM @DBs
WHILE @Loop IS NOT NULL
BEGIN
-- Database Names have to be in [dbname] format since some have - or _ in their name
SET @DBNAME = '['+(SELECT DBNAME FROM @DBs WHERE ID = @Loop)+']'
-- Set the current date and time n yyyyhhmmss format
SET @dateTime = REPLACE(CONVERT(VARCHAR, GETDATE(),101),'/','') + '_' + REPLACE(CONVERT(VARCHAR, GETDATE(),108),':','')
-- Create backup filename in path\filename.extension format for full,diff and log backups
IF @backupType = 'F'
SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_FULL_'+ @dateTime+ '.BAK'
ELSE IF @backupType = 'D'
SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_DIFF_'+ @dateTime+ '.BAK'
ELSE IF @backupType = 'L'
SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_LOG_'+ @dateTime+ '.TRN'
-- Provide the backup a name for storing in the media
IF @backupType = 'F'
SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' full backup for '+ @dateTime
IF @backupType = 'D'
SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' differential backup for '+ @dateTime
IF @backupType = 'L'
SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' log backup for '+ @dateTime
-- Generate the dynamic SQL command to be executed
IF @backupType = 'F'
BEGIN
SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
END
IF @backupType = 'D'
BEGIN
SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH DIFFERENTIAL, INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
END
IF @backupType = 'L'
BEGIN
SET @sqlCommand = 'BACKUP LOG ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
END
-- Execute the generated SQL command
EXEC(@sqlCommand)
-- Goto the next database
SELECT @Loop = min(ID) FROM @DBs where ID>@Loop
END
And batch file can look like this:
sqlcmd -S localhost\myDB -Q "EXEC sp_BackupDatabases @backupLocation='c:\Dropbox\backup\DB\', @backupType='F'" >> c:\Dropbox\backup\DB\full.log 2>&1
and
sqlcmd -S localhost\myDB -Q "EXEC sp_BackupDatabases @backupLocation='c:\Dropbox\backup\DB\', @backupType='D'" >> c:\Dropbox\backup\DB\diff.log 2>&1
The advantage of this method is that you don't need to change anything if you add new database or delete a database, you don't even need to list the databases in the script. Answer from JohnB is better/simpler for server with one database, this approach is more suitable for multi database servers.
this can be done easily with a vbs code (as i'm not so familiar with js )
<input type="button" id="btn" Value="Close" onclick="check">
<script Language="VBScript">
sub check
if btn.Value="Close" then btn.Value="Open"
end sub
</script>
and you're done , however this changes the Name to display only and does not change the function {onclick} , i did some researches on how to do the second one and seem there isnt' something like
btn.onclick = ".."
but i figured out a way using <"span"> tag it goes like this :
<script Language="VBScript">
Sub function1
MsgBox "function1"
span.InnerHTML= "<Input type=""button"" Value=""button2"" onclick=""function2"">"
End Sub
Sub function2
MsgBox "function2"
span.InnerHTML = "<Input type=""button"" Value=""button1"" onclick=""function1"">"
End Sub
</script>
<body>
<span id="span" name="span" >
<input type="button" Value="button1" onclick="function1">
</span>
</body>
try it yourself , change the codes in sub function1 and sub function2, basically all you need to know to make it in jscript is the line
span.InnerHTML = "..."
the rest is your code you wanna execute
hope this helps :D
You can easily create a persistent session using:
s = requests.Session()
After that, continue with your requests as you would:
s.post('https://localhost/login.py', login_data)
#logged in! cookies saved for future requests.
r2 = s.get('https://localhost/profile_data.json', ...)
#cookies sent automatically!
#do whatever, s will keep your cookies intact :)
For more about sessions: https://requests.kennethreitz.org/en/master/user/advanced/#session-objects
You can use this query:
ALTER TABLE tableName ADD ColumnName datatype DEFAULT DefaultValue;
Try using BindingExpression.UpdateTarget()
You can do :
1) javac -cp /path/to/jar/file Myprogram.java
2) java -cp .:/path/to/jar/file Myprogram
So, lets suppose your current working directory
in terminal is src/Report/
javac -cp src/external/myfile.jar Reporter.java
java -cp .:src/external/myfile.jar Reporter
Take a look here to setup Classpath
The first argument denotes placeholders for the variables / parameters that follow.
For example, %s
indicates that you're expecting a String
to be your first print parameter.
Java also has a printf
, which is very similar.
According to the MediaPlayer
life cycle, which you can view in the Android API guide, I think that you have to call reset()
instead of stop()
, and after that prepare again the media player (use only one) to play the sound from the beginning. Take also into account that the sound may have finished. So I would also recommend to implement setOnCompletionListener()
to make sure that if you try to play again the sound it doesn't fail.
Google got me here, so i am updating this late for other to find when searching. A much simpler way is to use BigInteger, like so:
BigInteger("625b", 16)
Use the code below it worked for me.
MediaPlayer mp = new MediaPlayer();
mp.setDataSource("/mnt/sdcard/yourdirectory/youraudiofile.mp3");
mp.prepare();
mp.start();
Adding this answer partially because it fixed my problem of the same issue and so I can bookmark this question myself.
I was able to fix it by doing the following:
sudo apt-get install gcc-multilib g++-multilib
If you've installed a version of gcc
/ g++
that doesn't ship by default (such as g++-4.8
on lucid) you'll want to match the version as well:
sudo apt-get install gcc-4.8-multilib g++-4.8-multilib
<input type="button" value="Clear" onclick="javascript: functionName();" >
you just need to set the onclick event, call your desired function on this onclick event.
function functionName()
{
$("#output").val("");
}
Above function will set the value of text area to empty string.
A solution which works quite well is described right here: https://developer.mozilla.org/fr/docs/Web/HTML/Element/Input/radio
The idea is to use the property (appearance), which when sets to none allows to change the width and height of the radio button. The radio buttons are not blurry, and you can add other effect like transitions and stuff.
Here's an example :
input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
border-radius: 50%;
width: 16px;
height: 16px;
border: 2px solid #999;
transition: 0.2s all linear;
margin-right: 5px;
position: relative;
top: 4px;
}
input:checked {
border: 6px solid black;
outline: unset !important /* I added this one for Edge (chromium) support */
}
The only drawback is that it is not supported yet on IE.
Here's a GIF (with a not so good rendering) below to give an idea of what can be achieved: you will get way better results on an actual browser.
And the plunker : https://plnkr.co/plunk/1W3QXWPi7hdxZJuT
from PIL import Image
image = Image.open('File.jpg')
image.show()
Just create and save a page token in global variable with window.nextPageToken
. Send this to API server everytime you make a request and have it return the next one with response and you can easily keep track of last token. The below is an example how you can move forward and backward from search results. The key is the offset you send to API based on the nextPageToken that you have saved:
function getPrev() {
var offset = Number(window.nextPageToken) - limit * 2;
if (offset < 0) {
offset = 0;
}
window.nextPageToken = offset;
if (canSubmit(searchForm, offset)) {
searchForm.submit();
}
}
function getNext() {
var offset = Number(window.nextPageToken);
window.nextPageToken = offset;
if (canSubmit(searchForm, offset)) {
searchForm.submit();
}
}
Since Kevin's answer is not complete.
This is more correct answer if you use RecyclerAdapter
's notifyItemInserted
and notifyItemRemoved
to update dataset.
See the Kotlin version another user added below.
Java:
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
@Override
public void onChanged() {
super.onChanged();
checkEmpty();
}
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
checkEmpty();
}
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
super.onItemRangeRemoved(positionStart, itemCount);
checkEmpty();
}
void checkEmpty() {
mEmptyView.setVisibility(mAdapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
}
});
Kotlin
adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
override fun onChanged() {
super.onChanged()
checkEmpty()
}
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
super.onItemRangeInserted(positionStart, itemCount)
checkEmpty()
}
override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
super.onItemRangeRemoved(positionStart, itemCount)
checkEmpty()
}
fun checkEmpty() {
empty_view.visibility = (if (adapter.itemCount == 0) View.VISIBLE else View.GONE)
}
})
I used this blog post to install it in my machine: http://luminite.wordpress.com/2012/09/06/installing-oracle-database-xe-11g-on-windows-7-64-bit-machine/
The only thing you have to do is replace a registry value during the installation, I've done it about three times already, and every time found a different reference on-line, none here on stackoverflow.
EDIT: as @kc2001 noted, regedit must be run as Administrator, and added this tutorial: (a bit more colorful): http://www.hanmiaojuan.com/2013/03/install-oracle-xe-11g-for-windows7-64bits.html
Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.
For more information about the network errors
You could define controller at the <html>
level.
<html ng-app="app" ng-controller="titleCtrl">
<head>
<title>{{ Page.title() }}</title>
...
You create service: Page
and modify from controllers.
myModule.factory('Page', function() {
var title = 'default';
return {
title: function() { return title; },
setTitle: function(newTitle) { title = newTitle }
};
});
Inject Page
and Call 'Page.setTitle()' from controllers.
Here is the concrete example: http://plnkr.co/edit/0e7T6l
Even I was facing a similar error. Try below 2 steps (the first of which has been recommended here already) -
1. Add the dependencies to your pom.xml
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
jar
files in your .m2\repository\javax\<folder>\<version>\
directory.Another solution to this is border-spacing
property:
table td {_x000D_
border-bottom: 2px solid black;_x000D_
}_x000D_
_x000D_
table {_x000D_
border-spacing: 0px;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td>ABC</td>_x000D_
<td>XYZ</td>_x000D_
</table>
_x000D_
How about:
using (ModelName context = new ModelName())
{
var ptx = (from r in context.TableName select r);
}
ModelName is the class auto-generated by the designer, which inherits from ObjectContext
.
The first danger lies in reload(sys)
.
When you reload a module, you actually get two copies of the module in your runtime. The old module is a Python object like everything else, and stays alive as long as there are references to it. So, half of the objects will be pointing to the old module, and half to the new one. When you make some change, you will never see it coming when some random object doesn't see the change:
(This is IPython shell)
In [1]: import sys
In [2]: sys.stdout
Out[2]: <colorama.ansitowin32.StreamWrapper at 0x3a2aac8>
In [3]: reload(sys)
<module 'sys' (built-in)>
In [4]: sys.stdout
Out[4]: <open file '<stdout>', mode 'w' at 0x00000000022E20C0>
In [11]: import IPython.terminal
In [14]: IPython.terminal.interactiveshell.sys.stdout
Out[14]: <colorama.ansitowin32.StreamWrapper at 0x3a9aac8>
Now, sys.setdefaultencoding()
proper
All that it affects is implicit conversion str<->unicode
. Now, utf-8
is the sanest encoding on the planet (backward-compatible with ASCII and all), the conversion now "just works", what could possibly go wrong?
Well, anything. And that is the danger.
UnicodeError
being thrown for non-ASCII input, or does the transcoding with an error handler, which now produces an unexpected result. And since all code is tested with the default setting, you're strictly on "unsupported" territory here, and no-one gives you guarantees about how their code will behave.How about splay trees?
Also, Chris Okasaki's purely functional data structures come to mind.
In case you are here looking for a fast string concatenation method in Python, then you do not need a special StringBuilder class. Simple concatenation works just as well without the performance penalty seen in C#.
resultString = ""
resultString += "Append 1"
resultString += "Append 2"
See Antoine-tran's answer for performance results
I find the most perfectly working answer is this
.noBorder {
border: 0px;
padding:0;
margin:0;
border-collapse: collapse;
}
You can provide your own image and reference it in the head, for example:
<link rel="shortcut icon" href="images/favicon.ico">
If the columns that you are having trouble with are "hashes", then consider the following...
If the "hash" is a binary string, you should really use BINARY(...)
datatype.
If the "hash" is a hex string, you do not need utf8, and should avoid such because of character checks, etc. For example, MySQL's MD5(...)
yields a fixed-length 32-byte hex string. SHA1(...)
gives a 40-byte hex string. This could be stored into CHAR(32) CHARACTER SET ascii
(or 40 for sha1).
Or, better yet, store UNHEX(MD5(...))
into BINARY(16)
. This cuts in half the size of the column. (It does, however, make it rather unprintable.) SELECT HEX(hash) ...
if you want it readable.
Comparing two BINARY
columns has no collation issues.
This is sort of an appendage @znq's answer...
There are many cases where you want to know the row position for a clicked item AND you want to know which view in the row was tapped. This is going to be a lot more important in tablet UIs.
You can do this with the following custom adapter:
private static class CustomCursorAdapter extends CursorAdapter {
protected ListView mListView;
protected static class RowViewHolder {
public TextView mTitle;
public TextView mText;
}
public CustomCursorAdapter(Activity activity) {
super();
mListView = activity.getListView();
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// do what you need to do
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = View.inflate(context, R.layout.row_layout, null);
RowViewHolder holder = new RowViewHolder();
holder.mTitle = (TextView) view.findViewById(R.id.Title);
holder.mText = (TextView) view.findViewById(R.id.Text);
holder.mTitle.setOnClickListener(mOnTitleClickListener);
holder.mText.setOnClickListener(mOnTextClickListener);
view.setTag(holder);
return view;
}
private OnClickListener mOnTitleClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
final int position = mListView.getPositionForView((View) v.getParent());
Log.v(TAG, "Title clicked, row %d", position);
}
};
private OnClickListener mOnTextClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
final int position = mListView.getPositionForView((View) v.getParent());
Log.v(TAG, "Text clicked, row %d", position);
}
};
}
To add yet another reason to the list ... in my case I found this problem was being caused by an SELinux permissions problem on the server. This is worth checking if your server is running Fedora / CentOS / Red Hat. To test this scenario you can run:
Client: ssh -vT git@<gitlab-server>
-- asks for password
Server: sudo setenforce 0
Client: ssh -vT git@<gitlab-server>
-- succeeds
Server: sudo setenforce 1
In my case the gitlab/git user's authorized_keys
file had the wrong SELinux file context, and the ssh service was being denied permission to read it. I fixed this on the server side as follows:
sudo semanage fcontext -a -t ssh_home_t /gitlab/.ssh/
sudo semanage fcontext -a -t ssh_home_t /gitlab/.ssh/authorized_keys
sudo restorecon -F -Rv /gitlab/.ssh/
And I was then able to git clone
on the client side as expected.
Actually sed -n '/pattern/{n;p}' filename
will fail if the pattern
match continuous
lines:
$ seq 15 |sed -n '/1/{n;p}'
2
11
13
15
The expected answers should be:
2
11
12
13
14
15
My solution is:
$ sed -n -r 'x;/_/{x;p;x};x;/pattern/!s/.*//;/pattern/s/.*/_/;h' filename
For example:
$ seq 15 |sed -n -r 'x;/_/{x;p;x};x;/1/!s/.*//;/1/s/.*/_/;h'
2
11
12
13
14
15
Explains:
x;
: at the beginning of each line from input, use x
command to exchange the contents in pattern space
& hold space
./_/{x;p;x};
: if pattern space
, which is the hold space
actually, contains _
(this is just a indicator
indicating if last line matched the pattern
or not), then use x
to exchange the actual content of current line
to pattern space
, use p
to print current line
, and x
to recover this operation. x
: recover the contents in pattern space
and hold space
./pattern/!s/.*//
: if current line
does NOT match pattern
, which means we should NOT print the NEXT following line, then use s/.*//
command to delete all contents in pattern space
./pattern/s/.*/_/
: if current line
matches pattern
, which means we should print the NEXT following line, then we need to set a indicator
to tell sed
to print NEXT line, so use s/.*/_/
to substitute all contents in pattern space
to a _
(the second command will use it to judge if last line matched the pattern
or not).h
: overwrite the hold space
with the contents in pattern space
; then, the content in hold space
is ^_$
which means current line
matches the pattern
, or ^$
, which means current line
does NOT match the pattern
.s/.*/_/
, the pattern space
can NOT match /pattern/
, so the s/.*//
MUST be executed!The awk solution is what I would use, but if you want to understand your problems with bash, here is a revised version of your script.
#!/bin/bash -vx
##config file with ip addresses like 10.10.10.1:80
file=config.txt
while read line ; do
##this line is not correct, should strip :port and store to ip var
ip=$( echo "$line" |cut -d\: -f1 )
ping $ip
done < ${file}
You could write your top line as
for line in $(cat $file) ; do ...
(but not recommended).
You needed command substitution $( ... )
to get the value assigned to $ip
reading lines from a file is usually considered more efficient with the while read line ... done < ${file}
pattern.
I hope this helps.
Use the <sup></sup>
tag (<sub></sub>
is the equivalent for subscripts). See this gist for an example.
For LINQ -> SQL:
SingleOrDefault
FirstOrDefault
use the String.Trim()
function.
string foo = " hello ";
string bar = foo.Trim();
Console.WriteLine(bar); // writes "hello"
(\d+)\s+(\(.*?\))?\s?Z
Note the escaped parentheses, and the ?
(zero or once) quantifiers. Any of the groups you don't want to capture can be (?:
non-capture groups).
I agree about the spaces. \s
is a better option there. I also changed the quantifier to insure there are digits at the beginning. As far as newlines, that would depend on context: if the file is parsed line by line it won't be a problem. Another option is to anchor the start and end of the line (add a ^
at the front and a $
at the end).
maybe this works?
grep A1 file | tail -1 | awk '{print $NF}'
select @DateCreated, DATEDIFF(WEEK, @DateCreated, GETDATE())
Alternatively, keep your docker images small by not installing unnecessary editors. You can edit the files over ssh from the docker host to the container:
vim scp://remoteuser@container-ip//path/to/document
This will replace your existing mySelect with a new mySelect.
$('#mySelect').replaceWith('<Select id="mySelect" size="9">
<option value="whatever" selected="selected" >text</option>
</Select>');
$result = mysql_query('SELECT COUNT(1) FROM table');
$num_rows = mysql_result($result, 0, 0);
If you are looking for PERFORMANCE, give where condition inside the db link query. Otherwise it fetch all data from the foreign table and apply the where condition.
INSERT INTO tblA (id,time)
SELECT id, time FROM dblink('dbname=dbname port=5432 host=10.10.90.190 user=postgresuser password=pass123',
'select id, time from tblB where time>'''||1000||'''')
AS t1(id integer, time integer)
The problem with the former is that what you're doing is USE 'myDB'
rather than USE myDB
.
you're passing a string; but USE is looking for an explicit reference.
The latter example works for me.
declare @sql varchar(20)
select @sql = 'USE myDb'
EXEC sp_sqlexec @Sql
-- also works
select @sql = 'USE [myDb]'
EXEC sp_sqlexec @Sql
Python Extension. From the Python Docs:
The solution chosen by the Perl developers was to use (?...) as the extension syntax. ? immediately after a parenthesis was a syntax error because the ? would have nothing to repeat, so this didn’t introduce any compatibility problems. The characters immediately after the ? indicate what extension is being used, so (?=foo) is one thing (a positive lookahead assertion) and (?:foo) is something else (a non-capturing group containing the subexpression foo).
Python supports several of Perl’s extensions and adds an extension syntax to Perl’s extension syntax.If the first character after the question mark is a P, you know that it’s an extension that’s specific to Python
This is the fastest way:
if ($coll->isEmpty()) {...}
Other solutions like count
do a bit more than you need which costs slightly more time.
Plus, the isEmpty()
name quite precisely describes what you want to check there so your code will be more readable.
You can use the JSON stringify
method.
JSON.stringify({x: 5, y: 6}); // '{"x":5,"y":6}' or '{"y":6,"x":5}'
There is pretty good support for this across the board when it comes to browsers, as shown on http://caniuse.com/#search=JSON. You will note, however, that versions of IE earlier than 8 do not support this functionality natively.
If you wish to cater to those users as well you will need a shim. Douglas Crockford has provided his own JSON Parser on github.
You can not run/execute an .exe file that is in the users local machine or through a site. The user must first download the exe file and then run the executable file.
So there is no possible way
The following code works only when the EXE is Present in the User's Machine.
<a href = "C:\folder_name\program.exe">
Simple is:
server {
listen 80;
server_name p3000;
location / {
proxy_pass http://0.0.0.0:3000;
include /etc/nginx/proxy_params;
}
}
Opy
Opy will obfuscate your extensive, real world, multi module Python source code for free! And YOU choose per project what to obfuscate and what not, by editing the config file:
You can recursively exclude all identifiers of certain modules from obfuscation. You can exclude human readable configuration files containing Python code. You can use getattr, setattr, exec and eval by excluding the identifiers they use. You can even obfuscate module file names and string literals. You can run your obfuscated code from any platform.
Unlike some of the other options posted, this works for both Python 2 and 3! It is also free / opensource, and it is not an online only tool (unless you pay) like some of the others out there.
I am admittedly still evaluating this myself, but all of initial tests of it worked perfectly. It appears this is exactly what I was looking for!
The official version runs as a standalone utility, with the original intended design being that you drop a script into the root of the directory you want to obfuscate, along with a config file to define the details/options you want to employ. I wasn't in love with that plan, so I added a fork from project, allowing you to import and utilize the tool from a library instead. That way, you can roll this directly into a more encompassing packaging script. (You could of course wrap multiple py scripts in bash/batch, but I think a pure python solution is ideal). I requested my fork be merged into the original work, but in case that never happens, here's the url to my revised version: