for python 3.6, the following worked for me launch cmd.exe as administrator
pip install numpy-1.13.0+mkl-cp36-cp36m-win32
pip install scipy-0.19.1-cp36-cp36m-win32
Or you can convert it into Char Array first by:
string Something = "1,5,12,34,";
char[] SomeGoodThing=Something.ToCharArray[];
Now you have each character indexed
:
SomeGoodThing[0] -> '1'
SomeGoodThing[1] -> ','
Play around it
You can use ARG
- see https://docs.docker.com/engine/reference/builder/#arg
The
ARG
instruction defines a variable that users can pass at build-time to the builder with thedocker build
command using the--build-arg <varname>=<value>
flag. If a user specifies a build argument that was not defined in the Dockerfile, the build outputs an error.
Yes:
bigInt.sign = !(number < 0);
The !
operator always evaluates to true
or false
. When converted to int
, these become 1
and 0
respectively.
Of course this is equivalent to:
bigInt.sign = (number >= 0);
Here the parentheses are redundant but I add them for clarity. All of the comparison and relational operator evaluate to true
or false
.
In my case it happened after I moved my solution folder from one location to another, re-organized it a bit and in the process its relative folder structure changed.
So I had to edit all entries similar to the following one in my .csproj
file from
<Import Project="..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets" Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" />
to
<Import Project="packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets" Condition="Exists('packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" />
(Note the change from ..\packages\
to packages\
. It might be a different relative structure in your case, but you get the idea.)
Alternatively you could add to ~/.npmrc
right prefix. I've got C:\Program Files\nodejs
for 64 Win7.
Google threw out this page to the "image fallback html" keywords, but because non of the above helped me, and I was looking for a "svg fallback support for IE below 9", I kept on searching and this is what I found:
<img src="base-image.svg" alt="picture" />
<!--[if (lte IE 8)|(!IE)]><image src="fallback-image.png" alt="picture" /><![endif]-->
It might be off-topic, but it resolved my own issue and it might help someone else too.
In my case the symbols I create (Tax1, Tax2, etc.) already had values but I wanted to use a loop and assign the symbols to another variable. So the above two answers gave me a way to accomplish this. This may be helpful in answering your question as the assignment of a value can take place anytime later.
output=NULL
for(i in 1:8){
Tax=eval(as.symbol(paste("Tax",i,sep="")))
L_Data1=L_Data_all[which(L_Data_all$Taxon==Tax[1] | L_Data_all$Taxon==Tax[2] | L_Data_all$Taxon==Tax[3] | L_Data_all$Taxon==Tax[4] | L_Data_all$Taxon==Tax[5]),]
L_Data=L_Data1$Length[which(L_Data1$Station==Plant[1] | L_Data1$Station==Plant[2])]
h=hist(L_Data,breaks=breaks,plot=FALSE)
output=cbind(output,h$counts)
}
This seems to happen from time to time with programs that are very sensitive to command lines, but one option is to just use the DOS path instead of the Windows path. This means that C:\Program Files\
would resolve to C:\PROGRA~1\
and generally avoid any issues with spacing.
To get the short path you can create a quick Batch file that echos the short path:
@ECHO OFF
echo %~s1
Which is then called as follows:
C:\>shortPath.bat "C:\Program Files"
C:\PROGRA~1
The M in MVC is for "Model" and in the MVC paradigm the role of model classes is to manage a program's data. A model is the opposite of a view -- a view knows how to display data, but it knows nothing about what to do with data, whereas a model knows everything about how to work with data, but nothing about how to display it. Models can be complicated, but they don't have to be -- the model for your app might be as simple as an array of strings or dictionaries.
The role of a controller is to mediate between view and model. Therefore, they need a reference to one or more view objects and one or more model objects. Let's say that your model is an array of dictionaries, with each dictionary representing one row in your table. The root view for your app displays that table, and it might be responsible for loading the array from a file. When the user decides to add a new row to the table, they tap some button and your controller creates a new (mutable) dictionary and adds it to the array. In order to fill in the row, the controller creates a detail view controller and gives it the new dictionary. The detail view controller fills in the dictionary and returns. The dictionary is already part of the model, so nothing else needs to happen.
On your branch - say master, pull and allow unrelated histories
git pull origin master --allow-unrelated-histories
Worked for me.
Something likes this
public void testPrintOut() {
int val1 = 8;
String val2 = "$951.23";
String val3 = "$215.92";
String val4 = "$198,301.22";
System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4));
val1 = 9;
val2 = "$950.19";
val3 = "$216.95";
val4 = "$198,084.26";
System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4));
}
I landed here because I was looking for something like that too. In my case, I was copying the data from a set of staging tables with many columns into one table while also assigning row ids to the target table. Here is a variant of the above approaches that I used. I added the serial column at the end of my target table. That way I don't have to have a placeholder for it in the Insert statement. Then a simple select * into the target table auto populated this column. Here are the two SQL statements that I used on PostgreSQL 9.6.4.
ALTER TABLE target ADD COLUMN some_column SERIAL;
INSERT INTO target SELECT * from source;
using sizeof()
char h[] = "hello";
printf("%d\n",sizeof(h)-1); //Output = 5
using string.h
#include <string.h>
char h[] = "hello";
printf("%d\n",strlen(h)); //Output = 5
using function (
strlen
implementation)
int strsize(const char* str);
int main(){
char h[] = "hello";
printf("%d\n",strsize(h)); //Output = 5
return 0;
}
int strsize(const char* str){
return (*str) ? strsize(++str) + 1 : 0;
}
I find using tokens pretty clean. It is integrated into core in Drupal 7.
<?php print token_replace('[current-page:url]'); ?>
I think some would also want to know how to find the my.ini file on your PC. For windows users, I think the best way is as follows:
I got this answer from http://bugs.mysql.com/bug.php?id=68516
putting a quick example, should be a sufficient starting point
Code in Form A
public event EventHandler<EventArgs> RowAdded;
private void btnRowAdded_Click(object sender, EventArgs e)
{
// insert data
// if successful raise event
OnRowAddedEvent();
}
private void OnRowAddedEvent()
{
var listener = RowAdded;
if (listener != null)
listener(this, EventArgs.Empty);
}
Code in Form B
private void button1_Click(object sender, EventArgs e)
{
var frm = new Form2();
frm.RowAdded += new EventHandler<EventArgs>(frm_RowAdded);
frm.Show();
}
void frm_RowAdded(object sender, EventArgs e)
{
// retrieve data again
}
You can even consider creating your own EventArgs
class that can contain the newly added data. You can then use this to directly add the data to a new row in DatagridView
Use the getResourceAsStream()
method on the ServletContext object, e.g.
servletContext.getResourceAsStream("/WEB-INF/myfile");
How you get a reference to the ServletContext depends on your application... do you want to do it from a Servlet or from a JSP?
EDITED: If you're inside a Servlet object, then call getServletContext()
. If you're in JSP, use the predefined variable application
.
The great answers have already been given, I just need to give my piece in the form of code blocks in javascript (I will also include more modern and better solution for cross-origin requests: CORS with HTTP Headers):
JSONP:
1.client_jsonp.js
$.ajax({
url: "http://api_test_server.proudlygeek.c9.io/?callback=?",
dataType: "jsonp",
success: function(data) {
console.log(data);
}
});??????????????????
2.server_jsonp.js
var http = require("http"),
url = require("url");
var server = http.createServer(function(req, res) {
var callback = url.parse(req.url, true).query.callback || "myCallback";
console.log(url.parse(req.url, true).query.callback);
var data = {
'name': "Gianpiero",
'last': "Fiorelli",
'age': 37
};
data = callback + '(' + JSON.stringify(data) + ');';
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(data);
});
server.listen(process.env.PORT, process.env.IP);
console.log('Server running at ' + process.env.PORT + ':' + process.env.IP);
CORS:
3.client_cors.js
$.ajax({
url: "http://api_test_server.proudlygeek.c9.io/",
success: function(data) {
console.log(data);
}
});?
4.server_cors.js
var http = require("http"),
url = require("url");
var server = http.createServer(function(req, res) {
console.log(req.headers);
var data = {
'name': "Gianpiero",
'last': "Fiorelli",
'age': 37
};
res.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
res.end(JSON.stringify(data));
});
server.listen(process.env.PORT, process.env.IP);
console.log('Server running at ' + process.env.PORT + ':' + process.env.IP);
Check your X Window environment variables using the "env" command.
You have the wrong table set on the command. You should use the following on your setup:
ALTER TABLE scode_tracker.ap_visits ENGINE=MyISAM;
Alternatively, and this would give you more flexibility if testing for values other than 1 or 2 in future, is to use a switch statement
switch(value)
{
case 1:
case 2:
return true;
default:
return false
}
I realize this is an old question, but it pops up in Google when you search for 'javascript dictionaries', so I'd like to add to the above answers that in ECMAScript 6, the official Map
object has been introduced, which is a dictionary implementation:
var dict = new Map();
dict.set("foo", "bar");
//returns "bar"
dict.get("foo");
Unlike javascript's normal objects, it allows any object as a key:
var foo = {};
var bar = {};
var dict = new Map();
dict.set(foo, "Foo");
dict.set(bar, "Bar");
//returns "Bar"
dict.get(bar);
//returns "Foo"
dict.get(foo);
//returns undefined, as {} !== foo and {} !== bar
dict.get({});
Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\New.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
If you want a method in which you know the algorithm, or the functions mentioned in the previous answer aren't available: convert the date to Julian Day number (which is a way of counting days from January 1st, 4713 B.C), then subtract five, then convert back to calendar date (year, month, day). Sources of the algorithms for the two conversions is section 9 of http://www.hermetic.ch/cal_stud/jdn.htm or http://en.wikipedia.org/wiki/Julian_day
read
does not export the variable (which is a good thing most of the time). Here's an alternative which can be exported in one command, can preserve or discard linefeeds, and allows mixing of quoting-styles as needed. Works for bash and zsh.
oneLine=$(printf %s \
a \
" b " \
$'\tc\t' \
'd ' \
)
multiLine=$(printf '%s\n' \
a \
" b " \
$'\tc\t' \
'd ' \
)
I admit the need for quoting makes this ugly for SQL, but it answers the (more generally expressed) question in the title.
I use it like this
export LS_COLORS=$(printf %s \
':*rc=36:*.ini=36:*.inf=36:*.cfg=36:*~=33:*.bak=33:*$=33' \
...
':bd=40;33;1:cd=40;33;1:or=1;31:mi=31:ex=00')
in a file sourced from both my .bashrc
and .zshrc
.
The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:
A data frame of four rows:
df = pd.DataFrame({'A': [1,2,3,4]})
Now trying to assign a list/array of two elements to it:
df['B'] = [3,4] # or df['B'] = np.array([3,4])
Both errors out:
ValueError: Length of values does not match length of index
Because the data frame has four rows but the list and array has only two elements.
Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:
df['B'] = pd.Series([3,4])
df
# A B
#0 1 3.0
#1 2 4.0
#2 3 NaN # NaN because the value at index 2 and 3 doesn't exist in the Series
#3 4 NaN
For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:
df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))
# A B
#0 1 1.0
#1 2 5.0
#2 7 9.0
#3 8 NaN
You can use += to concatenate strings, for example:
declare @test nvarchar(max)
set @test = ''
select @test += name from names
if you select @test, it will give you all names concatenated
I'm using Maven 3+ version. In my case everything was fine. But while adding the M2_HOME along with bin directory, I missed the '\' at the end. Previously it was like: %M2_HOME%\bin , which was throwing the mvn not recognizable error. After adding "\" at the end, mvn started working fine. I guess "\" acts as pointer to next folder. "%M2_HOME%\bin\" Should work, if you missed it.
FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"
I could not get Blorgbeard's suggestion to work, but I was able to get it to work with RMDIR instead of RD:
FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"
Since RMDIR won't delete folders that aren't empty so I also ended up using this code to delete the files that were over 10 days and then the folders that were over 10 days old.
FOR /d %%K in ("n:\test*") DO (
FOR /d %%J in ("%%K*") DO (
FORFILES /P %%J /S /M . /D -10 /C "cmd /c del @file"
)
)
FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"
I used this code to purge out the sub folders in the folders within test (example n:\test\abc\123 would get purged when empty, but n:\test\abc would not get purged
Here a solution if you want an empty data frame with a defined number of rows and NO columns:
df = data.frame(matrix(NA, ncol=1, nrow=10)[-1]
Using the "Add Service Reference" tool in Visual Studio, you can insert the address as:
file:///path/to/wsdl/file.wsdl
And it will load properly.
There is one example where in
actually kills your performance.
If you use in
on a O(1) container that only implements __getitem__
and has_key()
but not __contains__
you will turn an O(1) search into an O(N) search (as in
falls back to a linear search via __getitem__
).
Fix is obviously trivial:
def __contains__(self, x):
return self.has_key(x)
public class Statistics {
double[] data;
int size;
public Statistics(double[] data) {
this.data = data;
size = data.length;
}
double getMean() {
double sum = 0.0;
for(double a : data)
sum += a;
return sum/size;
}
double getVariance() {
double mean = getMean();
double temp = 0;
for(double a :data)
temp += (a-mean)*(a-mean);
return temp/(size-1);
}
double getStdDev() {
return Math.sqrt(getVariance());
}
public double median() {
Arrays.sort(data);
if (data.length % 2 == 0)
return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0;
return data[data.length / 2];
}
}
You don't need to use a type assertion, instead just use the %v
format specifier with Sprintf
:
hostAndPort := fmt.Sprintf("%v:%v", arguments["<host>"], arguments["<port>"])
In MySQL you can use:
SELECT CONCAT(Address1, " ", Address2)
WHERE SOUNDEX(CONCAT(Address1, " ", Address2)) = SOUNDEX("Center St 3B")
The SOUNDEX
function works similarly in most database systems, I can't think of the syntax for MSSQL at the minute, but it wouldn't be too far away from the above.
or you can add the AutoCompleteBox into the toolbox by clicking on it and then Choose Items, go to WPF Components, type in the filter AutoCompleteBox, which is on the System.Windows.Controls namespace and the just drag into your xaml file. This is way much easier than doing these other stuff, since the AutoCompleteBox is a native control.
In JavaScript the invocation type defines the behaviour of the function:
func()
obj.func()
new func()
func.call()
or func.apply()
The function is invoked as a constructor when calling using new
operator:
function Cat(name) {
this.name = name;
}
Cat.prototype.getName = function() {
return this.name;
}
var myCat = new Cat('Sweet'); // Cat function invoked as a constructor
Any instance or prototype object in JavaScript have a property constructor
, which refers to the constructor function.
Cat.prototype.constructor === Cat // => true
myCat.constructor === Cat // => true
Check this post about constructor property.
In Python 3, print is a function, you need to call it like print("hello world")
.
Oh, I just found that command on PostgreSQL forum:
SELECT * FROM pg_stat_activity;
In Swift 3 / iOS 10+ this now looks like
if let url = URL(string: "App-Prefs:root=LOCATION_SERVICES") {
UIApplication.shared.open(url, completionHandler: .none)
}
The command below will store in a variable all the file in your folder, matchting the extension ".txt":
$allfiles=Get-ChildItem -Path C:\temp\*" -Include *.txt
foreach ($file in $allfiles) {
Write-Host $file
Write-Host $file.name
Write-Host $file.basename
}
$file
gives the file with path, name and extension: c:\temp\myfile.txt
$file.name
gives file name & extension: myfile.txt
$file.basename
gives only filename: myfile
I hope this complete example will help you.
This is the TaxiInfo class which holds information about a taxi ride:
namespace Taxi.Models
{
public class TaxiInfo
{
public String Driver { get; set; }
public Double Fare { get; set; }
public Double Distance { get; set; }
public String StartLocation { get; set; }
public String EndLocation { get; set; }
}
}
We also have a convenience model which holds a List of TaxiInfo(s):
namespace Taxi.Models
{
public class TaxiInfoSet
{
public List<TaxiInfo> TaxiInfoList { get; set; }
public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
{
TaxiInfoList = new List<TaxiInfo>();
foreach(var TaxiInfo in TaxiInfos)
{
TaxiInfoList.Add(TaxiInfo);
}
}
}
}
Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:
public ActionResult Index()
{
var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };
return View(new TaxiInfoSet(taxi1,taxi2));
}
The code for the view is as follows:
@model Taxi.Models.TaxiInfoSet
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@foreach(var TaxiInfo in Model.TaxiInfoList){
<form>
<h1>Cost: [email protected]</h1>
<h2>Distance: @(TaxiInfo.Distance) km</h2>
<p>
Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
</p>
@Html.ActionLink("Home","Booking",TaxiInfo)
</form>
}
The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:
public ActionResult Booking(TaxiInfo Taxi)
{
return View(Taxi);
}
This returns a the following view:
@model Taxi.Models.TaxiInfo
@{
ViewBag.Title = "Booking";
}
<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>
A visual tour:
append 0 before it by checking if the value falls between 1 and 9 by first casting it to varchar
select case when DATEPART(month, getdate()) between 1 and 9
then '0' else '' end + cast(DATEPART(month, getdate()) as varchar(2))
sum = Double.parseDouble(""+marks.get(i));
$.getJSon expects a callback functions either you pass it to the callback function or in callback function assign it to global variale.
var globalJsonVar;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
//do some thing with json or assign global variable to incoming json.
globalJsonVar=json;
});
IMO best is to call the callback function. which is nicer to eyes, readability aspects.
$.getJSON("http://127.0.0.1:8080/horizon-update", callbackFuncWithData);
function callbackFuncWithData(data)
{
// do some thing with data
}
While the previous answers may work in a fashion, I think that using BehaviorSubject is the correct way if you want to continue using observables.
Example:
this.store.subscribe(
(data:any) => {
myService.myBehaviorSubject.next(data)
}
)
In the Service:
let myBehaviorSubject = new BehaviorSubjet(value);
In component.ts:
this.myService.myBehaviorSubject.subscribe(data => this.myData = data)
I hope this helps!
I recommend you to use enums :)
Check this out:
public enum Foo
{
BAR("bar"),
BAZ("baz"),
BAM("bam");
private final String description;
private Foo(String description)
{
this.description = description;
}
public String getDescription()
{
return description;
}
}
Then you can use it like this:
System.out.println(Foo.BAR.getDescription());
When docker kill CONTAINER_ID
does not work and docker stop -t 1 CONTAINER_ID
also does not work, you can try to delete the container:
docker container rm CONTAINER_ID
I had a similar issue today where containers were in a continuous restart loop.
The issue in my case was related to me being a poor engineer.
Anyway, I fixed the issue by deleting the container, fixing my code, and then rebuilding and running the container.
Hope that this helps anyone stuck with this issue in future
The biggest difference is their functionality. push_back
always puts a new element at the end of the vector
and insert
allows you to select new element's position. This impacts the performance. vector
elements are moved in the memory only when it's necessary to increase it's length because too little memory was allocated for it. On the other hand insert
forces to move all elements after the selected position of a new element. You simply have to make a place for it. This is why insert
might often be less efficient than push_back
.
First, you'll need to add session_start()
at the top of any page that you wish to use SESSION
variables on.
Also, you should check to make sure the variable is set first before using it:
if(isset($_SESSION['SESS_fname'])){
echo $_SESSION['SESS_fname'];
}
Or, simply:
echo (isset($_SESSION['SESS_fname']) ? $_SESSION['SESS_fname'] : "Visitor");
Regex is unnecessary for this. Just use some_string.split(' ', 1)[0]
or some_string.partition(' ')[0]
.
The above method can be tweaked for assemblies already loaded within the process by using the file's image in memory (as opposed to re-reading it from storage):
using System;
using System.Runtime.InteropServices;
using Assembly = System.Reflection.Assembly;
static class Utils
{
public static DateTime GetLinkerDateTime(this Assembly assembly, TimeZoneInfo tzi = null)
{
// Constants related to the Windows PE file format.
const int PE_HEADER_OFFSET = 60;
const int LINKER_TIMESTAMP_OFFSET = 8;
// Discover the base memory address where our assembly is loaded
var entryModule = assembly.ManifestModule;
var hMod = Marshal.GetHINSTANCE(entryModule);
if (hMod == IntPtr.Zero - 1) throw new Exception("Failed to get HINSTANCE.");
// Read the linker timestamp
var offset = Marshal.ReadInt32(hMod, PE_HEADER_OFFSET);
var secondsSince1970 = Marshal.ReadInt32(hMod, offset + LINKER_TIMESTAMP_OFFSET);
// Convert the timestamp to a DateTime
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var linkTimeUtc = epoch.AddSeconds(secondsSince1970);
var dt = TimeZoneInfo.ConvertTimeFromUtc(linkTimeUtc, tzi ?? TimeZoneInfo.Local);
return dt;
}
}
Run gpresult
at a Windows command prompt. You'll get an abundance of information about the current domain, current user, user & computer security groups, group policy names, Active Directory Distinguished Name, and so on.
Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.
I had a opened record set of the post that was created by:
Set RecSet = Conn.Execute()
This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...
RecSet.Close
Set RecSet = Nothing
...everything worked just fine.
So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.
Copied from MSDN:
At compile time, verbatim strings are converted to ordinary strings with all the same escape sequences. Therefore, if you view a verbatim string in the debugger watch window, you will see the escape characters that were added by the compiler, not the verbatim version from your source code. For example, the verbatim string
@"C:\files.txt"
will appear in the watch window as"C:\\files.txt"
.
Ipaper::geom_boxplot2 is just what you want.
# devtools::install_github('kongdd/Ipaper')
library(Ipaper)
library(ggplot2)
p <- ggplot(mpg, aes(class, hwy))
p + geom_boxplot2(width = 0.8, width.errorbar = 0.5)
For 2D arrays, you can do this. Create a 2D mask using the condition. Typecast the condition mask to int or float, depending on the array, and multiply it with the original array.
In [8]: arr
Out[8]:
array([[ 1., 2., 3., 4., 5.],
[ 6., 7., 8., 9., 10.]])
In [9]: arr*(arr % 2 == 0).astype(np.int)
Out[9]:
array([[ 0., 2., 0., 4., 0.],
[ 6., 0., 8., 0., 10.]])
It is also possible to create a div element in the following way:
var my_div = document.createElement('div');
add class
my_div.classList.add('col-10');
also can perform append()
and appendChild()
git log --grep=<pattern>
Limit the commits output to ones with log message that matches the
specified pattern (regular expression).
If anyone is using GoDaddy Shared Hosting, you can try for following solution, worked for me.
When starting DB connection, set the time_zone command in my PDO object e.g.:
$pdo = new PDO($dsn, $user, $pass, $opt);
$pdo->exec("SET time_zone='+05:30';");
Where "+05:30" is the TimeZone of India. You can change it as per your need.
After that; all the MySQL processes related to Date and Time are set with required timezone.
Source : https://in.godaddy.com/community/cPanel-Hosting/How-to-change-TimeZone-for-MySqL/td-p/31861
You can invoke MySQL show status command
show status like 'Conn%';
For more info read Show open database connections
Password Protected Zip File
if you want to compress files with password you can take a look at this library that can zip files with password easily:
Zip:
ZipArchive zipArchive = new ZipArchive();
zipArchive.zip(targetPath,destinationPath,password);
Unzip:
ZipArchive zipArchive = new ZipArchive();
zipArchive.unzip(targetPath,destinationPath,password);
Rar:
RarArchive rarArchive = new RarArchive();
rarArchive.extractArchive(file archive, file destination);
The documentation of this library is good enough, I just added a few examples from there. It's totally free and wrote specially for android.
This also happens if you include one file with different names or from different locations twice, especially if these are two different versions of the same file.
See the docs for the update
command:
npm update [-g] [<pkg>...]
This command will update all the packages listed to the latest version (specified by the tag config), respecting semver.
Additionally, see the documentation on Node.js and NPM installation and Upgrading NPM.
The following original answer is from the old FAQ that no longer exists, but should work for Linux and Mac:
How do I update npm?
npm install -g npm
Please note that this command will remove your current version of npm. Make sure to use
sudo npm install -g npm
if on a Mac.You can also update all outdated local packages by doing
npm update
without any arguments, or global packages by doingnpm update -g
.Occasionally, the version of npm will progress such that the current version cannot be properly installed with the version that you have installed already. (Consider, if there is ever a bug in the update command.) In those cases, you can do this:
curl https://www.npmjs.com/install.sh | sh
To update Node.js itself, I recommend you use nvm, the Node Version Manager.
A much simpler way nowadays is to use the jquery filter() as follows:
var options = $('select option');
var query = $('input').val();
options.filter(function() {
$(this).toggle($(this).val().toLowerCase().indexOf(query) > -1);
});
You should be using indexes to help SQL server performance. Usually that implies that columns that are used to find rows in a table are indexed.
Clustered indexes makes SQL server order the rows on disk according to the index order. This implies that if you access data in the order of a clustered index, then the data will be present on disk in the correct order. However if the column(s) that have a clustered index is frequently changed, then the row(s) will move around on disk, causing overhead - which generally is not a good idea.
Having many indexes is not good either. They cost to maintain. So start out with the obvious ones, and then profile to see which ones you miss and would benefit from. You do not need them from start, they can be added later on.
Most column datatypes can be used when indexing, but it is better to have small columns indexed than large. Also it is common to create indexes on groups of columns (e.g. country + city + street).
Also you will not notice performance issues until you have quite a bit of data in your tables. And another thing to think about is that SQL server needs statistics to do its query optimizations the right way, so make sure that you do generate that.
Use the function advance(startIndex, endIndex)
:
var str = "45+22"
str = str.substringToIndex(advance(str.startIndex, countElements(str) - 1))
The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct
approach is executed like:
business_key
values to a temporary tableThe group by
could be executed like:
business key
in a hashtableThe first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.
Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.
cmsjr had the right solution. I just wanted to point out a couple of things for your future trigger development. If you are using the values statement in an insert in a trigger, there is a stong possibility that you are doing the wrong thing. Triggers fire once for each batch of records inserted, deleted, or updated. So if ten records were inserted in one batch, then the trigger fires once. If you are refering to the data in the inserted or deleted and using variables and the values clause then you are only going to get the data for one of those records. This causes data integrity problems. You can fix this by using a set-based insert as cmsjr shows above or by using a cursor. Don't ever choose the cursor path. A cursor in a trigger is a problem waiting to happen as they are slow and may well lock up your table for hours. I removed a cursor from a trigger once and improved an import process from 40 minutes to 45 seconds.
You may think nobody is ever going to add multiple records, but it happens more frequently than most non-database people realize. Don't write a trigger that will not work under all the possible insert, update, delete conditions. Nobody is going to use the one record at a time method when they have to import 1,000,000 sales target records from a new customer or update all the prices by 10% or delete all the records from a vendor whose products you don't sell anymore.
Go to Phone Settings --> Developer Options --> Simulate Secondary Displays
and turn it to None
.
If you don't see Developer Options
in the settings menu
(it should be at the bottom, go Settings ==> About phone
and tap on the Build number
a lot of times)
These days I use the same approach as the answer described by @Behe below instead, updated link: https://stackoverflow.com/a/35292719/3423146 (old link: https://stackoverflow.com/a/35292719/1597808)
You can use the API in combination with depth, XPath, and wrapper arguments.
The following will query the API of the pluginManager to list all plugins installed, but only to return their shortName and version attributes. You can of course retrieve additional fields by adding '|' to the end of the XPath parameter and specifying the pattern to identify the node.
wget http://<jenkins>/pluginManager/api/xml?depth=1&xpath=/*/*/shortName|/*/*/version&wrapper=plugins
The wrapper argument is required in this case, because it's returning more than one node as part of the result, both in that it is matching multiple fields with the XPath and multiple plugin nodes.
It's probably useful to use the following URL in a browser to see what information on the plugins is available and then decide what you want to limit using XPath:
http://<jenkins>/pluginManager/api/xml?depth=1
Neither is better than the other, they do exactly the same thing. However, using .encode()
and .decode()
is the more common way to do it. It is also compatible with Python 2.
In Kotlin we can create array using arrayOf()
, intArrayOf()
, charArrayOf()
, booleanArrayOf()
, longArrayOf()
functions.
For example:
var Arr1 = arrayOf(1,10,4,6,15)
var Arr2 = arrayOf<Int>(1,10,4,6,15)
var Arr3 = arrayOf<String>("Surat","Mumbai","Rajkot")
var Arr4 = arrayOf(1,10,4, "Ajay","Prakesh")
var Arr5: IntArray = intArrayOf(5,10,15,20)
Gives you the list of files with full path:
Sys.glob(file.path(file_dir, "*.dbf")) ## file_dir = file containing directory
Idle Timeout is if no action has been asked from your web app, it the process will drop and release everything from memory
Recycle is a forced action on the application where your processed is closed and started again, for memory leaking purposes and system health
The negative impact of both is usually the use of your Session and Application state is lost if you mess with Recycle to a faster time.(logged in users etc will be logged out, if they where about to "check out" all would have been lost" that's why recycle is at such a large time out value, idle timeout doesn't matter because nobody is logged in anyway and figure 20 minutes an no action they are not still "shopping"
The positive would be get rid of the idle time out as your website will respond faster on its "first" response if its not a highly active site where a user would have to wait for it to load if you have 1 user every 20 minutes lets say. So a website that get his less then 1 time in 20 minutes actually you would want to increase this value as the website has to load up again from scratch for each user. but if you set this to 0 over a long time, any memory leaks in code could over a certain amount of time, entirely take over the server.
Compatible with all SDK versions (android.permission.ACCESS_FINE_LOCATION
became dangerous
permission in Android M and requires user to manually grant it).
In Android versions below Android M ContextCompat.checkSelfPermission(...)
always returns true
if you add these permission(s) in AndroidManifest.xml
)
public void onSomeButtonClick() {
...
if (!permissionsGranted()) {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 123);
} else doLocationAccessRelatedJob();
...
}
private Boolean permissionsGranted() {
return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED);
}
@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 123) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted.
doLocationAccessRelatedJob();
} else {
// User refused to grant permission. You can add AlertDialog here
Toast.makeText(this, "You didn't give permission to access device location", Toast.LENGTH_LONG).show();
startInstalledAppDetailsActivity();
}
}
}
private void startInstalledAppDetailsActivity() {
Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:" + getPackageName()));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
in AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
This should do what you want:
import datetime
yesterday = datetime.datetime.now() - datetime.timedelta(days = 1)
print yesterday.strftime("%m%d%y")
Here is the code
String str = "Hi There";
char[] arr = str.toCharArray();
for(int i=0;i<arr.length;i++)
System.out.print(" "+arr[i]);
You can't have a variable that points to nil
in Swift — there are no pointers, and no null pointers. But in an API, you often want to be able to indicate either a specific kind of value, or a lack of value — e.g. does my window have a delegate, and if so, who is it? Optionals are Swift's type-safe, memory-safe way to do this.
check it useing loop for each index in comboxlist.Items[i]
bool CheckedOrUnchecked= comboxlist.CheckedItems.Contains(comboxlist.Items[0]);
I think it solve your purpose
You can use
val drawableCompat = ContextCompat.getDrawable(context, R.drawable.ic_emoticon_happy)
or in java java
Drawable drawableCompat = ContextCompat.getDrawable(getContext(), R.drawable.ic_emoticon_happy)
Result Set
are actually contains multiple rows of data, and use a cursor to point out current position. So in your case, rs4.getString(1)
only get you the data in first column of first row. In order to change to next row, you need to call next()
a quick example
while (rs.next()) {
String sid = rs.getString(1);
String lid = rs.getString(2);
// Do whatever you want to do with these 2 values
}
there are many useful method in ResultSet
, you should take a look :)
you could make them all #
's.
You would then need to add return false;
to the end of any function that is called onclick of the anchor to not have the page jump up to the top.
Everyone tries Application.Wait
, but that's not really reliable. If you ask it to wait for less than a second, you'll get anything between 0 and 1, but closer to 10 seconds. Here's a demonstration using a wait of 0.5 seconds:
Sub TestWait()
Dim i As Long
For i = 1 To 5
Dim t As Double
t = Timer
Application.Wait Now + TimeValue("0:00:00") / 2
Debug.Print Timer - t
Next
End Sub
Here's the output, an average of 0.0015625 seconds:
0
0
0
0.0078125
0
Admittedly, Timer may not be the ideal way to measure these events, but you get the idea.
The Timer approach is better:
Sub TestTimer()
Dim i As Long
For i = 1 To 5
Dim t As Double
t = Timer
Do Until Timer - t >= 0.5
DoEvents
Loop
Debug.Print Timer - t
Next
End Sub
And the results average is very close to 0.5 seconds:
0.5
0.5
0.5
0.5
0.5
Change the return type to Nullable<T>
, and call the method with the non nullable parameter
static void Main(string[] args)
{
int? i = GetValueOrNull<int>(null, string.Empty);
}
public static Nullable<T> GetValueOrNull<T>(DbDataRecord reader, string columnName) where T : struct
{
object columnValue = reader[columnName];
if (!(columnValue is DBNull))
return (T)columnValue;
return null;
}
Create the hash:
hash = {:item1 => 1}
Add a new item to it:
hash[:item2] = 2
I found this question while Googling. Note that if you just want to make use of the URI's content via something like a string, consider using Apache's IOUtils.toString()
method.
For example, a sample line of code could be:
String pageContent = IOUtils.toString("http://maps.google.at/maps?saddr=4714&daddr=Marchtrenk&hl=de", Charset.UTF_8);
i think i hve some joined like this from 7 Tables
SELECT a.no_surat ,
a.nm_anggota ,
a.nrp_nip_anggota ,
a.tmpt_lahir ,
a.tgl_lahir ,
a.bln_lahir ,
a.thn_lahir ,
a.alamat ,
a.keperluan ,
a.nm_jabatan ,
b.id_polsek ,b.nm_polsek,
c.id_polres ,c.nm_polres ,
d.id_pangkat , d.nm_pangkat,
e.id_pejabat , e.nm_pejabat ,
f.id_ket , f.nm_ket,
g.id_pejabat,g.nm_pejabat
FROM tbl_skhp AS a
LEFT JOIN tbl_polsek AS b ON a.id_polsek=b.id_polsek
LEFT JOIN tbl_polres AS c ON a.id_polres=c.id_polres
LEFT JOIN tbl_pangkat AS d ON a.id_pangkat=d.id_pangkat
LEFT JOIN tbl_pejabat AS e ON a.id_pejabat=e.id_pejabat
LEFT JOIN tbl_ket AS f ON a.id_ket=f.id_ket
LEFT JOIN tbl_pejabat AS g ON a.id_pejabat=g.id_pejabat
i hope u understand.... i am just sharing worked code for me.... i am use it to fetch data to my readonly form just for priview...
Tensor.get_shape()
from this post.
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
print(c.get_shape())
==> TensorShape([Dimension(2), Dimension(3)])
This will cover all the possibility of a prime number . (order of the last 3 if statements is important)
function isPrime(num){
if (num==0 || num==1) return false;
if (num==2 || num==3 ) return true;
if (num % Math.sqrt(num)==0 ) return false;
for (let i=2;i< Math.floor(Math.sqrt(num));i++) if ( num % i==0 ) return false;
if ((num * num - 1) % 24 == 0) return true;
}
I think the fastest solution is
select * from table where rand() <= .3
Here is why I think this should do the job.
This assumes that rand() is generating numbers in a uniform distribution. It is the quickest way to do this.
I saw that someone had recommended that solution and they got shot down without proof.. here is what I would say to that -
mysql is very capable of generating random numbers for each row. Try this -
select rand() from INFORMATION_SCHEMA.TABLES limit 10;
Since the database in question is mySQL, this is the right solution.
There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.
Import one class and use the fully qualified name for the other one, i.e.
import com.text.Formatter;
private Formatter textFormatter;
private com.json.Formatter jsonFormatter;
Select from the table, use the ORDER BY __ DESC to sort in reverse order, then limit your results to 10.
SELECT * FROM big_table ORDER BY A DESC LIMIT 10
def matrixmult (A, B):
C = [[0 for row in range(len(A))] for col in range(len(B[0]))]
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
C[i][j] += A[i][k]*B[k][j]
return C
at second line you should change
C = [[0 for row in range(len(B[0]))] for col in range(len(A))]
I got this error when trying to run my friend's solution file by visual studio 2010 after convert it to 2010 version. The fix is easy, I create new project, right click the solution to add existing .cpp and .h file from my friend's project. Then it work.
The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects.
Using getmembers()
you can see all attributes of your class, along with their value. To exclude private or protected attributes use .startswith('_')
. To exclude methods or functions use inspect.ismethod()
or inspect.isfunction()
.
import inspect
class NewClass(object):
def __init__(self, number):
self.multi = int(number) * 2
self.str = str(number)
def func_1(self):
pass
a = NewClass(2)
for i in inspect.getmembers(a):
# Ignores anything starting with underscore
# (that is, private and protected attributes)
if not i[0].startswith('_'):
# Ignores methods
if not inspect.ismethod(i[1]):
print(i)
Note that ismethod()
is used on the second element of i
since the first is simply a string (its name).
Offtopic: Use CamelCase for class names.
You can use the clearfix
to do "layout preserving" the same way overflow: hidden
does.
.clearfix:before,
.clearfix:after {
content: ".";
display: block;
height: 0;
overflow: hidden;
}
.clearfix:after { clear: both; }
.clearfix { zoom: 1; } /* IE < 8 */
add class="clearfix"
class to the parent, and remove overflow: hidden;
This is CSS issues. I don't know why @Html.DropDownListFor in Bootstrap 4 doest work. Surely this is class design problem. Anyways the work arround is, if your Dropdown input box has CSS Padding: #px, # px; element then disable it. Hope this will work.
To make this complete: while others now solved your problem :) I would like to give you a piece of good advice: don't reinvent the wheel.
size_t forward_length = strlen(forward);
Efficient solution in C#
public class MyStack {
private Queue<int> q1 = new Queue<int>();
private Queue<int> q2 = new Queue<int>();
private int count = 0;
/**
* Initialize your data structure here.
*/
public MyStack() {
}
/**
* Push element x onto stack.
*/
public void Push(int x) {
count++;
q1.Enqueue(x);
while (q2.Count > 0) {
q1.Enqueue(q2.Peek());
q2.Dequeue();
}
var temp = q1;
q1 = q2;
q2 = temp;
}
/**
* Removes the element on top of the stack and returns that element.
*/
public int Pop() {
count--;
return q2.Dequeue();
}
/**
* Get the top element.
*/
public int Top() {
return q2.Peek();
}
/**
* Returns whether the stack is empty.
*/
public bool Empty() {
if (count > 0) return false;
return true;
}
}
import java.util.ArrayList;
import java.util.Random;
public class shuffle {
public static void main(String[] args) {
int a[] = {1,2,3,4,5,6,7,8,9};
ArrayList b = new ArrayList();
int i=0,q=0;
Random rand = new Random();
while(a.length!=b.size())
{
int l = rand.nextInt(a.length);
//this is one option to that but has a flaw on 0
// if(a[l] !=0)
// {
// b.add(a[l]);
// a[l]=0;
//
// }
//
// this works for every no.
if(!(b.contains(a[l])))
{
b.add(a[l]);
}
}
// for (int j = 0; j <b.size(); j++) {
// System.out.println(b.get(j));
//
// }
System.out.println(b);
}
}
I didn't want to have to have the YouTube app present on the device so I used this tutorial:
http://www.viralandroid.com/2015/09/how-to-embed-youtube-video-in-android-webview.html
...to produce this code in my app:
WebView mWebView;
@Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.video_webview);
mWebView=(WebView)findViewById(R.id.videoview);
//build your own src link with your video ID
String videoStr = "<html><body>Promo video<br><iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/embed/47yJ2XCRLZs\" frameborder=\"0\" allowfullscreen></iframe></body></html>";
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
WebSettings ws = mWebView.getSettings();
ws.setJavaScriptEnabled(true);
mWebView.loadData(videoStr, "text/html", "utf-8");
}
//video_webview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:background="#000000"
android:id="@+id/bmp_programme_ll"
android:orientation="vertical" >
<WebView
android:id="@+id/videoview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
This worked just how I wanted it. It doesn't autoplay but the video streams within my app. Worth noting that some restricted videos won't play when embedded.
Let's assume that (1) you don't have a large memory (2) you have row headings in a list (3) all the data values are floats; if they're all integers up to 32- or 64-bits worth, that's even better.
On a 32-bit Python, storing a float in a list takes 16 bytes for the float object and 4 bytes for a pointer in the list; total 20. Storing a float in an array.array('d') takes only 8 bytes. Increasingly spectacular savings are available if all your data are int (any negatives?) that will fit in 8, 4, 2 or 1 byte(s) -- especially on a recent Python where all ints are longs.
The following pseudocode assumes floats stored in array.array('d'). In case you don't really have a memory problem, you can still use this method; I've put in comments to indicate the changes needed if you want to use a list.
# Preliminary:
import array # list: delete
hlist = []
dlist = []
for each row:
hlist.append(some_heading_string)
dlist.append(array.array('d')) # list: dlist.append([])
# generate data
col_index = -1
for each column:
col_index += 1
for row_index in xrange(len(hlist)):
v = calculated_data_value(row_index, colindex)
dlist[row_index].append(v)
# write to csv file
for row_index in xrange(len(hlist)):
row = [hlist[row_index]]
row.extend(dlist[row_index])
csv_writer.writerow(row)
If your image is stored in a Blob format (i.e. in a database) you can use the same technique explained by Billal Begueradj to convert your image from Blobs to a byte array.
In my case, I needed my images where stored in a blob column in a db table:
def select_all_X_values(conn):
cur = conn.cursor()
cur.execute("SELECT ImageData from PiecesTable")
rows = cur.fetchall()
return rows
I then created a helper function to change my dataset into np.array:
X_dataset = select_all_X_values(conn)
imagesList = convertToByteIO(np.array(X_dataset))
def convertToByteIO(imagesArray):
"""
# Converts an array of images into an array of Bytes
"""
imagesList = []
for i in range(len(imagesArray)):
img = Image.open(BytesIO(imagesArray[i])).convert("RGB")
imagesList.insert(i, np.array(img))
return imagesList
After this, I was able to use the byteArrays in my Neural Network.
plt.imshow(imagesList[0])
If you want to move the position of the legend please use the following code:
library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
theme(legend.position="bottom")
This should give you the desired result.
java -cp CLASSPATH is necesssary if you wish to specify all code in the classpath. This is useful for debugging code.
The jarred executable format: java -jar JarFile
can be used if you wish to start the app with a single short command. You can specify additional dependent jar files in your MANIFEST using space separated jars in a Class-Path entry, e.g.:
Class-Path: mysql.jar infobus.jar acme/beans.jar
Both are comparable in terms of performance.
To give the second rule higher specificity you can always use parts of the first rule. In this case I would add table.rule1 tr
from rule one and add it to rule two.
table.rule1 tr td {
background-color: #ff0000;
}
table.rule1 tr td.rule2 {
background-color: #ffff00;
}
After a while I find this gets natural, but I know some people disagree. For those people I would suggest looking into LESS or SASS.
Contanis occur if using the method of the present letter, and store the corresponding number using the IndexOf method, see example below.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim myString As String = "abcdef"
Dim numberString As String = String.Empty
If myString.Contains("d") Then
numberString = myString.IndexOf("d")
End If
End Sub
Another sample with TextBox
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim myString As String = "abcdef"
Dim numberString As String = String.Empty
If myString.Contains(me.TextBox1.Text) Then
numberString = myString.IndexOf(Me.TextBox1.Text)
End If
End Sub
Regards
In addition to cletus' answer, JPA 2.0, final since december 2010, introduces an orphanRemoval
attribute on @OneToMany
annotations.
For more details see this blog entry.
Note that since the spec is relatively new, not all JPA 1 provider have a final JPA 2 implementation. For example, the Hibernate 3.5.0-Beta-2 release does not yet support this attribute.
Use a parameter expansion. This is much more efficient than any kind of external command, cut
(or grep
) included.
data=foo,bar,baz,qux
last=${data##*,}
See BashFAQ #100 for an introduction to native string manipulation in bash.
Yes the problem is here. It's related to your syntax.
Try using this
return this.http.post(this.BASE_URL, params, options)
.map(data => this.handleData(data))
.catch(this.handleError);
instead of
return this.http.post(this.BASE_URL, params, options)
.map(this.handleData)
.catch(this.handleError);
Also, the second parameter is supposed to be the body, not the url params.
For one-click (BATCH file) launch, this is what I've done:
c: cd C:\Program Files (x86)\Android\android-sdk\emulator\ emulator -avd Pixel_2_API_28
Explanations:
Using:
You have configured the auth.php
and used members
table for authentication but there is no user_email
field in the members
table so, Laravel says
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_email' in 'where clause' (SQL: select * from members where user_email = ? limit 1) (Bindings: array ( 0 => '[email protected]', ))
Because, it tries to match the user_email
in the members
table and it's not there. According to your auth
configuration, laravel
is using members
table for authentication not users
table.
For example, my
vector<int> foo
contains (5,2,6,87,251). A function takesvector<int>*
and I want to pass it a pointer to (2,6,87,251).
A pointer to a vector<int>
is not at all the same thing as a pointer to the elements of the vector.
In order to do this you will need to create a new vector<int>
with just the elements you want in it to pass a pointer to. Something like:
vector<int> tempVector( foo.begin()+1, foo.end());
// now you can pass &tempVector to your function
However, if your function takes a pointer to an array of int, then you can pass &foo[1]
.
Underscore has a _without() method perfect for removing an item from an array, especially if you have the object to remove.
Returns a copy of the array with all instances of the values removed.
_.without(["bob", "sam", "fred"], "sam");
=> ["bob", "fred"]
Works with more complex objects too.
var bob = { Name: "Bob", Age: 35 };
var sam = { Name: "Sam", Age: 19 };
var fred = { Name: "Fred", Age: 50 };
var people = [bob, sam, fred]
_.without(people, sam);
=> [{ Name: "Bob", Age: 35 }, { Name: "Fred", Age: 50 }];
If you don't have the item to remove, just a property of it, you can use _.findWhere
and then _.without
.
It is possible to get your second example (i.e., the one using a scoped enum) to work using the same syntax as unscoped enums. Furthermore, the solution is generic and will work for all scoped enums, versus writing code for each scoped enum (as shown in the answer provided by @ForEveR).
The solution is to write a generic operator<<
function which will work for any scoped enum. The solution employs SFINAE via std::enable_if
and is as follows.
#include <iostream>
#include <type_traits>
// Scoped enum
enum class Color
{
Red,
Green,
Blue
};
// Unscoped enum
enum Orientation
{
Horizontal,
Vertical
};
// Another scoped enum
enum class ExecStatus
{
Idle,
Started,
Running
};
template<typename T>
std::ostream& operator<<(typename std::enable_if<std::is_enum<T>::value, std::ostream>::type& stream, const T& e)
{
return stream << static_cast<typename std::underlying_type<T>::type>(e);
}
int main()
{
std::cout << Color::Blue << "\n";
std::cout << Vertical << "\n";
std::cout << ExecStatus::Running << "\n";
return 0;
}
It's important to make the difference between the App language and the device locale language (The code below is in Swift 3)
Will return the Device language:
let locale = NSLocale.current.languageCode
Will return the App language:
let pre = Locale.preferredLanguages[0]
There are two main uses of AtomicInteger
:
As an atomic counter (incrementAndGet()
, etc) that can be used by many threads concurrently
As a primitive that supports compare-and-swap instruction (compareAndSet()
) to implement non-blocking algorithms.
Here is an example of non-blocking random number generator from Brian Göetz's Java Concurrency In Practice:
public class AtomicPseudoRandom extends PseudoRandom {
private AtomicInteger seed;
AtomicPseudoRandom(int seed) {
this.seed = new AtomicInteger(seed);
}
public int nextInt(int n) {
while (true) {
int s = seed.get();
int nextSeed = calculateNext(s);
if (seed.compareAndSet(s, nextSeed)) {
int remainder = s % n;
return remainder > 0 ? remainder : remainder + n;
}
}
}
...
}
As you can see, it basically works almost the same way as incrementAndGet()
, but performs arbitrary calculation (calculateNext()
) instead of increment (and processes the result before return).
You need to provide your own implementation of equals()
in MyClass
.
@Override
public boolean equals(Object other) {
if (!(other instanceof MyClass)) {
return false;
}
MyClass that = (MyClass) other;
// Custom equality check here.
return this.field1.equals(that.field1)
&& this.field2.equals(that.field2);
}
You should also override hashCode()
if there's any chance of your objects being used in a hash table. A reasonable implementation would be to combine the hash codes of the object's fields with something like:
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 37 + this.field1.hashCode();
hashCode = hashCode * 37 + this.field2.hashCode();
return hashCode;
}
See this question for more details on implementing a hash function.
You can do the following:
class User(object):
fullName = "John Doe"
def __init__(self, name):
self.SName = name
def print_names(self):
print "Names: full name: '%s', name: '%s'" % (self.fullName, self.SName)
user = User('Test Name')
user.fullName # "John Doe"
user.SName # 'Test Name'
user.print_names() # will print you Names: full name: 'John Doe', name: 'Test Name'
E.g any object attributes could be retrieved using istance.
Ideally insertAfter
should work similar to insertBefore. The code below will perform the following:
Node
is appendedNode
, the new Node
is appendedNode
after the reference Node
, the new Node
is appendedNode
has a sibling after, then the new Node
is inserted before that siblingNode
Extending Node
Node.prototype.insertAfter = function(node, referenceNode) {
if (node)
this.insertBefore(node, referenceNode && referenceNode.nextSibling);
return node;
};
One common example
node.parentNode.insertAfter(newNode, node);
See the code running
// First extend_x000D_
Node.prototype.insertAfter = function(node, referenceNode) {_x000D_
_x000D_
if (node)_x000D_
this.insertBefore(node, referenceNode && referenceNode.nextSibling);_x000D_
_x000D_
return node;_x000D_
};_x000D_
_x000D_
var referenceNode,_x000D_
newNode;_x000D_
_x000D_
newNode = document.createElement('li')_x000D_
newNode.innerText = 'First new item';_x000D_
newNode.style.color = '#FF0000';_x000D_
_x000D_
document.getElementById('no-children').insertAfter(newNode);_x000D_
_x000D_
newNode = document.createElement('li');_x000D_
newNode.innerText = 'Second new item';_x000D_
newNode.style.color = '#FF0000';_x000D_
_x000D_
document.getElementById('no-reference-node').insertAfter(newNode);_x000D_
_x000D_
referenceNode = document.getElementById('no-sibling-after');_x000D_
newNode = document.createElement('li');_x000D_
newNode.innerText = 'Third new item';_x000D_
newNode.style.color = '#FF0000';_x000D_
_x000D_
referenceNode.parentNode.insertAfter(newNode, referenceNode);_x000D_
_x000D_
referenceNode = document.getElementById('sibling-after');_x000D_
newNode = document.createElement('li');_x000D_
newNode.innerText = 'Fourth new item';_x000D_
newNode.style.color = '#FF0000';_x000D_
_x000D_
referenceNode.parentNode.insertAfter(newNode, referenceNode);
_x000D_
<h5>No children</h5>_x000D_
<ul id="no-children"></ul>_x000D_
_x000D_
<h5>No reference node</h5>_x000D_
<ul id="no-reference-node">_x000D_
<li>First item</li>_x000D_
</ul>_x000D_
_x000D_
<h5>No sibling after</h5>_x000D_
<ul>_x000D_
<li id="no-sibling-after">First item</li>_x000D_
</ul>_x000D_
_x000D_
<h5>Sibling after</h5>_x000D_
<ul>_x000D_
<li id="sibling-after">First item</li>_x000D_
<li>Third item</li>_x000D_
</ul>
_x000D_
in Bootstrap 5 you can do something like this:
<div class="py-2 my-1 text-center position-relative mx-2">
<div class="position-absolute w-100 top-50 start-50 translate-middle" style="z-index: 2">
<span class="d-inline-block bg-white px-2 text-muted">or</span>
</div>
<div class="position-absolute w-100 top-50 start-0 border-muted border-top"></div>
</div>
Try this-
$('select').on('change', function() {_x000D_
alert( this.value );_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<select>_x000D_
<option value="1">One</option>_x000D_
<option value="2">Two</option>_x000D_
</select>
_x000D_
You can also reference with onchange event-
function getval(sel)_x000D_
{_x000D_
alert(sel.value);_x000D_
}
_x000D_
<select onchange="getval(this);">_x000D_
<option value="1">One</option>_x000D_
<option value="2">Two</option>_x000D_
</select>
_x000D_
You could use the PHP in_array function
if( in_array( "bla" ,$yourarray ) )
{
echo "has bla";
}
return None
or return
can be used to exit out of a function or program, both does the same thingquit()
function can be used, although use of this function is discouraged for making real world applications and should be used only in interpreter. import site
def func():
print("Hi")
quit()
print("Bye")
exit()
function can be used, similar to quit()
but the use is discouraged for making real world applications.import site
def func():
print("Hi")
exit()
print("Bye")
sys.exit([arg])
function can be used and need to import sys
module for that, this function can be used for real world applications unlike the other two functions.import sys
height = 150
if height < 165: # in cm
# exits the program
sys.exit("Height less than 165")
else:
print("You ride the rollercoaster.")
os._exit(n)
function can be used to exit from a process, and need to import os
module for that.You can use np.c_
np.c_[[1,2,3], [4,5,6]]
It will give you:
np.array([[1,4], [2,5], [3,6]])
In VB.NET:
Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString("http://api.hostip.info/?ip=68.180.206.184")
In C#:
System.Net.WebClient webClient = new System.Net.WebClient();
string result = webClient.DownloadString("http://api.hostip.info/?ip=68.180.206.184");
The answers above are already quite great, but I really want to share the following summary article: "6 Ways to Run Shell Commands in Ruby"
Basically, it tells us:
Kernel#exec
:
exec 'echo "hello $HOSTNAME"'
system
and $?
:
system 'false'
puts $?
Backticks (`):
today = `date`
IO#popen
:
IO.popen("date") { |f| puts f.gets }
Open3#popen3
-- stdlib:
require "open3"
stdin, stdout, stderr = Open3.popen3('dc')
Open4#popen4
-- a gem:
require "open4"
pid, stdin, stdout, stderr = Open4::popen4 "false" # => [26327, #<IO:0x6dff24>, #<IO:0x6dfee8>, #<IO:0x6dfe84>]
Watch this video, I had the same question. He shows you how to debug the service as well.
Here are his instructions using the basic C# Windows Service template in Visual Studio 2010/2012.
You add this to the Service1.cs file:
public void onDebug()
{
OnStart(null);
}
You change your Main() to call your service this way if you are in the DEBUG Active Solution Configuration.
static void Main()
{
#if DEBUG
//While debugging this section is used.
Service1 myService = new Service1();
myService.onDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
//In Release this section is used. This is the "normal" way.
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
#endif
}
Keep in mind that while this is an awesome way to debug your service. It doesn't call OnStop()
unless you explicitly call it similar to the way we called OnStart(null)
in the onDebug()
function.
Just to demonstrate the flexibility of javascript: you can use a oneliner for this
function padLeft(nr, n, str){
return Array(n-String(nr).length+1).join(str||'0')+nr;
}
//or as a Number prototype method:
Number.prototype.padLeft = function (n,str){
return Array(n-String(this).length+1).join(str||'0')+this;
}
//examples
console.log(padLeft(23,5)); //=> '00023'
console.log((23).padLeft(5)); //=> '00023'
console.log((23).padLeft(5,' ')); //=> ' 23'
console.log(padLeft(23,5,'>>')); //=> '>>>>>>23'
If you want to use this for negative numbers also:
Number.prototype.padLeft = function (n,str) {
return (this < 0 ? '-' : '') +
Array(n-String(Math.abs(this)).length+1)
.join(str||'0') +
(Math.abs(this));
}
console.log((-23).padLeft(5)); //=> '-00023'
Alternative if you don't want to use Array
:
number.prototype.padLeft = function (len,chr) {
var self = Math.abs(this)+'';
return (this<0 && '-' || '')+
(String(Math.pow( 10, (len || 2)-self.length))
.slice(1).replace(/0/g,chr||'0') + self);
}
If you're using a jupyter notebook, I found this to be the simplest solution for one off cases. Basically convert the numpy array to a list and then to a string and then print. This has the benefit of keeping the comma separators in the array, whereas using numpyp.printoptions(threshold=np.inf)
does not:
import numpy as np
print(str(np.arange(10000).reshape(250,40).tolist()))
body:before {
content: " ";
width: 100%;
height: 100%;
position: fixed;
z-index: -1;
top: 0;
left: 0;
background: rgba(0, 0, 0, 0.5);
}
The way I solved this problem was to place the image within a Border with it's ClipToBounds property set to True. The RenderTransformOrigin on the image is then set to 0.5,0.5 so the image will start zooming on the center of the image. The RenderTransform is also set to a TransformGroup containing a ScaleTransform and a TranslateTransform.
I then handled the MouseWheel event on the image to implement zooming
private void image_MouseWheel(object sender, MouseWheelEventArgs e)
{
var st = (ScaleTransform)image.RenderTransform;
double zoom = e.Delta > 0 ? .2 : -.2;
st.ScaleX += zoom;
st.ScaleY += zoom;
}
To handle the panning the first thing I did was to handle the MouseLeftButtonDown event on the image, to capture the mouse and to record it's location, I also store the current value of the TranslateTransform, this what is updated to implement panning.
Point start;
Point origin;
private void image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
image.CaptureMouse();
var tt = (TranslateTransform)((TransformGroup)image.RenderTransform)
.Children.First(tr => tr is TranslateTransform);
start = e.GetPosition(border);
origin = new Point(tt.X, tt.Y);
}
Then I handled the MouseMove event to update the TranslateTransform.
private void image_MouseMove(object sender, MouseEventArgs e)
{
if (image.IsMouseCaptured)
{
var tt = (TranslateTransform)((TransformGroup)image.RenderTransform)
.Children.First(tr => tr is TranslateTransform);
Vector v = start - e.GetPosition(border);
tt.X = origin.X - v.X;
tt.Y = origin.Y - v.Y;
}
}
Finally don't forget to release the mouse capture.
private void image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
image.ReleaseMouseCapture();
}
As for the selection handles for resizing this can be accomplished using an adorner, check out this article for more information.
It is also worth to mention, that if you DO NOT intent to modify the values of the list, it is possible (and better) to use the const_iterator
, as follows:
for (std::list<Student>::const_iterator it = data.begin(); it != data.end(); ++it){
// do whatever you wish but don't modify the list elements
std::cout << it->name;
}
// TypeScript
const today = new Date();
const firstDayOfYear = new Date(today.getFullYear(), 0, 1);
// Explicitly convert Date to Number
const pastDaysOfYear = ( Number(today) - Number(firstDayOfYear) );
Laravel Mix 4 switches from node-sass to dart-sass (which may not compile as you would expect, OR you have to deal with the issues one by one)
OR
npm install node-sass
mix.sass('resources/sass/app.sass', 'public/css', {
implementation: require('node-sass')
});
Ad hoc queries are those that are not already defined that are not needed on a regular basis, so they're not included in the typical set of reports or queries
try getHibernateTemplate().replicate(entity,ReplicationMode.LATEST_VERSION)
The output looks correct to me:
Invalid JavaScript code: sun.org.mozilla.javascript.internal.EvaluatorException: missing } after property list (<Unknown source>) in <Unknown source>; at line number 1
I think Invalid Javascript code: ..
is the start of the exception message.
Normally the stacktrace isn't returned with the message:
try {
throw new RuntimeException("hu?\ntrace-line1\ntrace-line2");
} catch (Exception e) {
System.out.println(e.getMessage()); // prints "hu?"
}
So maybe the code you are calling catches an exception and rethrows a ScriptException
. In this case maybe e.getCause().getMessage()
can help you.
Can't find anything simple and elegant just yet, but I have one idea: If you know the type of the property you wish to set, you can write your own default(T)
. There are two cases - T
is a value type, and T
is a reference type. You can see this by checking T.IsValueType
. If T
is a reference type, then you can simply set it to null
. If T
is a value type, then it will have a default parameterless constructor that you can call to get a "blank" value.
In framework 3.5, dt.Rows.Cast<System.Data.DataRow>().Take(n)
Otherwise the way you mentioned
JSR305 and FindBugs are authored by the same person. Both are poorly maintained but are as standard as it gets and are supported by all major IDEs. The good news is that they work well as-is.
Here is how to apply @Nonnull to all classes, methods and fields by default. See https://stackoverflow.com/a/13319541/14731 and https://stackoverflow.com/a/9256595/14731
@NotNullByDefault
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.annotation.Nonnull;
import javax.annotation.meta.TypeQualifierDefault;
/**
* This annotation can be applied to a package, class or method to indicate that the class fields,
* method return types and parameters in that element are not null by default unless there is: <ul>
* <li>An explicit nullness annotation <li>The method overrides a method in a superclass (in which
* case the annotation of the corresponding parameter in the superclass applies) <li> there is a
* default parameter annotation applied to a more tightly nested element. </ul>
* <p/>
* @see https://stackoverflow.com/a/9256595/14731
*/
@Documented
@Nonnull
@TypeQualifierDefault(
{
ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR,
ElementType.FIELD,
ElementType.LOCAL_VARIABLE,
ElementType.METHOD,
ElementType.PACKAGE,
ElementType.PARAMETER,
ElementType.TYPE
})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotNullByDefault
{
}
2. Add the annotation to each package: package-info.java
@NotNullByDefault
package com.example.foo;
UPDATE: As of December 12th, 2012 JSR 305 is listed as "Dormant". According to the documentation:
A JSR that was voted as "dormant" by the Executive Committee, or one that has reached the end of its natural lifespan.
It looks like JSR 308 is making it into JDK 8 and although the JSR does not define @NotNull, the accompanying Checkers Framework
does. At the time of this writing, the Maven plugin is unusable due to this bug: https://github.com/typetools/checker-framework/issues/183
This may be not the full answer to your question, however if you are looking for way to disable csrf protection you can do:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/web/admin/**").hasAnyRole(ADMIN.toString(), GUEST.toString())
.anyRequest().permitAll()
.and()
.formLogin().loginPage("/web/login").permitAll()
.and()
.csrf().ignoringAntMatchers("/contact-email")
.and()
.logout().logoutUrl("/web/logout").logoutSuccessUrl("/web/").permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("admin").roles(ADMIN.toString())
.and()
.withUser("guest").password("guest").roles(GUEST.toString());
}
}
I have included full configuration but the key line is:
.csrf().ignoringAntMatchers("/contact-email")
use the dbms_metadata package, as described here
Considering that XML data comes from a table 'table' and is stored in a column 'field': use the XML methods, extract values with xml.value()
, project nodes with xml.nodes()
, use CROSS APPLY
to join:
SELECT
p.value('(./firstName)[1]', 'VARCHAR(8000)') AS firstName,
p.value('(./lastName)[1]', 'VARCHAR(8000)') AS lastName
FROM table
CROSS APPLY field.nodes('/person') t(p)
You can ditch the nodes()
and cross apply
if each field contains exactly one element 'person'. If the XML is a variable you select FROM @variable.nodes(...)
and you don't need the cross apply
.
The closest thing would be the bind function:
$('#foo').bind('click', function() {
alert('User clicked on "foo."');
});
Use test -n "${var-}"
to check if the variable is not empty (and hence must be defined/set too). Usage:
if test -n "${name-}"; then
echo "name is set to $name"
else
echo "name is not set or empty"
fi
Use test ! -z "${var+}"
to check if the variable is defined/set (even if it's empty). Usage:
if test ! -z "${var+}"; then
echo "name is set to $name"
else
echo "name is not set"
fi
Note that the first use case is much more common in shell scripts and this is what you will usually want to use.
To understand how this solution works, you need to understand the POSIX test
command and POSIX shell parameter expansion (spec), so let's cover the absolute basics needed to understand the answer.
The test command evaluates an expression and returns true or false (via its exit status). The operator -n
returns true if the operand is a non-empty string. So for example, test -n "a"
returns true, while test -n ""
returns false. Now, to check if a variable is not empty (which means it must be defined), you could use test -n "$var"
. However, some shell scripts have an option set (set -u
) that causes any reference to undefined variables to emit an error, so if the variable var
is not defined, the expression $a
will cause an error. To handle this case correctly, you must use variable expansion, which will tell the shell to replace the variable with an alternative string if it's not defined, avoiding the aforementioned error.
The variable expansion ${var-}
means: if the variable var
is undefined (also called "unset"), replace it with an empty string. So test -n "${var-}"
will return true if $var
is not empty, which is almost always what you want to check in shell scripts. The reverse check, if $var
is undefined or not empty, would be test -z "${var-}"
.
Now to the second use case: checking if the variable var
is defined, whether empty or not. This is a less common use case and slightly more complex, and I would advise you to read Lionels's great answer to better understand it.
What is the underlying logic you want to implement? If, for instance, you want to test for the existence of a record to determine to insert or update then a better choice would be to use MERGE instead.
If you expect the record to exist most of the time, this is probably the most efficient way of doing things (although the CASE WHEN EXISTS solution is likely to be just as efficient):
begin
select null into dummy
from sales
where sales_type = 'Accessories'
and rownum = 1;
-- do things here when record exists
....
exception
when no_data_found then
-- do things here when record doesn't exists
.....
end;
You only need the ROWNUM line if SALES_TYPE is not unique. There's no point in doing a count when all you want to know is whether at least one record exists.
Depends why you want to replace it!
Many interpreters use 'computed gotos' instead of switch statements for opcode execution.
What I miss about C/C++ switch is the Pascal 'in' and ranges. I also wish I could switch on strings. But these, while trivial for a compiler to eat, are hard work when done using structures and iterators and things. So, on the contrary, there are plenty of things I wish I could replace with a switch, if only C's switch() was more flexible!
<html>
<head>
<title>Login page</title>
</head>
<body>
<h1>Simple Login Page</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
<script language="javascript">
function check(form) { /*function to check userid & password*/
/*the following code checkes whether the entered userid and password are matching*/
if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd") {
window.open('target.html')/*opens the target page while Id & password matches*/
}
else {
alert("Error Password or Username")/*displays error message*/
}
}
</script>
</body>
</html>
It is kind of a hack but wrapping it in a timeout seems to accomplish what you are looking for:
angular.module('myApp', [])
.controller('Ctrl', ['$scope', '$timeout', function ($scope, $timeout) {
$scope.todos = [{
'text': "get milk",
'done': true
}, {
'text': "get milk2",
'done': false
}];
$scope.onCompleteTodo = function (todo) {
$timeout(function(){
console.log("onCompleteTodo -done: " + todo.done + " : " + todo.text);
$scope.doneAfterClick = todo.done;
$scope.todoText = todo.text;
});
};
}]);
GitStack should meet your goal. I has a wizard setup. It is free for 2 users and has a web based user interface. It is based on msysgit.
If you configure the SWAGGER to your spring boot application, and invoke any API from your application there you can see that CURL Request as well.
I think this is the easy way of generating the requests through the CURL.
This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.
change it to:
$(function () {
var specialElementHandlers = {
'#editor': function (element,renderer) {
return true;
}
};
$('#cmd').click(function () {
var doc = new jsPDF();
doc.fromHTML(
$('#target').html(), 15, 15,
{ 'width': 170, 'elementHandlers': specialElementHandlers },
function(){ doc.save('sample-file.pdf'); }
);
});
});
and it will work.
Specify it on the command line for javac:
javac -Xlint:unchecked
Or if you are using Ant modify your javac target
<javac ...>
<compilerarg value="-Xlint"/>
</javac>
If you are using Maven, configure this in the maven-compiler-plugin
<compilerArgument>-Xlint:unchecked</compilerArgument>
First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:
global $db;
And I guess, when you wrote:
if($result->num_rows){
return (mysqli_result($query, 0) == 1) ? true : false;
what you really wanted was:
if ($result->num_rows==1) { return true; } else { return false; }
I tried this today and typed this:
I needed to display color markers in my lists (both bullets and numbers). I came upon this tip and wrote in in my stylesheet whith mutualization of the properties:
ul,
ol {
list-style: none;
padding: 0;
margin: 0 0 0 15px;
}
ul {}
ol {
counter-reset: li;
}
li {
padding-left: 1em;
}
ul li {}
ul li::before,
ol li::before {
color: #91be3c;
display: inline-block;
width: 1em;
}
ul li::before {
content: "\25CF";
margin: 0 0.1em 0 -1.1em;
}
ol li {
counter-increment: li;
}
ol li::before {
content: counter(li);
margin: 0 0 0 -1em;
}
I chose a different character to display a bullet, watching it here. I needed to adjust the margin accoardingly, maybe the values won't apply with the font you chose (the numbers use your webfont).
You can use ORDER BY ID DESC
, but it's WAY faster if you go that way:
SELECT * FROM bugs WHERE ID = (SELECT MAX(ID) FROM bugs WHERE user = 'me')
In case that you have a huge table, it could make a significant difference.
EDIT
You can even set a variable in case you need it more than once (or if you think it is easier to read).
SELECT @bug_id := MAX(ID) FROM bugs WHERE user = 'me';
SELECT * FROM bugs WHERE ID = @bug_id;
Your other option is to initialize j
:
j = [None] * len(i)
In Project Structure in Project SDK: modify SDK to 11 or higher and in Project language level: modify to 11 - Local variable syntax for lambda parameters
I was struggling with this for some time and after some help on a post I was able to come up with this formula =(DATEVALUE(LEFT(XX,10)))+(TIMEVALUE(MID(XX,12,5)))
where XX
is the cell in reference.
I've come across many other forums with people asking the same thing and this, to me, seems to be the simplest answer. What this will do is return text that is copied in from this format 2014/11/20 11:53 EST
and turn it in to a Date/Time format so it can be sorted oldest to newest. It works with short date/long date and if you want the time just format the cell to display time and it will show. Hope this helps anyone who goes searching around like I did.
It is absolutely possible to do any merge, even non-fast forward merges, without git checkout
. The worktree
answer by @grego is a good hint. To expand on that:
cd local_repo
git worktree add _master_wt master
cd _master_wt
git pull origin master:master
git merge --no-ff -m "merging workbranch" my_work_branch
cd ..
git worktree remove _master_wt
You have now merged the local work branch to the local master
branch without switching your checkout.
./gradlew clean
Uses your project's gradle wrapper to execute your project's clean
task. Usually, this just means the deletion of the build directory.
./gradlew clean assembleDebug
Again, uses your project's gradle wrapper to execute the clean
and assembleDebug
tasks, respectively. So, it will clean first, then execute assembleDebug
, after any non-up-to-date dependent tasks.
./gradlew clean :assembleDebug
Is essentially the same as #2. The colon represents the task path. Task paths are essential in gradle multi-project's, not so much in this context. It means run the root project's assembleDebug task. Here, the root project is the only project.
Android Studio --> Build --> Clean
Is essentially the same as ./gradlew clean
. See here.
For more info, I suggest taking the time to read through the Android docs, especially this one.
You can use Vim:
vim my.jar
Vim is able to edit compressed text files, given you have unzip
in your environment.
I just tried on windows XP, it worked
local computer: sc \\. delete [service-name]
Deleting services in Windows Server 2003
We can use sc.exe in the Windows Server 2003 to control services, create services and delete services. Since some people thought they must directly modify the registry to delete a service, I would like to share how to use sc.exe to delete a service without directly modifying the registry so that decreased the possibility for system failures.
To delete a service:
Click “start“ - “run“, and then enter “cmd“ to open Microsoft Command Console.
Enter command:
sc servername delete servicename
For instance, sc \\dc delete myservice
(Note: In this example, dc is my Domain Controller Server name, which is not the local machine, myservice is the name of the service I want to delete on the DC server.)
Below is the official help of all sc functions:
DESCRIPTION:
SC is a command line program used for communicating with the
NT Service Controller and services.
USAGE:
sc
/\S/.test(string)
returns true if and only if there's a non-space character in string
. Tab and newline count as spaces.
There is a convention (not necessary) of placing jsp pages under WEB-INF directory so that they cannot be deep linked or bookmarked to. This way all requests to jsp page must be directed through our application, so that user experience is guaranteed.
You'll first require to close the file using fclose($handle);
it's not deleting because the file is in use. So first close the file and then try.
The selected answer would work for as long as you know the key itself that you want to delete but if it should be truly dynamic you would need to use the [] notation instead of the dot notation.
For example:
var keyToDelete = "key1";
var myObj = {"test": {"key1": "value", "key2": "value"}}
//that will not work.
delete myObj.test.keyToDelete
instead you would need to use:
delete myObj.test[keyToDelete];
Substitute the dot notation with [] notation for those values that you want evaluated before being deleted.
You should call .addAnnotatedClass(Message.class)
on your AnnotationConfiguration
.
If you want your entities to be auto-discovered, use EntityManager
(JPA)
Update: it appears you have listed the class in hibernate.cfg.xml. So auto-discovery is not necessary. Btw, try javax.persistence.Entity
To check where the dump.rdb has to be placed when importing redis data,
start client
$redis-cli
and
then
redis 127.0.0.1:6379> CONFIG GET *
1) "dir"
2) "/Users/Admin"
Here /Users/Admin is the location of dump.rdb that is read from server and therefore this is the file that has to be replaced.
replot
This is another way to get multiple plots at once:
plot file1.data
replot file2.data
If you want a multiplatform solution, then check QFileSystemWatcher. Here an example code (not sanitized):
from PyQt4 import QtCore
@QtCore.pyqtSlot(str)
def directory_changed(path):
print('Directory Changed!!!')
@QtCore.pyqtSlot(str)
def file_changed(path):
print('File Changed!!!')
fs_watcher = QtCore.QFileSystemWatcher(['/path/to/files_1', '/path/to/files_2', '/path/to/files_3'])
fs_watcher.connect(fs_watcher, QtCore.SIGNAL('directoryChanged(QString)'), directory_changed)
fs_watcher.connect(fs_watcher, QtCore.SIGNAL('fileChanged(QString)'), file_changed)
Try:
SELECT * FROM information_schema.statistics
WHERE table_schema = [DATABASE NAME]
AND table_name = [TABLE NAME] AND column_name = [COLUMN NAME]
It will tell you if there is an index of any kind on a certain column without the need to know the name given to the index. It will also work in a stored procedure (as opposed to show index)
SmtpClient MyMail = new SmtpClient();
MailMessage MyMsg = new MailMessage();
MyMail.Host = "mail.eraygan.com";
MyMsg.Priority = MailPriority.High;
MyMsg.To.Add(new MailAddress(Mail));
MyMsg.Subject = Subject;
MyMsg.SubjectEncoding = Encoding.UTF8;
MyMsg.IsBodyHtml = true;
MyMsg.From = new MailAddress("username", "displayname");
MyMsg.BodyEncoding = Encoding.UTF8;
MyMsg.Body = Body;
MyMail.UseDefaultCredentials = false;
NetworkCredential MyCredentials = new NetworkCredential("username", "password");
MyMail.Credentials = MyCredentials;
MyMail.Send(MyMsg);
import java.io.*;
public class DataStreamExample {
public static void main(String args[]){
try{
FileWriter fin=new FileWriter("testout.txt");
BufferedWriter d = new BufferedWriter(fin);
int a[] = new int[3];
a[0]=1;
a[1]=22;
a[2]=3;
String s="";
for(int i=0;i<3;i++)
{
s=Integer.toString(a[i]);
d.write(s);
d.newLine();
}
System.out.println("Success");
d.close();
fin.close();
FileReader in=new FileReader("testout.txt");
BufferedReader br=new BufferedReader(in);
String i="";
int sum=0;
while ((i=br.readLine())!= null)
{
sum += Integer.parseInt(i);
}
System.out.println(sum);
}catch(Exception e){System.out.println(e);}
}
}
OUTPUT:: Success 26
Also, I used array to make it simple.... you can directly take integer input and convert it into string and send it to file. input-convert-Write-Process... its that simple.
Am adding few things related to jenkins configuration files storage.
As per my understanding all config file stores in the machine or OS that you have installed jenkins.
The jobs you are going to create in jenkins will be stored in jenkins server and you can find the config.xml etc., here.
After jenkins installation you will find jenkins workspace in server.
*cd>jenkins/jobs/`
cd>jenkins/jobs/$ls
job1 job2 job3 config.xml ....*
For node_modules you have to follow the below steps
1) In Command prompt -> Goto your project directory.
2) Command :npm init
3) It asks you to set up your package.json file
4) Command: npm install
or npm update
First of all, before providing an answer I would like to be upfront about the fact that by trusting headers you are opening the door to security vulnerabilities such as phishing. So for redirection purposes, don't use values from headers without first validating the URL is authorized.
Then, your operating system hostname might not necessarily match the DNS one. In fact, one IP might have more than one DNS name. So for HTTP purposes there is no guarantee that the hostname assigned to your machine in your operating system configuration is useable.
The best choice I can think of is to obtain your HTTP listener public IP and resolve its name via DNS. See the dns.reverse
method for more info. But then, again, note that an IP might have multiple names associated with it.
One way or another you must tell boto3 in which region you wish the kms
client to be created. This could be done explicitly using the region_name
parameter as in:
kms = boto3.client('kms', region_name='us-west-2')
or you can have a default region associated with your profile in your ~/.aws/config
file as in:
[default]
region=us-west-2
or you can use an environment variable as in:
export AWS_DEFAULT_REGION=us-west-2
but you do need to tell boto3 which region to use.
Try this:
System.Windows.Forms.MessageBox.Show("Here's a message!");
As written, this question is ambigous. The statement:
... they both have the same elements, regardless of their position within the list. Each MyType object may appear multiple times on a list.
does not indicate whether you want to ensure that the two lists have the same set of objects or the same distinct set.
If you want to ensure to collections have exactly the same set of members regardless of order, you can use:
// lists should have same count of items, and set difference must be empty
var areEquivalent = (list1.Count == list2.Count) && !list1.Except(list2).Any();
If you want to ensure two collections have the same distinct set of members (where duplicates in either are ignored), you can use:
// check that [(A-B) Union (B-A)] is empty
var areEquivalent = !list1.Except(list2).Union( list2.Except(list1) ).Any();
Using the set operations (Intersect
, Union
, Except
) is more efficient than using methods like Contains
. In my opinion, it also better expresses the expectations of your query.
EDIT: Now that you've clarified your question, I can say that you want to use the first form - since duplicates matter. Here's a simple example to demonstrate that you get the result you want:
var a = new[] {1, 2, 3, 4, 4, 3, 1, 1, 2};
var b = new[] { 4, 3, 2, 3, 1, 1, 1, 4, 2 };
// result below should be true, since the two sets are equivalent...
var areEquivalent = (a.Count() == b.Count()) && !a.Except(b).Any();
@Chris Haas has explained very well how to use itextSharp
to convert HTML
to PDF
, very helpful
my add is:
By using HtmlTextWriter
I put html tags inside HTML
table + inline CSS i got my PDF as I wanted without using XMLWorker
.
Edit: adding sample code:
ASPX page:
<asp:Panel runat="server" ID="PendingOrdersPanel">
<!-- to be shown on PDF-->
<table style="border-spacing: 0;border-collapse: collapse;width:100%;display:none;" >
<tr><td><img src="abc.com/webimages/logo1.png" style="display: none;" width="230" /></td></tr>
<tr style="line-height:10px;height:10px;"><td style="display:none;font-size:9px;color:#10466E;padding:0px;text-align:right;">blablabla.</td></tr>
<tr style="line-height:10px;height:10px;"><td style="display:none;font-size:9px;color:#10466E;padding:0px;text-align:right;">blablabla.</td></tr>
<tr style="line-height:10px;height:10px;"><td style="display:none;font-size:9px;color:#10466E;padding:0px;text-align:right;">blablabla</td></tr>
<tr style="line-height:10px;height:10px;"><td style="display:none;font-size:9px;color:#10466E;padding:0px;text-align:right;">blablabla</td></tr>
<tr style="line-height:10px;height:10px;"><td style="display:none;font-size:11px;color:#10466E;padding:0px;text-align:center;"><i>blablabla</i> Pending orders report<br /></td></tr>
</table>
<asp:GridView runat="server" ID="PendingOrdersGV" RowStyle-Wrap="false" AllowPaging="true" PageSize="10" Width="100%" CssClass="Grid" AlternatingRowStyle-CssClass="alt" AutoGenerateColumns="false"
PagerStyle-CssClass="pgr" HeaderStyle-ForeColor="White" PagerStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" RowStyle-HorizontalAlign="Center" DataKeyNames="Document#"
OnPageIndexChanging="PendingOrdersGV_PageIndexChanging" OnRowDataBound="PendingOrdersGV_RowDataBound" OnRowCommand="PendingOrdersGV_RowCommand">
<EmptyDataTemplate><div style="text-align:center;">no records found</div></EmptyDataTemplate>
<Columns>
<asp:ButtonField CommandName="PendingOrders_Details" DataTextField="Document#" HeaderText="Document #" SortExpression="Document#" ItemStyle-ForeColor="Black" ItemStyle-Font-Underline="true"/>
<asp:BoundField DataField="Order#" HeaderText="order #" SortExpression="Order#"/>
<asp:BoundField DataField="Order Date" HeaderText="Order Date" SortExpression="Order Date" DataFormatString="{0:d}"></asp:BoundField>
<asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status"></asp:BoundField>
<asp:BoundField DataField="Amount" HeaderText="Amount" SortExpression="Amount" DataFormatString="{0:C2}"></asp:BoundField>
</Columns>
</asp:GridView>
</asp:Panel>
C# code:
protected void PendingOrdersPDF_Click(object sender, EventArgs e)
{
if (PendingOrdersGV.Rows.Count > 0)
{
//to allow paging=false & change style.
PendingOrdersGV.HeaderStyle.ForeColor = System.Drawing.Color.Black;
PendingOrdersGV.BorderColor = Color.Gray;
PendingOrdersGV.Font.Name = "Tahoma";
PendingOrdersGV.DataSource = clsBP.get_PendingOrders(lbl_BP_Id.Text);
PendingOrdersGV.AllowPaging = false;
PendingOrdersGV.Columns[0].Visible = false; //export won't work if there's a link in the gridview
PendingOrdersGV.DataBind();
//to PDF code --Sam
string attachment = "attachment; filename=report.pdf";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/pdf";
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
htextw.AddStyleAttribute("font-size", "8pt");
htextw.AddStyleAttribute("color", "Grey");
PendingOrdersPanel.RenderControl(htextw); //Name of the Panel
Document document = new Document();
document = new Document(PageSize.A4, 5, 5, 15, 5);
FontFactory.GetFont("Tahoma", 50, iTextSharp.text.BaseColor.BLUE);
PdfWriter.GetInstance(document, Response.OutputStream);
document.Open();
StringReader str = new StringReader(stw.ToString());
HTMLWorker htmlworker = new HTMLWorker(document);
htmlworker.Parse(str);
document.Close();
Response.Write(document);
}
}
of course include iTextSharp Refrences to cs file
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using iTextSharp.tool.xml;
Hope this helps!
Thank you
// this will give all the forms on the page.
$('form')
// If you know the name of form then.
$('form[name="myFormName"]')
// If you don't know know the name but the position (starts with 0)
$('form:eq(1)') // 2nd form will be fetched.
See the UIScreen Reference: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIScreen_Class/Reference/UIScreen.html
if([[UIScreen mainScreen] respondsToSelector:NSSelectorFromString(@"scale")])
{
if ([[UIScreen mainScreen] scale] < 1.1)
NSLog(@"Standard Resolution Device");
if ([[UIScreen mainScreen] scale] > 1.9)
NSLog(@"High Resolution Device");
}
It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.
$(".overdue").each( function() {
alert("Your book is overdue.");
});
Note that ".addClass()" works because addClass is a function defined on the jQuery object. You can't just plop any old function on the end of a selector and expect it to work.
Also, probably a bad idea to bombard the user with n popups (where n = the number of books overdue).
Perhaps use the size function:
alert( "You have " + $(".overdue").size() + " books overdue." );
I encountered this issue it turned out to be.
Project B references Project A.
Project A compiled as A.dll (assembly name = A).
Project B compiled as A.dll (assembly name A).
Visual Studio 2010 wasn't catching this. Resharper was okay, but wouldn't compile. WinForms designer gave misleading error message saying likely resulting from incompatbile platform targets.
The solution, after a painful day, was to make sure assemblies don't have same name.
Best Option to use text and image in a single view try this:
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableBottom="@drawable/ic_launcher"
android:text="TextView" />
To generalize the good answer of Mike Nakis with String.CASE_INSENSITIVE_ORDER
, you can also use :
Collator.getInstance();
See Collator
As of jQuery 1.5, there is a headers
hash you can pass in as follows:
$.ajax({
url: "/test",
headers: {"X-Test-Header": "test-value"}
});
From http://api.jquery.com/jQuery.ajax:
headers (added 1.5): A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.
single element solution:
body{_x000D_
background:blue;_x000D_
}_x000D_
_x000D_
div{_x000D_
width:40px;_x000D_
height:40px;_x000D_
background-color:red;_x000D_
position:relative;_x000D_
border-radius:6px;_x000D_
box-shadow:2px 2px 4px 0 white;_x000D_
}_x000D_
_x000D_
div:before,div:after{_x000D_
content:'';_x000D_
position:absolute;_x000D_
width:36px;_x000D_
height:4px;_x000D_
background-color:white;_x000D_
border-radius:2px;_x000D_
top:16px;_x000D_
box-shadow:0 0 2px 0 #ccc;_x000D_
}_x000D_
_x000D_
div:before{_x000D_
-webkit-transform:rotate(45deg);_x000D_
-moz-transform:rotate(45deg);_x000D_
transform:rotate(45deg);_x000D_
left:2px;_x000D_
}_x000D_
div:after{_x000D_
-webkit-transform:rotate(-45deg);_x000D_
-moz-transform:rotate(-45deg);_x000D_
transform:rotate(-45deg);_x000D_
right:2px;_x000D_
}
_x000D_
<div></div>
_x000D_
If you leave it blank the framework will try to autodetect it since version 2.0.0
.
But not in 3.0.0
, see here: config.php
You could try a different approach like read the file line by line instead of dealing with all this nl2br / explode stuff.
$fh = fopen("employees.txt", "r"); if ($fh) { while (($line = fgets($fh)) !== false) { $line = trim($line); echo "<option value='".$line."'>".$line."</option>"; } } else { // error opening the file, do something }
Also maybe just doing a trim (remove whitespace from beginning/end of string) is your issue?
And maybe people are just misunderstanding what you mean by "submitting results to a spreadsheet" -- are you doing this with code? or a copy/paste from an HTML page into a spreadsheet? Maybe you can explain that in more detail. The delimiter for which you split the lines of the file shouldn't be displaying in the output anyway unless you have unexpected output for some other reason.
You can use (this)
to reference the object that fired the function.
'this'
is a DOM element when you are inside of a callback function (in the context of jQuery), for example, being called by the click, each, bind, etc. methods.
Here is where you can learn more: http://remysharp.com/2007/04/12/jquerys-this-demystified/
window.location = url;
'url' is the web url you want to redirect.
textarea#note {
width:100%;
direction:rtl;
display:block;
max-width:100%;
line-height:1.5;
padding:15px 15px 30px;
border-radius:3px;
border:1px solid #F7E98D;
font:13px Tahoma, cursive;
transition:box-shadow 0.5s ease;
box-shadow:0 4px 6px rgba(0,0,0,0.1);
font-smoothing:subpixel-antialiased;
background:-o-linear-gradient(#F9EFAF, #F7E98D);
background:-ms-linear-gradient(#F9EFAF, #F7E98D);
background:-moz-linear-gradient(#F9EFAF, #F7E98D);
background:-webkit-linear-gradient(#F9EFAF, #F7E98D);
background:linear-gradient(#F9EFAF, #F7E98D);
height:100%;
}
html{
height:100%;
}
body{
height:100%;
}
or javascript
var s_height = document.getElementById('note').scrollHeight;
document.getElementById('note').setAttribute('style','height:'+s_height+'px');