One ArrayList1 add to data,
mArrayList1.add(data);
and Second ArrayList2 to add other data,
mArrayList2.addAll(mArrayList1);
Turns out the binding of style to a string doesn't work. The solution would be to bind the background of the style.
<div class="circle" [style.background]="color">
In addition to the API key that is assigned to you, Google also verifies the source of the incoming request by looking at either the REFERRER
or the IP address. To run an example in curl, create a new Server Key
in Google APIs console. While creating it, you must provide the IP address of the server. In this case, it will be your local IP address. Once you have created a Server Key
and whitelisted your IP address, you should be able to use the new API key in curl.
My guess is you probably created your API key as a Browser Key
which does not require you to whitelist your IP address, but instead uses the REFERRER
HTTP header tag for validation. curl doesn't send this tag by default, so Google was failing to validate your request.
Got the solution and it's working fine. Set the environment variables as:
CATALINA_HOME=C:\Program Files\Java\apache-tomcat-7.0.59\apache-tomcat-7.0.59
(path where your Apache Tomcat is)JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25;
(path where your JDK is)JRE_Home=C:\Program Files\Java\jre1.8.0_25;
(path where your JRE is)CLASSPATH=%JAVA_HOME%\bin;%JRE_HOME%\bin;%CATALINA_HOME%\lib
Or you could just add some content to the div and use inline-table
Since you haven't posted any code, it's difficult to know exactly which problems you're encountering. However, the blog post you link to does seem to work pretty decently... aside from the extra comma in each call to CCCrypt()
which caused compile errors.
A later comment on that post includes this adapted code, which works for me, and seems a bit more straightforward. If you include their code for the NSData category, you can write something like this: (Note: The printf()
calls are only for demonstrating the state of the data at various points — in a real application, it wouldn't make sense to print such values.)
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *key = @"my password";
NSString *secret = @"text to encrypt";
NSData *plain = [secret dataUsingEncoding:NSUTF8StringEncoding];
NSData *cipher = [plain AES256EncryptWithKey:key];
printf("%s\n", [[cipher description] UTF8String]);
plain = [cipher AES256DecryptWithKey:key];
printf("%s\n", [[plain description] UTF8String]);
printf("%s\n", [[[NSString alloc] initWithData:plain encoding:NSUTF8StringEncoding] UTF8String]);
[pool drain];
return 0;
}
Given this code, and the fact that encrypted data will not always translate nicely into an NSString, it may be more convenient to write two methods that wrap the functionality you need, in forward and reverse...
- (NSData*) encryptString:(NSString*)plaintext withKey:(NSString*)key {
return [[plaintext dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptWithKey:key];
}
- (NSString*) decryptData:(NSData*)ciphertext withKey:(NSString*)key {
return [[[NSString alloc] initWithData:[ciphertext AES256DecryptWithKey:key]
encoding:NSUTF8StringEncoding] autorelease];
}
This definitely works on Snow Leopard, and @Boz reports that CommonCrypto is part of the Core OS on the iPhone. Both 10.4 and 10.5 have /usr/include/CommonCrypto
, although 10.5 has a man page for CCCryptor.3cc
and 10.4 doesn't, so YMMV.
EDIT: See this follow-up question on using Base64 encoding for representing encrypted data bytes as a string (if desired) using safe, lossless conversions.
Current date is in yyyy-mm-dd
format. You can convert it into yyyymmdd
format using substring
function:
select substr(current date,1,4)||substr(current date,6,2)||substr(currentdate,9,2)
A very simple solution, if separated by comma or if not separated by comma
public static void main(String[] args) {
String input = "a,1,b,2,c,3,d,4";
input = input.replaceAll(",", "");
String alpha ="";
String num = "";
char[] c_arr = input.toCharArray();
for(char c: c_arr) {
if(Character.isDigit(c)) {
alpha = alpha + c;
}
else {
num = num+c;
}
}
System.out.println("Alphabet: "+ alpha);
System.out.println("num: "+ num);
}
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
It should be :
public async Task<ActionResult> GetSomeJsonData()
{
var model = // ... get data or build model etc.
return Json(new { Data = model }, JsonRequestBehavior.AllowGet);
}
or more simply:
return Json(model, JsonRequestBehavior.AllowGet);
I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...
I know this doesn't help you, but I have to say that this is one of the reasons I jumped from XAMPP to WampServer. WampServer lets you install multiple versions of PHP, Apache and/or MySQL, and switch between them all via a menu option.
I had the same problem and fixed it by including jQuery UI. Here is the complete script :
<!-- include Google's AJAX API loader -->
<script src="http://www.google.com/jsapi"></script>
<!-- load JQuery and UI from Google (need to use UI to animate colors) -->
<script type="text/javascript">
google.load("jqueryui", "1.5.2");
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#menu ul li.item').hover(
function() {
$(this).stop().animate({backgroundColor:'#4E1402'}, 300);
}, function () {
$(this).stop().animate({backgroundColor:'#943D20'}, 100);
});
});
</script>
I tried this:
SELECT DISTINCT link,id,day,month FROM posted WHERE ad='$key' ORDER BY day, month
It doesn't work. It returns too many rows. Say there are 10 rows with same links, but different day/month/id. This script will return all 10, and I want only the first one (for this link).
What you're asking doesn't make sense.
Either you want the distinct value of all of link, id, day, month
, or you need to find a criterion to choose which of the values of id, day, month
you want to use, if you just want at most one distinct value of link
.
Otherwise, what you're after is similar to MySQL's hidden columns in GROUP BY
/HAVING
statements, which is non-standard SQL, and can actually be quite confusing.
You could in fact use a GROUP BY link
if it made sense to pick any row for a given link
value.
Alternatively, you could use a sub-select to pick the row with the minimal id
for a each link
value (as described in this answer):
SELECT link, id, day, month FROM posted
WHERE (link, id) IN
(SELECT link, MIN(id) FROM posted ad='$key' GROUP BY link)
You can use this code snippet for creating a two buttoned Alert box,
import 'package:flutter/material.dart';
class BaseAlertDialog extends StatelessWidget {
//When creating please recheck 'context' if there is an error!
Color _color = Color.fromARGB(220, 117, 218 ,255);
String _title;
String _content;
String _yes;
String _no;
Function _yesOnPressed;
Function _noOnPressed;
BaseAlertDialog({String title, String content, Function yesOnPressed, Function noOnPressed, String yes = "Yes", String no = "No"}){
this._title = title;
this._content = content;
this._yesOnPressed = yesOnPressed;
this._noOnPressed = noOnPressed;
this._yes = yes;
this._no = no;
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: new Text(this._title),
content: new Text(this._content),
backgroundColor: this._color,
shape:
RoundedRectangleBorder(borderRadius: new BorderRadius.circular(15)),
actions: <Widget>[
new FlatButton(
child: new Text(this._yes),
textColor: Colors.greenAccent,
onPressed: () {
this._yesOnPressed();
},
),
new FlatButton(
child: Text(this._no),
textColor: Colors.redAccent,
onPressed: () {
this._noOnPressed();
},
),
],
);
}
}
To show the dialog you can have a method that calls it NB after importing BaseAlertDialog
class
_confirmRegister() {
var baseDialog = BaseAlertDialog(
title: "Confirm Registration",
content: "I Agree that the information provided is correct",
yesOnPressed: () {},
noOnPressed: () {},
yes: "Agree",
no: "Cancel");
showDialog(context: context, builder: (BuildContext context) => baseDialog);
}
OUTPUT WILL BE LIKE THIS
I could not get anything to work I ended up just using powershell to start bat scripts .. sometimes even start cmd /c does not work not sure why .. I even tried stuff like start cmd /c notepad & exit
start-Process "c:\BACKUP\PRIVATE\MobaXterm_Portable\MobaXterm_Portable.bat" -WindowStyle Hidden
Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction()
function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!
<run your last command on this line>
a=${?}
if [ ${a} -ne 0 ]; then echo "do something"; fi
use whatever command you want to use instead of the echo "do something"
command
You could use read.table
with an empty string for the input text
as follows:
colClasses = c("Date", "character", "character")
col.names = c("Date", "File", "User")
df <- read.table(text = "",
colClasses = colClasses,
col.names = col.names)
Alternatively specifying the col.names
as a string:
df <- read.csv(text="Date,File,User", colClasses = colClasses)
Thanks to Richard Scriven for the improvement
Ok, I had the same problem with STS on a mac and solved it by deleting all the files in repository folder and from the STS IDE click on the project and then Maven -> Update project. Give it a couple of minutes to download all the dependencies and the problem is solved.
suptitle
seems the way to go, but for what it's worth, the figure
has a transFigure
property that you can use:
fig=figure(1)
text(0.5, 0.95, 'test', transform=fig.transFigure, horizontalalignment='center')
Pythonic way to do this is ...
np.divide(data.T,vector).T
This takes care of reshaping and also the results are in floating point format. In other answers results are in rounded integer format.
#NOTE: No of columns in both data and vector should match
I've created a systematic approach to CSS development. This way I can utilize a standard that never changes. First I started with the 960 grid system. Then I created single lines of css for basic layouts, margins, padding, fonts and sizes. I then string them together as needed. This allows me to keep a consistent layout across all of my projects and utilize the same css files over and over. Because they are not specific. Here's an example: ----div class="c12 bg0 m10 p5 white fl"/div--- This means that the container is 12 columns across, utilizes bg0 has margins of 10px padding of 5 the text is white and it floats left. I could easily change this by removing or adding a new - What I call a "light" style- Instead of creating a single class with all these attributes; I simply combine the single styles as I code the page. This allows me to create any combination of styles and does not limit my creativity or cause me to create a massive number of styles that are similar. Your style sheets become a lot more manageable, minimized and allow you to re-use it over and over. This method I have found to be fantastic for rapid design. I also no longer design first in PSD but in the browser which also saves time. In addition because I have also created a naming system for my backgrounds and page design attributes I simply change out my image file when creating a new project.(bg0 = body background according to my naming system) That means that if I previously had a white background with one project simply changing it to black simply means that on the next project bg0 will be a black background or another image..... I have not found anything wrong with this method yet and it seems to work very well.
@ECHO off & SETLOCAL EnableDelayedExpansion
SET "_dir=" REM Must finish with '\'
SET "_ext=jpg"
SET "_toEdit=Vacation2010"
SET "_with=December"
FOR %%f IN ("%_dir%*.%_ext%") DO (
CALL :modifyString "%_toEdit%" "%_with%" "%%~Nf" fileName
RENAME "%%f" "!fileName!%%~Xf"
)
GOTO end
:modifyString what with in toReturn
SET "__in=%~3"
SET "__in=!__in:%~1=%~2!"
IF NOT "%~4" == "" (
SET %~4=%__in%
) ELSE (
ECHO %__in%
)
EXIT /B
:end
This script allows you to change the name of all the files that contain Vacation2010
with the same name, but with December
instead of Vacation2010
.
If you copy and paste the code, you have to save the .bat
in the same folder of the photos.
If you want to save the script in another directory [E.G. you have a favorite folder for the utilities] you have to change the value of _dir
with the path of the photos.
If you have to do the same work for other photos [or others files changig _ext
] you have to change the value of _toEdit
with the string you want to change [or erase] and the value of _with
with the string you want to put instead of _toEdit
[SET "_with="
if you simply want to erase the string specified in _toEdit
].
I had a similar situation where I had the proxy settings already set and the SDK manager wasn't able to modify them permanently. Modifying manually the ~/.android/androidtool.cfg
file fixed the issue.
this should do it
((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getRequestURI();
In Android, application-level meta data is accessed through the Context
reference, which an activity is a descendant of.
For example, you can get the source directory via the getApplicationInfo().sourceDir
property.
There are methods for other folders as well (assets directory, data dir, database dir, etc.).
Another approach is to create an association table that contains columns for each potential resource type. In your example, each of the two existing owner types has their own table (which means you have something to reference). If this will always be the case you can have something like this:
CREATE TABLE dbo.Group
(
ID int NOT NULL,
Name varchar(50) NOT NULL
)
CREATE TABLE dbo.User
(
ID int NOT NULL,
Name varchar(50) NOT NULL
)
CREATE TABLE dbo.Ticket
(
ID int NOT NULL,
Owner_ID int NOT NULL,
Subject varchar(50) NULL
)
CREATE TABLE dbo.Owner
(
ID int NOT NULL,
User_ID int NULL,
Group_ID int NULL,
{{AdditionalEntity_ID}} int NOT NULL
)
With this solution, you would continue to add new columns as you add new entities to the database and you would delete and recreate the foreign key constraint pattern shown by @Nathan Skerl. This solution is very similar to @Nathan Skerl but looks different (up to preference).
If you are not going to have a new Table for each new Owner type then maybe it would be good to include an owner_type instead of a foreign key column for each potential Owner:
CREATE TABLE dbo.Group
(
ID int NOT NULL,
Name varchar(50) NOT NULL
)
CREATE TABLE dbo.User
(
ID int NOT NULL,
Name varchar(50) NOT NULL
)
CREATE TABLE dbo.Ticket
(
ID int NOT NULL,
Owner_ID int NOT NULL,
Owner_Type string NOT NULL, -- In our example, this would be "User" or "Group"
Subject varchar(50) NULL
)
With the above method, you could add as many Owner Types as you want. Owner_ID would not have a foreign key constraint but would be used as a reference to the other tables. The downside is that you would have to look at the table to see what the owner types there are since it isn't immediately obvious based upon the schema. I would only suggest this if you don't know the owner types beforehand and they won't be linking to other tables. If you do know the owner types beforehand, I would go with a solution like @Nathan Skerl.
Sorry if I got some SQL wrong, I just threw this together.
For check it with ngModel, make a merge between "ngModel" and "value", Example:
<mat-checkbox [(ngModel)]="myVariable" value="1" >Subscribe</mat-checkbox>
Where, myVariable = 1
Greeting
in Kotlin You can use,
webView.isScrollbarFadingEnabled = true
webView.setInitialScale(100)
Use ...from table(... :
create or replace type numbertype
as object
(nr number(20,10) )
/
create or replace type number_table
as table of numbertype
/
create or replace procedure tableselect
( p_numbers in number_table
, p_ref_result out sys_refcursor)
is
begin
open p_ref_result for
select *
from employees , (select /*+ cardinality(tab 10) */ tab.nr from table(p_numbers) tab) tbnrs
where id = tbnrs.nr;
end;
/
This is one of the rare cases where you need a hint, else Oracle will not use the index on column id. One of the advantages of this approach is that Oracle doesn't need to hard parse the query again and again. Using a temporary table is most of the times slower.
edit 1 simplified the procedure (thanks to jimmyorr) + example
create or replace procedure tableselect
( p_numbers in number_table
, p_ref_result out sys_refcursor)
is
begin
open p_ref_result for
select /*+ cardinality(tab 10) */ emp.*
from employees emp
, table(p_numbers) tab
where tab.nr = id;
end;
/
Example:
set serveroutput on
create table employees ( id number(10),name varchar2(100));
insert into employees values (3,'Raymond');
insert into employees values (4,'Hans');
commit;
declare
l_number number_table := number_table();
l_sys_refcursor sys_refcursor;
l_employee employees%rowtype;
begin
l_number.extend;
l_number(1) := numbertype(3);
l_number.extend;
l_number(2) := numbertype(4);
tableselect(l_number, l_sys_refcursor);
loop
fetch l_sys_refcursor into l_employee;
exit when l_sys_refcursor%notfound;
dbms_output.put_line(l_employee.name);
end loop;
close l_sys_refcursor;
end;
/
This will output:
Raymond
Hans
Since the page you load inside the iframe can execute the "break out" code with a setInterval, onbeforeunload might not be that practical, since it could flud the user with 'Are you sure you want to leave?' dialogs.
There is also the iframe security attribute which only works on IE & Opera
:(
please try this below command :
sudo php artisan cache:clear
sudo php artisan view:clear
sudo php artisan config:cache
This works very well:
<template *ngFor="let item of items; let i=index" >
<ion-slide *ngIf="i<5" >
<img [src]="item.ItemPic">
</ion-slide>
</template>
unfortunately we can't use in MySQL after INSERT or UPDATE description, like in Oracle
It works fine for me, but it's a little tricky :)
Now you have settings for this session set (every time you load session it will be logged).
Create a file called NuGet.config next to your solution file with the following contents
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="LocalPackages" value="./LocalPackages" />
</packageSources>
<activePackageSource>
<!-- this tells that all of them are active -->
<add key="All" value="(Aggregate source)" />
</activePackageSource>
</configuration>
If the solution is open in Visual Studio, close it, then re-open it.
Now your packages should appear in the browser, or be installable using Install-Package
Got this from Bing. Seems Microsoft has removed some features from the core framework and added it to a separate optional(?) framework component.
To quote from MSDN (http://msdn.microsoft.com/en-us/library/cc656912.aspx)
The .NET Framework 4 Client Profile does not include the following features. You must install the .NET Framework 4 to use these features in your application:
* ASP.NET * Advanced Windows Communication Foundation (WCF) functionality * .NET Framework Data Provider for Oracle * MSBuild for compiling
@Override
public void onPause() {
super.onPause();
if(pDialog != null)
pDialog .dismiss();
pDialog = null;
}
refer this.
$DBH = new PDO( "connection string goes here" );
$STH - $DBH -> prepare( "select figure from table1 ORDER BY x LIMIT 1" );
$STH -> execute();
$result = $STH -> fetch();
echo $result ["figure"];
$DBH = null;
You can use fetch and LIMIT together. LIMIT has the effect that the database returns only one entry so PHP has to handle very less data. With fetch you get the first (and only) result entry from the database reponse.
You can do more optimizing by setting the fetching type, see http://www.php.net/manual/de/pdostatement.fetch.php. If you access it only via column names you need to numbered array.
Be aware of the ORDER clause. Use ORDER or WHERE to get the needed row. Otherwise you will get the first row in the table alle the time.
Use the following code for getting lat and long using php. Here are two methods:
<?php
// Get lat and long by address
$address = $dlocation; // Google HQ
$prepAddr = str_replace(' ','+',$address);
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
$latitude = $output->results[0]->geometry->location->lat;
$longitude = $output->results[0]->geometry->location->lng;
?>
edit - Google Maps requests must be over https
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(50.804400, -1.147250);
var mapOptions = {
zoom: 6,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas12'), mapOptions);
}
function codeAddress(address,tutorname,url,distance,prise,postcode) {
var address = address;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var infowindow = new google.maps.InfoWindow({
content: 'Tutor Name: '+tutorname+'<br>Price Guide: '+prise+'<br>Distance: '+distance+' Miles from you('+postcode+')<br> <a href="'+url+'" target="blank">View Tutor profile</a> '
});
infowindow.open(map,marker);
} /*else {
alert('Geocode was not successful for the following reason: ' + status);
}*/
});
}
google.maps.event.addDomListener(window, 'load', initialize);
window.onload = function(){
initialize();
// your code here
<?php foreach($addr as $add) {
?>
codeAddress('<?php echo $add['address']; ?>','<?php echo $add['tutorname']; ?>','<?php echo $add['url']; ?>','<?php echo $add['distance']; ?>','<?php echo $add['prise']; ?>','<?php echo substr( $postcode1,0,4); ?>');
<?php } ?>
};
</script>
<div id="map-canvas12"></div>
I can't get it to work on $.get()
because it has no complete
event.
I suggest to use $.ajax()
like this,
$.ajax({
url: 'http://www.example.org',
data: {'a':1,'b':2,'c':3},
dataType: 'xml',
complete : function(){
alert(this.url)
},
success: function(xml){
}
});
BrixenDK is right.
.ajaxStop()
callback executed when all ajax call completed. This is a best place to put your handler.
$(document).ajaxStop(function(){
window.location.reload();
});
Try reducing the range of the for loop to range(len(a)-1)
:
a = [0,1,2,3]
b = []
for i in range(len(a)-1):
b.append(a[i]+a[i+1])
print(b)
This can also be written as a list comprehension:
b = [a[i] + a[i+1] for i in range(len(a)-1)]
print(b)
run the following command by creating a virtual enviroment using python 3 and run
pip3 install opencv-python
to check it has installed correctly run
python3 -c "import cv2"
You need to let Gson know additional type of your response as below
import com.google.common.reflect.TypeToken;
import java.lang.reflect.Type;
Type collectionType = new TypeToken<List<UserSite>>(){}.getType();
List<UserSite> userSites = gson.fromJson( response.getBody() , collectionType);
You can select the "Runnable JAR File" after you click on "Export".
You can specify your main driver in "Launch Configuration"
INSERT INTO servers (server_name, online_status, exchange, disk_space, network_shares)
VALUES('m1','ONLINE','exchange','disk_space','network_shares', NOW())
You can try this to get infos like:
git config --get user.name
git config --get user.email
There's nothing like "first name" and "last name" for the user.
Hope this will help.
REST is not necessarily tied to HTTP. RESTful web services are just web services that follow a RESTful architecture.
What is Rest -
1- Client-server
2- Stateless
3- Cacheable
4- Layered system
5- Code on demand
6- Uniform interface
If you need to do anything more with office documents in Java, go for POI as mentioned.
For simple reading/writing an excel document like you requested, you can use the CSV format (also as mentioned):
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class CsvWriter {
public static void main(String args[]) throws IOException {
String fileName = "test.xls";
PrintWriter out = new PrintWriter(new FileWriter(fileName));
out.println("a,b,c,d");
out.println("e,f,g,h");
out.println("i,j,k,l");
out.close();
BufferedReader in = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = in.readLine()) != null) {
Scanner scanner = new Scanner(line);
String sep = "";
while (scanner.hasNext()) {
System.out.println(sep + scanner.next());
sep = ",";
}
}
in.close();
}
}
By the way, in case you dont know what is the exact location of your JSONObject inside your JSONArray i suggest using the following code: (I assumed that "jsonArray" is your main variable with all the data, and i'm searching the exact object inside the array with equals function)
JSONArray list = new JSONArray();
if (jsonArray != null){
int len = jsonArray.length();
for (int i=0;i<len;i++)
{
boolean flag;
try {
flag = jsonArray.get(i).toString().equals(obj.toString());
//Excluding the item at position
if (!flag)
{
list.put(jsonArray.get(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
jsonArray = list;
Process of generating RPM from source file: 1) download source file with.gz extention. 2) install rpm-build and rpmdevtools from yum install. (rpmbuild folder will be generated...SPECS,SOURCES,RPMS.. folders will should be generated inside the rpmbuild folder). 3) copy the source code.gz to SOURCES folder.(rpmbuild/SOURCES) 4)Untar the tar ball by using the following command. go to SOURCES folder :rpmbuild/SOURCES where tar file is present. command: e.g tar -xvzf httpd-2.22.tar.gz httpd-2.22 folder will be generated in the same path. Check if apr and apr-util and there in httpd-2.22/srclib folder. If apr and apr-util doesnt exist download latest version from apache site ,untar it and put it inside httpd-2.22/srclib folder. Also make sure you have pcre install in your system .
5)go to extracted folder and then type below command: ./configure --prefix=/usr/local/apache2 --with-included-apr --enable-proxy --enable-proxy-balancer --with-mpm=worker --enable-mods-static=all 6)run below command once the configure is successful: make 7)after successfull execution od make command run: checkinstall in tha same folder. (if you dont have checkinstall software please download latest version from site) Also checkinstall software has bug which can be solved by following way::::: locate checkinstallrc and then replace TRANSLATE = 1 to TRANSLATE=0 using vim command. Also check for exclude package: EXCLUDE="/selinux" 8)checkinstall will ask for option (type R if you want tp build rpm for source file) 9)Done .rpm file will be built in RPMS folder inside rpmbuild/RPMS file... ALL the BEST ....
Regards, Prerana
You can get some limited memory information from the Runtime class. It really isn't exactly what you are looking for, but I thought I would provide it for the sake of completeness. Here is a small example. Edit: You can also get disk usage information from the java.io.File class. The disk space usage stuff requires Java 1.6 or higher.
public class Main {
public static void main(String[] args) {
/* Total number of processors or cores available to the JVM */
System.out.println("Available processors (cores): " +
Runtime.getRuntime().availableProcessors());
/* Total amount of free memory available to the JVM */
System.out.println("Free memory (bytes): " +
Runtime.getRuntime().freeMemory());
/* This will return Long.MAX_VALUE if there is no preset limit */
long maxMemory = Runtime.getRuntime().maxMemory();
/* Maximum amount of memory the JVM will attempt to use */
System.out.println("Maximum memory (bytes): " +
(maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory));
/* Total memory currently available to the JVM */
System.out.println("Total memory available to JVM (bytes): " +
Runtime.getRuntime().totalMemory());
/* Get a list of all filesystem roots on this system */
File[] roots = File.listRoots();
/* For each filesystem root, print some info */
for (File root : roots) {
System.out.println("File system root: " + root.getAbsolutePath());
System.out.println("Total space (bytes): " + root.getTotalSpace());
System.out.println("Free space (bytes): " + root.getFreeSpace());
System.out.println("Usable space (bytes): " + root.getUsableSpace());
}
}
}
I got new way to resolve this issue. Here I have used google http service to get total information of location based on longitude and latitude. You just need to pass latitude and longitude in url and your api key (ex : latlng=21.1497409, 79.08747970000002 & key=YOUR API KEY). Here is my get service in ExampleService
Class
getService(url) {
return this.http.get(url).map((data: any) => data.json())
}
this you can put anywhere you want and just call below service from component where you need location data
this._exampleService.getService("https://maps.googleapis.com/maps/api/geocode/json?latlng=21.1497409, 79.08747970000002&key=YOUR API KEY").subscribe(getplaceData => {
var placeDataDest: any;
placeDataDest = getplaceData;
console.log("i got place id yeee " + placeDataDest['results'][0]['place_id']);
console.log("i got place details yeee " + placeDataDest['results']);
});
similarly find city name....hope you will find this useful
Try a category on UILabel:
Here's how it's used:
myLabel.text = @"Updated: 2012/10/14 21:59 PM";
[myLabel boldSubstring: @"Updated:"];
[myLabel boldSubstring: @"21:59 PM"];
And here's the category
UILabel+Boldify.h
- (void) boldSubstring: (NSString*) substring;
- (void) boldRange: (NSRange) range;
UILabel+Boldify.m
- (void) boldRange: (NSRange) range {
if (![self respondsToSelector:@selector(setAttributedText:)]) {
return;
}
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
[attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:self.font.pointSize]} range:range];
self.attributedText = attributedText;
}
- (void) boldSubstring: (NSString*) substring {
NSRange range = [self.text rangeOfString:substring];
[self boldRange:range];
}
Note that this will only work in iOS 6 and later. It will simply be ignored in iOS 5 and earlier.
since HashMap
implements Serializable
interface, you can simply use ObjectOutputStream
class to write whole Map
to file, and read it again using ObjectInputStream
class
below simple code that explain usage of ObjectOutStream
and ObjectInputStream
import java.util.*;
import java.io.*;
public class A{
HashMap<String,String> hm;
public A() {
hm=new HashMap<String,String>();
hm.put("1","A");
hm.put("2","B");
hm.put("3","C");
method1(hm);
}
public void method1(HashMap<String,String> map) {
//write to file : "fileone"
try {
File fileOne=new File("fileone");
FileOutputStream fos=new FileOutputStream(fileOne);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(map);
oos.flush();
oos.close();
fos.close();
} catch(Exception e) {}
//read from file
try {
File toRead=new File("fileone");
FileInputStream fis=new FileInputStream(toRead);
ObjectInputStream ois=new ObjectInputStream(fis);
HashMap<String,String> mapInFile=(HashMap<String,String>)ois.readObject();
ois.close();
fis.close();
//print All data in MAP
for(Map.Entry<String,String> m :mapInFile.entrySet()){
System.out.println(m.getKey()+" : "+m.getValue());
}
} catch(Exception e) {}
}
public static void main(String args[]) {
new A();
}
}
or if you want to write data as text to file you can simply iterate through Map
and write key and value line by line, and read it again line by line and add to HashMap
import java.util.*;
import java.io.*;
public class A{
HashMap<String,String> hm;
public A(){
hm=new HashMap<String,String>();
hm.put("1","A");
hm.put("2","B");
hm.put("3","C");
method2(hm);
}
public void method2(HashMap<String,String> map) {
//write to file : "fileone"
try {
File fileTwo=new File("filetwo.txt");
FileOutputStream fos=new FileOutputStream(fileTwo);
PrintWriter pw=new PrintWriter(fos);
for(Map.Entry<String,String> m :map.entrySet()){
pw.println(m.getKey()+"="+m.getValue());
}
pw.flush();
pw.close();
fos.close();
} catch(Exception e) {}
//read from file
try {
File toRead=new File("filetwo.txt");
FileInputStream fis=new FileInputStream(toRead);
Scanner sc=new Scanner(fis);
HashMap<String,String> mapInFile=new HashMap<String,String>();
//read data from file line by line:
String currentLine;
while(sc.hasNextLine()) {
currentLine=sc.nextLine();
//now tokenize the currentLine:
StringTokenizer st=new StringTokenizer(currentLine,"=",false);
//put tokens ot currentLine in map
mapInFile.put(st.nextToken(),st.nextToken());
}
fis.close();
//print All data in MAP
for(Map.Entry<String,String> m :mapInFile.entrySet()) {
System.out.println(m.getKey()+" : "+m.getValue());
}
}catch(Exception e) {}
}
public static void main(String args[]) {
new A();
}
}
NOTE: above code may not be the fastest way to doing this task, but i want to show some application of classes
See ObjectOutputStream , ObjectInputStream, HashMap, Serializable, StringTokenizer
SELECT DISTINCT (column1), column2
FROM table1
GROUP BY column1
If we just do x.append(y)
, y gets referenced into x such that any changes made to y will affect appended x as well. So if we need to insert only elements, we should do following:
x = [1,2,3]
y = [4,5,6]
x.append(y[:])
The LIBXML_NOCDATA
is optional third parameter of simplexml_load_file()
function. This returns the XML object with all the CDATA data converted into strings.
$xml = simplexml_load_file($this->filename, 'SimpleXMLElement', LIBXML_NOCDATA);
echo "<pre>";
print_r($xml);
echo "</pre>";
If you don't want the $.ajax()
function to return immediately, set the async
option to false
:
$(".my_link").click(
function(){
$.ajax({
url: $(this).attr('href'),
type: 'GET',
async: false,
cache: false,
timeout: 30000,
fail: function(){
return true;
},
done: function(msg){
if (parseFloat(msg)){
return false;
} else {
return true;
}
}
});
});
But, I would note that this would be counter to the point of AJAX. Also, you should be handling the response in the fail
and done
functions. Those functions will only be called when the response is received from the server.
I've just stumbled over the same problem and found some interesting information and I wanted to put in my two cents and add it here.
First of all, as others have already mentioned, long-running operations should be done by a thread, which can be a background worker, an explicit thread, a thread from the threadpool or (since .Net 4.0) a task: Stackoverflow 570537: update-label-while-processing-in-windows-forms, so that the UI keeps responsive.
But for short tasks there is no real need for threading although it doesn't hurt of course.
I have created a winform with one button and one label to analyze this problem:
System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
label1->Text = "Start 1";
label1->Update();
System::Threading::Thread::Sleep(5000); // do other work
}
My analysis was stepping over the code (using F10) and seeing what happened. And after reading this article Multithreading in WinForms I have found something interesting. The article says at the bottom of the first page, that the UI thread can not repaint the UI until the currently executed function finishes and the window is marked by Windows as "not responding" instead after a while. I have also noticed that on my test application from above while stepping through it, but only in certain cases.
(For the following test it is important to not have Visual Studio set to fullscreen, you must be able to see your little application window at the same time next to it, You must not have to switch between the Visual Studio window for debugging and your application window to see what happens. Start the application, set a breakpoint at label1->Text ...
, put the application window beside the VS window and place the mouse cursor over the VS window.)
When I click once on VS after app start (to put the focues there and enable stepping) and step through it WITHOUT moving the mouse, the new text is set and the label is updated in the update() function. This means, the UI is repainted obviously.
When I step over the first line, then move the mouse around a lot and click somewhere, then step further, the new text is likely set and the update() function is called, but the UI is not updated/repainted and the old text remains there until the button1_click() function finishes. Instead of repainting, the window is marked as "not responsive"! It also doesn't help to add this->Update();
to update the whole form.
Adding Application::DoEvents();
gives the UI a chance to update/repaint. Anyway you have to take care that the user can not press buttons or perform other operations on the UI that are not permitted!! Therefore: Try to avoid DoEvents()!, better use threading (which I think is quite simple in .Net).
But (@Jagd, Apr 2 '10 at 19:25) you can omit .refresh()
and .invalidate()
.
My explanations is as following: AFAIK winform still uses the WINAPI function. Also MSDN article about System.Windows.Forms Control.Update method refers to WINAPI function WM_PAINT. The MSDN article about WM_PAINT states in its first sentence that the WM_PAINT command is only sent by the system when the message queue is empty. But as the message queue is already filled in the 2nd case, it is not send and thus the label and the application form are not repainted.
<>joke> Conclusion: so you just have to keep the user from using the mouse ;-) <>/joke>
In case you can't for some reason use the same Random
again and again, try initializing it with something that changes all the time, like the time itself.
new Random(new System.DateTime().Millisecond).Next();
Remember this is bad practice though.
EDIT: The default constructor already takes its seed from the clock, and probably better than we would. Quoting from MSDN:
Random() : Initializes a new instance of the Random class, using a time-dependent default seed value.
The code below is probably your best option:
new Random().Next();
my "keep it simple stupid" way ...it waste some resources , i know , but i dont care as my code keep simple so... First, add a footer with visibility GONE to your item_layout
<LinearLayout
android:id="@+id/footer"
android:layout_width="match_parent"
android:layout_height="80dp"
android:orientation="vertical"
android:visibility="gone">
</LinearLayout>
Then, set it visible on the last item
public void onBindViewHolder(ChannelAdapter.MyViewHolder holder, int position) {
boolean last = position==data.size()-1;
//....
holder.footer.setVisibility(View.GONE);
if (last && showFooter){
holder.footer.setVisibility(View.VISIBLE);
}
}
do the opposite for header
Could you do the following:
obj = {
"1":"aa",
"2":"bb"
};
var newNum = "3";
var newVal = "cc";
obj[newNum] = newVal;
alert(obj["3"]); // this would alert 'cc'
Understand that .children
is a property of an Element. 1 Only Elements have .children
, and these children are all of type Element. 2
However, .childNodes
is a property of Node. .childNodes
can contain any node. 3
A concrete example would be:
let el = document.createElement("div");
el.textContent = "foo";
el.childNodes.length === 1; // Contains a Text node child.
el.children.length === 0; // No Element children.
Most of the time, you want to use .children
because generally you don't want to loop over Text or Comment nodes in your DOM manipulation.
If you do want to manipulate Text nodes, you probably want .textContent
instead. 4
1. Technically, it is an attribute of ParentNode, a mixin included by Element.
2. They are all elements because .children
is a HTMLCollection, which can only contain elements.
3. Similarly, .childNodes
can hold any node because it is a NodeList.
4. Or .innerText
. See the differences here or here.
Put your JavaScript code after your tag <canvas></canvas>
Adding to @David Roussel answer, classes may be loaded by multiple class loaders.
Lets understand how class loader works.
From javin paul blog in javarevisited :
ClassLoader
follows three principles.
A class is loaded in Java, when its needed. Suppose you have an application specific class called Abc.class, first request of loading this class will come to Application ClassLoader which will delegate to its parent Extension ClassLoader which further delegates to Primordial or Bootstrap class loader
Bootstrap ClassLoader is responsible for loading standard JDK class files from rt.jar and it is parent of all class loaders in Java. Bootstrap class loader don't have any parents.
Extension ClassLoader delegates class loading request to its parent, Bootstrap and if unsuccessful, loads class form jre/lib/ext directory or any other directory pointed by java.ext.dirs system property
System or Application class loader and it is responsible for loading application specific classes from CLASSPATH environment variable, -classpath or -cp command line option, Class-Path attribute of Manifest file inside JAR.
Application class loader is a child of Extension ClassLoader and its implemented by sun.misc.Launcher$AppClassLoader
class.
NOTE: Except Bootstrap class loader, which is implemented in native language mostly in C, all Java class loaders are implemented using java.lang.ClassLoader
.
According to visibility principle, Child ClassLoader can see class loaded by Parent ClassLoader but vice-versa is not true.
According to this principle a class loaded by Parent should not be loaded by Child ClassLoader again
table {
border-spacing: 10px;
}
This worked for me once I removed
border-collapse: separate;
from my table tag.
YOu can also rewrite it like this
FROM Resource r WHERE r.ResourceNo IN
(
SELECT m.ResourceNo FROM JobMember m
JOIN Job j ON j.JobNo = m.JobNo
WHERE j.ProjectManagerNo = @UserResourceNo
OR
j.AlternateProjectManagerNo = @UserResourceNo
Union All
SELECT m.ResourceNo FROM JobMember m
JOIN JobTask t ON t.JobTaskNo = m.JobTaskNo
WHERE t.TaskManagerNo = @UserResourceNo
OR
t.AlternateTaskManagerNo = @UserResourceNo
)
Also a return table is expected in your RETURN statement
Try this for the parent, it worked for me.
overflow:auto;
UPDATE:
One more solution that worked:
Parent:
display: table;
Child:
display: table-row;
LR is link register used to hold the return address for a function call.
SP is stack pointer. The stack is generally used to hold "automatic" variables and context/parameters across function calls. Conceptually you can think of the "stack" as a place where you "pile" your data. You keep "stacking" one piece of data over the other and the stack pointer tells you how "high" your "stack" of data is. You can remove data from the "top" of the "stack" and make it shorter.
From the ARM architecture reference:
SP, the Stack Pointer
Register R13 is used as a pointer to the active stack.
In Thumb code, most instructions cannot access SP. The only instructions that can access SP are those designed to use SP as a stack pointer. The use of SP for any purpose other than as a stack pointer is deprecated. Note Using SP for any purpose other than as a stack pointer is likely to break the requirements of operating systems, debuggers, and other software systems, causing them to malfunction.
LR, the Link Register
Register R14 is used to store the return address from a subroutine. At other times, LR can be used for other purposes.
When a BL or BLX instruction performs a subroutine call, LR is set to the subroutine return address. To perform a subroutine return, copy LR back to the program counter. This is typically done in one of two ways, after entering the subroutine with a BL or BLX instruction:
• Return with a BX LR instruction.
• On subroutine entry, store LR to the stack with an instruction of the form: PUSH {,LR} and use a matching instruction to return: POP {,PC} ...
The shortest and most elegant way to do this is:
#!/bin/bash
DIRECTORY=$(cd `dirname $0` && pwd)
echo $DIRECTORY
This would work on all platforms and is super clean.
More details can be found in "Which directory is that bash script in?".
I got this error on a report I copied from another project and changed the data source. I solved it by opening the properties of my dataset, going to the Parameters section, and literally just reselecting all the parameters in the right column, like I just clicked the dropdown and selected the same column. Then I hit preview, and it worked!
An alternative to other layouts, might be to put your panel with the GridLayout, inside another panel that is a FlowLayout. That way your spacing will be intact but will not expand across the entire available space.
Use the zip function to decouple elements:
>>> inpt = [(1, u'abc'), (2, u'def')]
>>> unzipped = zip(*inpt)
>>> print unzipped
[(1, 2), (u'abc', u'def')]
>>> print list(unzipped[0])
[1, 2]
Edit (@BradSolomon):
The above works for Python 2.x, where zip
returns a list.
In Python 3.x, zip
returns an iterator and the following is equivalent to the above:
>>> print(list(list(zip(*inpt))[0]))
[1, 2]
This is a JQuery plugin to change the button text of an input file element.
Example HTML:
<input type="file" id="choose-file" />
Example JS:
$('#choose-file').inputFileText({
text: 'Select File'
});
Result:
You can do the following :-
$(document).ready(function(){
$("#id").trigger("click");
});
Difference between app.use
& app.get
:
app.use
? It is generally used for introducing middlewares in your application and can handle all type of HTTP requests.
app.get
? It is only for handling GET HTTP requests.
Now, there is a confusion between app.use
& app.all
. No doubt, there is one thing common in them, that both can handle all kind of HTTP requests.
But there are some differences which recommend us to use app.use for middlewares and app.all for route handling.
app.use()
? It takes only one callback.
app.all()
? It can take multiple callbacks.
app.use()
will only see whether url starts with specified path.
But, app.all()
will match the complete path.
For example,
app.use( "/book" , middleware);
// will match /book
// will match /book/author
// will match /book/subject
app.all( "/book" , handler);
// will match /book
// won't match /book/author
// won't match /book/subject
app.all( "/book/*" , handler);
// won't match /book
// will match /book/author
// will match /book/subject
next()
call inside the app.use()
will call either the next middleware or any route handler, but next()
call inside app.all()
will invoke the next route handler (app.all()
, app.get/post/put...
etc.) only. If there is any middleware after, it will be skipped. So, it is advisable to put all the middlewares always above the route handlers.Actually, for UTC I used Z
instead of X
, e.g.
${__time(yyyy-MM-dd'T'hh:mm:ssZ)}
which gave me:
2017-09-14T09:24:54-0400
Replacing one string with another can be done in the below methods
Method 1: Using String replaceAll
String myInput = "HelloBrother";
String myOutput = myInput.replaceAll("HelloBrother", "Brother"); // Replace hellobrother with brother
---OR---
String myOutput = myInput.replaceAll("Hello", ""); // Replace hello with empty
System.out.println("My Output is : " +myOutput);
Method 2: Using Pattern.compile
import java.util.regex.Pattern;
String myInput = "JAVAISBEST";
String myOutputWithRegEX = Pattern.compile("JAVAISBEST").matcher(myInput).replaceAll("BEST");
---OR -----
String myOutputWithRegEX = Pattern.compile("JAVAIS").matcher(myInput).replaceAll("");
System.out.println("My Output is : " +myOutputWithRegEX);
Method 3: Using Apache Commons
as defined in the link below:
http://commons.apache.org/proper/commons-lang/javadocs/api-z.1/org/apache/commons/lang3/StringUtils.html#replace(java.lang.String, java.lang.String, java.lang.String)
I think if you closed a program
taskkill /f /im "winamp.exe"
//....(winamp.exe is example)...
end, so if you want to start a program that you can use
start "" /normal winamp.exe
(/norma,/max/min are that process value cpu)
ALSO
if you want command line without openning an new window you write that
/B is Start application without creating a new window. The application has ^C handling ignored. Unless the application enables ^C processing, ^Break is the only way to interrupt the application.
$('input:text').filter(function() { return this.value.length > 0; });
YourAdapter yourAdapter =
new YourAdapter (getActivity(),
R.layout.list_view_item,arrData);
yourAdapter .setDropDownViewResource(R.layout.list_view_item);
mySpinner.setAdapter(yourAdapter );
String strCompare = "Indonesia";
for (int i = 0; i < arrData.length ; i++){
if(arrData[i].getCode().equalsIgnoreCase(strCompare)){
int spinnerPosition = yourAdapter.getPosition(arrData[i]);
mySpinner.setSelection(spinnerPosition);
}
}
Here is what worked for me:
Create the new branch first:
git push github newname :refs/heads/newname
On the GitHub site, go to settings and change the Default branch to newname
Delete the oldname
git push github --delete oldname
There's no need for you to use super-call of the ActionBarDrawerToggle
which requires the Toolbar. This means instead of using the following constructor:
ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes)
You should use this one:
ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, int openDrawerContentDescRes, int closeDrawerContentDescRes)
So basically the only thing you have to do is to remove your custom drawable
:
super(mActivity, mDrawerLayout, R.string.ns_menu_open, R.string.ns_menu_close);
More about the "new" ActionBarDrawerToggle in the Docs (click).
See String Formatting Operations:
%d
is the format code for an integer. %f
is the format code for a float.
%s
prints the str()
of an object (What you see when you print(object)
).
%r
prints the repr()
of an object (What you see when you print(repr(object))
.
For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:
>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
1.12
You have to allocate the buffer with mallock, and give the read write the pointer to it.
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
ssize_t nrd;
int fd;
int fd1;
char* buffer = malloc(100*sizeof(char));
fd = open("bli.txt", O_RDONLY);
fd1 = open("bla.txt", O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
while (nrd = read(fd,buffer,sizeof(buffer))) {
write(fd1,buffer,nrd);
}
close(fd);
close(fd1);
free(buffer);
return 0;
}
Make sure that the rad file exists and contains something. It's not perfect but it works.
When you set a string variable, it doesn't save quotes of it, they are a part of its definition. so you don't need to use :1
You can do:
struct employee_s {
int id;
char* name;
} employee_default = {0, "none"};
typedef struct employee_s employee;
And then you just have to remember to do the default initialization when you declare a new employee variable:
employee foo = employee_default;
Alternatively, you can just always build your employee struct via a factory function.
Integers are inherently finite. The closest you can get is by setting a
to int
's maximum value:
#include <limits>
// ...
int a = std::numeric_limits<int>::max();
Which would be 2^31 - 1
(or 2 147 483 647
) if int
is 32 bits wide on your implementation.
If you really need infinity, use a floating point number type, like float
or double
. You can then get infinity with:
double a = std::numeric_limits<double>::infinity();
If you use Fedora, in order to generate core dump file in the same directory of binary file:
echo "core.%e.%p" > /proc/sys/kernel/core_pattern
And
ulimit -c unlimited
LastRow = ActiveSheet.UsedRange.Rows.Count
I got confused by the answer to this question, so I created a test case in MySQL, hope this helps
-- Schema
CREATE TABLE T1 (
`ID` int not null auto_increment,
`Label` varchar(50),
primary key (`ID`)
);
CREATE TABLE T2 (
`ID` int not null auto_increment,
`Label` varchar(50),
primary key (`ID`)
);
CREATE TABLE TT (
`IDT1` int not null,
`IDT2` int not null,
primary key (`IDT1`,`IDT2`)
);
ALTER TABLE `TT`
ADD CONSTRAINT `fk_tt_t1` FOREIGN KEY (`IDT1`) REFERENCES `T1`(`ID`) ON DELETE CASCADE,
ADD CONSTRAINT `fk_tt_t2` FOREIGN KEY (`IDT2`) REFERENCES `T2`(`ID`) ON DELETE CASCADE;
-- Data
INSERT INTO `T1` (`Label`) VALUES ('T1V1'),('T1V2'),('T1V3'),('T1V4');
INSERT INTO `T2` (`Label`) VALUES ('T2V1'),('T2V2'),('T2V3'),('T2V4');
INSERT INTO `TT` (`IDT1`,`IDT2`) VALUES
(1,1),(1,2),(1,3),(1,4),
(2,1),(2,2),(2,3),(2,4),
(3,1),(3,2),(3,3),(3,4),
(4,1),(4,2),(4,3),(4,4);
-- Delete
DELETE FROM `T2` WHERE `ID`=4; -- Delete one field, all the associated fields on tt, will be deleted, no change in T1
TRUNCATE `T2`; -- Can't truncate a table with a referenced field
DELETE FROM `T2`; -- This will do the job, delete all fields from T2, and all associations from TT, no change in T1
Used below code to set driver type based on need of Headless / Head for both Firefox and chrome:
// Can pass browser type
if brower.lower() == 'chrome':
driver = webdriver.Chrome('..\drivers\chromedriver')
elif brower.lower() == 'headless chrome':
ch_Options = Options()
ch_Options.add_argument('--headless')
ch_Options.add_argument("--disable-gpu")
driver = webdriver.Chrome('..\drivers\chromedriver',options=ch_Options)
elif brower.lower() == 'firefox':
driver = webdriver.Firefox(executable_path=r'..\drivers\geckodriver.exe')
elif brower.lower() == 'headless firefox':
ff_option = FFOption()
ff_option.add_argument('--headless')
ff_option.add_argument("--disable-gpu")
driver = webdriver.Firefox(executable_path=r'..\drivers\geckodriver.exe', options=ff_option)
elif brower.lower() == 'ie':
driver = webdriver.Ie('..\drivers\IEDriverServer')
else:
raise Exception('Invalid Browser Type')
int resolution =Toolkit.getDefaultToolkit().getScreenResolution();
System.out.println(resolution);
When calling a promise defined in a service or in a factory make sure to use service as I could not get response from a promise defined in a factory. This is how I call a promise defined in a service.
myApp.service('serverOperations', function($http) {
this.get_data = function(user) {
return $http.post('http://localhost/serverOperations.php?action=get_data', user);
};
})
myApp.controller('loginCtrl', function($http, $q, serverOperations, user) {
serverOperations.get_data(user)
.then( function(response) {
console.log(response.data);
}
);
})
To convert an integer to a string:
integer :: i
character* :: s
if (i.LE.9) then
s=char(48+i)
else if (i.GE.10) then
s=char(48+(i/10))// char(48-10*(i/10)+i)
endif
This way works fine for me:
var request = new RestSharp.RestRequest("RESOURCE", RestSharp.Method.POST) { RequestFormat = RestSharp.DataFormat.Json }
.AddBody(BODY);
var response = Client.Execute(request);
// Handle response errors
HandleResponseErrors(response);
if (Errors.Length == 0)
{ }
else
{ }
Hope this helps! (Although it is a bit late)
Actually although the answer of bmdhacks is almost good, there is a slight chance the second script to run after first checked the lockfile and before it wrote it. So they both will write the lock file and they will both be running. Here is how to make it work for sure:
lockfile=/var/lock/myscript.lock
if ( set -o noclobber; echo "$$" > "$lockfile") 2> /dev/null ; then
trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT
else
# or you can decide to skip the "else" part if you want
echo "Another instance is already running!"
fi
The noclobber
option will make sure that redirect command will fail if file already exists. So the redirect command is actually atomic - you write and check the file with one command. You don't need to remove the lockfile at the end of file - it'll be removed by the trap. I hope this helps to people that will read it later.
P.S. I didn't see that Mikel already answered the question correctly, although he didn't include the trap command to reduce the chance the lock file will be left over after stopping the script with Ctrl-C for example. So this is the complete solution
Edit file "C:\Users\Your User\AppData\Roaming\Code\User\settings.json" and add these python.linting.pylintArgs
lines at the end as shown below:
{
"team.showWelcomeMessage": false,
"python.dataScience.sendSelectionToInteractiveWindow": true,
"git.enableSmartCommit": true,
"powershell.codeFormatting.useCorrectCasing": true,
"files.autoSave": "onWindowChange",
"python.linting.pylintArgs": [
"--load-plugins=pylint_django",
"--errors-only"
],
}
You should be using iostream
without the .h
.
Early implementations used the .h
variants but the standard mandates the more modern style.
tl;dr
post-JDK8 : Use AssertJ or custom lambdas to assert exceptional behaviour.
pre-JDK8 : I will recommend the old good try
-catch
block. (Don't forget to add a fail()
assertion before the catch
block)
Regardless of Junit 4 or JUnit 5.
the long story
It is possible to write yourself a do it yourself try
-catch
block or use the JUnit tools (@Test(expected = ...)
or the @Rule ExpectedException
JUnit rule feature).
But these ways are not so elegant and don't mix well readability wise with other tools. Moreover, JUnit tooling does have some pitfalls.
The try
-catch
block you have to write the block around the tested behavior and write the assertion in the catch block, that may be fine but many find that this style interrupts the reading flow of a test. Also, you need to write an Assert.fail
at the end of the try
block. Otherwise, the test may miss one side of the assertions; PMD, findbugs or Sonar will spot such issues.
The @Test(expected = ...)
feature is interesting as you can write less code and then writing this test is supposedly less prone to coding errors. But this approach is lacking in some areas.
Also as the expectation is placed around in the method, depending on how the tested code is written then the wrong part of the test code can throw the exception, leading to false-positive test and I'm not sure that PMD, findbugs or Sonar will give hints on such code.
@Test(expected = WantedException.class)
public void call2_should_throw_a_WantedException__not_call1() {
// init tested
tested.call1(); // may throw a WantedException
// call to be actually tested
tested.call2(); // the call that is supposed to raise an exception
}
The ExpectedException
rule is also an attempt to fix the previous caveats, but it feels a bit awkward to use as it uses an expectation style, EasyMock users know very well this style. It might be convenient for some, but if you follow Behaviour Driven Development (BDD) or Arrange Act Assert (AAA) principles the ExpectedException
rule won't fit in those writing style. Aside from that it may suffer from the same issue as the @Test
way, depending on where you place the expectation.
@Rule ExpectedException thrown = ExpectedException.none()
@Test
public void call2_should_throw_a_WantedException__not_call1() {
// expectations
thrown.expect(WantedException.class);
thrown.expectMessage("boom");
// init tested
tested.call1(); // may throw a WantedException
// call to be actually tested
tested.call2(); // the call that is supposed to raise an exception
}
Even the expected exception is placed before the test statement, it breaks your reading flow if the tests follow BDD or AAA.
Also, see this comment issue on JUnit of the author of ExpectedException
. JUnit 4.13-beta-2 even deprecates this mechanism:
Pull request #1519: Deprecate ExpectedException
The method Assert.assertThrows provides a nicer way for verifying exceptions. In addition, the use of ExpectedException is error-prone when used with other rules like TestWatcher because the order of rules is important in that case.
So these above options have all their load of caveats, and clearly not immune to coder errors.
There's a project I became aware of after creating this answer that looks promising, it's catch-exception.
As the description of the project says, it let a coder write in a fluent line of code catching the exception and offer this exception for the latter assertion. And you can use any assertion library like Hamcrest or AssertJ.
A rapid example taken from the home page :
// given: an empty list
List myList = new ArrayList();
// when: we try to get the first element of the list
when(myList).get(1);
// then: we expect an IndexOutOfBoundsException
then(caughtException())
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessage("Index: 1, Size: 0")
.hasNoCause();
As you can see the code is really straightforward, you catch the exception on a specific line, the then
API is an alias that will use AssertJ APIs (similar to using assertThat(ex).hasNoCause()...
). At some point the project relied on FEST-Assert the ancestor of AssertJ. EDIT: It seems the project is brewing a Java 8 Lambdas support.
Currently, this library has two shortcomings :
At the time of this writing, it is noteworthy to say this library is based on Mockito 1.x as it creates a mock of the tested object behind the scene. As Mockito is still not updated this library cannot work with final classes or final methods. And even if it was based on Mockito 2 in the current version, this would require to declare a global mock maker (inline-mock-maker
), something that may not what you want, as this mock maker has different drawbacks that the regular mock maker.
It requires yet another test dependency.
These issues won't apply once the library supports lambdas. However, the functionality will be duplicated by the AssertJ toolset.
Taking all into account if you don't want to use the catch-exception tool, I will recommend the old good way of the try
-catch
block, at least up to the JDK7. And for JDK 8 users you might prefer to use AssertJ as it offers may more than just asserting exceptions.
With the JDK8, lambdas enter the test scene, and they have proved to be an interesting way to assert exceptional behaviour. AssertJ has been updated to provide a nice fluent API to assert exceptional behaviour.
And a sample test with AssertJ :
@Test
public void test_exception_approach_1() {
...
assertThatExceptionOfType(IOException.class)
.isThrownBy(() -> someBadIOOperation())
.withMessage("boom!");
}
@Test
public void test_exception_approach_2() {
...
assertThatThrownBy(() -> someBadIOOperation())
.isInstanceOf(Exception.class)
.hasMessageContaining("boom");
}
@Test
public void test_exception_approach_3() {
...
// when
Throwable thrown = catchThrowable(() -> someBadIOOperation());
// then
assertThat(thrown).isInstanceOf(Exception.class)
.hasMessageContaining("boom");
}
With a near-complete rewrite of JUnit 5, assertions have been improved a bit, they may prove interesting as an out of the box way to assert properly exception. But really the assertion API is still a bit poor, there's nothing outside assertThrows
.
@Test
@DisplayName("throws EmptyStackException when peeked")
void throwsExceptionWhenPeeked() {
Throwable t = assertThrows(EmptyStackException.class, () -> stack.peek());
Assertions.assertEquals("...", t.getMessage());
}
As you noticed assertEquals
is still returning void
, and as such doesn't allow chaining assertions like AssertJ.
Also if you remember name clash with Matcher
or Assert
, be prepared to meet the same clash with Assertions
.
I'd like to conclude that today (2017-03-03) AssertJ's ease of use, discoverable API, the rapid pace of development and as a de facto test dependency is the best solution with JDK8 regardless of the test framework (JUnit or not), prior JDKs should instead rely on try
-catch
blocks even if they feel clunky.
This answer has been copied from another question that don't have the same visibility, I am the same author.
This is because $pjs
is an one-element-array of objects, so first you should access the array element, which is an object and then access its attributes.
echo $pjs[0]->player_name;
Actually dump result that you pasted tells it very clearly.
export class ClassComponent implements OnInit {
classes = [
{
name: 'string',
level: 'string',
code: 'number',
currentLesson: '1'
}]
checkCurrentLession(current){
this.classes.forEach((obj)=>{
if(obj.currentLession == current){
return true;
}
});
return false;
}
<ul class="table lessonOverview">
<li>
<p>Lesson 1</p>
<button [routerLink]="['/lesson1']"
[disabled]="checkCurrentLession(1)" class="primair">
Start lesson</button>
</li>
<li>
<p>Lesson 2</p>
<button [routerLink]="['/lesson2']"
[disabled]="!checkCurrentLession(2)" class="primair">
Start lesson</button>
</li>
</ul>
Simpler way (if your only keyword is "code" ) may be:
string ErrorCode = yourString.Split(new string[]{"code"}, StringSplitOptions.None).Last();
If the content is a variable, it will be necessary to concatenate it with quotation marks. It worked for me. Like this:
itemSelected(id: number){ console.log('label contains', document.querySelector("label[for='" + id + "']")); }
Actually the navigation bar on tablets (at least Nexus 7) has different size in portrait and landscape so this function should look like this:
private int getNavigationBarHeight(Context context, int orientation) {
Resources resources = context.getResources();
int id = resources.getIdentifier(
orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_height_landscape",
"dimen", "android");
if (id > 0) {
return resources.getDimensionPixelSize(id);
}
return 0;
}
on Windows insert:
set http_proxy=<proxy>
set https_proxy=<proxy>
before
php "%~dp0composer.phar" %*
or on Linux insert:
export http_proxy=<proxy>
export https_proxy=<proxy>
before
php "${dir}/composer.phar" "$@"
Use GSON for converting POJO to JSONObject. Refer here.
For converting JSONObject to POJO, just call the setter method in the POJO and assign the values directly from the JSONObject.
Node.js is built upon libuv, a cross-platform library that abstracts apis/syscalls for asynchronous (non-blocking) input/output provided by the supported OSes (Unix, OS X and Windows at least).
In this programming model open/read/write operation on devices and resources (sockets, filesystem, etc.) managed by the file-system don't block the calling thread (as in the typical synchronous c-like model) and just mark the process (in kernel/OS level data structure) to be notified when new data or events are available. In case of a web-server-like app, the process is then responsible to figure out which request/context the notified event belongs to and proceed processing the request from there. Note that this will necessarily mean you'll be on a different stack frame from the one that originated the request to the OS as the latter had to yield to a process' dispatcher in order for a single threaded process to handle new events.
The problem with the model I described is that it's not familiar and hard to reason about for the programmer as it's non-sequential in nature. "You need to make request in function A and handle the result in a different function where your locals from A are usually not available."
Node tackles the problem leveraging javascript's language features to make this model a little more synchronous-looking by inducing the programmer to employ a certain programming style. Every function that requests IO has a signature like function (... parameters ..., callback)
and needs to be given a callback that will be invoked when the requested operation is completed (keep in mind that most of the time is spent waiting for the OS to signal the completion - time that can be spent doing other work). Javascript's support for closures allows you to use variables you've defined in the outer (calling) function inside the body of the callback - this allows to keep state between different functions that will be invoked by the node runtime independently. See also Continuation Passing Style.
Moreover, after invoking a function spawning an IO operation the calling function will usually return
control to node's event loop. This loop will invoke the next callback or function that was scheduled for execution (most likely because the corresponding event was notified by the OS) - this allows the concurrent processing of multiple requests.
You can think of node's event loop as somewhat similar to the kernel's dispatcher: the kernel would schedule for execution a blocked thread once its pending IO is completed while node will schedule a callback when the corresponding event has occured.
As a final remark, the phrase "everything runs in parallel except your code" does a decent job of capturing the point that node allows your code to handle requests from hundreds of thousands open socket with a single thread concurrently by multiplexing and sequencing all your js logic in a single stream of execution (even though saying "everything runs in parallel" is probably not correct here - see Concurrency vs Parallelism - What is the difference?). This works pretty well for webapp servers as most of the time is actually spent on waiting for network or disk (database / sockets) and the logic is not really CPU intensive - that is to say: this works well for IO-bound workloads.
Steps to generate Create table DDLs for all the tables in the Hive database and export into text file to run later:
step 1)
create a .sh
file with the below content, say hive_table_ddl.sh
#!/bin/bash
rm -f tableNames.txt
rm -f HiveTableDDL.txt
hive -e "use $1; show tables;" > tableNames.txt
wait
cat tableNames.txt |while read LINE
do
hive -e "use $1;show create table $LINE;" >>HiveTableDDL.txt
echo -e "\n" >> HiveTableDDL.txt
done
rm -f tableNames.txt
echo "Table DDL generated"
step 2)
Run the above shell script by passing 'db name' as paramanter
>bash hive_table_dd.sh <<databasename>>
output :
All the create table statements of your DB will be written into the HiveTableDDL.txt
you should use position: relative; for one iframe and position:absolute; for the second;
Example: for first iframe use:
<div id="contentframe" style="position:relative; top: 100px; left: 50px;">
for second iframe use:
<div id="contentframe" style="position:absolute; top: 0px; left: 690px;">
Good example without custom validate methods, but with metadata plugin and some extra html.
Converting Using OpenSSL
These commands allow you to convert certificates and keys to different formats to make them compatible with specific types of servers or software.
Convert a DER file (.crt .cer .der) to PEM
openssl x509 -inform der -in certificate.cer -out certificate.pem
Convert a PEM file to DER
openssl x509 -outform der -in certificate.pem -out certificate.der
Convert a PKCS#12 file (.pfx .p12) containing a private key and certificates to PEM
openssl pkcs12 -in keyStore.pfx -out keyStore.pem -nodes
You can add -nocerts to only output the private key or add -nokeys to only output the certificates.
Convert a PEM certificate file and a private key to PKCS#12 (.pfx .p12)
openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt
Convert PEM to CRT (.CRT file)
openssl x509 -outform der -in certificate.pem -out certificate.crt
OpenSSL Convert PEM
Convert PEM to DER
openssl x509 -outform der -in certificate.pem -out certificate.der
Convert PEM to P7B
openssl crl2pkcs7 -nocrl -certfile certificate.cer -out certificate.p7b -certfile CACert.cer
Convert PEM to PFX
openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt
OpenSSL Convert DER
Convert DER to PEM
openssl x509 -inform der -in certificate.cer -out certificate.pem
OpenSSL Convert P7B
Convert P7B to PEM
openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer
Convert P7B to PFX
openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer
openssl pkcs12 -export -in certificate.cer -inkey privateKey.key -out certificate.pfx -certfile CACert.cer
OpenSSL Convert PFX
Convert PFX to PEM
openssl pkcs12 -in certificate.pfx -out certificate.cer -nodes
Generate rsa keys by OpenSSL
Using OpenSSL on the command line you’d first need to generate a public and private key, you should password protect this file using the -passout argument, there are many different forms that this argument can take so consult the OpenSSL documentation about that.
openssl genrsa -out private.pem 1024
This creates a key file called private.pem that uses 1024 bits. This file actually have both the private and public keys, so you should extract the public one from this file:
openssl rsa -in private.pem -out public.pem -outform PEM -pubout
or
openssl rsa -in private.pem -pubout > public.pem
or
openssl rsa -in private.pem -pubout -out public.pem
You’ll now have public.pem containing just your public key, you can freely share this with 3rd parties. You can test it all by just encrypting something yourself using your public key and then decrypting using your private key, first we need a bit of data to encrypt:
Example file :
echo 'too many secrets' > file.txt
You now have some data in file.txt, lets encrypt it using OpenSSL and the public key:
openssl rsautl -encrypt -inkey public.pem -pubin -in file.txt -out file.ssl
This creates an encrypted version of file.txt calling it file.ssl, if you look at this file it’s just binary junk, nothing very useful to anyone. Now you can unencrypt it using the private key:
openssl rsautl -decrypt -inkey private.pem -in file.ssl -out decrypted.txt
You will now have an unencrypted file in decrypted.txt:
cat decrypted.txt
|output -> too many secrets
RSA TOOLS Options in OpenSSL
NAME
rsa - RSA key processing tool
SYNOPSIS
openssl rsa [-help] [-inform PEM|NET|DER] [-outform PEM|NET|DER] [-in filename] [-passin arg] [-out filename] [-passout arg] [-aes128] [-aes192] [-aes256] [-camellia128] [-camellia192] [-camellia256] [-des] [-des3] [-idea] [-text] [-noout] [-modulus] [-check] [-pubin] [-pubout] [-RSAPublicKey_in] [-RSAPublicKey_out] [-engine id]
DESCRIPTION
The rsa command processes RSA keys. They can be converted between various forms and their components printed out. Note this command uses the traditional SSLeay compatible format for private key encryption: newer applications should use the more secure PKCS#8 format using the pkcs8 utility.
COMMAND OPTIONS
-help
Print out a usage message.
-inform DER|NET|PEM
This specifies the input format. The DER option uses an ASN1 DER encoded form compatible with the PKCS#1 RSAPrivateKey or SubjectPublicKeyInfo format. The PEM form is the default format: it consists of the DER format base64 encoded with additional header and footer lines. On input PKCS#8 format private keys are also accepted. The NET form is a format is described in the NOTES section.
-outform DER|NET|PEM
This specifies the output format, the options have the same meaning as the -inform option.
-in filename
This specifies the input filename to read a key from or standard input if this option is not specified. If the key is encrypted a pass phrase will be prompted for.
-passin arg
the input file password source. For more information about the format of arg see the PASS PHRASE ARGUMENTS section in openssl.
-out filename
This specifies the output filename to write a key to or standard output if this option is not specified. If any encryption options are set then a pass phrase will be prompted for. The output filename should not be the same as the input filename.
-passout password
the output file password source. For more information about the format of arg see the PASS PHRASE ARGUMENTS section in openssl.
-aes128|-aes192|-aes256|-camellia128|-camellia192|-camellia256|-des|-des3|-idea
These options encrypt the private key with the specified cipher before outputting it. A pass phrase is prompted for. If none of these options is specified the key is written in plain text. This means that using the rsa utility to read in an encrypted key with no encryption option can be used to remove the pass phrase from a key, or by setting the encryption options it can be use to add or change the pass phrase. These options can only be used with PEM format output files.
-text
prints out the various public or private key components in plain text in addition to the encoded version.
-noout
this option prevents output of the encoded version of the key.
-modulus
this option prints out the value of the modulus of the key.
-check
this option checks the consistency of an RSA private key.
-pubin
by default a private key is read from the input file: with this option a public key is read instead.
-pubout
by default a private key is output: with this option a public key will be output instead. This option is automatically set if the input is a public key.
-RSAPublicKey_in, -RSAPublicKey_out
like -pubin and -pubout except RSAPublicKey format is used instead.
-engine id
specifying an engine (by its unique id string) will cause rsa to attempt to obtain a functional reference to the specified engine, thus initialising it if needed. The engine will then be set as the default for all available algorithms.
NOTES
The PEM private key format uses the header and footer lines:
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----
The PEM public key format uses the header and footer lines:
-----BEGIN PUBLIC KEY-----
-----END PUBLIC KEY-----
The PEM RSAPublicKey format uses the header and footer lines:
-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----
The NET form is a format compatible with older Netscape servers and Microsoft IIS .key files, this uses unsalted RC4 for its encryption. It is not very secure and so should only be used when necessary.
Some newer version of IIS have additional data in the exported .key files. To use these with the utility, view the file with a binary editor and look for the string "private-key", then trace back to the byte sequence 0x30, 0x82 (this is an ASN1 SEQUENCE). Copy all the data from this point onwards to another file and use that as the input to the rsa utility with the -inform NET option.
EXAMPLES
To remove the pass phrase on an RSA private key:
openssl rsa -in key.pem -out keyout.pem
To encrypt a private key using triple DES:
openssl rsa -in key.pem -des3 -out keyout.pem
To convert a private key from PEM to DER format:
openssl rsa -in key.pem -outform DER -out keyout.der
To print out the components of a private key to standard output:
openssl rsa -in key.pem -text -noout
To just output the public part of a private key:
openssl rsa -in key.pem -pubout -out pubkey.pem
Output the public part of a private key in RSAPublicKey format:
openssl rsa -in key.pem -RSAPublicKey_out -out pubkey.pem
Mongoose 4.4.0 introduces --true-- bulk insert with the model method .insertMany()
. It is way faster than looping on .create()
or providing it with an array.
Usage:
var rawDocuments = [/* ... */];
Book.insertMany(rawDocuments)
.then(function(mongooseDocuments) {
/* ... */
})
.catch(function(err) {
/* Error handling */
});
Or
Book.insertMany(rawDocuments, function (err, mongooseDocuments) { /* Your callback function... */ });
You can track it on:
Someone edited this question to remove the code I used, so I was forced to add it as an answer. Thanks to all who participated in answering this question! I think most of the other answers are better than this code, I'm just leaving this here for reference purposes.
With thanks to Paul H, and unutbu (who answered this question), I have some pretty nice-looking output:
import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)
# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[1])+0.5, minor=False)
# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()
ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()
And here's the output:
If you could add the
final
modifier to a local variable, it was effectively final.
Lambda expressions can access
static variables,
instance variables,
effectively final method parameters, and
effectively final local variables.
Additionally,
An
effectively final
variable is a variable whose value is never changed, but it isn’t declared with thefinal
keyword.
Source: Starting Out with Java: From Control Structures through Objects (6th Edition), Tony Gaddis
Furthermore, don't forget the meaning of final
that it is initialized exactly once before it is used for the first time.
Once I realized I was running an Oracle database, not MySQL, I found the answer
select * from v$database;
or
select ora_database_name from dual;
Try both. Credit and source goes to: http://www.perlmonks.org/?node_id=520376.
You can imitate open source Dockerfile, for example:
Node: node12-github
RUN groupadd --gid 1000 node \
&& useradd --uid 1000 --gid node --shell /bin/bash --create-home node
superset: superset-github
RUN useradd --user-group --create-home --no-log-init --shell /bin/bash
superset
I think it's a good way to follow open source.
function in_array(what, where) {
var a=false;
for (var i=0; i<where.length; i++) {
if(what == where[i]) {
a=true;
break;
}
}
return a;
}
Example 1:
This is how the and operator works.
x and y => if x is false, then x, else y
So in other words, since mylist1
is not False
, the result of the expression is mylist2
. (Only empty lists evaluate to False
.)
Example 2:
The &
operator is for a bitwise and, as you mention. Bitwise operations only work on numbers. The result of a & b is a number composed of 1s in bits that are 1 in both a and b. For example:
>>> 3 & 1
1
It's easier to see what's happening using a binary literal (same numbers as above):
>>> 0b0011 & 0b0001
0b0001
Bitwise operations are similar in concept to boolean (truth) operations, but they work only on bits.
So, given a couple statements about my car
The logical "and" of these two statements is:
(is my car red?) and (does car have wheels?) => logical true of false value
Both of which are true, for my car at least. So the value of the statement as a whole is logically true.
The bitwise "and" of these two statements is a little more nebulous:
(the numeric value of the statement 'my car is red') & (the numeric value of the statement 'my car has wheels') => number
If python knows how to convert the statements to numeric values, then it will do so and compute the bitwise-and of the two values. This may lead you to believe that &
is interchangeable with and
, but as with the above example they are different things. Also, for the objects that can't be converted, you'll just get a TypeError
.
Example 3 and 4:
Numpy implements arithmetic operations for arrays:
Arithmetic and comparison operations on ndarrays are defined as element-wise operations, and generally yield ndarray objects as results.
But does not implement logical operations for arrays, because you can't overload logical operators in python. That's why example three doesn't work, but example four does.
So to answer your and
vs &
question: Use and
.
The bitwise operations are used for examining the structure of a number (which bits are set, which bits aren't set). This kind of information is mostly used in low-level operating system interfaces (unix permission bits, for example). Most python programs won't need to know that.
The logical operations (and
, or
, not
), however, are used all the time.
In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.
EDIT
It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.
var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>"
I submitted a pull request to update this.
sudo python3 -m pip install mysql-connector-python
It looks like the repos for CentOS 5 are disappearing. Most of the ones mentioned in this question are no longer online, don't seem to have Git, or have a really old version of Git. Below is the script I use to build OpenSSL, IDN2, PCRE, cURL and Git from sources. Both the git://
and https://
protocols will be available for cloning.
Over time the names of the archives will need to be updates. For example, as of this writing, openssl-1.0.2k.tar.gz
is the latest available in the 1.0.2 family.
Dale Anderson's answer using RHEL repos looks good at the moment, but its a fairly old version. Red Hat provides Git version 1.8, while the script below builds 2.12 from sources.
#!/usr/bin/env bash
# OpenSSL installs into lib64/, while cURL installs into lib/
INSTALL_ROOT=/usr/local
INSTALL_LIB32="$INSTALL_ROOT/lib"
INSTALL_LIB64="$INSTALL_ROOT/lib64"
OPENSSL_TAR=openssl-1.0.2k.tar.gz
OPENSSL_DIR=openssl-1.0.2k
ZLIB_TAR=zlib-1.2.11.tar.gz
ZLIB_DIR=zlib-1.2.11
UNISTR_TAR=libunistring-0.9.7.tar.gz
UNISTR_DIR=libunistring-0.9.7
IDN2_TAR=libidn2-0.16.tar.gz
IDN2_DIR=libidn2-0.16
PCRE_TAR=pcre2-10.23.tar.gz
PCRE_DIR=pcre2-10.23
CURL_TAR=curl-7.53.1.tar.gz
CURL_DIR=curl-7.53.1
GIT_TAR=v2.12.2.tar.gz
GIT_DIR=git-2.12.2
###############################################################################
# I don't like doing this, but...
read -s -p "Please enter password for sudo: " SUDO_PASSWWORD
###############################################################################
echo
echo "********** zLib **********"
wget "http://www.zlib.net/$ZLIB_TAR" -O "$ZLIB_TAR"
if [[ "$?" -ne "0" ]]; then
echo "Failed to download zLib"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
rm -rf "$ZLIB_DIR" &>/dev/null
tar -xzf "$ZLIB_TAR"
cd "$ZLIB_DIR"
LIBS="-ldl -lpthread" ./configure --enable-shared --libdir="$INSTALL_LIB64"
if [[ "$?" -ne "0" ]]; then
echo "Failed to configure zLib"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
make -j 4
if [ "$?" -ne "0" ]; then
echo "Failed to build zLib"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
echo "$SUDO_PASSWWORD" | sudo -S make install
cd ..
###############################################################################
echo
echo "********** Unistring **********"
# https://savannah.gnu.org/bugs/?func=detailitem&item_id=26786
wget "https://ftp.gnu.org/gnu/libunistring/$UNISTR_TAR" --no-check-certificate -O "$UNISTR_TAR"
if [[ "$?" -ne "0" ]]; then
echo "Failed to download IDN"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
rm -rf "$UNISTR_DIR" &>/dev/null
tar -xzf "$UNISTR_TAR"
cd "$UNISTR_DIR"
LIBS="-ldl -lpthread" ./configure --enable-shared --libdir="$INSTALL_LIB64"
if [[ "$?" -ne "0" ]]; then
echo "Failed to configure IDN"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
make -j 4
if [ "$?" -ne "0" ]; then
echo "Failed to build IDN"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
echo "$SUDO_PASSWWORD" | sudo -S make install
cd ..
###############################################################################
echo
echo "********** IDN **********"
# https://savannah.gnu.org/bugs/?func=detailitem&item_id=26786
wget "https://alpha.gnu.org/gnu/libidn/$IDN2_TAR" --no-check-certificate -O "$IDN2_TAR"
if [[ "$?" -ne "0" ]]; then
echo "Failed to download IDN"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
rm -rf "$IDN2_DIR" &>/dev/null
tar -xzf "$IDN2_TAR"
cd "$IDN2_DIR"
LIBS="-ldl -lpthread" ./configure --enable-shared --libdir="$INSTALL_LIB64"
if [[ "$?" -ne "0" ]]; then
echo "Failed to configure IDN"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
make -j 4
if [ "$?" -ne "0" ]; then
echo "Failed to build IDN"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
echo "$SUDO_PASSWWORD" | sudo -S make install
cd ..
###############################################################################
echo
echo "********** OpenSSL **********"
wget "https://www.openssl.org/source/$OPENSSL_TAR" -O "$OPENSSL_TAR"
if [[ "$?" -ne "0" ]]; then
echo "Failed to download OpenSSL"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
rm -rf "$OPENSSL_DIR" &>/dev/null
tar -xzf "$OPENSSL_TAR"
cd "$OPENSSL_DIR"
# OpenSSL and enable-ec_nistp_64_gcc_12 option
IS_X86_64=$(uname -m 2>&1 | egrep -i -c "(amd64|x86_64)")
CONFIG=./config
CONFIG_FLAGS=(no-ssl2 no-ssl3 no-comp shared "-Wl,-rpath,$INSTALL_LIB64" --prefix="$INSTALL_ROOT" --openssldir="$INSTALL_ROOT")
if [[ "$IS_X86_64" -eq "1" ]]; then
CONFIG_FLAGS+=("enable-ec_nistp_64_gcc_128")
fi
"$CONFIG" "${CONFIG_FLAGS[@]}"
if [[ "$?" -ne "0" ]]; then
echo "Failed to configure OpenSSL"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
make depend
make -j 4
if [ "$?" -ne "0" ]; then
echo "Failed to build OpenSSL"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
echo "$SUDO_PASSWWORD" | sudo -S make install_sw
cd ..
###############################################################################
echo
echo "********** PCRE **********"
# https://savannah.gnu.org/bugs/?func=detailitem&item_id=26786
wget "https://ftp.pcre.org/pub/pcre//$PCRE_TAR" --no-check-certificate -O "$PCRE_TAR"
if [[ "$?" -ne "0" ]]; then
echo "Failed to download PCRE"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
rm -rf "$PCRE_DIR" &>/dev/null
tar -xzf "$PCRE_TAR"
cd "$PCRE_DIR"
make configure
CPPFLAGS="-I$INSTALL_ROOT/include" LDFLAGS="-Wl,-rpath,$INSTALL_LIB64 -L$INSTALL_LIB64" \
LIBS="-lidn2 -lz -ldl -lpthread" ./configure --enable-shared --enable-pcre2-8 --enable-pcre2-16 --enable-pcre2-32 \
--enable-unicode-properties --enable-pcregrep-libz --prefix="$INSTALL_ROOT" --libdir="$INSTALL_LIB64"
if [[ "$?" -ne "0" ]]; then
echo "Failed to configure PCRE"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
make all -j 4
if [ "$?" -ne "0" ]; then
echo "Failed to build PCRE"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
echo "$SUDO_PASSWWORD" | sudo -S make install
cd ..
###############################################################################
echo
echo "********** cURL **********"
# https://savannah.gnu.org/bugs/?func=detailitem&item_id=26786
wget "https://curl.haxx.se/download/$CURL_TAR" --no-check-certificate -O "$CURL_TAR"
if [[ "$?" -ne "0" ]]; then
echo "Failed to download cURL"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
rm -rf "$CURL_DIR" &>/dev/null
tar -xzf "$CURL_TAR"
cd "$CURL_DIR"
CPPFLAGS="-I$INSTALL_ROOT/include" LDFLAGS="-Wl,-rpath,$INSTALL_LIB64 -L$INSTALL_LIB64" \
LIBS="-lidn2 -lssl -lcrypto -lz -ldl -lpthread" \
./configure --enable-shared --with-ssl="$INSTALL_ROOT" --with-libidn2="$INSTALL_ROOT" --libdir="$INSTALL_LIB64"
if [[ "$?" -ne "0" ]]; then
echo "Failed to configure cURL"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
make -j 4
if [ "$?" -ne "0" ]; then
echo "Failed to build cURL"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
echo "$SUDO_PASSWWORD" | sudo -S make install
cd ..
###############################################################################
echo
echo "********** Git **********"
wget "https://github.com/git/git/archive/$GIT_TAR" -O "$GIT_TAR"
if [[ "$?" -ne "0" ]]; then
echo "Failed to download Git"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
rm -rf "$GIT_DIR" &>/dev/null
tar -xzf "$GIT_TAR"
cd "$GIT_DIR"
make configure
CPPFLAGS="-I$INSTALL_ROOT/include" LDFLAGS="-Wl,-rpath,$INSTALL_LIB64,-rpath,$INSTALL_LIB32 -L$INSTALL_LIB64 -L$INSTALL_LIB32" \
LIBS="-lidn2 -lssl -lcrypto -lz -ldl -lpthread" ./configure --with-openssl --with-curl --with-libpcre --prefix="$INSTALL_ROOT"
if [[ "$?" -ne "0" ]]; then
echo "Failed to configure Git"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
make all -j 4
if [ "$?" -ne "0" ]; then
echo "Failed to build Git"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
MAKE=make
MAKE_FLAGS=(install)
if [[ ! -z `which asciidoc 2>/dev/null | grep -v 'no asciidoc'` ]]; then
if [[ ! -z `which xmlto 2>/dev/null | grep -v 'no xmlto'` ]]; then
MAKE_FLAGS+=("install-doc" "install-html" "install-info")
fi
fi
echo "$SUDO_PASSWWORD" | sudo -S "$MAKE" "${MAKE_FLAGS[@]}"
cd ..
###############################################################################
echo
echo "********** Cleanup **********"
rm -rf "$OPENSSL_TAR $OPENSSL_DIR $UNISTR_TAR $UNISTR_DIR $CURL_TAR $CURL_DIR"
rm -rf "$PCRE_TAR $PCRE_DIR $ZLIB_TAR $ZLIB_DIR $IDN2_TAR $IDN2_DIR $GIT_TAR $GIT_DIR"
[[ "$0" = "$BASH_SOURCE" ]] && exit 0 || return 0
i had this problem and overcoming like this.
var newtags='<div class="addedimage"><h5>preview image</h5><img src="'+one+'?nocache='+Math.floor(Math.random() * 1000)+'"></div>';
Second Thomas David Kehoe, with the following caveat --
If you are using node version manager (nvm), your global node modules will be stored under whatever version of node you are using at the time you saved the module.
So ~/.nvm/versions/node/{version}/lib/node_modules/
.
There are errors here :
var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");
The code must change to:
var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");
By the way, there is another error at line 129 :
var createLi.appendChild(createSubList);
Replace it with:
createLi.appendChild(createSubList);
I've been testing v4 for a few days now and .. I'm loving it so far! It just makes sense after a while.
I also had the same question and I found handling it like the following worked best (and might even be how it is intended). It uses state, a ternary operator and <Redirect>
.
In the constructor()
this.state = {
redirectTo: null
}
this.clickhandler = this.clickhandler.bind(this);
In the render()
render(){
return (
<div>
{ this.state.redirectTo ?
<Redirect to={{ pathname: this.state.redirectTo }} /> :
(
<div>
..
<button onClick={ this.clickhandler } />
..
</div>
)
}
In the clickhandler()
this.setState({ redirectTo: '/path/some/where' });
Hope it helps. Let me know.
HTTPScoop is awesome for inspecting the web traffic on your Mac. It's been incredibly helpful for me. I didn't think twice about the $15 price tag. There is a 14 day trial.
This is purely because I had to spend time making/editing this when it should be widely available, so I'm providing it to everyone else.
The below script will Output a couple of CSV files to TEMP with the versions and vulnerability status of each machine in a selected (in the code) OU. You'll be able to remotely "security audit" an OU of machines.
Powershell 7.0 needed for the connection test line RSAT needed to get the AD module Visual Studio Code needed to get powershell 7.0 (on win7)
By the time you read this, the version list will probably be out of date within the file. Use this website https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/versions-and-dependencies to add newer dotnet entries. It's just a bunch of key values in "DotNet4Builds"
If within CompromisedCheck.csv a machine shows as =0, it's had it's security turned off manually, and you should raise whether the supplier did it, or a suspect employee.
I hope this helps someone searching for it for their business.
<#
Script Name : Get-DotNetVersions_Tweaked.ps1
Description : This script reports the various .NET Framework versions installed on the local or a remote set of computers
Author : Original by Martin Schvartzman - Edited by Mark Purnell
Reference : https://msdn.microsoft.com/en-us/library/hh925568
#>
$ErrorActionPreference = "Continue”
import-module ActiveDirectory
$searchOU = "OU=OU LEVEL 1,OU=OU LEVEL 2,OU=MACHINES,OU=OUR LAPTOPS,DC=PUT,DC=MY,DC=DOMAIN,DC=CONTROLLER,DC=HERE,DC=OK"
$computerList = Get-ADComputer -searchbase $searchOU -Filter *
function Get-DotNetFrameworkVersion($computerList)
{
$dotNetter = @()
$compromisedCheck = @()
$dotNetRoot = 'SOFTWARE\Microsoft\.NETFramework'
$dotNetRegistry = 'SOFTWARE\Microsoft\NET Framework Setup\NDP'
$dotNet4Registry = 'SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full'
$dotNet4Builds = @{
'30319' = @{ Version = [System.Version]'4.0' }
'378389' = @{ Version = [System.Version]'4.5' }
'378675' = @{ Version = [System.Version]'4.5.1' ; Comment = '(8.1/2012R2)' }
'378758' = @{ Version = [System.Version]'4.5.1' ; Comment = '(8/7 SP1/Vista SP2)' }
'379893' = @{ Version = [System.Version]'4.5.2' }
'380042' = @{ Version = [System.Version]'4.5' ; Comment = 'and later with KB3168275 rollup' }
'393295' = @{ Version = [System.Version]'4.6' ; Comment = '(Windows 10)' }
'393297' = @{ Version = [System.Version]'4.6' ; Comment = '(NON Windows 10)' }
'394254' = @{ Version = [System.Version]'4.6.1' ; Comment = '(Windows 10)' }
'394271' = @{ Version = [System.Version]'4.6.1' ; Comment = '(NON Windows 10)' }
'394802' = @{ Version = [System.Version]'4.6.2' ; Comment = '(Windows 10 Anniversary Update)' }
'394806' = @{ Version = [System.Version]'4.6.2' ; Comment = '(NON Windows 10)' }
'460798' = @{ Version = [System.Version]'4.7' ; Comment = '(Windows 10 Creators Update)' }
'460805' = @{ Version = [System.Version]'4.7' ; Comment = '(NON Windows 10)' }
'461308' = @{ Version = [System.Version]'4.7.1' ; Comment = '(Windows 10 Fall Creators Update)' }
'461310' = @{ Version = [System.Version]'4.7.1' ; Comment = '(NON Windows 10)' }
'461808' = @{ Version = [System.Version]'4.7.2' ; Comment = '(Windows 10 April & Winserver)' }
'461814' = @{ Version = [System.Version]'4.7.2' ; Comment = '(NON Windows 10)' }
'528040' = @{ Version = [System.Version]'4.8' ; Comment = '(Windows 10 May 2019 Update)' }
'528049' = @{ Version = [System.Version]'4.8' ; Comment = '(NON Windows 10)' }
}
foreach($computerObject in $computerList)
{
$computerName = $computerObject.DNSHostName
write-host("PCName is " + $computerName)
if(test-connection -TargetName $computerName -Quiet -TimeOutSeconds 1 -count 2){
if($regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computerName))
{
$os = (Get-WMIObject win32_operatingsystem -ComputerName SPL305350).Name
if(!$?){
write-host("wim not available")
$dotNetter += New-Object -TypeName PSObject -Property @{
'ComputerName' = $computerName
'OS' = "WIM not available"
'Build' = "WIM not available"
'Version' = "WIM not available"
'Comment' = "WIM not available"
}
}
else{
if ($netRegKey = $regKey.OpenSubKey("$dotNetRegistry"))
{
foreach ($versionKeyName in $netRegKey.GetSubKeyNames())
{
if ($versionKeyName -match '^v[123]') {
$versionKey = $netRegKey.OpenSubKey($versionKeyName)
$version = [System.Version]($versionKey.GetValue('Version', ''))
write-host("adding old dotnet")
$dotNetter += New-Object -TypeName PSObject -Property @{
ComputerName = $computerName
OS = $os
Build = $version.Build
Version = $version
Comment = ''
}
}
}
}
if ($net4RegKey = $regKey.OpenSubKey("$dotNet4Registry"))
{
if(-not ($net4Release = $net4RegKey.GetValue('Release')))
{
$net4Release = 30319
}
write-host("adding new dotnet")
$dotNetter += New-Object -TypeName PSObject -Property @{
'ComputerName' = $computerName
'OS' = $os
'Build' = $net4Release
'Version' = $dotNet4Builds["$net4Release"].Version
'Comment' = $dotNet4Builds["$net4Release"].Comment
}
}
if ($netRegKey = $regKey.OpenSubKey("$dotNetRoot")){
write-host("Checking for hacked keys")
foreach ($versionKeyName in $netRegKey.GetSubKeyNames())
{
if ($versionKeyName -match '^v[1234]') {
$versionKey = $netRegKey.OpenSubKey($versionKeyName)
write-host("versionKeyName is" + $versionKeyName)
write-host('ASPNetEnforceViewStateMac = ' + $versionKey.GetValue('ASPNetEnforceViewStateMac', ''))
$compromisedCheck += New-Object -TypeName PSObject -Property @{
'ComputerName' = $computerName
'version' = $versionKeyName
'compromisedCheck' = ('ASPNetEnforceViewStateMac = ' + $versionKey.GetValue('ASPNetEnforceViewStateMac', ''))
}
}
}
}
}
}
}
else{
write-host("could not connect to machine")
$dotNetter += New-Object -TypeName PSObject -Property @{
'ComputerName' = $computerName
'OS' = $os
'Build' = "Could not connect"
'Version' = "Could not connect"
'Comment' = "Could not connect"
}
}
}
$dotNetter | export-CSV c:\temp\DotNetVersions.csv
$compromisedCheck | export-CSV C:\temp\CompromisedCheck.csv
}
get-dotnetframeworkversion($computerList)
Microsoft API Code Pack. ShellObjectWatcher class.
Not an answer here and more like a comment, sorry but I can't comment.
In node V10, you can use the flag --experimental-modules
to tell Nodejs you want to use import
. But your entry script should end with .mjs
.
Note this is still an experimental thing and should not be used in production.
// main.mjs
import utils from './utils.js'
utils.print();
// utils.js
module.exports={
print:function(){console.log('print called')}
}
I don't think it's possible to do it in the way you are trying to do it.
Indication of the accepted data format is usually done through adding the extension to the resource name. So, if you have resource like
/resources/resource
and GET /resources/resource
returns its HTML representation, to indicate that you want its XML representation instead, you can use following pattern:
/resources/resource.xml
You have to do the accepted content type determination magic on the server side, then.
Or use Javascript as James suggests.
http://rreddy.blogspot.com/2009/07/vncviewer-clipboard-operations-like.html
Many times you must have observed that clipboard operations like copy/cut and paste suddenly stops workings with the vncviewer. The main reason for this there is a program called as vncconfig responsible for these clipboard transfers. Some times the program may get closed because of some bug in vnc or some other reasons like you closed that window.
To get those clipboard operations back you need to run the program "vncconfig &".
After this your clipboard actions should work fine with out any problems.
Run "vncconfig &" on the client.
If you bring in to the code same library from 2 different sources that will cause the error.
EDIT: The smartest approach IMHO, it removes the last point and following text from a filename (aka the extension):
$name = basename($filename, '.' . end(explode('.', $filename)));
Cheers ;)
For this thing you can use @property
as an decorator, so you could use instance methods as attributes. For example:
class Word_Parser:
def __init__(self, sentences):
self.sentences = sentences
@property
def parser(self):
self.word_list = self.sentences.split()
@property
def sort_word_list(self):
self.sorted_word_list = self.word_list.sort()
@property
def num_words(self):
self.num_words = len(self.word_list)
test = Word_Parser("mary had a little lamb")
test.parser()
test.sort_word_list()
test.num_words()
print test.word_list
print test.sort_word_list
print test.num_words
so you can use access the attributes without calling (i.e., without the ()
).
Just expanding the answers:
Spacer
is an option no one mentioned yet; it is used in case you prefer not to use Positioned
/ Align
.Align
works if you want to specify the alignment of a child inside a parent. Use it anywhere but directly inside Stack
Positioned
is similar to Align, but works only under Stack
directly..setGame
is discontinued. Use:
client.user.setActivity("Game");
To set a playing game status.
As an addition, if you were using an earlier version of discord.js, try this:
client.user.setGame("Game");
In newer versions of discord.js, this is deprecated.
Try setting the HOME environment variable in Windows to your home folder (c:\users\username
).
( you can confirm that this is the problem by doing echo $HOME
in git bash and echo %HOME%
in cmd - latter might not be available )
If you're using Laravel, my problem was in the name of my Route. Instead:
Route::put('/reason/update', 'REASONController@update');
I wrote:
Route::put('/reason/update', 'RESONController@update');
and when I fixed the controller name, the code worked!
First you need to do is run (replace with your port number):
fuser -k 3000/tcp
This will release the port. After you run the above command run:
service docker restart
And your problem is resolved.
Mutations expect two arguments: state
and payload
, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.
The easiest way to pass a number of parameters is to destruct them:
mutations: {
authenticate(state, { token, expiration }) {
localStorage.setItem('token', token);
localStorage.setItem('expiration', expiration);
}
}
Then later on in your actions you can simply
store.commit('authenticate', {
token,
expiration,
});
This:
<table id="test">
<tr id="TEST1" >
<td align="left" valign="middle"><div align="right">Contact</div></td>
<td colspan="4" align="left" valign="middle">
<input type="text" id="contact1" size="20" /> Number
<input type="text" id="number1" size="20" />
</td>
<td>
<input type="button" value="Button 1" id="contact1" /></td>
</tr>
<tr id="TEST2" >
<td align="left" valign="middle"><div align="right">Contact</div></td>
<td colspan="4" align="left" valign="middle">
<input type="text" id="contact2" size="20" /> Number
<input type="text" id="number2" size="20" />
</td>
<td>
<input type="button" value="Button 1" id="contact2" />
</td>
</tr>
<tr id="TEST3" >
<td align="left" valign="middle"><div align="right">Contact</div></td>
<td colspan="4" align="left" valign="middle">
<input type="text" id="contact3" size="20" /> Number
<input type="text" id="number3" size="20" />
</td>
<td>
<input type="button" value="Button 1" id="contact2" />
</td>
</tr>
and javascript:
$(function() {
var bid, trid;
$('#test tr').click(function() {
trid = $(this).attr('id'); // table row ID
alert(trid);
});
});
It worked here!
I've seen your code in web.php as follows: Route::post('/edit/{id}','ProjectController@update');
Step 1: remove the {id} random parameter so it would be like this: Route::post('/edit','ProjectController@update');
Step 2: Then remove the @method('PUT') in your form, so let's say we'll just plainly use the POST method
Then how can I pass the ID to my method?
Step 1: make an input field in your form with the hidden attribute for example
<input type="hidden" value="{{$project->id}}" name="id">
Step 2: in your update method in your controller, fetch that ID for example:
$id = $request->input('id');
then you may not use it to find which project to edit
$project = Project::find($id)
//OR
$project = Project::where('id',$id);
If you use instanceof
, making your equals
implementation final
will preserve the symmetry contract of the method: x.equals(y) == y.equals(x)
. If final
seems restrictive, carefully examine your notion of object equivalence to make sure that your overriding implementations fully maintain the contract established by the Object
class.
Have you tried performing an svn cleanup?
If you want to bind a string to the src
attribute, you should wrap it on single quotes:
<img v-bind:src="'/static/img/clear.gif'">
<!-- or shorthand -->
<img :src="'/static/img/clear.gif'">
IMO you do not need to bind a string, you could use the simple way:
<img src="/static/img/clear.gif">
Check an example about the image preload here: http://codepen.io/pespantelis/pen/RWVZxL
The GNU assembler (gas) and NASM are both good choices. However, they have some differences, the big one being the order you put operations and their operands.
gas uses AT&T syntax (guide: https://stackoverflow.com/tags/att/info):
mnemonic source, destination
nasm uses Intel style (guide: https://stackoverflow.com/tags/intel-syntax/info):
mnemonic destination, source
Either one will probably do what you need. GAS also has an Intel-syntax mode, which is a lot like MASM, not NASM.
Try out this tutorial: http://asm.sourceforge.net/intro/Assembly-Intro.html
See also more links to guides and docs in Stack Overflow's x86 tag wiki
At first, a config file is appropriate for this kind of things but you may also use another approach, which is as given below (Laravel - 4):
// You can keep this in your filters.php file
App::before(function($request) {
App::singleton('site_settings', function(){
return Setting::all();
});
// If you use this line of code then it'll be available in any view
// as $site_settings but you may also use app('site_settings') as well
View::share('site_settings', app('site_settings'));
});
To get the same data in any controller you may use:
$site_settings = app('site_settings');
There are many ways, just use one or another, which one you prefer but I'm using the Container
.
This is how I would do it (tested in FF/Chrome):
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function autoResize(iframe) {
$(iframe).height($(iframe).contents().find('html').height());
}
</script>
<iframe src="page.html" width="100%" height="100" marginheight="0" frameborder="0" onload="autoResize(this);"></iframe>
Instead of taking a performance hit each time you want to look up a value, how about you flatten the dictionary once then simply look up the key like b:v:y
def flatten(mydict):
new_dict = {}
for key,value in mydict.items():
if type(value) == dict:
_dict = {':'.join([key, _key]):_value for _key, _value in flatten(value).items()}
new_dict.update(_dict)
else:
new_dict[key]=value
return new_dict
dataDict = {
"a":{
"r": 1,
"s": 2,
"t": 3
},
"b":{
"u": 1,
"v": {
"x": 1,
"y": 2,
"z": 3
},
"w": 3
}
}
flat_dict = flatten(dataDict)
print flat_dict
{'b:w': 3, 'b:u': 1, 'b:v:y': 2, 'b:v:x': 1, 'b:v:z': 3, 'a:r': 1, 'a:s': 2, 'a:t': 3}
This way you can simply look up items using flat_dict['b:v:y']
which will give you 1
.
And instead of traversing the dictionary on each lookup, you may be able to speed this up by flattening the dictionary and saving the output so that a lookup from cold start would mean loading up the flattened dictionary and simply performing a key/value lookup with no traversal.
I don’t know how helpful will that be but in my case I just created another circle with border only and placed it “inside” the other shape.
Think of it as Java's answer to the PATH environment variable - OSes search for EXEs on the PATH, Java searches for classes and packages on the classpath.
Another interesting solution in ORACLE PL/SQL:
SELECT LEVEL n
FROM DUAL
CONNECT BY LEVEL <= 100;
The keepNA = TRUE option prevents problems with NA
nchar(NA)
## [1] 2
nchar(NA, keepNA=TRUE)
## [1] NA
Updating @Crashalot's answer for Swift 3.x:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let currentPoint = touch.location(in: self)
// do something with your currentPoint
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let currentPoint = touch.location(in: self)
// do something with your currentPoint
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let currentPoint = touch.location(in: self)
// do something with your currentPoint
}
}
The given answers will only delete files (which admittedly is what is in the title of this post), but here's some code that will first delete all of the files older than 15 days, and then recursively delete any empty directories that may have been left behind. My code also uses the -Force
option to delete hidden and read-only files as well. Also, I chose to not use aliases as the OP is new to PowerShell and may not understand what gci
, ?
, %
, etc. are.
$limit = (Get-Date).AddDays(-15)
$path = "C:\Some\Path"
# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
# Delete any empty directories left behind after deleting the old files.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse
And of course if you want to see what files/folders will be deleted before actually deleting them, you can just add the -WhatIf
switch to the Remove-Item
cmdlet call at the end of both lines.
The code shown here is PowerShell v2.0 compatible, but I also show this code and the faster PowerShell v3.0 code as handy reusable functions on my blog.
With Git 2.7 (release January 5th, 2015), you have a more coherent solution using git remote
:
git remote get-url origin
(nice pendant of git remote set-url origin <newurl>
)
See commit 96f78d3 (16 Sep 2015) by Ben Boeckel (mathstuf
).
(Merged by Junio C Hamano -- gitster
-- in commit e437cbd, 05 Oct 2015):
remote: add get-url subcommand
Expanding
insteadOf
is a part ofls-remote --url
and there is no way to expandpushInsteadOf
as well.
Add aget-url
subcommand to be able to query both as well as a way to get all configured URLs.
get-url:
Retrieves the URLs for a remote.
Configurations forinsteadOf
andpushInsteadOf
are expanded here.
By default, only the first URL is listed.
- With '
--push
', push URLs are queried rather than fetch URLs.- With '
--all
', all URLs for the remote will be listed.
Before git 2.7, you had:
git config --get remote.[REMOTE].url
git ls-remote --get-url [REMOTE]
git remote show [REMOTE]
Use setResizable on your JFrame
yourFrame.setResizable(false);
But extending JFrame is generally a bad idea.
A simple solution to get a transparent background in a windows form is to overwrite the OnPaintBackground
method like this:
protected override void OnPaintBackground(PaintEventArgs e)
{
//empty implementation
}
(Notice that the base.OnpaintBackground(e)
is removed from the function)
The question is answered already, but I want add more information about the causes.
Android app unable to start activity componentinfo
This error often comes with appropriate logs. You can read logs and can solve this issue easily.
Here is a sample log. In which you can see clearly ClassCastException
. So this issue came because TextView
cannot be cast to EditText
.
Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.403: D/AndroidRuntime(1050): Shutting down VM
11-04 01:24:10.403: W/dalvikvm(1050): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:24:10.543: E/AndroidRuntime(1050): FATAL EXCEPTION: main
11-04 01:24:10.543: E/AndroidRuntime(1050): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.os.Looper.loop(Looper.java:137)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:24:10.543: E/AndroidRuntime(1050): at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050): at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:24:10.543: E/AndroidRuntime(1050): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:24:10.543: E/AndroidRuntime(1050): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:24:10.543: E/AndroidRuntime(1050): at dalvik.system.NativeStart.main(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050): at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:45)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:24:10.543: E/AndroidRuntime(1050): ... 11 more
11-04 01:29:11.177: I/Process(1050): Sending signal. PID: 1050 SIG: 9
11-04 01:31:32.080: D/AndroidRuntime(1109): Shutting down VM
11-04 01:31:32.080: W/dalvikvm(1109): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:31:32.194: E/AndroidRuntime(1109): FATAL EXCEPTION: main
11-04 01:31:32.194: E/AndroidRuntime(1109): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.os.Looper.loop(Looper.java:137)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:31:32.194: E/AndroidRuntime(1109): at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109): at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:31:32.194: E/AndroidRuntime(1109): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:31:32.194: E/AndroidRuntime(1109): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:31:32.194: E/AndroidRuntime(1109): at dalvik.system.NativeStart.main(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109): at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:31:32.194: E/AndroidRuntime(1109): ... 11 more
11-04 01:36:33.195: I/Process(1109): Sending signal. PID: 1109 SIG: 9
11-04 02:11:09.684: D/AndroidRuntime(1167): Shutting down VM
11-04 02:11:09.684: W/dalvikvm(1167): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 02:11:09.855: E/AndroidRuntime(1167): FATAL EXCEPTION: main
11-04 02:11:09.855: E/AndroidRuntime(1167): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.os.Looper.loop(Looper.java:137)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 02:11:09.855: E/AndroidRuntime(1167): at java.lang.reflect.Method.invokeNative(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167): at java.lang.reflect.Method.invoke(Method.java:525)
11-04 02:11:09.855: E/AndroidRuntime(1167): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 02:11:09.855: E/AndroidRuntime(1167): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 02:11:09.855: E/AndroidRuntime(1167): at dalvik.system.NativeStart.main(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167): at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.Activity.performCreate(Activity.java:5133)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 02:11:09.855: E/AndroidRuntime(1167): ... 11 more
findViewById()
of non existing viewLike when you use findViewById(R.id.button)
when button id does not exist in layout XML.
If you wrong cast some class, then you get this error. Like you cast RelativeLayout
to LinearLayout
or EditText
to TextView
.
manifest.xml
If you did not register Activity in manifest.xml
then this error comes.
findViewById()
with declaration at top levelBelow code is incorrect. This will create error. Because you should do findViewById()
after calling setContentView()
. Because an View can be there after it is created.
public class MainActivity extends Activity {
ImageView mainImage = (ImageView) findViewById(R.id.imageViewMain); //incorrect way
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainImage = (ImageView) findViewById(R.id.imageViewMain); //correct way
//...
}
}
abstract
Activity class.When you try to start an Activity which is abstract, you will will get this error. So just remove abstract
keyword before activity class name.
If your activity is written in Kotlin and you have not setup kotlin in your app. then you will get error. You can follow simple steps as written in Android Link or Kotlin Link. You can check this answer too.
Read about Downcast and Upcast
var postdata = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};
var data = [];
data.push(postdata);
console.log(data);
See this example. You need to bind the event key propagation
$(document).ready(function () {
$('#confirmEmail').keydown(function (e) {
if (e.ctrlKey && (e.keyCode == 88 || e.keyCode == 67 || e.keyCode == 86)) {
return false;
}
});
});
If someone still needs it (like I do).
The specified role_name must be a role that the current session user is a member of. https://www.postgresql.org/docs/10/sql-set-role.html
We need to make the current session user a member of the role:
create role myrole;
set role myrole;
grant myrole to myuser;
set role myrole;
produces:
Role ROLE created.
Error starting at line : 4 in command -
set role myrole
Error report -
ERROR: permission denied to set role "myrole"
Grant succeeded.
Role SET succeeded.
Make sure to select "All" to find the enable bitcode build settings:
Documentation on UISwitch says:
[mySwitch setOn:NO];
In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.
I came across this one that is written in java javaANPR, I am looking for a c# library as well.
I would like a system where I can point a video camera at some sailing boats, all of which have large, identifiable numbers on them, and have it identify the boats and send a tweet when they sail past a video camera.
(a) Django is a framework, not a language
(b) I'm not sure what you're missing - there is no reason why you can't have business logic in a web application. In Django, you would normally expect presentation logic to be separated from business logic. Just because it is hosted in the same application server, it doesn't follow that the two layers are entangled.
(c) Django does provide templating, but it doesn't provide rich libraries for generating client-side content.
Bootstrap sometimes uses contextual class constructs. Those are what you should target to change styling.
You don't need to create your own custom class as suggested in the answer from Kiran Varti.
So you only need:
CSS:
.panel-default > .panel-heading {
background: #black;
}
HTML:
<div class="panel panel-default">
Explanation here. Also see contextual class section here.
To match navbar-inverse use #222. Panel-inverse was requested in V3, but rejected due to larger priorities.
You can change the foreground color in that heading override or you can do it separately for panel titles. Depends what you are trying to achieve.
.panel-title {
color: white;
}
1. Pass By Value / Call By Value
void printvalue(int x)
{
x = x + 1 ;
cout << x ; // 6
}
int x = 5;
printvalue(x);
cout << x; // 5
In call by value, when you pass a value to printvalue(x)
i.e. the argument which is 5
, it is copied to void printvalue(int x)
. Now, we have two different values 5
and the copied value 5
and these two values are stored in different memory locations. So if you make any change inside void printvalue(int x)
it won't reflect back to the argument.
2. Pass By Reference/ Call By Reference
void printvalue(int &x)
{
x = x + 1 ;
cout << x ; // 6
}
int x = 5;
printvalue(x);
cout << x; // 6
In call by reference, there's only one difference. We use &
i.e. the address operator. By doing
void printvalue(int &x)
we are referring to the address of x
which tells us that it both refers to the same location. Hence, any changes made inside the function will reflect outside.
Now that you're here, you should also know about ...
3. Pass By Pointer/ Call By Address
void printvalue(int* x)
{
*x = *x + 1 ;
cout << *x ; // 6
}
int x = 5;
printvalue(&x);
cout << x; // 6
In pass by address, the pointer int* x
holds the address passed to it printvalue(&x)
. Hence, any changes done inside the function will reflect outside.
I would just raise ValueError, unless you need a more specific exception..
def import_to_orm(name, save=False, recurse=False):
if recurse and not save:
raise ValueError("save must be True if recurse is True")
There's really no point in doing class BadValueError(ValueError):pass
- your custom class is identical in use to ValueError, so why not use that?
NULL
is not a keyword. It's an identifier defined in some standard headers. You can include
#include <cstddef>
To have it in scope, including some other basics, like std::size_t
.
You forgot to reset the position of the memory stream:
private void Test()
{
System.IO.MemoryStream data = new System.IO.MemoryStream();
System.IO.Stream str = TestStream();
str.CopyTo(data);
// Reset memory stream
data.Seek(0, SeekOrigin.Begin);
byte[] buf = new byte[data.Length];
data.Read(buf, 0, buf.Length);
}
Update:
There is one more thing to note: It usually pays not to ignore the return values of methods. A more robust implementation should check how many bytes have been read after the call returns:
private void Test()
{
using(MemoryStream data = new MemoryStream())
{
using(Stream str = TestStream())
{
str.CopyTo(data);
}
// Reset memory stream
data.Seek(0, SeekOrigin.Begin);
byte[] buf = new byte[data.Length];
int bytesRead = data.Read(buf, 0, buf.Length);
Debug.Assert(bytesRead == data.Length,
String.Format("Expected to read {0} bytes, but read {1}.",
data.Length, bytesRead));
}
}
If you're using more than one argument it has to be in a tuple (note the extra parentheses):
'%s in %s' % (unicode(self.author), unicode(self.publication))
As EOL points out, the unicode()
function usually assumes ascii encoding as a default, so if you have non-ASCII characters, it's safer to explicitly pass the encoding:
'%s in %s' % (unicode(self.author,'utf-8'), unicode(self.publication('utf-8')))
And as of Python 3.0, it's preferred to use the str.format()
syntax instead:
'{0} in {1}'.format(unicode(self.author,'utf-8'),unicode(self.publication,'utf-8'))
If you are using multiple flavors?
-make sure the resource file is not declared/added both in only one of the flavors and in main.
Example: a_layout_file.xml
file containing the symbol variable(s)
src:
flavor1/res/layout/(no file)
flavor2/res/layout/a_layout_file.xml
main/res/layout/a_layout_file.xml
This setup will give the error: cannot find symbol variable, this is because the resource file can only be in both flavors or only in the main.
To enable your app to listen for both http
and https
on ports 80
and 443
respectively, do the following
Create an express app:
var express = require('express');
var app = express();
The app returned by express()
is a JavaScript function. It can be be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app using the same code base.
You can do so as follows:
var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
var app = express();
var options = {
key: fs.readFileSync('/path/to/key.pem'),
cert: fs.readFileSync('/path/to/cert.pem')
};
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
For complete detail see the doc
I suspect this is what the numpy diff command does anyway, but just for completeness you can simply difference the sub-vectors:
from numpy import array as a
a(x[1:])-a(x[:-1])
In addition, I wanted to add these solutions to generalizations of the question:
Solution with periodic boundaries
Sometimes with numerical integration you will want to difference a list with periodic boundary conditions (so the first element calculates the difference to the last. In this case the numpy.roll function is helpful:
v-np.roll(v,1)
Solutions with zero prepended
Another numpy solution (just for completeness) is to use
numpy.ediff1d(v)
This works as numpy.diff, but only on a vector (it flattens the input array). It offers the ability to prepend or append numbers to the resulting vector. This is useful when handling accumulated fields that is often the case fluxes in meteorological variables (e.g. rain, latent heat etc), as you want a resulting list of the same length as the input variable, with the first entry untouched.
Then you would write
np.ediff1d(v,to_begin=v[0])
Of course, you can also do this with the np.diff command, in this case though you need to prepend zero to the series with the prepend keyword:
np.diff(v,prepend=0.0)
All the above solutions return a vector that is the same length as the input.
Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false?
Its not a matter of being smart, its a requirement specified in the language. Otherwise you couldn't write expressions like.
if(s != null && s.length() > 0)
or
if(s == null || s.length() == 0)
BTW if you use &
and |
it will always evaluate both sides of the expression.
Solution provided by lukesUbuntu from github works for me:
Just use brew
$ brew install http://git.io/sshpass.rb
Your format is not the expected ISO format, you should try
DateTimeFormatter format = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime time = format.parseDateTime("04/02/2011 20:27:05");
Like any project setting, the buildevents can be configured per Configuration. Just select the configuration you want to change in the dropdown of the Property Pages dialog and edit the post build step.
your max factor is not more than your number, so, let's say
def factors(n):
factors = []
for i in range(1, n//2+1):
if n % i == 0:
factors.append (i)
factors.append(n)
return factors
voilá!
Default parameter values must appear on the declaration, since that is the only thing that the caller sees.
EDIT: As others point out, you can have the argument on the definition, but I would advise writing all code as if that wasn't true.
I really like Tovask's answer but it doesn't work due to the function having the name download
(this answer explains why). I also don't see the point in replacing "data:image/..." with "data:application/...".
The following code has been tested in Chrome and Firefox and seems to work fine in both.
JavaScript:
function prepDownload(a, canvas, name) {
a.download = name
a.href = canvas.toDataURL()
}
HTML:
<a href="#" onclick="prepDownload(this, document.getElementById('canvasId'), 'imgName.png')">Download</a>
<canvas id="canvasId"></canvas>
Live streaming in HTML5 is possible via the use of Media Source Extensions (MSE) - the relatively new W3C standard: https://www.w3.org/TR/media-source/
MSE is an an extension of HTML5 <video>
tag; the javascript on webpage can fetch audio/video segments from the server and push them to MSE for playback. The fetching mechanism can be done via HTTP requests (MPEG-DASH) or via WebSockets. As of September 2016 all major browsers on all devices support MSE. iOS is the only exception.
For high latency (5+ seconds) HTML5 live video streaming you can consider MPEG-DASH implementations by video.js or Wowza streaming engine.
For low latency, near real-time HTML5 live video streaming, take a look at EvoStream media server, Unreal media server, and WebRTC.
(I would have added a comment directly to vasekt's answer but I don't have enough reputation points (not sure the logic there)
Anyway... what I wanted to say is that even if you aren't explicitly creating/asking for a PoolingConnection, doesn't mean you aren't getting one.
I was going crazy trying to figure out why the original solution didn't work for me, but I ignored vasekt's answer as it "didn't apply to my case" - wrong!
I was staring at my stack-trace when low and behold I saw a PoolingConnection in the middle of it. Bang - I tired his addition and success!! (our demo is tomorrow and I was getting desperate) :-)
Tested in Xcode 9.4, Swift 4 Another way to solve this issue is , You can add
override func layoutSubviews() {
self.frame = (self.superview?.bounds)!
}
in subview class.
These answers, including the selected answer, are good for introducing promises conceptually, but lacking in specifics of what exactly the differences are in the terminology that arises when using libraries implementing them (and there are important differences).
Since it is still an evolving spec, the answer currently comes from attempting to survey both references (like wikipedia) and implementations (like jQuery):
Deferred: Never described in popular references,
1
2
3
4
but commonly used by implementations as the arbiter of promise resolution (implementing resolve
and reject
).
5
6
7
Sometimes deferreds are also promises (implementing then
),
5
6
other times it's seen as more pure to have the Deferred only
capable of resolution, and forcing the user to access the promise for
using then
.
7
Promise: The most all-encompasing word for the strategy under discussion.
A proxy object storing the result of a target function whose
synchronicity we would like to abstract, plus exposing a then
function
accepting another target function and returning a new promise.
2
Example from CommonJS:
> asyncComputeTheAnswerToEverything()
.then(addTwo)
.then(printResult);
44
Always described in popular references, although never specified as to whose responsibility resolution falls to. 1 2 3 4
Always present in popular implementations, and never given resolution abilites. 5 6 7
Future: a seemingly deprecated term found in some popular references 1 and at least one popular implementation, 8 but seemingly being phased out of discussion in preference for the term 'promise' 3 and not always mentioned in popular introductions to the topic. 9
However, at least one library uses the term generically for abstracting
synchronicity and error handling, while not providing then
functionality.
10
It's unclear if avoiding the term 'promise' was intentional, but probably a
good choice since promises are built around 'thenables.'
2
Difference between Promises/A and Promises/A+
(TL;DR, Promises/A+ mostly resolves ambiguities in Promises/A)
Try this:
var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));
This should return true
.
UPDATED: Added isNaN
check to handle the case commented by Julian H. Lam
it worked for me
$(document).scroll(function() {
var y = $(document).scrollTop(), //get page y value
header = $("#myarea"); // your div id
if(y >= 400) {
header.css({position: "fixed", "top" : "0", "left" : "0"});
} else {
header.css("position", "static");
}
});
To update main pom.xml and parent version on submodules:
mvn versions:set -DnewVersion=1.3.0-SNAPSHOT -N versions:update-child-modules -DgenerateBackupPoms=false
Yes, you can do this by creating a DoubleStream
from the array, filtering out the negatives, and converting the stream back to an array. Here is an example:
double[] d = {8, 7, -6, 5, -4};
d = Arrays.stream(d).filter(x -> x > 0).toArray();
//d => [8, 7, 5]
If you want to filter a reference array that is not an Object[]
you will need to use the toArray
method which takes an IntFunction
to get an array of the original type as the result:
String[] a = { "s", "", "1", "", "" };
a = Arrays.stream(a).filter(s -> !s.isEmpty()).toArray(String[]::new);
How to access screen size or pixel density or aspect ratio in flutter ?
We can access screen size and other like pixel density, aspect ration etc. with helps of MediaQuery.
syntex : MediaQuery.of(context).size.height
From what the error message complains about, it sounds like you should rather try to fix the source code. The compiler complains about difference in declaration, similar to for instance
void foo(int i);
...
void foo(double d) {
...
}
and this is not valid C code, hence the compiler complains.
Maybe your problem is that there is no prototype available when the function is used the first time and the compiler implicitly creates one that will not be static. If so the solution is to add a prototype somewhere before it is first used.
You can try P4Merge.
Visualize the differences between file versions with P4Merge. Resolve conflicts that result from parallel or concurrent development via color coding.
The features includes:
OPTIONS
method returns info about API (methods/content type)
HEAD
method returns info about resource (version/length/type)
Server response
OPTIONS
HTTP/1.1 200 OK
Allow: GET,HEAD,POST,OPTIONS,TRACE
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:24:43 GMT
Content-Length: 0
HEAD
HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:12:29 GMT
ETag: "780602-4f6-4db31b2978ec0"
Last-Modified: Thu, 25 Apr 2013 16:13:23 GMT
Content-Length: 1270
OPTIONS
Identifying which HTTP methods a resource supports, e.g. can we DELETE it or update it via a PUT?HEAD
Checking whether a resource has changed. This is useful when maintaining a cached version of a resourceHEAD
Retrieving metadata about the resource, e.g. its media type or its size, before making a possibly costly retrievalHEAD, OPTIONS
Testing whether a resource exists and is accessible. For example, validating user-submitted links in an application
Here is nice and concise article about how HEAD and OPTIONS fit into RESTful architecture.