finalName is created as:
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
</build>
One of the solutions is to add own property:
<properties>
<finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
<finalName>${finalName}</finalName>
</build>
And now try:
mvn -DfinalName=build clean package
If you want to install ASP.NET MVC 5 and ASP.NET Web API 2 into VS 2012 Ultimage so, you can download MSI installer from
http://www.microsoft.com/en-us/download/details.aspx?id=41532.
I have downloaded and intalled just know. I got MVC 5 and Web API 2
:)
Try:
output=$(ps -ef | awk '/siebsvc –s siebsrvr/ && !/awk/ { a++ } END { print a }'); echo $output
Wrapping your command in $( )
tells the shell to run that command, instead of attempting to set the command itself to the variable named "output". (Note that you could also use backticks `command`.)
I can highly recommend http://tldp.org/LDP/abs/html/commandsub.html to learn more about command substitution.
Also, as 1_CR correctly points out in a comment, the extra space between the equals sign and the assignment is causing it to fail. Here is a simple example on my machine of the behavior you are experiencing:
jed@MBP:~$ foo=$(ps -ef |head -1);echo $foo
UID PID PPID C STIME TTY TIME CMD
jed@MBP:~$ foo= $(ps -ef |head -1);echo $foo
-bash: UID: command not found
UID PID PPID C STIME TTY TIME CMD
Try putting
Display:inline;
In the CSS.
The main thread here seems to be a corrupted user account profile for the account that is used to start the DB engine. This is the account that was specified for the "SQL Server Database" engine during installation. In the setup event log, it's also indicated by the following entry:
SQLSVCACCOUNT: NT AUTHORITY\SYSTEM
According to the link provided by @royki:
The root cause of this issue, in most cases, is that the profile of the user being used for the service account (in my case it was local system) is corrupted.
This would explain why other respondents had success after changing to different accounts:
To fix the user profile that's causing the error, follow the steps listed KB947215.
The main steps from KB947215 are summarized as follows:-
regedit
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
Navigate to the SID for the corrupted profile
To find the SID, click on each SID GUID, review the value for the ProfileImagePath
value, and see if it's the correct account. For system accounts, there's a different way to know the SID for the account that failed:
The main system account SIDs of interest are:
SID Name Also Known As
S-1-5-18 Local System NT AUTHORITY\SYSTEM
S-1-5-19 LocalService NT AUTHORITY\LOCAL SERVICE
S-1-5-20 NetworkService NT AUTHORITY\NETWORK SERVICE
For information on additional SIDs, see Well-known security identifiers in Windows operating systems.
RefCount
and State
to be 0
.Integer.decode
You can also use public static Integer decode(String nm) throws NumberFormatException
.
It also works for base 8 and 16:
// base 10
Integer.parseInt("12"); // 12 - int
Integer.valueOf("12"); // 12 - Integer
Integer.decode("12"); // 12 - Integer
// base 8
// 10 (0,1,...,7,10,11,12)
Integer.parseInt("12", 8); // 10 - int
Integer.valueOf("12", 8); // 10 - Integer
Integer.decode("012"); // 10 - Integer
// base 16
// 18 (0,1,...,F,10,11,12)
Integer.parseInt("12",16); // 18 - int
Integer.valueOf("12",16); // 18 - Integer
Integer.decode("#12"); // 18 - Integer
Integer.decode("0x12"); // 18 - Integer
Integer.decode("0X12"); // 18 - Integer
// base 2
Integer.parseInt("11",2); // 3 - int
Integer.valueOf("11",2); // 3 - Integer
If you want to get int
instead of Integer
you can use:
Unboxing:
int val = Integer.decode("12");
intValue()
:
Integer.decode("12").intValue();
You can create your jar without Main-Class in its Manifest file. Then :
java -cp MyJar.jar com.mycomp.myproj.dir2.MainClass2 /home/myhome/datasource.properties /home/myhome/input.txt
There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn't shrink or expand the window. Two, if the frame is a container for other widget, turn grid or pack propagation off so that the frame doesn't shrink or expand to fit its own contents.
Note, however, that this won't prevent you from resizing a window to be smaller than an internal frame. In that case the frame will just be clipped.
import Tkinter as tk
root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")
frame1.pack(fill=None, expand=False)
frame2.place(relx=.5, rely=.5, anchor="c")
root.mainloop()
Based on the solution of Édouard Lopez, but in two lines:
import jQuery from "jquery";
window.$ = window.jQuery = jQuery;
There is a third option: the x command, which allows you to set a different limit for the specific command instead of changing a global setting. To print the first 300 characters of a string you can use x/300s your_string
. The output might be a bit harder to read. For example printing a SQL query results in:
(gdb) x/300sb stmt.c_str() 0x9cd948: "SELECT article.r"... 0x9cd958: "owid FROM articl"... ..
File permissions are restrictive on the Postgres db owned by the Mac OS. These permissions are reset after reboot, or restart of Postgres: e.g. serveradmin start postgres.
So, temporarily reset the permissions or ownership:
sudo chmod o+rwx /var/pgsql_socket/.s.PGSQL.5432
sudo chown "webUser" /var/pgsql_socket/.s.PGSQL.5432
Permissions resetting is not secure, so install a version of the db that you own for a solution.
Just in case someone still needs it. The successful, not official, way to rename indexes are:
If you happen to get this error "dangled index directory name is", remove index folder in all master nodes (not data nodes), and restart one of the data nodes.
I'm particularly fond of this date picker built for Mootools: http://electricprism.com/aeron/calendar/
It's lovely right out of the box.
There seems to be multiple modules to do that, some are deprecated.
This one looks active:
https://github.com/jshttp/basic-auth
Here's a use example:
// auth.js
var auth = require('basic-auth');
var admins = {
'[email protected]': { password: 'pa$$w0rd!' },
};
module.exports = function(req, res, next) {
var user = auth(req);
if (!user || !admins[user.name] || admins[user.name].password !== user.pass) {
res.set('WWW-Authenticate', 'Basic realm="example"');
return res.status(401).send();
}
return next();
};
// app.js
var auth = require('./auth');
var express = require('express');
var app = express();
// ... some not authenticated middlewares
app.use(auth);
// ... some authenticated middlewares
Make sure you put the auth
middleware in the correct place, any middleware before that will not be authenticated.
Step 1: Do File
-> Import Settings...
and select the settings jar
file
Step 2: Go to Settings
-> Editor
-> Colors and Fonts
to choose the theme you just installed.
In addition from the command prompt run SET.
This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).
Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.
[::-1] gives a slice of the string a. the full syntax is a[begin:end:step]
which gives a[begin], a[begin+step], ... a[end-1]. WHen step is negative, you start at end and move to begin.
Finally, begin defaults to the beginning of the sequence, end to the end, and step to -1.
With the devel version of tidyr
‘0.8.3.9000’
, there is pivot_wider
and pivot_longer
which is generalized to do the reshaping (long -> wide, wide -> long, respectively) from 1 to multiple columns. Using the OP's data
-single column long -> wide
library(dplyr)
library(tidyr)
dat1 %>%
pivot_wider(names_from = numbers, values_from = value)
# A tibble: 2 x 5
# name `1` `2` `3` `4`
# <fct> <dbl> <dbl> <dbl> <dbl>
#1 firstName 0.341 -0.703 -0.380 -0.746
#2 secondName -0.898 -0.335 -0.501 -0.175
-> created another column for showing the functionality
dat1 %>%
mutate(value2 = value * 2) %>%
pivot_wider(names_from = numbers, values_from = c("value", "value2"))
# A tibble: 2 x 9
# name value_1 value_2 value_3 value_4 value2_1 value2_2 value2_3 value2_4
# <fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 firstName 0.341 -0.703 -0.380 -0.746 0.682 -1.41 -0.759 -1.49
#2 secondName -0.898 -0.335 -0.501 -0.175 -1.80 -0.670 -1.00 -0.349
You can handle the error appropriately when it propagates back to the calling program (or ignore it if that's what you want). In C# any errors that occur in SQL will throw an exception that I can catch and then handle in my code, just like any other error.
I agree with Beska in that you do not want to hide the error. You may not be dealing with a nuclear reactor but hiding errors in general is bad programming practice. This is one of the reasons most modern programming languages implement structured exception handling to decouple the actual return value with an error / status code. This is especially true when you are doing math. The biggest problem is that you cannot distinguish between a correctly computed 0 being returned or a 0 as the result of an error. Instead any value returned is the computed value and if anything goes wrong an exception is thrown. This will of course differ depending on how you are accessing the database and what language you are using but you should always be able to get an error message that you can deal with.
try
{
Database.ComputePercentage();
}
catch (SqlException e)
{
// now you can handle the exception or at least log that the exception was thrown if you choose not to handle it
// Exception Details: System.Data.SqlClient.SqlException: Divide by zero error encountered.
}
I use backgroundrb.
http://backgroundrb.rubyforge.org/
I use it to run scheduled tasks as well as tasks that take too long for the normal client/server relationship.
With PowerShell 5.1 (PackageManagement module)
Install-Package -Name MyPackage -Source (Get-Location).Path -Destination C:\outputdirectory
This is a quick way to do that, I mean.
It does not use an expensive regex function. It also does not use multiple replacement functions that each individually did loop over the data with several checks, allocations, etc.
So the search is done directly in one for
loop. For the number of times that the capacity of the result array has to be increased, a loop is also used within the Array.Copy
function. That are all the loops.
In some cases, a larger page size might be more efficient.
public static string NormalizeNewLine(this string val)
{
if (string.IsNullOrEmpty(val))
return val;
const int page = 6;
int a = page;
int j = 0;
int len = val.Length;
char[] res = new char[len];
for (int i = 0; i < len; i++)
{
char ch = val[i];
if (ch == '\r')
{
int ni = i + 1;
if (ni < len && val[ni] == '\n')
{
res[j++] = '\r';
res[j++] = '\n';
i++;
}
else
{
if (a == page) // Ensure capacity
{
char[] nres = new char[res.Length + page];
Array.Copy(res, 0, nres, 0, res.Length);
res = nres;
a = 0;
}
res[j++] = '\r';
res[j++] = '\n';
a++;
}
}
else if (ch == '\n')
{
int ni = i + 1;
if (ni < len && val[ni] == '\r')
{
res[j++] = '\r';
res[j++] = '\n';
i++;
}
else
{
if (a == page) // Ensure capacity
{
char[] nres = new char[res.Length + page];
Array.Copy(res, 0, nres, 0, res.Length);
res = nres;
a = 0;
}
res[j++] = '\r';
res[j++] = '\n';
a++;
}
}
else
{
res[j++] = ch;
}
}
return new string(res, 0, j);
}
I now that '\n\r' is not actually used on basic platforms. But who would use two types of linebreaks in succession to indicate two linebreaks?
If you want to know that, then you need to take a look before to know if the \n and \r both are used separately in the same document.
You need to make an additional group of data for each color group that represent the Y values for that particular group. You can use these groups to make multiple data sets within your graph.
Here is an example using your data:
A B C D E F G
----------------------------------------------------------------------------------------------------------------------
1| COMPANY XVALUE YVALUE GROUP Red Orange Green
2| Apple 45 35 red =IF($D2="red",$C2,NA()) =IF($D2="orange",$C2,NA()) =IF($D2="green",$C2,NA())
3| Xerox 45 38 red =IF($D3="red",$C3,NA()) =IF($D3="orange",$C3,NA()) =IF($D3="green",$C3,NA())
4| KMart 63 50 orange =IF($D4="red",$C4,NA()) =IF($D4="orange",$C4,NA()) =IF($D4="green",$C4,NA())
5| Exxon 53 59 green =IF($D5="red",$C5,NA()) =IF($D5="orange",$C5,NA()) =IF($D5="green",$C5,NA())
It should look like this afterwards:
A B C D E F G
---------------------------------------------------------------------
1| COMPANY XVALUE YVALUE GROUP Red Orange Green
2| Apple 45 35 red 35 #N/A #N/A
3| Xerox 45 38 red 38 #N/A #N/A
4| KMart 63 50 orange #N/A 50 #N/A
5| Exxon 53 59 green #N/a #N/A 59
Now you can generate your graph using different data sets. Here is a picture showing just this example data:
You can change the series (X;Y)
values to B:B ; E:E
, B:B ; F:F
, B:B ; G:G
respectively, to make it so the graph is automatically updated when you add more data.
user1462299's response works great, but if you include fragments, they will use the original activities theme. To apply the theme to all fragments as well you can override the getTheme() method of the Context instead:
@Override
public Resources.Theme getTheme() {
Resources.Theme theme = super.getTheme();
if(useAlternativeTheme){
theme.applyStyle(R.style.AlternativeTheme, true);
}
// you could also use a switch if you have many themes that could apply
return theme;
}
You do not need to call setTheme() in the onCreate() Method anymore. You are overriding every request to get the current theme within this context this way.
ginalx's answer should be set as the default one imo: this method allows for many optimizations.
The problem
Say that we have a list of items and on every item we want to include a menu that needs to be toggled. We include a toggle on a button that listens for a click
event on itself (click)="toggle()"
, but we also want to toggle the menu whenever the user clicks outside of it. If the list of items grows and we attach a @HostListener('document:click')
on every menu, then every menu loaded within the item will start listening for the click on the entire document, even when the menu is toggled off. Besides the obvious performance issues, this is unnecessary.
You can, for example, subscribe whenever the popup gets toggled via a click and start listening for "outside clicks" only then.
isActive: boolean = false;
// to prevent memory leaks and improve efficiency, the menu
// gets loaded only when the toggle gets clicked
private _toggleMenuSubject$: BehaviorSubject<boolean>;
private _toggleMenu$: Observable<boolean>;
private _toggleMenuSub: Subscription;
private _clickSub: Subscription = null;
constructor(
...
private _utilitiesService: UtilitiesService,
private _elementRef: ElementRef,
){
...
this._toggleMenuSubject$ = new BehaviorSubject(false);
this._toggleMenu$ = this._toggleMenuSubject$.asObservable();
}
ngOnInit() {
this._toggleMenuSub = this._toggleMenu$.pipe(
tap(isActive => {
logger.debug('Label Menu is active', isActive)
this.isActive = isActive;
// subscribe to the click event only if the menu is Active
// otherwise unsubscribe and save memory
if(isActive === true){
this._clickSub = this._utilitiesService.documentClickedTarget
.subscribe(target => this._documentClickListener(target));
}else if(isActive === false && this._clickSub !== null){
this._clickSub.unsubscribe();
}
}),
// other observable logic
...
).subscribe();
}
toggle() {
this._toggleMenuSubject$.next(!this.isActive);
}
private _documentClickListener(targetElement: HTMLElement): void {
const clickedInside = this._elementRef.nativeElement.contains(targetElement);
if (!clickedInside) {
this._toggleMenuSubject$.next(false);
}
}
ngOnDestroy(){
this._toggleMenuSub.unsubscribe();
}
And, in *.component.html
:
<button (click)="toggle()">Toggle the menu</button>
I do it with boolean = !boolean;
I've come up with an awkward but functional solution for my problem. It works for a one-dimensional array (more dimensions would be tricky) and input that fits into a varchar
:
declare pos int; -- Keeping track of the next item's position
declare item varchar(100); -- A single item of the input
declare breaker int; -- Safeguard for while loop
-- The string must end with the delimiter
if right(inputString, 1) <> '|' then
set inputString = concat(inputString, '|');
end if;
DROP TABLE IF EXISTS MyTemporaryTable;
CREATE TEMPORARY TABLE MyTemporaryTable ( columnName varchar(100) );
set breaker = 0;
while (breaker < 2000) && (length(inputString) > 1) do
-- Iterate looking for the delimiter, add rows to temporary table.
set breaker = breaker + 1;
set pos = INSTR(inputString, '|');
set item = LEFT(inputString, pos - 1);
set inputString = substring(inputString, pos + 1);
insert into MyTemporaryTable values(item);
end while;
For example, input for this code could be the string Apple|Banana|Orange
. MyTemporaryTable
will be populated with three rows containing the strings Apple
, Banana
, and Orange
respectively.
I thought the slow speed of string handling would render this approach useless, but it was quick enough (only a fraction of a second for a 1,000 entries array).
Hope this helps somebody.
Create a new list and add a sublist view of the source list using the addAll()
method to create a new sublist
List<T> newList = new ArrayList<T>();
newList.addAll(sourceList.subList(startIndex, endIndex));
You can solve it by following code
@font-face {
font-family: 'Font-Name';
src: url('../fonts/Font-Name.ttf');
src: url('../fonts/Font-Name.eot?#iefix') format('embedded-opentype');
}
To toggle ascending and descending, I use a method in my app's BasePage to cache the sort expression and sort direction:
protected void SetPageSort(GridViewSortEventArgs e)
{
if (e.SortExpression == SortExpression)
{
if (SortDirection == "ASC")
{
SortDirection = "DESC";
}
else
{
SortDirection = "ASC";
}
}
else
{
SortDirection = "ASC";
SortExpression = e.SortExpression;
}
}
SortExpression and SortDirection are both properties in BasePage that store and retrieve their values from ViewState.
So all of my derived pages just call SetPageSort from the GridView's Sorting method, and bind the GridView:
protected void gv_Sorting(object sender, GridViewSortEventArgs e)
{
SetPageSort(e);
BindGrid();
}
BindGrid checks the SortExpression and uses it and SortDirection to do an ORDERY BY on the grid's data source, something like this:
if (SortExpression.Length > 0)
{
qry.ORDER_BY(SortExpression + " " + SortDirection);
}
gv.DataSource = qry.ExecuteReader();
gv.DataBind();
So, the base class' SetPageSort removes much of the drudgery of GridView sorting. I feel like I'm forgetting something, but that's the general idea.
public static void Each<T>(this IEnumerable<T> items, Action<T> action) {
foreach (var item in items) {
action(item);
} }
... and call it thusly:
myList.Each(x => { x.Enabled = false; });
For xcode 8.3.3 I just checked tried the above code and observe that, now in this casewe have to change the commands to like this
first you can create a .gitignore file by using
touch .gitignore
after that you can delete all the userInterface file by using this command and by using this command it will respect your .gitignore file.
git rm --cached [project].xcworkspace/xcuserdata/[username].xcuserdatad/UserInterfaceState.xcuserstate
git commit -m "Removed file that shouldn't be tracked"
This is what I use (extracted from a lot of different questions/answers):
nnoremap <silent> <Esc><Esc> :let @/=""<CR>
With "double" Esc you remove the highlighting, but as soon as you search again, the highlighting reappears.
Another alternative:
nnoremap <silent> <Esc><Esc> :noh<CR> :call clearmatches()<CR>
According to vim documentation:
clearmatches()
Clears all matches previously defined by |matchadd()| and the |:match| commands.
l = [4,76,2,8,6,4,3,7,2,1]
l = l[:5]
Assuming you know the size of your footer, you can do this:
footer {
position: sticky;
height: 100px;
top: calc( 100vh - 100px );
}
You need to install Visual Studio Tools for Office Runtime Redistributable:
1.Export a Secret Key (this is what your boss should have done for you)
gpg --export-secret-keys yourKeyName > privateKey.asc
2.Import Secret Key (import your privateKey)
gpg --import privateKey.asc
3.Not done yet, you still need to ultimately trust a key. You will need to make sure that you also ultimately trust a key.
gpg --edit-key yourKeyName
Enter trust, 5, y, and then quit
Source: https://medium.com/@GalarnykMichael/public-key-asymmetric-cryptography-using-gpg-5a8d914c9bca
You will find de log4j.properties in solr/examples/resources.
If you don't find the file, i put it here:
# Logging level
solr.log=logs/
log4j.rootLogger=INFO, file, CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x \u2013 %m%n
#- size rotation with log cleanup.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.MaxFileSize=4MB
log4j.appender.file.MaxBackupIndex=9
#- File to log to and log format
log4j.appender.file.File=${solr.log}/solr.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS}; %C; %m\n
log4j.logger.org.apache.zookeeper=WARN
log4j.logger.org.apache.hadoop=WARN
# set to INFO to enable infostream log messages
log4j.logger.org.apache.solr.update.LoggingInfoStream=OFF
Regards
Hi if you are using react-router v-6.0.0-beta or V6 in This version Redirect Changes to Navigate like this
import { Navigate } from 'react-router-dom'; // like this CORRECT in v6 import { Redirect } from 'react-router-dom'; // like this CORRECT in v5
import { Redirect } from 'react-router-dom'; // like this WRONG in v6 // This will give you error in V6 of react-router and react-router dom
please make sure use both same version in package.json { "react-router": "^6.0.0-beta.0", //Like this "react-router-dom": "^6.0.0-beta.0", // like this }
this above things only works well in react Router Version 6
If you know in advance the position in the file (rather the line number), you can use file.seek() to go to that position.
Edit: you can use the linecache.getline(filename, lineno) function, which will return the contents of the line lineno, but only after reading the entire file into memory. Good if you're randomly accessing lines from within the file (as python itself might want to do to print a traceback) but not good for a 15MB file.
I thinks it is vary helpful way.
models.py
from django.db import models
class User(models.Model):
user_name = models.CharField(max_length=100)
password = models.CharField(max_length=32)
forms.py
from django import forms
from Admin.models import *
class User_forms(forms.ModelForm):
class Meta:
model= User
fields=[
'user_name',
'password'
]
widgets = {
'password': forms.PasswordInput()
}
Flask applications can optionally be executed in debug mode. In this mode, two very convenient modules of the development server called the reloader and the debugger are enabled by default. When the reloader is enabled, Flask watches all the source code files of your project and automatically restarts the server when any of the files are modified.
By default, debug mode is disabled. To enable it, set a FLASK_DEBUG=1
environment variable before invoking flask run
:
(venv) $ export FLASK_APP=hello.py for Windows use > set FLASK_APP=hello.py
(venv) $ export FLASK_DEBUG=1 for Windows use > set FLASK_DEBUG=1
(venv) $ flask run
* Serving Flask app "hello"
* Forcing debug mode on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 273-181-528
Having a server running with the reloader enabled is extremely useful during development, because every time you modify and save a source file, the server automatically restarts and picks up the change.
So far I found this is a good and quick solution
//CPID[] is the array
string cps = "";
if (CPID.Length > 0)
{
foreach (var item in CPID)
{
cps += item.Trim() + ",";
}
}
//Use the string cps
Bitmap memoryImage;
//Set full width, height for image
memoryImage = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height,
PixelFormat.Format32bppArgb);
Size s = new Size(memoryImage.Width, memoryImage.Height);
Graphics memoryGraphics = Graphics.FromImage(memoryImage);
memoryGraphics.CopyFromScreen(0, 0, 0, 0, s);
string str = "";
try
{
str = string.Format(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
@"\Screenshot.png");//Set folder to save image
}
catch { };
memoryImage.save(str);
With the latest version of dotnet cli (2.1.400 or greater), you can just set this msbuild property $(EnvironmentName)
and publish tooling will take care of adding ASPNETCORE_ENVIRONMENT to the web.config with the environment name.
Also, XDT support is available starting 2.2.100-preview1.
Sample: https://github.com/vijayrkn/webconfigtransform/blob/master/README.md
Do it like this...
if (!Array.prototype.indexOf) {
}
As recommended compatibility by MDC.
In general, browser detection code is a big no-no.
I wanted a solution that didn't involve looping over every single item and doing if
s. Here's a solution that is just a simple recursive function over Get-ChildItem
. We just loop and recurse over directories.
function Get-RecurseItem {
[Cmdletbinding()]
param (
[Parameter(ValueFromPipeline=$true)][string]$Path,
[string[]]$Exclude = @(),
[string]$Include = '*'
)
Get-ChildItem -Path (Join-Path $Path '*') -Exclude $Exclude -Directory | ForEach-Object {
@(Get-ChildItem -Path (Join-Path $_ '*') -Include $Include -Exclude $Exclude -File) + ``
@(Get-RecurseItem -Path $_ -Include $Include -Exclude $Exclude)
}
}
If I feel that useful information is being imparted, why shouldn't I put it right there where it's available?
Then who cares what anybody else thinks? If you find it useful, then use the notation.
Aditya or others, can you join or match up t2 with t1 in your example, i.e. translated to my code,
with t1 as (select * from AA where FIRSTNAME like 'Kermit'),
t2 as (select * from BB B join t1 on t1.FIELD1 = B.FIELD1)
I am not clear whether only WHERE is supported for joining, or what joining approach is supported within the 2nd WITH entity. Some of the examples have the WHERE A=B down in the body of the select "below" the WITH clauses.
The error I'm getting following these WITH declarations is the identifiers (field names) in B are not recognized, down in the body of the rest of the SQL. So the WITH syntax seems to run OK, but cannot access the results from t2.
I recently came across a similar issue. I found simply reading the data in chunks and appending it as I write it in chunks to the same csv works well. My problem was adding a date column based on information in another table, using the value of certain columns as follows. This may help those confused by dask and hdf5 but more familiar with pandas like myself.
def addDateColumn():
"""Adds time to the daily rainfall data. Reads the csv as chunks of 100k
rows at a time and outputs them, appending as needed, to a single csv.
Uses the column of the raster names to get the date.
"""
df = pd.read_csv(pathlist[1]+"CHIRPS_tanz.csv", iterator=True,
chunksize=100000) #read csv file as 100k chunks
'''Do some stuff'''
count = 1 #for indexing item in time list
for chunk in df: #for each 100k rows
newtime = [] #empty list to append repeating times for different rows
toiterate = chunk[chunk.columns[2]] #ID of raster nums to base time
while count <= toiterate.max():
for i in toiterate:
if i ==count:
newtime.append(newyears[count])
count+=1
print "Finished", str(chunknum), "chunks"
chunk["time"] = newtime #create new column in dataframe based on time
outname = "CHIRPS_tanz_time2.csv"
#append each output to same csv, using no header
chunk.to_csv(pathlist[2]+outname, mode='a', header=None, index=None)
Quite a bit:
The rank of a row is one plus the number of ranks that come before the row in question.
Row_number is the distinct rank of rows, without any gap in the ranking.
Why use java.awt.Robot when org.openqa.selenium.interactions.Actions.class would probably work fine? Just sayin.
Actions builder = new Actions(driver);
builder.keyDown(Keys.CONTROL)
.click(someElement)
.moveByOffset( 10, 25 );
.click(someOtherElement)
.keyUp(Keys.CONTROL).build().perform();
Just declare the enum outside the bounds of the class. Like this:
public enum card_suits
{
Clubs,
Hearts,
Spades,
Diamonds
}
public class Card
{
...
}
Remember that an enum is a type. You might also consider putting the enum in its own file if it's going to be used by other classes. (You're programming a card game and the suit is a very important attribute of the card that, in well-structured code, will need to be accessible by a number of classes.)
For MSSQL Server 2012
CREATE TABLE usrgroup(
usr_id int FOREIGN KEY REFERENCES users(id),
grp_id int FOREIGN KEY REFERENCES groups(id),
PRIMARY KEY (usr_id, grp_id)
)
UPDATE
I should add !
If you want to add foreign / primary keys altering, firstly you should create the keys with constraints or you can not make changes. Like this below:
CREATE TABLE usrgroup(
usr_id int,
grp_id int,
CONSTRAINT FK_usrgroup_usrid FOREIGN KEY (usr_id) REFERENCES users(id),
CONSTRAINT FK_usrgroup_groupid FOREIGN KEY (grp_id) REFERENCES groups(id),
CONSTRAINT PK_usrgroup PRIMARY KEY (usr_id,grp_id)
)
Actually last way is healthier and serial. You can look the FK/PK Constraint names (dbo.dbname > Keys > ..) but if you do not use a constraint, MSSQL auto-creates random FK/PK names. You will need to look at every change (alter table) you need.
I recommend that you set a standard for yourself; the constraint should be defined according to the your standard. You will not have to memorize and you will not have to think too long. In short, you work faster.
When you set a string variable, it doesn't save quotes of it, they are a part of its definition. so you don't need to use :1
Procedure successful but any outpout
Error line1: Unexpected identifier
Here is the code:
SET SERVEROUTPUT ON
DECLARE
-- Curseurs
CURSOR c1 IS
SELECT RWID FROM J_EVT
WHERE DT_SYST < TO_DATE(TO_CHAR(SYSDATE,'DD/MM') || '/' || TO_CHAR(TO_NUMBER(TO_CHAR(SYSDATE, 'YYYY')) - 3));
-- Collections
TYPE tc1 IS TABLE OF c1%RWTYPE;
-- Variables de type record
rtc1 tc1;
vCpt NUMBER:=0;
BEGIN
OPEN c1;
LOOP
FETCH c1 BULK COLLECT INTO rtc1 LIMIT 5000;
FORALL i IN 1..rtc1.COUNT
DELETE FROM J_EVT
WHERE RWID = rtc1(i).RWID;
COMMIT;
-- Nombres lus : 5025651
FOR i IN 1..rtc1.COUNT LOOP
vCpt := vCpt + SQL%BULK_RWCOUNT(i);
END LOOP;
EXIT WHEN c1%NOTFOUND;
END LOOP;
CLOSE c1;
COMMIT;
DBMS_OUTPUT.PUT_LINE ('Nombres supprimes : ' || TO_CHAR(vCpt));
END;
/
exit
It seems that you catch not the exception you wanna catch out there :)
if the s
is a socket.socket()
object, then the right way to call .connect
would be:
import socket
s = socket.socket()
address = '127.0.0.1'
port = 80 # port number is a number, not string
try:
s.connect((address, port))
# originally, it was
# except Exception, e:
# but this syntax is not supported anymore.
except Exception as e:
print("something's wrong with %s:%d. Exception is %s" % (address, port, e))
finally:
s.close()
Always try to see what kind of exception is what you're catching in a try-except loop.
You can check what types of exceptions in a socket module represent what kind of errors (timeout, unable to resolve address, etc) and make separate except
statement for each one of them - this way you'll be able to react differently for different kind of problems.
I suspect because of modules, which remove the need for the #import <Cocoa/Cocoa.h>
.
As to where to put code that you would put in a prefix header, there is no code you should put in a prefix header. Put your imports into the files that need them. Put your definitions into their own files. Put your macros...nowhere. Stop writing macros unless there is no other way (such as when you need __FILE__
). If you do need macros, put them in a header and include it.
The prefix header was necessary for things that are huge and used by nearly everything in the whole system (like Foundation.h
). If you have something that huge and ubiquitous, you should rethink your architecture. Prefix headers make code reuse hard, and introduce subtle build problems if any of the files listed can change. Avoid them until you have a serious build time problem that you can demonstrate is dramatically improved with a prefix header.
In that case you can create one and pass it into clang, but it's incredibly rare that it's a good idea.
EDIT: To your specific question about a HUD you use in all your view controllers, yes, you should absolutely import it into every view controller that actually uses it. This makes the dependencies clear. When you reuse your view controller in a new project (which is common if you build your controllers well), you will immediately know what it requires. This is especially important for categories, which can make code very hard to reuse if they're implicit.
The PCH file isn't there to get rid of listing dependencies. You should still import UIKit.h
or Foundation.h
as needed, as the Xcode templates do. The reason for the PCH is to improve build times when dealing with really massive headers (like in UIKit).
public async Task<ActionResult> Index()
{
apiTable table = new apiTable();
table.Name = "Asma Nadeem";
table.Roll = "6655";
string str = "";
string str2 = "";
HttpClient client = new HttpClient();
string json = JsonConvert.SerializeObject(table);
StringContent httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://YourSite.com/api/apiTables", httpContent);
str = "" + response.Content + " : " + response.StatusCode;
if (response.IsSuccessStatusCode)
{
str2 = "Data Posted";
}
return View();
}
1) do
svn revert . --recursive
2) parse output for errors like
"Failed to revert 'dir1/dir2' -- try updating instead."
3) call svn up for each of error directories:
svn up dir1/dir2
Guid.NewGuid()
, as it creates GUIDs as intended.
Guid.NewGuid()
creates an empty Guid
object, initializes it by calling CoCreateGuid
and returns the object.
new Guid()
merely creates an empty GUID (all zeros, I think).
I guess they had to make the constructor public as Guid
is a struct
.
I'm quite ashamed that there are so many incorrect or undisclosed partial applicability.
The easiest way to do this is through Chrome or Opera (my examples will use Chrome) using the Console. Enter the following code into the console (generally in 1 line):
var l = document.getElementById('testLink');
for(var i=0; i<5; i++){
l.click();
}
This will generate the required result
On a vanilla Apache2 install in CentOS, when you install mod_ssl it will automatically add a configuration file in:
{apache_dir}/conf.d/ssl.conf
This configuration file contains a default virtual host definition for port 443, named default:443. If you also have your own virtual host definition for 443 (i.e. in httpd.conf) then you will have a confict. Since the conf.d files are included first, they will win over yours.
To solve the conflict you can either remove the virtual host definition from conf.d/ssl.conf
or update it to your own settings.
In case you're wondering about the performance of the different approaches, here are some timings:
In [1]: words = [str(i) for i in range(10000)]
In [2]: %timeit replaced = [w.replace('1', '<1>') for w in words]
100 loops, best of 3: 2.98 ms per loop
In [3]: %timeit replaced = map(lambda x: str.replace(x, '1', '<1>'), words)
100 loops, best of 3: 5.09 ms per loop
In [4]: %timeit replaced = map(lambda x: x.replace('1', '<1>'), words)
100 loops, best of 3: 4.39 ms per loop
In [5]: import re
In [6]: r = re.compile('1')
In [7]: %timeit replaced = [r.sub('<1>', w) for w in words]
100 loops, best of 3: 6.15 ms per loop
as you can see for such simple patterns the accepted list comprehension is the fastest, but look at the following:
In [8]: %timeit replaced = [w.replace('1', '<1>').replace('324', '<324>').replace('567', '<567>') for w in words]
100 loops, best of 3: 8.25 ms per loop
In [9]: r = re.compile('(1|324|567)')
In [10]: %timeit replaced = [r.sub('<\1>', w) for w in words]
100 loops, best of 3: 7.87 ms per loop
This shows that for more complicated substitutions a pre-compiled reg-exp (as in 9-10
) can be (much) faster. It really depends on your problem and the shortest part of the reg-exp.
Another approach is to (ab)use the PostgreSQL GUC mechanism to create variables. See this prior answer for details and examples.
You declare the GUC in postgresql.conf
, then change its value at runtime with SET
commands and get its value with current_setting(...)
.
I don't recommend this for general use, but it could be useful in narrow cases like the one mentioned in the linked question, where the poster wanted a way to provide the application-level username to triggers and functions.
Here is a simple way using ExtractToDirectory from System.IO.Compression.ZipFile:
Add-Type -AssemblyName System.IO.Compression.FileSystem
function Unzip
{
param([string]$zipfile, [string]$outpath)
[System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)
}
Unzip "C:\a.zip" "C:\a"
Note that if the target folder doesn't exist, ExtractToDirectory will create it. Other caveats:
See also:
Change your code to:
int total=0, number=0;
float percentage=0.0f;
percentage=((float)number/total)*100f;
printf("%.2f", (double)percentage);
To create a label for text:
JLabel label1 = new JLabel("Test");
To change the text in the label:
label1.setText("Label Text");
And finally to clear the label:
label1.setText("");
And all you have to do is place the label in your layout, or whatever layout system you are using, and then just add it to the JFrame...
You could use the substr
function to return a substring starting from the 5th character:
$str = "The quick brown fox jumps over the lazy dog."
$str2 = substr($str, 4); // "quick brown fox jumps over the lazy dog."
update mytable set online_status = 'online'
If you want to assign different values, you should use the TRANSACTION technique.
For checking if a string contains whitespace use a Matcher
and call it's find method.
Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();
If you want to check if it only consists of whitespace then you can use String.matches
:
boolean isWhitespace = s.matches("^\\s*$");
The 32-bit vs 64-bit difference does become more important when you are interfacing with native libraries. 64-bit Java will not be able to interface with a 32-bit non-Java dll (via JNI)
Finally this is for Hibernate 5
in Tomcat
.
Compiled all the answers from the above and added my tips which works like a charm for Hibernate 5 and SQL Server 2014
.
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.SQLServerDialect
</property>
<property name="hibernate.connection.driver_class">
com.microsoft.sqlserver.jdbc.SQLServerDriver
</property>
<property name="hibernate.connection.url">
jdbc:sqlserver://localhost\ServerInstanceOrServerName:1433;databaseName=DATABASE_NAME
</property>
<property name="hibernate.default_schema">theSchemaNameUsuallydbo</property>
<property name="hibernate.connection.username">
YourUsername
</property>
<property name="hibernate.connection.password">
YourPasswordForMSSQL
</property>
You should use ContextWrapper like this:
ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("media", Context.MODE_PRIVATE);
As always, refer to documentation, ContextWrapper has a lot to offer.
As the accepted answer requires you to add a Frame Layout, here how you can do it with material design.
Add this if you haven't already
implementation 'com.google.android.material:material:1.0.0'
Now change to Cardview to MaterialCardView
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:cardCornerRadius="8dp"
app:cardElevation="2dp"
app:strokeWidth="1dp"
app:strokeColor="@color/black">
Now you need to change the activity theme to Theme.Material. If you are using Theme.Appcompact I will suggest you to move to Theme.Material for future projects for having better material design in you app.
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
I'm using jupyter_core-4.4.0
& jupyter notebook.
![Screen%20Shot%202019-08-06%20at%201.48.10%20PM.png](attachment:Screen%20Shot%202019-08-06%20at%201.48.10%20PM.png)
attachment
links don't work:<img src="attachment:Screen%20Shot%202019-08-06%20at%201.48.10%20PM.png" width="500"/>
Just add div brackets.
<div>
<img src="attachment:Screen%20Shot%202019-08-06%20at%201.48.10%20PM.png" width="500"/>
</div>
Hope this helps!
Implementing Comparable
means "I can compare myself with another object." This is typically useful when there's a single natural default comparison.
Implementing Comparator
means "I can compare two other objects." This is typically useful when there are multiple ways of comparing two instances of a type - e.g. you could compare people by age, name etc.
I use below in my MR project.
<exclusions>
<exclusion>
<artifactId>jdk.tools</artifactId>
<groupId>jdk.tools</groupId>
</exclusion>
</exclusions>
In addition to others' answers :
static:: will be computed using runtime information.
That means you can't use static::
in a class property because properties values :
Must be able to be evaluated at compile time and must not depend on run-time information.
class Foo {
public $name = static::class;
}
$Foo = new Foo;
echo $Foo->name; // Fatal error
Using self::
class Foo {
public $name = self::class;
}
$Foo = new Foo;
echo $Foo->name; // Foo
Please note that the Fatal error comment in the code i made doesn't indicate where the error happened, the error happened earlier before the object was instantiated as @Grapestain mentioned in the comments
The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
index.php
<html>
<body>
<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
site2.php
<html>
<body>
Hello <?php echo $_POST["name"]; ?>!<br>
Your mail is <?php echo $_POST["mail"]; ?>.
</body>
</html>
output
Hello "name" !
Your email is "[email protected]" .
Yes you can. I've used it with Word and PowerPoint. You will need Office 2010 client apps and SharePoint 2010 foundation at least. You must also allow editing without checking out on the document library.
It's quite cool, you can mark regions as 'locked' so no-one can change them and you can see what other people have changed every time you save your changes to the server. You also get to see who's working on the document from the Office app. The merging happens on SharePoint 2010.
REGEXP_COUNT should do the trick:
select REGEXP_COUNT('123-345-566', '-') from dual;
It seems that the problem with IE comes when you try and access the iframe via the document.frames object - if you store a reference to the created iframe in a variable then you can access the injected iframe via the variable (my_iframe in the code below).
I've gotten this to work in IE6/7/8
var my_iframe;
var iframeId = "my_iframe_name"
if (navigator.userAgent.indexOf('MSIE') !== -1) {
// IE wants the name attribute of the iframe set
my_iframe = document.createElement('<iframe name="' + iframeId + '">');
} else {
my_iframe = document.createElement('iframe');
}
iframe.setAttribute("src", "javascript:void(0);");
iframe.setAttribute("scrolling", "no");
iframe.setAttribute("frameBorder", "0");
iframe.setAttribute("name", iframeId);
var is = iframe.style;
is.border = is.width = is.height = "0px";
if (document.body) {
document.body.appendChild(my_iframe);
} else {
document.appendChild(my_iframe);
}
Here's a future-proof approach.
Combining @CamHart's and @Yuval's suggestions with @RoshOxymoron's accepted answer has the benefit of avoiding:
_hidden
and potentially deprecated methodsSo I think this plays nice with future python versions (tested on 2.7.3 and 3.3.2):
from __future__ import print_function
import inspect
def bar():
print("my name is '{}'".format(inspect.currentframe().f_code.co_name))
Best answer I found
To get the remote ip address the quickest way possible. You must have to use a downloader, or create a server on your computer.
The downsides to using this simple code: (which is recommended) is that it will take 3-5 seconds to get your Remote IP Address because the WebClient when initialized always takes 3-5 seconds to check for your proxy settings.
public static string GetIP()
{
string externalIP = "";
externalIP = new WebClient().DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
.Matches(externalIP)[0].ToString();
return externalIP;
}
Here is how I fixed it.. (first time still takes 3-5 seconds) but after that it will always get your Remote IP Address in 0-2 seconds depending on your connection.
public static WebClient webclient = new WebClient();
public static string GetIP()
{
string externalIP = "";
externalIP = webclient.DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
.Matches(externalIP)[0].ToString();
return externalIP;
}
tabs = {}
def new_tab():
global browser
hpos = browser.window_handles.index(browser.current_window_handle)
browser.execute_script("window.open('');")
browser.switch_to.window(browser.window_handles[hpos + 1])
return(browser.current_window_handle)
def switch_tab(name):
global tabs
global browser
if not name in tabs.keys():
tabs[name] = {'window_handle': new_tab(), 'url': url+name}
browser.get(tabs[name]['url'])
else:
browser.switch_to.window(tabs[name]['window_handle'])
To find all tables with a particular column:
select owner, table_name from all_tab_columns where column_name = 'ID';
To find tables that have any or all of the 4 columns:
select owner, table_name, column_name
from all_tab_columns
where column_name in ('ID', 'FNAME', 'LNAME', 'ADDRESS');
To find tables that have all 4 columns (with none missing):
select owner, table_name
from all_tab_columns
where column_name in ('ID', 'FNAME', 'LNAME', 'ADDRESS')
group by owner, table_name
having count(*) = 4;
A small improvement: above solutions will not remove leading or trailing spaces in the actual String. It's better to call trim before calling split. Instead of this,
String[] animalsArray = animals.split("\\s*,\\s*");
use
String[] animalsArray = animals.trim().split("\\s*,\\s*");
Answered this just to emphasize @rblarsen comment on question :
You don't need the style tags in the CSS-file
If you remove the style tag from your css file it will work.
Adding to italo's answer, you can also do this using jQuery.
function isEllipsisActive($jQueryObject) {
return ($jQueryObject.width() < $jQueryObject[0].scrollWidth);
}
Also, as Smoky pointed out, you may want to use jQuery outerWidth() instead of width().
function isEllipsisActive($jQueryObject) {
return ($jQueryObject.outerWidth() < $jQueryObject[0].scrollWidth);
}
In JSP, you'd normally like to use JSTL <fmt:formatDate>
for this. You can of course also throw in a scriptlet with SimpleDateFormat
, but scriptlets are strongly discouraged since 2003.
Assuming that ${bean.date}
returns java.util.Date
, here's how you can use it:
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
...
<fmt:formatDate value="${bean.date}" pattern="yyyy-MM-dd HH:mm:ss" />
If you're actually using a java.util.Calendar
, then you can invoke its getTime()
method to get a java.util.Date
out of it that <fmt:formatDate>
accepts:
<fmt:formatDate value="${bean.calendar.time}" pattern="yyyy-MM-dd HH:mm:ss" />
Or, if you're actually holding the date in a java.lang.String
(this indicates a serious design mistake in the model; you should really fix your model to store dates as java.util.Date
instead of as java.lang.String
!), here's how you can convert from one date string format e.g. MM/dd/yyyy
to another date string format e.g. yyyy-MM-dd
with help of JSTL <fmt:parseDate>
.
<fmt:parseDate pattern="MM/dd/yyyy" value="${bean.dateString}" var="parsedDate" />
<fmt:formatDate value="${parsedDate}" pattern="yyyy-MM-dd" />
Add an item and set its "Selected" property to true, you will probably want to set "appenddatabounditems" property to true also so your initial value isn't deleted when databound.
If you are talking about setting an initial value that is in your databound items then hook into your ondatabound event and set which index you want to selected=true you will want to wrap it in "if not page.isPostBack then ...." though
Protected Sub DepartmentDropDownList_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles DepartmentDropDownList.DataBound
If Not Page.IsPostBack Then
DepartmentDropDownList.SelectedValue = "somevalue"
End If
End Sub
If you have an Asp.Net web application, you can also set it in the web.config
so that it is the same throughout the whole web application
<system.web>
...
<globalization
requestEncoding="utf-8"
responseEncoding="utf-8"
culture="en-GB"
uiCulture="en-GB"
enableClientBasedCulture="false"/>
...
</system.web>
Linq With Or Condition by using Lambda expression you can do as below
DataTable dtEmp = new DataTable();
dtEmp.Columns.Add("EmpID", typeof(int));
dtEmp.Columns.Add("EmpName", typeof(string));
dtEmp.Columns.Add("Sal", typeof(decimal));
dtEmp.Columns.Add("JoinDate", typeof(DateTime));
dtEmp.Columns.Add("DeptNo", typeof(int));
dtEmp.Rows.Add(1, "Rihan", 10000, new DateTime(2001, 2, 1), 10);
dtEmp.Rows.Add(2, "Shafi", 20000, new DateTime(2000, 3, 1), 10);
dtEmp.Rows.Add(3, "Ajaml", 25000, new DateTime(2010, 6, 1), 10);
dtEmp.Rows.Add(4, "Rasool", 45000, new DateTime(2003, 8, 1), 20);
dtEmp.Rows.Add(5, "Masthan", 22000, new DateTime(2001, 3, 1), 20);
var res2 = dtEmp.AsEnumerable().Where(emp => emp.Field<int>("EmpID")
== 1 || emp.Field<int>("EmpID") == 2);
foreach (DataRow row in res2)
{
Label2.Text += "Emplyee ID: " + row[0] + " & Emplyee Name: " + row[1] + ", ";
}
You can get current time in milliseconds since January 1st, 1970 using an NSDate:
- (double)currentTimeInMilliseconds {
NSDate *date = [NSDate date];
return [date timeIntervalSince1970]*1000;
}
First create an object of class2 in class1 and then use that object to call any function of class2 for example write this in class1
class2 obj= new class2();
obj.thefunctioname(args);
I generally prefer defining my own: const double PI = 2*acos(0.0);
because not all implementations provide it for you.
The question of whether this function gets called at runtime or is static'ed out at compile time is usually not an issue, because it only happens once anyway.
Here is the recent fix for dlib users link
cv::Mat img = ...
IplImage iplImage = cvIplImage(img);
Your configure file contains CRLF line endings (windows style) instead of simple LF line endings (unix style). Did you transfer it using FTP mode ASCII from Windows?
You can use
dos2unix configure
to fix this, or open it in vi and use :%s/^M//g;
to substitute them all (use CTRL+V, CTRL+M to get the ^M)
In Apache 2.4, the authorization configuration syntax has changed, and the Order
, Deny
or Allow
directives should no longer be used.
The new way to do this would be:
<VirtualHost *:8080>
<Location />
Require ip 192.168.1.0
</Location>
...
</VirtualHost>
Further examples using the new syntax can be found in the Apache documentation: Upgrading to 2.4 from 2.2
Try this code:
Bitmap bitmap = null;
File f = new File(_path);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
try {
bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
image.setImageBitmap(bitmap);
If you like python and have an option to install a package, you can use this utility that I made.
# install pythonp
python -m pip install pythonp
pythonp "5*5"
25
pythonp "1 / (1+math.exp(0.5))"
0.3775406687981454
# define a custom function and pass it to another higher-order function
pythonp "n=10;functools.reduce(lambda x,y:x*y, range(1,n+1))"
3628800
Using Moment library, see their website -> https://momentjs.com/timezone/docs/#/using-timezones/converting-to-zone/
i notice they also user their own library in their website, so you can have a try using the browser console before installing it
moment().tz(String);
The moment#tz mutator will change the time zone and update the offset.
moment("2013-11-18").tz("America/Toronto").format('Z'); // -05:00
moment("2013-11-18").tz("Europe/Berlin").format('Z'); // +01:00
This information is used consistently in other operations, like calculating the start of the day.
var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.format(); // 2013-11-18T11:55:00-05:00
m.startOf("day").format(); // 2013-11-18T00:00:00-05:00
m.tz("Europe/Berlin").format(); // 2013-11-18T06:00:00+01:00
m.startOf("day").format(); // 2013-11-18T00:00:00+01:00
Without an argument, moment#tz returns:
the time zone name assigned to the moment instance or
undefined if a time zone has not been set.
var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.tz(); // America/Toronto
var m = moment.tz("2013-11-18 11:55");
m.tz() === undefined; // true
If you want to use pure Ruby (no Rails), don't want to create extension methods (maybe you need this only in one or two places and don't want to pollute namespace with tons of methods) and don't want to edit hash in place (i.e., you're fan of functional programming like me), you can 'select':
>> x = {:a => 1, :b => 2, :c => 3}
=> {:a=>1, :b=>2, :c=>3}
>> x.select{|x| x != :a}
=> {:b=>2, :c=>3}
>> x.select{|x| ![:a, :b].include?(x)}
=> {:c=>3}
>> x
=> {:a=>1, :b=>2, :c=>3}
You may use also
select * from pg_tables where schemaname = 'information_schema'
In generall pg* tables allow you to see everything in the db, not constrained to your permissions (if you have access to the tables of course).
This will return true if input
is all numbers. Don't know if it's any better than TryParse
, but it will work.
Regex.IsMatch(input, @"^\d+$")
If you just want to know if it has one or more numbers mixed in with characters, leave off the ^
+
and $
.
Regex.IsMatch(input, @"\d")
Edit: Actually I think it is better than TryParse because a very long string could potentially overflow TryParse.
You want this:
function validate() {
var acc = document.getElementsByName('acc')[0].value;
var pass = document.getElementsByName('pass')[0].value;
alert (acc);
}
I had the same problem. This work fine for me:
str(objdata).encode('utf-8')
This 100% works:
HTML:
<li class="dropdown">
<a href="https://www.bkweb.co.in/" class="dropdown-toggle" >bkWeb.co.in Dropdown <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">Separated link</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
CSS:
@media (min-width:991px){
ul.nav li.dropdown:hover ul.dropdown-menu {
display: block;
}
}
Instead of doing a git pull
, you can do:
git fetch
git reset --hard origin/master
Neither of those require you to configure your git user name / email.
This will destroy any uncommitted local changes / commits, and will leave your HEAD pointing to a commit (not a branch). But neither of those should be a problem for an app server since you shouldn't be making local changes or committing to that repository.
No need to use jquery for any major browser to swap elements at the moment. Native dom method, insertAdjacentElement
does the trick no matter how they are located:
var el1 = $("el1");
var el2 = $("el2");
el1[0].insertAdjacentElement("afterend", el2[0]);
git ls-tree --full-tree -r HEAD
and git ls-files
return all files at once. For a large project with hundreds or thousands of files, and if you are interested in a particular file/directory, you may find more convenient to explore specific directories. You can do it by obtaining the ID/SHA-1 of the directory that you want to explore and then use git cat-file -p [ID/SHA-1 of directory]
. For example:
git cat-file -p 14032aabd85b43a058cfc7025dd4fa9dd325ea97
100644 blob b93a4953fff68df523aa7656497ee339d6026d64 glyphicons-halflings-regular.eot
100644 blob 94fb5490a2ed10b2c69a4a567a4fd2e4f706d841 glyphicons-halflings-regular.svg
100644 blob 1413fc609ab6f21774de0cb7e01360095584f65b glyphicons-halflings-regular.ttf
100644 blob 9e612858f802245ddcbf59788a0db942224bab35 glyphicons-halflings-regular.woff
100644 blob 64539b54c3751a6d9adb44c8e3a45ba5a73b77f0 glyphicons-halflings-regular.woff2
In the example above, 14032aabd85b43a058cfc7025dd4fa9dd325ea97
is the ID/SHA-1 of the directory that I wanted to explore. In this case, the result was that four files within that directory were being tracked by my Git repo. If the directory had additional files, it would mean those extra files were not being tracked. You can add files using git add <file>...
of course.
Another way to read/write Excel files is to use Windmill. It provides a fluent API to process Excel and CSV files.
try (Stream<Row> rowStream = Windmill.parse(FileSource.of(new FileInputStream("myFile.xlsx")))) {
rowStream
// skip the header row that contains the column names
.skip(1)
.forEach(row -> {
System.out.println(
"row n°" + row.rowIndex()
+ " column 'User login' value : " + row.cell("User login").asString()
+ " column n°3 number value : " + row.cell(2).asDouble().value() // index is zero-based
);
});
}
Windmill
.export(Arrays.asList(bean1, bean2, bean3))
.withHeaderMapping(
new ExportHeaderMapping<Bean>()
.add("Name", Bean::getName)
.add("User login", bean -> bean.getUser().getLogin())
)
.asExcel()
.writeTo(new FileOutputStream("Export.xlsx"));
Steven is right, in theory:
the “correct” way to center a table using CSS. Conforming browsers ought to center tables if the left and right margins are equal. The simplest way to accomplish this is to set the left and right margins to “auto.” Thus, one might write in a style sheet:
table
{
margin-left: auto;
margin-right: auto;
}
But the article mentioned in the beginning of this answer gives you all the other way to center a table.
An elegant css cross-browser solution: This works in both MSIE 6 (Quirks and Standards), Mozilla, Opera and even Netscape 4.x without setting any explicit widths:
div.centered
{
text-align: center;
}
div.centered table
{
margin: 0 auto;
text-align: left;
}
<div class="centered">
<table>
…
</table>
</div>
This can be done as
list.Sort( (emp1,emp2)=>emp1.FirstName.CompareTo(emp2.FirstName) );
The .NET framework is casting the lambda (emp1,emp2)=>int
as a Comparer<Employee>.
This has the advantage of being strongly typed.
You are looking for the break statement.
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
if ($val == 'stop') {
break; /* You could also write 'break 1;' here. */
}
echo "$val<br />\n";
}
A CRLF is two characters, of course, the CR and the LF. However, `n
consists of both. For example:
PS C:\> $x = "Hello
>> World"
PS C:\> $x
Hello
World
PS C:\> $x.contains("`n")
True
PS C:\> $x.contains("`r")
False
PS C:\> $x.replace("o`nW","o There`nThe W")
Hello There
The World
PS C:\>
I think you're running into problems with the `r
. I was able to remove the `r
from your example, use only `n
, and it worked. Of course, I don't know exactly how you generated the original string so I don't know what's in there.
I solved my problem using this code, is a somewhat replacement for the missing splice.
let str = "I need to remove a character from this";
let pos = str.indexOf("character")
if(pos>-1){
let result = str.slice(0, pos-2) + str.slice(pos, str.length);
console.log(result) //I need to remove character from this
}
I needed to remove a character before/after a certain word, after you get the position the string is split in two and then recomposed by flexibly removing characters using an offset along pos
Firstly you need to install a SSH server in the images you wish to ssh-into. You can use a base image for all your container with the ssh server installed.
Then you only have to run each container mapping the ssh port (default 22) to one to the host's ports (Remote Server in your image), using -p <hostPort>:<containerPort>
. i.e:
docker run -p 52022:22 container1
docker run -p 53022:22 container2
Then, if ports 52022 and 53022 of host's are accessible from outside, you can directly ssh to the containers using the ip of the host (Remote Server) specifying the port in ssh with -p <port>
. I.e.:
ssh -p 52022 myuser@RemoteServer
--> SSH to container1
ssh -p 53022 myuser@RemoteServer
--> SSH to container2
The international versions:
Public Shared Function GetDouble(ByVal doublestring As String) As Double
Dim retval As Double
Dim sep As String = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
Double.TryParse(Replace(Replace(doublestring, ".", sep), ",", sep), retval)
Return retval
End Function
' NULLABLE VERSION:
Public Shared Function GetDoubleNullable(ByVal doublestring As String) As Double?
Dim retval As Double
Dim sep As String = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
If Double.TryParse(Replace(Replace(doublestring, ".", sep), ",", sep), retval) Then
Return retval
Else
Return Nothing
End If
End Function
Results:
' HUNGARIAN REGIONAL SETTINGS (NumberDecimalSeparator: ,)
' Clean Double.TryParse
' -------------------------------------------------
Double.TryParse("1.12", d1) ' Type: DOUBLE Value: d1 = 0.0
Double.TryParse("1,12", d2) ' Type: DOUBLE Value: d2 = 1.12
Double.TryParse("abcd", d3) ' Type: DOUBLE Value: d3 = 0.0
' GetDouble() method
' -------------------------------------------------
d1 = GetDouble("1.12") ' Type: DOUBLE Value: d1 = 1.12
d2 = GetDouble("1,12") ' Type: DOUBLE Value: d2 = 1.12
d3 = GetDouble("abcd") ' Type: DOUBLE Value: d3 = 0.0
' Nullable version - GetDoubleNullable() method
' -------------------------------------------------
d1n = GetDoubleNullable("1.12") ' Type: DOUBLE? Value: d1n = 1.12
d2n = GetDoubleNullable("1,12") ' Type: DOUBLE? Value: d2n = 1.12
d3n = GetDoubleNullable("abcd") ' Type: DOUBLE? Value: d3n = Nothing
I am constructing a building of 300 floors
The building's blueprint interface
Building constructed up to 200 floors - partially completed---abstract
Building construction completed-concrete
Interface
Abstract
Taken from DurgaJobs Website
Just for the record, using requests library.
import requests
f = open('00000001.jpg','wb')
f.write(requests.get('http://www.gunnerkrigg.com//comics/00000001.jpg').content)
f.close()
Though it should check for requests.get() error.
Install Babun instead -> https://babun.github.io/index.html It contains Cygwin ;)
What you are probably really wanting to do here is use the union operator like this:
(select ID from Logo where AccountID = 1 and Rendered = 'True')
union
(select ID from Design where AccountID = 1 and Rendered = 'True')
order by ID limit 0, 51
Here's the docs for it https://dev.mysql.com/doc/refman/5.0/en/union.html
You need to quote that filename:
f = open("D\\python\\HW\\2_1 - Copy.cp", "r")
Otherwise the bare backslash after the D is interpreted as a line-continuation character, and should be followed by a newline. This is used to extend long expressions over multiple lines, for readability:
print "This is a long",\
"line of text",\
"that I'm printing."
Also, you shouldn't have semicolons (;
) at the end of your statements in Python.
Using the == operator will compare the references to the strings not the string themselves.
Ok, you have to toString() the Editable. I loaded up some of the code I had before that dealt with this situation.
String passwd1Text = passw1.getText().toString();
String passwd2Text = passw2.getText().toString();
if (passwd1Text.equals(passwd2Text))
{
}
You could use find along with the -exec flag in a single command line to do the job
find . -name "*.zip" -exec unzip {} \;
The issue could be that your deployed files are not updated with the correct RMI methods. Check to see that your RMI interface has updated parameters, or updated data structures that your client does not have. Or that your RMI client has no parameters that differ from what your server version has.
This is just an educated guess. After re-deploying my server application's class files and re-testing, the problem of "Broken pipe" went away.
Here are 3 separate approaches to the problem in hand along with the best choices of indexing for each of those queries (please try out the indexes yourselves and see the logical read, elapsed time, execution plan. I have provided the suggestions from my experience on such queries without executing for this specific problem).
Approach 1: Using ROW_NUMBER(). If rowstore index is not being able to enhance the performance, you can try out nonclustered/clustered columnstore index as for queries with aggregation and grouping and for tables which are ordered by in different columns all the times, columnstore index usually is the best choice.
;WITH CTE AS
(
SELECT *,
RN = ROW_NUMBER() OVER (PARTITION BY DocumentID ORDER BY DateCreated DESC)
FROM DocumentStatusLogs
)
SELECT ID
,DocumentID
,Status
,DateCreated
FROM CTE
WHERE RN = 1;
Approach 2: Using FIRST_VALUE. If rowstore index is not being able to enhance the performance, you can try out nonclustered/clustered columnstore index as for queries with aggregation and grouping and for tables which are ordered by in different columns all the times, columnstore index usually is the best choice.
SELECT DISTINCT
ID = FIRST_VALUE(ID) OVER (PARTITION BY DocumentID ORDER BY DateCreated DESC)
,DocumentID
,Status = FIRST_VALUE(Status) OVER (PARTITION BY DocumentID ORDER BY DateCreated DESC)
,DateCreated = FIRST_VALUE(DateCreated) OVER (PARTITION BY DocumentID ORDER BY DateCreated DESC)
FROM DocumentStatusLogs;
Approach 3: Using CROSS APPLY. Creating rowstore index on DocumentStatusLogs table covering the columns used in the query should be enough to cover the query without need of a columnstore index.
SELECT DISTINCT
ID = CA.ID
,DocumentID = D.DocumentID
,Status = CA.Status
,DateCreated = CA.DateCreated
FROM DocumentStatusLogs D
CROSS APPLY (
SELECT TOP 1 I.*
FROM DocumentStatusLogs I
WHERE I.DocumentID = D.DocumentID
ORDER BY I.DateCreated DESC
) CA;
I ran this in the command prompt(have windows 7 os): JAVA_HOME=C:\Program Files\Android\Android Studio\jre
where what its = to is the path to that jre folder, so anyone's can be different.
The simplest Solution :
var dt=new DataTable();
dt.Load(myDataReader);
list<DataRow> dr=dt.AsEnumerable().ToList();
you should not use Nested List in List.
List<List<T>>
is not legal, even if T were a defined type.
THIS IS A VERY SIMPLE PROBLEM
Here is the best method for solve this problem.
Step 1 : Login to your cPanel (http://website.com/cpanel OR http://cpanel.website.com).
Step 2 : SOFTWARE -> Select PHP Version
Step 3 : Change Your Current PHP version : 5.6
Step 3 : HIT 'Set as current' [ ENJOY ]
The helper methods from the accepted answer are not needed. Streams can be used with lambdas or usually shortened using Method References. Streams enable functional operations. map()
converts the elements and collect(...)
or toArray()
wrap the stream back up into an array or collection.
Venkat Subramaniam's talk (video) explains it better than me.
1 Convert List<String>
to List<Integer>
List<String> l1 = Arrays.asList("1", "2", "3");
List<Integer> r1 = l1.stream().map(Integer::parseInt).collect(Collectors.toList());
// the longer full lambda version:
List<Integer> r1 = l1.stream().map(s -> Integer.parseInt(s)).collect(Collectors.toList());
2 Convert List<String>
to int[]
int[] r2 = l1.stream().mapToInt(Integer::parseInt).toArray();
3 Convert String[]
to List<Integer>
String[] a1 = {"4", "5", "6"};
List<Integer> r3 = Stream.of(a1).map(Integer::parseInt).collect(Collectors.toList());
4 Convert String[]
to int[]
int[] r4 = Stream.of(a1).mapToInt(Integer::parseInt).toArray();
5 Convert String[]
to List<Double>
List<Double> r5 = Stream.of(a1).map(Double::parseDouble).collect(Collectors.toList());
6 (bonus) Convert int[]
to String[]
int[] a2 = {7, 8, 9};
String[] r6 = Arrays.stream(a2).mapToObj(Integer::toString).toArray(String[]::new);
Lots more variations are possible of course.
Also see Ideone version of these examples. Can click fork and then run to run in the browser.
That is the textarea
's job - for multiline text input. The input
won't do it; it wasn't designed to do it.
So use a textarea
. Besides their visual differences, they are accessed via JavaScript the same way (use value
property).
You can prevent newlines being entered via the input
event and simply using a replace(/\n/g, '')
.
The two code segments work the same. However, unsigned int" route is correct. Using unsigned int types will work better with the vector in the instance you used it. Calling the size() member function on a vector returns an unsigned integer value, so you want to be comparing the variable "i" to a value of its own type.
Also, if you are still a little uneasy about how "unsigned int" looks in your code, try "uint". This is basically a shortened version of "unsigned int" and it works exactly the same. You also don't need to include other headers to use it.
This worked for me .
.tooltip .arrow:before {
border-top-color: #008ec3 !important;
}
.tooltip .tooltip-inner {
background-color: #008ec3;
}
Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).
You need to do a deep equals.
From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.
Object.extend(Object, {
deepEquals: function(o1, o2) {
var k1 = Object.keys(o1).sort();
var k2 = Object.keys(o2).sort();
if (k1.length != k2.length) return false;
return k1.zip(k2, function(keyPair) {
if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
} else {
return o1[keyPair[0]] == o2[keyPair[1]];
}
}).all();
}
});
Usage:
var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);
if (Object.deepEquals(anObj, anotherObj))
...
Well, for starters, a struct is passed by value rather than by reference. Structs are good for relatively simple data structures, while classes have a lot more flexibility from an architectural point of view via polymorphism and inheritance.
Others can probably give you more detail than I, but I use structs when the structure that I am going for is simple.
Much like leonardocsouza, I had the same problem. To clarify a bit, this is what my folder structure looked like when I ran node server.js
node_modules/
app/
index.html
server.js
After printing out the __dirname
path, I realized that the __dirname
path was where my server was running (app/
).
So, the answer to your question is this:
If your server.js
file is in the same folder as the files you are trying to render, then
app.use( express.static( path.join( application_root, 'site') ) );
should actually be
app.use(express.static(application_root));
The only time you would want to use the original syntax that you had would be if you had a folder tree like so:
app/
index.html
node_modules
server.js
where index.html
is in the app/
directory, whereas server.js
is in the root directory (i.e. the same level as the app/
directory).
Side note: Intead of calling the path
utility, you can use the syntax application_root + 'site'
to join a path.
Overall, your code could look like:
// Module dependencies.
var application_root = __dirname,
express = require( 'express' ), //Web framework
mongoose = require( 'mongoose' ); //MongoDB integration
//Create server
var app = express();
// Configure server
app.configure( function() {
//Don't change anything here...
//Where to serve static content
app.use( express.static( application_root ) );
//Nothing changes here either...
});
//Start server --- No changes made here
var port = 5000;
app.listen( port, function() {
console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
});
Using &
is fine for short commands, but that single line can get very long very quick. When that happens, switch to multi-line syntax.
FOR /r %%X IN (*.txt) DO (
ECHO %%X
DEL %%X
)
Placement of (
and )
matters. The round brackets after DO
must be placed on the same line, otherwise the batch file will be incorrect.
See if /?|find /V ""
for details.
You can use the DateTime.Add() method to add the time to the date.
DateTime date = DateTime.Now;
TimeSpan time = new TimeSpan(36, 0, 0, 0);
DateTime combined = date.Add(time);
Console.WriteLine("{0:dddd}", combined);
You can also create your timespan by parsing a String, if that is what you need to do.
Alternatively, you could look at using other controls. You didn't mention if you are using winforms, wpf or asp.net, but there are various date and time picker controls that support selection of both date and time.
As Bokan has mentioned, you can up the memory if available, and he is right on how counter productive setting TTL to 0 is.
NotE: This is how I fixed this error for my particular problem. Its a generic issue that can be caused by allot of things so only follow the below if you get the error and you think its caused by duplicate PHP files being loaded into APC.
The issue I was having was when I released a new version of my PHP application. Ie replaced all my .php files with new ones APC would load both versions into cache.
Because I didnt have enough memory for two versions of the php files APC would run out of memory.
There is a option called apc.stat to tell APC to check if a particular file has changed and if so replace it, this is typically ok for development because you are constantly making changes however on production its usually turned off as it was with in my case - http://www.php.net/manual/en/apc.configuration.php#ini.apc.stat
Turning apc.stat on would fix this issue if you are ok with the performance hit.
The solution I came up with for my problem is check if the the project version has changed and if so empty the cache and reload the page.
define('PROJECT_VERSION', '0.28');
if(apc_exists('MY_APP_VERSION') ){
if(apc_fetch('MY_APP_VERSION') != PROJECT_VERSION){
apc_clear_cache();
apc_store ('MY_APP_VERSION', PROJECT_VERSION);
header('Location: ' . 'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']);
exit;
}
}else{
apc_store ('MY_APP_VERSION', PROJECT_VERSION);
}
Here is the example to sort implemented linked list in java without using any standard java libraries.
package SelFrDemo;
class NodeeSort {
Object value;
NodeeSort next;
NodeeSort(Object val) {
value = val;
next = null;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public NodeeSort getNext() {
return next;
}
public void setNext(NodeeSort next) {
this.next = next;
}
}
public class SortLinkList {
NodeeSort head;
int size = 0;
NodeeSort add(Object val) {
// TODO Auto-generated method stub
if (head == null) {
NodeeSort nodee = new NodeeSort(val);
head = nodee;
size++;
return head;
}
NodeeSort temp = head;
while (temp.next != null) {
temp = temp.next;
}
NodeeSort newNode = new NodeeSort(val);
temp.setNext(newNode);
newNode.setNext(null);
size++;
return head;
}
NodeeSort sort(NodeeSort nodeSort) {
for (int i = size - 1; i >= 1; i--) {
NodeeSort finalval = nodeSort;
NodeeSort tempNode = nodeSort;
for (int j = 0; j < i; j++) {
int val1 = (int) nodeSort.value;
NodeeSort nextnode = nodeSort.next;
int val2 = (int) nextnode.value;
if (val1 > val2) {
if (nodeSort.next.next != null) {
NodeeSort CurrentNext = nodeSort.next.next;
nextnode.next = nodeSort;
nextnode.next.next = CurrentNext;
if (j == 0) {
finalval = nextnode;
} else
nodeSort = nextnode;
for (int l = 1; l < j; l++) {
tempNode = tempNode.next;
}
if (j != 0) {
tempNode.next = nextnode;
nodeSort = tempNode;
}
} else if (nodeSort.next.next == null) {
nextnode.next = nodeSort;
nextnode.next.next = null;
for (int l = 1; l < j; l++) {
tempNode = tempNode.next;
}
tempNode.next = nextnode;
nextnode = tempNode;
nodeSort = tempNode;
}
} else
nodeSort = tempNode;
nodeSort = finalval;
tempNode = nodeSort;
for (int k = 0; k <= j && j < i - 1; k++) {
nodeSort = nodeSort.next;
}
}
}
return nodeSort;
}
public static void main(String[] args) {
SortLinkList objsort = new SortLinkList();
NodeeSort nl1 = objsort.add(9);
NodeeSort nl2 = objsort.add(71);
NodeeSort nl3 = objsort.add(6);
NodeeSort nl4 = objsort.add(81);
NodeeSort nl5 = objsort.add(2);
NodeeSort NodeSort = nl5;
NodeeSort finalsort = objsort.sort(NodeSort);
while (finalsort != null) {
System.out.println(finalsort.getValue());
finalsort = finalsort.getNext();
}
}
}
Below are some of the way by which you can create a link button in MVC.
@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)
@Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })
@Html.Action("Action", "Controller", new { area = "AreaName" })
@Url.Action("Action", "Controller", new { area = "AreaName" })
<a class="ui-btn" data-val="abc" href="/Home/Edit/ANTON">Edit</a>
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#CustomerList" href="/Home/Germany">Customer from Germany</a>
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#CustomerList" href="/Home/Mexico">Customer from Mexico</a>
Hope this will help you.
Note: Since a while back, there are binary wheels for Windows in PyPI, so this should no longer be an issue for Windows users. Below are solutions for Linux, Mac users, since lots of them find this post through web searches.
Install the psycopg2-binary
PyPI package instead, it has Python wheels for Linux and Mac OS.
pip install psycopg2-binary
Install the prerequsisites for building the psycopg2
package from source:
sudo apt install libpq-dev python3-dev
You might need to install python3.8-dev
or similar for e.g. Python 3.8.
sudo apt install libpq-dev python-dev
If that's not enough, try
sudo apt install build-essential
or
sudo apt install postgresql-server-dev-all
as well before installing psycopg2 again.
See Banjer's answer
1 Really? It's 2020
Agree with Nick. Here is more elaborated code.
#count=0
for idx, item in enumerate(list):
print item
#count +=1
#if count % 10 == 0:
if (idx+1) % 10 == 0:
print 'did ten'
I have commented out the count variable in your code.
If I recall correctly Twig doesn't support ||
and &&
operators, but requires or
and and
to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.
{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}
Expressions
Expressions can be used in {% blocks %} and ${ expressions }.
Operator Description
== Does the left expression equal the right expression?
+ Convert both arguments into a number and add them.
- Convert both arguments into a number and substract them.
* Convert both arguments into a number and multiply them.
/ Convert both arguments into a number and divide them.
% Convert both arguments into a number and calculate the rest of the integer division.
~ Convert both arguments into a string and concatenate them.
or True if the left or the right expression is true.
and True if the left and the right expression is true.
not Negate the expression.
For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:
{% if (foo and bar) or (fizz and (foo + bar == 3)) %}
The answer by shufler is correct. Stated another way: Instead of passing the values to Write-Output using the ARRAY FORM,
Write-Output "Parameters are:" $Year $Month $Day
or the equivalent by multiple calls to Write-Output,
Write-Output "Parameters are:"
Write-Output $Year
Write-Output $Month
Write-Output $Day
Write-Output "Done."
concatenate your components into a STRING VARIABLE first:
$msg="Parameters are: $Year $Month $Day"
Write-Output $msg
This will prevent the intermediate CRLFs caused by calling Write-Output multiple times (or ARRAY FORM), but of course will not suppress the final CRLF of the Write-Output commandlet. For that, you will have to write your own commandlet, use one of the other convoluted workarounds listed here, or wait until Microsoft decides to support the -NoNewline
option for Write-Output.
Your desire to provide a textual progress meter to the console (i.e. "....") as opposed to writing to a log file, should also be satisfied by using Write-Host. You can accomplish both by collecting the msg text into a variable for writing to the log AND using Write-Host to provide progress to the console. This functionality can be combined into your own commandlet for greatest code reuse.
This solution is working with Android Studio 4.0.1.
Apart from creating a new module as suggested in above solution, you can try this solution.
If you have multiple modules in your application and want to add aar to just one of the module then this solution come handy.
In your root project build.gradle
add
repositories {
flatDir {
dirs 'libs'
}}
Then in the module where you want to add the .aar file locally. simply add below lines of code.
dependencies {
api fileTree(include: ['*.aar'], dir: 'libs')
implementation files('libs/<yourAarName>.aar')
}
Happy Coding :)
You should use somevar.constructor.name
like a:
_x000D_
const getVariableType = a => a.constructor.name.toLowerCase();_x000D_
_x000D_
const d = new Date();_x000D_
const res1 = getVariableType(d); // 'date'_x000D_
const num = 5;_x000D_
const res2 = getVariableType(num); // 'number'_x000D_
const fn = () => {};_x000D_
const res3 = getVariableType(fn); // 'function'_x000D_
_x000D_
console.log(res1); // 'date'_x000D_
console.log(res2); // 'number'_x000D_
console.log(res3); // 'function'
_x000D_
find /home/test -regextype posix-extended -regex '^.*test\.log\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.zip' -mtime +3
-name
uses globular expressions,
aka wildcards. What you want is
-regex
find
to use Extended
Regular Expressions via the
-regextype posix-extended
flag\.
+
as
in -mtime +3
.$ find . -regextype posix-extended -regex '^.*test\.log\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.zip'
./test.log.1234-12-12.zip
This tripped me up today, but I realized it was because on Android 9.0 (Pie), Do Not Disturb by default also hides all notifications, rather than just silencing them like in Android 8.1 (Oreo) and before. This doesn't apply to notifications.
I like having DND on for my development device, so going into the DND settings and changing the setting to simply silence the notifications (but not hide them) fixed it for me.
With reference to man ssh-keygen
, the length of a DSA key is restricted to exactly 1024 bit to remain compliant with NIST's FIPS 186-2. Nonetheless, longer DSA keys are theoretically possible; FIPS 186-3 explicitly allows them. Furthermore, security is no longer guaranteed with 1024 bit long RSA or DSA keys.
In conclusion, a 2048 bit RSA key is currently the best choice.
Establishing a secure SSH connection entails more than selecting safe encryption key pair technology. In view of Edward Snowden's NSA revelations, one has to be even more vigilant than what previously was deemed sufficient.
To name just one example, using a safe key exchange algorithm is equally important. Here is a nice overview of current best SSH hardening practices.
The most robust mechanism for listing all resources in the classpath is currently to use this pattern with ClassGraph, because it handles the widest possible array of classpath specification mechanisms, including the new JPMS module system. (I am the author of ClassGraph.)
How to know the name of the JAR file where my main class lives?
URI mainClasspathElementURI;
try (ScanResult scanResult = new ClassGraph().whitelistPackages("x.y.z")
.enableClassInfo().scan()) {
mainClasspathElementURI =
scanResult.getClassInfo("x.y.z.MainClass").getClasspathElementURI();
}
How can I read the contents of a directory in a similar fashion within a JAR file?
List<String> classpathElementResourcePaths;
try (ScanResult scanResult = new ClassGraph().overrideClasspath(mainClasspathElementURI)
.scan()) {
classpathElementResourcePaths = scanResult.getAllResources().getPaths();
}
There are lots of other ways to deal with resources too.
This is a linker issue. Try:
g++ -o test_1 test_1.cpp `pkg-config opencv --cflags --libs`
This should work to compile the source. However, if you recently compiled OpenCV from source, you will meet linking issue in run-time, the library will not be found. In most cases, after compiling libraries from source, you need to do finally:
sudo ldconfig
Assign after the EXEC
token:
DECLARE @returnValue INT
EXEC @returnValue = SP_One
I could solve the problem using enctype="application/x-www-form-urlencoded" as the default is "text/plain". When you check in $DATA the seperator is a space for "text/plain" and a special character for the "urlencoded".
Kind regards Frank
as @Jörg W Mittag pointed out: in jruby, fix num size is always 8 bytes long. This code snippet shows the truth:
fmax = ->{
if RUBY_PLATFORM == 'java'
2**63 - 1
else
2**(0.size * 8 - 2) - 1
end
}.call
p fmax.class # Fixnum
fmax = fmax + 1
p fmax.class #Bignum
All created by user files saved in C:\xampp\htdocs
directory by default,
so no need to type the default path in a browser window, just type
http://localhost/yourfilename.php
or http://localhost/yourfoldername/yourfilename.php
this will show you the content of your new page.
MYSQL_HOME variable value:C:\Program Files\MySQL\MySQL Server 5.0\bin %MYSQL_HOME%\bin
See the problem? This resolves to a path of C:\Program Files\MySQL\MySQL Server 5.0\bin\bin
If suppose you spotted this error after removing certain node modules, ideally should not be present the library under build.gradle(Module:app) . It can be removed manually and sync the project again.
Nicest solution that I was able to figure out was with bluebird
promises. You can just do Promise.resolve(files).each(fs.readFileAsync);
which guarantees that promises are resolved sequentially in order.
shopt -s nocasematch
if [[ sed-4.2.2.$LINE =~ (yes|y)$ ]]
then exit 0
fi
Would not creating a UserJsonResponse
class and populating with the wanted fields be a cleaner solution?
Returning directly a JSON seems a great solution when you want to give all the model back. Otherwise it just gets messy.
In the future, for example you might want to have a JSON field that does not match any Model field and then you're in a bigger trouble.
try this
var value = iterate('tr.item span.value');
var quantity = iterate('tr.item span.quantity');
function iterate(selector)
{
var result = '';
if ($(selector))
{
$(selector).each(function ()
{
if (result == '')
{
result = $(this).html();
}
else
{
result = result + "," + $(this).html();
}
});
}
}
You can avoid the repetition with an attribute test instead:
a/b/*[local-name()='c' or local-name()='d' or local-name()='e']
Contrary to Dimitre's antagonistic opinion, the above is not incorrect in a vacuum where the OP has not specified the interaction with namespaces. The self::
axis is namespace restrictive, local-name()
is not. If the OP's intention is to capture c|d|e
regardless of namespace (which I'd suggest is even a likely scenario given the OR nature of the problem) then it is "another answer that still has some positive votes" which is incorrect.
You can't be definitive without definition, though I'm quite happy to delete my answer as genuinely incorrect if the OP clarifies his question such that I am incorrect.
An alternative stacking arrangement which works and is perhaps a bit more intuitive is the following:
struct ContentView: View {
var body: some View {
HStack() {
VStack(alignment: .leading) {
Text("Hello World")
.font(.title)
Text("Another")
.font(.body)
Spacer()
}
Spacer()
}.background(Color.red)
}
}
The content can also easily be re-positioned by removing the Spacer()
's if necessary.
I had this problem with chrome when I was working on a WordPress site. I added this code
$_SERVER['HTTPS'] = false;
into the theme's functions.php file - it asks you to log in again when you save the file but once it's logged in it works straight away.
Why not use an empty ajax update panel and wire the linkbutton's click event to it? This way only the update panel will get updated, thus avoiding a postback and allowing you to run your javascript
If you have a view with no background this line will help you
android:outlineProvider="bounds"
By default shadow is determined by view's background, so if there is no background, there will be no shadow also.
I think the others have answered your second question. As for the first, the "Hello World" of CUDA, I don't think there is a set standard, but personally, I'd recommend a parallel adder (i.e. a programme that sums N integers).
If you look the "reduction" example in the NVIDIA SDK, the superficially simple task can be extended to demonstrate numerous CUDA considerations such as coalesced reads, memory bank conflicts and loop unrolling.
See this presentation for more info:
http://www.gpgpu.org/sc2007/SC07_CUDA_5_Optimization_Harris.pdf
The permanent space is where the classes, methods, internalized strings, and similar objects used by the VM are stored and never deallocated (hence the name).
This Oracle article succinctly presents the working and parameterization of the HotSpot GC and advises you to augment this space if you load many classes (this is typically the case for application servers and some IDE like Eclipse) :
The permanent generation does not have a noticeable impact on garbage collector performance for most applications. However, some applications dynamically generate and load many classes; for example, some implementations of JavaServer Pages (JSP) pages. These applications may need a larger permanent generation to hold the additional classes. If so, the maximum permanent generation size can be increased with the command-line option -XX:MaxPermSize=.
Note that this other Oracle documentation lists the other HotSpot arguments.
Update : Starting with Java 8, both the permgen space and this setting are gone. The memory model used for loaded classes and methods is different and isn't limited (with default settings). You should not see this error any more.
If you are looking for a very extensible option or have a specific problem domain you could consider rolling your own using the Java Object Oriented Neural Engine. Another JOONE reference.
I used it successfully in a personal project to identify the letter from an image such as this, you can find all the source for the OCR component of my application on github, here.
An assertion allows for detecting defects in the code. You can turn on assertions for testing and debugging while leaving them off when your program is in production.
Why assert something when you know it is true? It is only true when everything is working properly. If the program has a defect, it might not actually be true. Detecting this earlier in the process lets you know something is wrong.
An assert
statement contains this statement along with an optional String
message.
The syntax for an assert statement has two forms:
assert boolean_expression;
assert boolean_expression: error_message;
Here are some basic rules which govern where assertions should be used and where they should not be used. Assertions should be used for:
Validating input parameters of a private method. NOT for public methods. public
methods should throw regular exceptions when passed bad parameters.
Anywhere in the program to ensure the validity of a fact which is almost certainly true.
For example, if you are sure that it will only be either 1 or 2, you can use an assertion like this:
...
if (i == 1) {
...
}
else if (i == 2) {
...
} else {
assert false : "cannot happen. i is " + i;
}
...
Assertions should not be used for:
Validating input parameters of a public method. Since assertions may not always be executed, the regular exception mechanism should be used.
Validating constraints on something that is input by the user. Same as above.
Should not be used for side effects.
For example this is not a proper use because here the assertion is used for its side effect of calling of the doSomething()
method.
public boolean doSomething() {
...
}
public void someMethod() {
assert doSomething();
}
The only case where this could be justified is when you are trying to find out whether or not assertions are enabled in your code:
boolean enabled = false;
assert enabled = true;
if (enabled) {
System.out.println("Assertions are enabled");
} else {
System.out.println("Assertions are disabled");
}
i had the similar error, because i had defined
ng-class="GetLink()"
instead of
ng-click="GetLink()"
I find the most valuable feature of .FormulaR1C1 is sheer speed. Versus eg a couple of very large loops filling some data into a sheet, If you can convert what you are doing into a .FormulaR1C1 form. Then a single operation eg myrange.FormulaR1C1 = "my particular formuala" is blindingly fast (can be a thousand times faster). No looping and counting - just fill the range at high speed.
txtSearch.onkeydown= e => (e.key=="Enter") ? btnSearch.click() : 1
txtSearch.onkeydown= e => (e.key=="Enter") ? btnSearch.click() : 1
function doSomething() {
console.log('');
}
_x000D_
<input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
_x000D_
try - Add sensitive code catch - to handle exception finally - always executed whether exception caught or not. Associated with try -catch. Used to close the resource which we opened in try block throw - To handover our created exception to JVM manually. Used to throw customized exception throws - To delegate the responsibility of exception handling to caller method or main method.
for(i=0;i<((s3)/2);i++)
{
z=s2[i];
s2[i]=s2[(s3-1)-i];
s2[(s3-1)-i]=z;
}
//arraylist/Pojo you can Pass using bundle like this
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
Bundle args = new Bundle();
args.putSerializable("imageSliders",(Serializable)allStoriesPojo.getImageSliderPojos());
intent.putExtra("BUNDLE",args);
startActivity(intent);
Get SecondActivity like this
Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
String filter = bundle.getString("imageSliders");
//Happy coding
Here's my take on the problem. I create AbsoluteLayout
overlay which contains Info Window (a regular view with every bit of interactivity and drawing capabilities). Then I start Handler
which synchronizes the info window's position with position of point on the map every 16 ms. Sounds crazy, but actually works.
Demo video: https://www.youtube.com/watch?v=bT9RpH4p9mU (take into account that performance is decreased because of emulator and video recording running simultaneously).
Code of the demo: https://github.com/deville/info-window-demo
An article providing details (in Russian): http://habrahabr.ru/post/213415/
Simplicity is a virtue. Use this naturally readable array:
char alphabet[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
Thanks to Vitaliy Gozhenko
I just want to add that you can add IB_DESIGNABLE before your button @interface and set your button class in storyborad. Then you can watch it layout in real time without app launch just at interface building stage
var ww1 = "";_x000D_
var ww2 = 0;_x000D_
var myVar1 ;_x000D_
var myVar2 ;_x000D_
function wm1(){_x000D_
myVar1 =setInterval(w1, 15);_x000D_
}_x000D_
function wm2(){_x000D_
myVar2 =setInterval(w2, 15);_x000D_
}_x000D_
function w1(){_x000D_
ww1=document.getElementById('chartdiv').style.height;_x000D_
ww2= ww1.replace("px", ""); _x000D_
if(parseFloat(ww2) <= 200){_x000D_
document.getElementById('chartdiv').style.height = (parseFloat(ww2)+5) + 'px';_x000D_
}else{_x000D_
clearInterval(myVar1);_x000D_
}_x000D_
}_x000D_
function w2(){_x000D_
ww1=document.getElementById('chartdiv').style.height;_x000D_
ww2= ww1.replace("px", ""); _x000D_
if(parseFloat(ww2) >= 50){_x000D_
document.getElementById('chartdiv').style.height = (parseFloat(ww2)-5) + 'px';_x000D_
}else{_x000D_
clearInterval(myVar2);_x000D_
}_x000D_
}
_x000D_
<html>_x000D_
<head> _x000D_
</head>_x000D_
_x000D_
<body >_x000D_
<button type="button" onClick = "wm1()">200px</button>_x000D_
<button type="button" onClick = "wm2()">50px</button>_x000D_
<div id="chartdiv" style="width: 100%; height: 50px; background-color:#ccc"></div>_x000D_
_x000D_
<div id="demo"></div>_x000D_
</body>
_x000D_
Use DATESTR
>> datestr(40189)
ans =
12-Jan-0110
Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM
>> datenum(2010,1,11)
ans =
734149
>> datenum(2010,1,11)-40189
ans =
693960
>> datestr(40189+693960)
ans =
11-Jan-2010
In other words, to convert any serial Excel date, call
datestr(excelSerialDate + 693960)
EDIT
To get the date in mm/dd/yyyy format, call datestr
with the specified format
excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010
Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things
excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010
When you install Python or Python3 using MacOS installer (downloaded from Python website) - it adds an export
er to your ~/.profile
script. All you need to do is just source
it. Restarting all the terminals should also do the trick.
WARNING - I believe it's better to just use pip3 with Python3 - for future benefits.
If you already have Python3 installed, the following steps work for me on macOS Mojave:
Install ansible first using sudo
- sudo -H pip3 install ansible
you create a symlink to the Python's bin
path
sudo ln -s /Library/Frameworks/Python.framework/Versions/Current/bin /Library/Frameworks/Python.framework/current_python_bin
and staple it to .profile
export PATH=$PATH:/Library/Frameworks/Python.framework/current_python_bin
run source ~/.profile
and restart all terminal shells.
Type ansible --version
In case you wonder, In Bootstrap templating system (which is very accurate), here is how they divide the columns when you apply the class .col-md-4 (1/3 of the 12 column system)
CSS
.col-md-4{
float: left;
width: 33.33333333%;
}
I'm not a fan of float, but if you really want your element to be perfectly 1/3 of your page, then you don't have a choice because sometimes when you use inline-block element, browser can consider space in your HTML as a 1px space which would break your perfect 1/3. Hope it helped !
To compare, there are more options:
import (
"fmt"
"regexp"
"strings"
)
const (
str = "something"
substr = "some"
)
// 1. Contains
res := strings.Contains(str, substr)
fmt.Println(res) // true
// 2. Index: check the index of the first instance of substr in str, or -1 if substr is not present
i := strings.Index(str, substr)
fmt.Println(i) // 0
// 3. Split by substr and check len of the slice, or length is 1 if substr is not present
ss := strings.Split(str, substr)
fmt.Println(len(ss)) // 2
// 4. Check number of non-overlapping instances of substr in str
c := strings.Count(str, substr)
fmt.Println(c) // 1
// 5. RegExp
matched, _ := regexp.MatchString(substr, str)
fmt.Println(matched) // true
// 6. Compiled RegExp
re = regexp.MustCompile(substr)
res = re.MatchString(str)
fmt.Println(res) // true
Benchmarks:
Contains
internally calls Index
, so the speed is almost the same (btw Go 1.11.5 showed a bit bigger difference than on Go 1.14.3).
BenchmarkStringsContains-4 100000000 10.5 ns/op 0 B/op 0 allocs/op
BenchmarkStringsIndex-4 117090943 10.1 ns/op 0 B/op 0 allocs/op
BenchmarkStringsSplit-4 6958126 152 ns/op 32 B/op 1 allocs/op
BenchmarkStringsCount-4 42397729 29.1 ns/op 0 B/op 0 allocs/op
BenchmarkStringsRegExp-4 461696 2467 ns/op 1326 B/op 16 allocs/op
BenchmarkStringsRegExpCompiled-4 7109509 168 ns/op 0 B/op 0 allocs/op
Many distinctions have already been mentioned. Here is one more:
Running npm install
at the top of your source directory will run various scripts: prepublish
, preinstall
, install
, postinstall
. Depending on what these scripts do, a npm install
may do considerably more work than just installing dependencies.
I've just had a use case where prepublish
would call make
and the Makefile
was designed to fetch dependencies if the package.json
got updated. Calling npm install
from within the Makefile
would have lead to an infinite recursion, while calling npm update
worked just fine, installing all dependencies so that the build could proceed even if make
was called directly.
go test -v -timeout 30s <path_to_package> -run ^(TestFuncRegEx)
go
test file in that package-run TestCaseFunc
h2 { display: inline }
In Sql the with statement specifies a temporary named result set, known as a common table expression (CTE). It can be used for recursive queries, but in this case, it specifies as subset. If mysql allows for subselectes i would try
select t1.*
from (
SELECT article.*,
userinfo.*,
category.*
FROM question INNER JOIN
userinfo ON userinfo.user_userid=article.article_ownerid INNER JOIN category ON article.article_categoryid=category.catid
WHERE article.article_isdeleted = 0
) t1
ORDER BY t1.article_date DESC Limit 1, 3
Just a note for @"John Sansom" answer,
If the foreign key dependencies are sought, I think that the PT Where clause should be:
i1.CONSTRAINT_TYPE = 'FOREIGN KEY' -- instead of 'PRIMARY KEY'
and its the ON condition:
ON PT.TABLE_NAME = FK.TABLE_NAME – instead of PK.TABLE_NAME
As commonly is used the primary key of the foreign table, I think this issue has not been noticed before.
sed
is the Stream EDitor. It can do a whole pile of really cool things, but the most common is text replacement.
The s,%,$,g
part of the command line is the sed
command to execute. The s
stands for substitute, the ,
characters are delimiters (other characters can be used; /
, :
and @
are popular). The %
is the pattern to match (here a literal percent sign) and the $
is the second pattern to match (here a literal dollar sign). The g
at the end means to g
lobally replace on each line (otherwise it would only update the first match).