For latest OSX versions,
Get Info
Sharing & Permission
sectionRead & Write
privilege for the users+
icon to add usernameFinally click settings icon
and select Apply to enclosed items...
You can pass it as Action<string>
- which means it is a method with a single parameter of type string
that doesn't return anything (void) :
public void DoRequest(string request, Action<string> callback)
{
// do stuff....
callback("asdf");
}
$key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion'
(Get-ItemProperty -Path $key -Name ProgramFilesDir).ProgramFilesDir
I've never liked how this was provider was implemented like this : /
Basically, it makes every registry value a PSCustomObject
object with PsPath
, PsParentPath
, PsChildname
, PSDrive
and PSProvider
properties and then a property for its actual value. So even though you asked for the item by name, to get its value you have to use the name once more.
that's just a shorthand notation in most languages.which means that
x=x+1;
we can do the same operation for x-=1,x*=1,x/=1; which means
The same reason there isn't an int.Empty
. Containers can be empty, scalar values cannot. If you mean 0 (which is not empty), then use '\0'
. If you mean null
, then use null
:)
The curses
package in python can be used to enter "raw" mode for character input from the terminal with just a few statements. Curses' main use is to take over the screen for output, which may not be what you want. This code snippet uses print()
statements instead, which are usable, but you must be aware of how curses changes line endings attached to output.
#!/usr/bin/python3
# Demo of single char terminal input in raw mode with the curses package.
import sys, curses
def run_one_char(dummy):
'Run until a carriage return is entered'
char = ' '
print('Welcome to curses', flush=True)
while ord(char) != 13:
char = one_char()
def one_char():
'Read one character from the keyboard'
print('\r? ', flush= True, end = '')
## A blocking single char read in raw mode.
char = sys.stdin.read(1)
print('You entered %s\r' % char)
return char
## Must init curses before calling any functions
curses.initscr()
## To make sure the terminal returns to its initial settings,
## and to set raw mode and guarantee cleanup on exit.
curses.wrapper(run_one_char)
print('Curses be gone!')
Please try something like:
=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))
You seem to have three main possible scenarios:
ColumnA below is formatted General and ColumnB as Date (my default setting). ColumnC also as date but with custom formatting to suit the appearances mentioned in your question.
A clue as to whether or not text format is the left or right alignment of the cells’ contents.
I am suggesting separate treatment for each of the above three main cases, so use =IF to differentiate them.
This is longer than any of the others, so can be distinguished as having a length greater than say 10 characters, with =LEN.
In this case we want all but the last six characters but for added flexibility (for instance, in case the time element included seconds) I have chosen to count from the left rather than from the right. The problem then is that the month names may vary in length, so I have chosen to look for the space that immediately follows the year to indicate the limit for the relevant number of characters.
This with =FIND which looks for a space (" "
) in C1
, starting with the eighth character within C1
counting from the left, on the assumption that for this case days will be expressed as two characters and months as three or more.
Since =LEFT is a string function it returns a string, but this can be converted to a value with=VALUE.
So
=VALUE(LEFT(C1,FIND(" ",C1,8)))
returns 40671
in this example – in Excel’s 1900 date system the date serial number for May 5, 2011.
If the length of C1 is not greater than 10 characters, we still need to distinguish between a text entry or a value entry which I have chosen to do with =ISTEXT and, where the if condition is TRUE (as for C2) apply =DATE which takes three parameters, here provided by:
=RIGHT(C2,4)
Takes the last four characters of C2, hence 2011
in this example.
=MID(C2,4,2)
Starting at the fourth character, takes the next two characters of C2, hence 05
in this example (representing May).
=LEFT(C2,2))
Takes the first two characters of C2, hence 08
in this example (representing the 8th day of the month).
Date is not a text function so does not need to be wrapped in =VALUE.
Taken together
=DATE(RIGHT(C2,4),MID(C2,4,2),LEFT(C2,2))
also returns 40671
in this example, but from different input from Case #1.
Is simple because already a date serial number, so just
=C2
is sufficient.
Put the above together to cover all three cases in a single formula:
=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))
as applied in ColumnF (formatted to suit OP) or in General format (to show values are integers) in ColumnH:
Your code is way more cluttered than necessary.
Replace (Not (X Is Nothing))
with X IsNot Nothing
and omit the outer parentheses:
If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
For i As Integer = 0 To comp.Container.Components.Count() - 1
fixUIIn(comp.Container.Components(i), style)
Next
End If
Much more readable. … Also notice that I’ve removed the redundant Step 1
and the probably redundant .Item
.
But (as pointed out in the comments), index-based loops are out of vogue anyway. Don’t use them unless you absolutely have to. Use For Each
instead:
If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
For Each component In comp.Container.Components
fixUIIn(component, style)
Next
End If
You mean fast enumeration? You question is very unclear.
A normal for loop would look a bit like this:
unsigned int i, cnt = [someArray count];
for(i = 0; i < cnt; i++)
{
// do loop stuff
id someObject = [someArray objectAtIndex:i];
}
And a loop with fast enumeration, which is optimized by the compiler, would look like this:
for(id someObject in someArray)
{
// do stuff with object
}
Keep in mind that you cannot change the array you are using in fast enumeration, thus no deleting nor adding when using fast enumeration
You should have sdiff
for side-by-side merge of file differences. Take a read of man sdiff
for the full story.
Just the same as what should be but change the button component to be label like so
<form id='uploadForm'
action='http://localhost:8000/upload'
method='post'
encType="multipart/form-data">
<input type="file" id="sampleFile" style="display: none;" />
<Button htmlFor="sampleFile" component="label" type={'submit'}>Upload</Button>
</form>
@Garret Wilson Thank you so much! As a noob to android coding, I've been stuck with the preferences incompatibility issue for so many hours, and I find it so disappointing they deprecated the use of some methods/approaches for new ones that aren't supported by the older APIs thus having to resort to all sorts of workarounds to make your app work in a wide range of devices. It's really frustrating!
Your class is great, for it allows you to keep working in new APIs wih preferences the way it used to be, but it's not backward compatible. Since I'm trying to reach a wide range of devices I tinkered with it a bit to make it work in pre API 11 devices as well as in newer APIs:
import android.annotation.TargetApi;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
public class MyPrefsActivity extends PreferenceActivity
{
private static int prefs=R.xml.myprefs;
@Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try {
getClass().getMethod("getFragmentManager");
AddResourceApi11AndGreater();
} catch (NoSuchMethodException e) { //Api < 11
AddResourceApiLessThan11();
}
}
@SuppressWarnings("deprecation")
protected void AddResourceApiLessThan11()
{
addPreferencesFromResource(prefs);
}
@TargetApi(11)
protected void AddResourceApi11AndGreater()
{
getFragmentManager().beginTransaction().replace(android.R.id.content,
new PF()).commit();
}
@TargetApi(11)
public static class PF extends PreferenceFragment
{
@Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(MyPrefsActivity.prefs); //outer class
// private members seem to be visible for inner class, and
// making it static made things so much easier
}
}
}
Tested in two emulators (2.2 and 4.2) with success.
Why my code looks so crappy:
I'm a noob to android coding, and I'm not the greatest java fan.
In order to avoid the deprecated warning and to force Eclipse to allow me to compile I had to resort to annotations, but these seem to affect only classes or methods, so I had to move the code onto two new methods to take advantage of this.
I wouldn't like having to write my xml resource id twice anytime I copy&paste the class for a new PreferenceActivity, so I created a new variable to store this value.
I hope this will be useful to somebody else.
P.S.: Sorry for my opinionated views, but when you come new and find such handicaps, you can't help it but to get frustrated!
http://forums.iis.net/t/1187650.aspx has the answer. Setting the iis authentication to appliction pool identity will resolve this.
In IIS Authentication, Anonymous Authentication was set to "Specific User". When I changed it to Application Pool, I can access the site.
To set, click on your website in IIS and double-click "Authentication". Right-click on "Anonymous Authentication" and click "Edit..." option. Switch from "Specific User" to "Application pool identity". Now you should be able to set file and folder permissions using the IIS AppPool\{Your App Pool Name}.
Here is example code showing how to compute a centered moving average and a trailing moving average using the rollmean
function from the zoo package.
library(tidyverse)
library(zoo)
some_data = tibble(day = 1:10)
# cma = centered moving average
# tma = trailing moving average
some_data = some_data %>%
mutate(cma = rollmean(day, k = 3, fill = NA)) %>%
mutate(tma = rollmean(day, k = 3, fill = NA, align = "right"))
some_data
#> # A tibble: 10 x 3
#> day cma tma
#> <int> <dbl> <dbl>
#> 1 1 NA NA
#> 2 2 2 NA
#> 3 3 3 2
#> 4 4 4 3
#> 5 5 5 4
#> 6 6 6 5
#> 7 7 7 6
#> 8 8 8 7
#> 9 9 9 8
#> 10 10 NA 9
The short version is: The efficient way to use readlines()
is to not use it. Ever.
I read some doc notes on
readlines()
, where people has claimed that thisreadlines()
reads whole file content into memory and hence generally consumes more memory compared to readline() or read().
The documentation for readlines()
explicitly guarantees that it reads the whole file into memory, and parses it into lines, and builds a list
full of str
ings out of those lines.
But the documentation for read()
likewise guarantees that it reads the whole file into memory, and builds a str
ing, so that doesn't help.
On top of using more memory, this also means you can't do any work until the whole thing is read. If you alternate reading and processing in even the most naive way, you will benefit from at least some pipelining (thanks to the OS disk cache, DMA, CPU pipeline, etc.), so you will be working on one batch while the next batch is being read. But if you force the computer to read the whole file in, then parse the whole file, then run your code, you only get one region of overlapping work for the entire file, instead of one region of overlapping work per read.
You can work around this in three ways:
readlines(sizehint)
, read(size)
, or readline()
.mmap
the file, which allows you to treat it as a giant string without first reading it in.For example, this has to read all of foo
at once:
with open('foo') as f:
lines = f.readlines()
for line in lines:
pass
But this only reads about 8K at a time:
with open('foo') as f:
while True:
lines = f.readlines(8192)
if not lines:
break
for line in lines:
pass
And this only reads one line at a time—although Python is allowed to (and will) pick a nice buffer size to make things faster.
with open('foo') as f:
while True:
line = f.readline()
if not line:
break
pass
And this will do the exact same thing as the previous:
with open('foo') as f:
for line in f:
pass
Meanwhile:
but should the garbage collector automatically clear that loaded content from memory at the end of my loop, hence at any instant my memory should have only the contents of my currently processed file right ?
Python doesn't make any such guarantees about garbage collection.
The CPython implementation happens to use refcounting for GC, which means that in your code, as soon as file_content
gets rebound or goes away, the giant list of strings, and all of the strings within it, will be freed to the freelist, meaning the same memory can be reused again for your next pass.
However, all those allocations, copies, and deallocations aren't free—it's much faster to not do them than to do them.
On top of that, having your strings scattered across a large swath of memory instead of reusing the same small chunk of memory over and over hurts your cache behavior.
Plus, while the memory usage may be constant (or, rather, linear in the size of your largest file, rather than in the sum of your file sizes), that rush of malloc
s to expand it the first time will be one of the slowest things you do (which also makes it much harder to do performance comparisons).
Putting it all together, here's how I'd write your program:
for filename in os.listdir(input_dir):
with open(filename, 'rb') as f:
if filename.endswith(".gz"):
f = gzip.open(fileobj=f)
words = (line.split(delimiter) for line in f)
... my logic ...
Or, maybe:
for filename in os.listdir(input_dir):
if filename.endswith(".gz"):
f = gzip.open(filename, 'rb')
else:
f = open(filename, 'rb')
with contextlib.closing(f):
words = (line.split(delimiter) for line in f)
... my logic ...
If you have integers in your file fscanf returns 1 until integer occurs. For example:
FILE *in = fopen("./task.in", "r");
int length = 0;
int counter;
int sequence;
for ( int i = 0; i < 10; i++ ) {
counter = fscanf(in, "%d", &sequence);
if ( counter == 1 ) {
length += 1;
}
}
To find out the end of the file with symbols you can use EOF. For example:
char symbol;
FILE *in = fopen("./task.in", "r");
for ( ; fscanf(in, "%c", &symbol) != EOF; ) {
printf("%c", symbol);
}
Below code for best examples for nested loops, while using two for loops please remember the output of the first loop is input for the second loop. Loop termination also important while using the nested loops
for x in range(1, 10, 1):
for y in range(1,x):
print y,
print
OutPut :
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
I know this is very late, but is useful for newbies. We can atuload url helper and it will be available throughout the application. For this in application\config\autoload.php modify as follows -
$autoload['helper'] = array('url');
try this
if(isset($itemCost) != '' && isset($itemQty) != '')
{
$diffPricePercent = (($actual * 100) / $itemCost) / $itemQty;
}
else
{
echo "either of itemCost or itemQty are null";
}
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.
x <-c(1,2,3)
y <-c(100,200,300)
x_name <- "cond"
y_name <- "rating"
require(reshape2)
df <- melt(data.frame(x,y))
colnames(df) <- c(x_name, y_name)
print(df)
UPDATE (2017-02-07): As an answer to @cdaringe comment - there are multiple solutions possible, one of them is below.
library(dplyr)
library(magrittr)
x <- c(1, 2, 3)
y <- c(100, 200, 300)
z <- c(1, 2, 3, 4, 5)
x_name <- "cond"
y_name <- "rating"
# Helper function to create data.frame for the chunk of the data
prepare <- function(name, value, xname = x_name, yname = y_name) {
data_frame(rep(name, length(value)), value) %>%
set_colnames(c(xname, yname))
}
bind_rows(
prepare("x", x),
prepare("y", y),
prepare("z", z)
)
Files named __init__.py
are used to mark directories on disk as Python package directories.
If you have the files
mydir/spam/__init__.py
mydir/spam/module.py
and mydir
is on your path, you can import the code in module.py
as
import spam.module
or
from spam import module
If you remove the __init__.py
file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.
The __init__.py
file is usually empty, but can be used to export selected portions of the package under more convenient name, hold convenience functions, etc.
Given the example above, the contents of the init module can be accessed as
import spam
based on this
I tried every thing, but still I was unable to do that, I am using mysql, jpa with hibernate, I resolved my issue by assigning value of id 0 in constructor Following is my id declaration code
@Id
@Column(name="id",updatable=false,nullable=false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
Using keySet-
id1.keySet().stream()
.filter(x -> x == 1)
.map(x -> id1.get(x))
.collect(Collectors.toList())
I found a GitHub project that successfully uses CommonCrypto in a Swift framework: SHA256-Swift. Also, this article about the same problem with sqlite3 was useful.
Based on the above, the steps are:
1) Create a CommonCrypto
directory inside the project directory. Within, create a module.map
file. The module map will allow us to use the CommonCrypto library as a module within Swift. Its contents are:
module CommonCrypto [system] {
header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.0.sdk/usr/include/CommonCrypto/CommonCrypto.h"
link "CommonCrypto"
export *
}
2) In Build Settings, within Swift Compiler - Search Paths, add the CommonCrypto
directory to Import Paths (SWIFT_INCLUDE_PATHS
).
3) Finally, import CommonCrypto inside your Swift files as any other modules. For example:
import CommonCrypto
extension String {
func hnk_MD5String() -> String {
if let data = self.dataUsingEncoding(NSUTF8StringEncoding)
{
let result = NSMutableData(length: Int(CC_MD5_DIGEST_LENGTH))
let resultBytes = UnsafeMutablePointer<CUnsignedChar>(result.mutableBytes)
CC_MD5(data.bytes, CC_LONG(data.length), resultBytes)
let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, length: result.length)
let MD5 = NSMutableString()
for c in resultEnumerator {
MD5.appendFormat("%02x", c)
}
return MD5
}
return ""
}
}
Using the custom framework in another project fails at compile time with the error missing required module 'CommonCrypto'
. This is because the CommonCrypto module does not appear to be included with the custom framework. A workaround is to repeat step 2 (setting Import Paths
) in the project that uses the framework.
The module map is not platform independent (it currently points to a specific platform, the iOS 8 Simulator). I don't know how to make the header path relative to the current platform.
Updates for iOS 8 <= We should remove the line link "CommonCrypto", to get the successful compilation.
UPDATE / EDIT
I kept getting the following build error:
ld: library not found for -lCommonCrypto for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)
Unless I removed the line link "CommonCrypto"
from the module.map
file I created. Once I removed this line it built ok.
Starting from Windows Vista, a service cannot interact with the desktop. You will not be able to see any windows or console windows that are started from a service. See this MSDN forum thread.
On other OS, there is an option that is available in the service option called "Allow Service to interact with desktop". Technically, you should program for the future and should follow the Vista guideline even if you don't use it on Vista.
If you still want to run an application that never interact with the desktop, try specifying the process to not use the shell.
ProcessStartInfo info = new ProcessStartInfo(@"c:\myprogram.exe");
info.UseShellExecute = false;
info.RedirectStandardError = true;
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.CreateNoWindow = true;
info.ErrorDialog = false;
info.WindowStyle = ProcessWindowStyle.Hidden;
Process process = Process.Start(info);
See if this does the trick.
First you inform Windows that the program won't use the shell (which is inaccessible in Vista to service).
Secondly, you redirect all consoles interaction to internal stream (see process.StandardInput
and process.StandardOutput
.
Simple and neet : use vw
units for a responsive height/width according to the viewport width.
vw : 1/100th of the width of the viewport. (Source MDN)
HTML:
<div></div>
CSS for a 1:1 aspect ratio:
div{
width:80vw;
height:80vw; /* same as width */
}
Table to calculate height according to the desired aspect ratio and width of element.
aspect ratio | multiply width by
-----------------------------------
1:1 | 1
1:3 | 3
4:3 | 0.75
16:9 | 0.5625
This technique allows you to :
position:absolute;
These units are supported by IE9+ see canIuse for more info
You cannot change the img src using css. You can use the following pure css solution though. HTML:
<div id="asks"></div>
CSS:
#asks {
width: 100px;
height: 100px;
background-image: url('http://dummyimage.com/100x100/0000/fff');
}
#asks:hover {
background-image: url('http://dummyimage.com/100x100/eb00eb/fff');
}
Or, if you don't want to use a div with a background image, you can use a javascript/jQuery solution. Html:
<img id="asks" src="http://dummyimage.com/100x100/000/fff" />
jQuery:
$('#asks')
.mouseenter(function(){$('#asks').attr('src', 'http://dummyimage.com/100x100/eb00eb/fff');})
.mouseleave(function(){$('#asks').attr('src', 'http://dummyimage.com/100x100/000/fff');});
Your best bet is to use find with tar, via xargs (to handle the large number of arguments). For example:
find / -print0 | xargs -0 tar cjf tarfile.tar.bz2
psql
below 9.2 does not accept this URL-like syntax for options.
The use of SSL can be driven by the sslmode=value
option on the command line or the PGSSLMODE environment variable, but the default being prefer
, SSL connections will be tried first automatically without specifying anything.
Example with a conninfo string (updated for psql 8.4)
psql "sslmode=require host=localhost dbname=test"
Read the manual page for more options.
I noticed that almost every solution posted involved ax.imshow(im, ...)
and did not normalize the colors displayed to the colorbar for the multiple subfigures. The im
mappable is taken from the last instance, but what if the values of the multiple im
-s are different? (I'm assuming these mappables are treated in the same way that the contour-sets and surface-sets are treated.) I have an example using a 3d surface plot below that creates two colorbars for a 2x2 subplot (one colorbar per one row). Although the question asks explicitly for a different arrangement, I think the example helps clarify some things. I haven't found a way to do this using plt.subplots(...)
yet because of the 3D axes unfortunately.
If only I could position the colorbars in a better way... (There is probably a much better way to do this, but at least it should be not too difficult to follow.)
import matplotlib
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
cmap = 'plasma'
ncontours = 5
def get_data(row, col):
""" get X, Y, Z, and plot number of subplot
Z > 0 for top row, Z < 0 for bottom row """
if row == 0:
x = np.linspace(1, 10, 10, dtype=int)
X, Y = np.meshgrid(x, x)
Z = np.sqrt(X**2 + Y**2)
if col == 0:
pnum = 1
else:
pnum = 2
elif row == 1:
x = np.linspace(1, 10, 10, dtype=int)
X, Y = np.meshgrid(x, x)
Z = -np.sqrt(X**2 + Y**2)
if col == 0:
pnum = 3
else:
pnum = 4
print("\nPNUM: {}, Zmin = {}, Zmax = {}\n".format(pnum, np.min(Z), np.max(Z)))
return X, Y, Z, pnum
fig = plt.figure()
nrows, ncols = 2, 2
zz = []
axes = []
for row in range(nrows):
for col in range(ncols):
X, Y, Z, pnum = get_data(row, col)
ax = fig.add_subplot(nrows, ncols, pnum, projection='3d')
ax.set_title('row = {}, col = {}'.format(row, col))
fhandle = ax.plot_surface(X, Y, Z, cmap=cmap)
zz.append(Z)
axes.append(ax)
## get full range of Z data as flat list for top and bottom rows
zz_top = zz[0].reshape(-1).tolist() + zz[1].reshape(-1).tolist()
zz_btm = zz[2].reshape(-1).tolist() + zz[3].reshape(-1).tolist()
## get top and bottom axes
ax_top = [axes[0], axes[1]]
ax_btm = [axes[2], axes[3]]
## normalize colors to minimum and maximum values of dataset
norm_top = matplotlib.colors.Normalize(vmin=min(zz_top), vmax=max(zz_top))
norm_btm = matplotlib.colors.Normalize(vmin=min(zz_btm), vmax=max(zz_btm))
cmap = cm.get_cmap(cmap, ncontours) # number of colors on colorbar
mtop = cm.ScalarMappable(cmap=cmap, norm=norm_top)
mbtm = cm.ScalarMappable(cmap=cmap, norm=norm_btm)
for m in (mtop, mbtm):
m.set_array([])
# ## create cax to draw colorbar in
# cax_top = fig.add_axes([0.9, 0.55, 0.05, 0.4])
# cax_btm = fig.add_axes([0.9, 0.05, 0.05, 0.4])
cbar_top = fig.colorbar(mtop, ax=ax_top, orientation='vertical', shrink=0.75, pad=0.2) #, cax=cax_top)
cbar_top.set_ticks(np.linspace(min(zz_top), max(zz_top), ncontours))
cbar_btm = fig.colorbar(mbtm, ax=ax_btm, orientation='vertical', shrink=0.75, pad=0.2) #, cax=cax_btm)
cbar_btm.set_ticks(np.linspace(min(zz_btm), max(zz_btm), ncontours))
plt.show()
plt.close(fig)
## orientation of colorbar = 'horizontal' if done by column
When I tried @vipw's suggestion, I was faced with this exception:
The method getJSONObject(int) is undefined for the type JSONArray
This worked for me instead:
int myJsonArraySize = myJsonArray.size();
for (int i = 0; i < myJsonArraySize; i++) {
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
// Do whatever you have to do to myJsonObject...
}
In short, no, you can't.
Long answer, extension methods are just syntactic sugar. IE:
If you have an extension method on string let's say:
public static string SomeStringExtension(this string s)
{
//whatever..
}
When you then call it:
myString.SomeStringExtension();
The compiler just turns it into:
ExtensionClass.SomeStringExtension(myString);
So as you can see, there's no way to do that for static methods.
And another thing just dawned on me: what would really be the point of being able to add static methods on existing classes? You can just have your own helper class that does the same thing, so what's really the benefit in being able to do:
Bool.Parse(..)
vs.
Helper.ParseBool(..);
Doesn't really bring much to the table...
If its working when you are using a browser and then passing on your username and password for the first time - then this means that once authentication is done Request header of your browser is set with required authentication values, which is then passed on each time a request is made to hosting server.
So start with inspecting Request Header (this could be done using Web Developers tools), Once you established whats required in header then you could pass this within your HttpWebRequest Header.
Example with Digest Authentication:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
namespace NUI
{
public class DigestAuthFixer
{
private static string _host;
private static string _user;
private static string _password;
private static string _realm;
private static string _nonce;
private static string _qop;
private static string _cnonce;
private static DateTime _cnonceDate;
private static int _nc;
public DigestAuthFixer(string host, string user, string password)
{
// TODO: Complete member initialization
_host = host;
_user = user;
_password = password;
}
private string CalculateMd5Hash(
string input)
{
var inputBytes = Encoding.ASCII.GetBytes(input);
var hash = MD5.Create().ComputeHash(inputBytes);
var sb = new StringBuilder();
foreach (var b in hash)
sb.Append(b.ToString("x2"));
return sb.ToString();
}
private string GrabHeaderVar(
string varName,
string header)
{
var regHeader = new Regex(string.Format(@"{0}=""([^""]*)""", varName));
var matchHeader = regHeader.Match(header);
if (matchHeader.Success)
return matchHeader.Groups[1].Value;
throw new ApplicationException(string.Format("Header {0} not found", varName));
}
private string GetDigestHeader(
string dir)
{
_nc = _nc + 1;
var ha1 = CalculateMd5Hash(string.Format("{0}:{1}:{2}", _user, _realm, _password));
var ha2 = CalculateMd5Hash(string.Format("{0}:{1}", "GET", dir));
var digestResponse =
CalculateMd5Hash(string.Format("{0}:{1}:{2:00000000}:{3}:{4}:{5}", ha1, _nonce, _nc, _cnonce, _qop, ha2));
return string.Format("Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", " +
"algorithm=MD5, response=\"{4}\", qop={5}, nc={6:00000000}, cnonce=\"{7}\"",
_user, _realm, _nonce, dir, digestResponse, _qop, _nc, _cnonce);
}
public string GrabResponse(
string dir)
{
var url = _host + dir;
var uri = new Uri(url);
var request = (HttpWebRequest)WebRequest.Create(uri);
// If we've got a recent Auth header, re-use it!
if (!string.IsNullOrEmpty(_cnonce) &&
DateTime.Now.Subtract(_cnonceDate).TotalHours < 1.0)
{
request.Headers.Add("Authorization", GetDigestHeader(dir));
}
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
// Try to fix a 401 exception by adding a Authorization header
if (ex.Response == null || ((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)
throw;
var wwwAuthenticateHeader = ex.Response.Headers["WWW-Authenticate"];
_realm = GrabHeaderVar("realm", wwwAuthenticateHeader);
_nonce = GrabHeaderVar("nonce", wwwAuthenticateHeader);
_qop = GrabHeaderVar("qop", wwwAuthenticateHeader);
_nc = 0;
_cnonce = new Random().Next(123400, 9999999).ToString();
_cnonceDate = DateTime.Now;
var request2 = (HttpWebRequest)WebRequest.Create(uri);
request2.Headers.Add("Authorization", GetDigestHeader(dir));
response = (HttpWebResponse)request2.GetResponse();
}
var reader = new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
}
Then you could call it:
DigestAuthFixer digest = new DigestAuthFixer(domain, username, password);
string strReturn = digest.GrabResponse(dir);
if Url is: http://xyz.rss.com/folder/rss then domain: http://xyz.rss.com (domain part) dir: /folder/rss (rest of the url)
you could also return it as stream and use XmlDocument Load() method.
I had the same issue. In my home folder I've got a script named sqlplus.sh that takes care of this for me, containing:
ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/server
export ORACLE_HOME
ORACLE_SID=XE
export ORACLE_SID
NLS_LANG=`$ORACLE_HOME/bin/nls_lang.sh`
export NLS_LANG
PATH=$ORACLE_HOME/bin:$PATH
export PATH
sqlplus /nolog
You can use the following methods to update the value of a reactive form control. Any of the following method will suit for your need.
Methods using setValue()
this.form.get("dept").setValue(selected.id);
this.form.controls["dept"].setValue(selected.id);
Methods using patchValue()
this.form.get("dept").patchValue(selected.id);
this.form.controls['dept'].patchValue(selected.id);
this.form.patchValue({"dept": selected.id});
Last method will loop thorough all the controls in the form so it is not preferred when updating single control
You can use any of the method inside the event handler
deptSelected(selected: { id: string; text: string }) {
// any of the above method can be added here
}
You can update multiple controls in the form group if required using the
this.form.patchValue({"dept": selected.id, "description":"description value"});
I'm afraid that WhatsApp for Android does not currently support to be called from a web browser.
I had the same requirement for my current project, and since I couldn't find any proper information I ended up downloading the APK file.
In Android, if an application wants to be called from a web browser, it needs to define an Activity with the category android.intent.category.BROWSABLE.
You can find more information about this here: https://developers.google.com/chrome/mobile/docs/intents
If you take a look to the WhatsApp AndroidManifest.xml file, the only Activiy with category BROWSABLE is this one:
<activity android:name="com.whatsapp.Conversation" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:windowSoftInputMode="stateUnchanged">
<intent-filter>
<action android:name="android.intent.action.SENDTO" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="sms" />
<data android:scheme="smsto" />
</intent-filter>
</activity>
I've been playing with it for a while, and I couldn't make it to work. The most I got was to open the WhatsApp application from Chrome, but I couldn't figure out a way to set the message content and recipient.
Since it is not documented by the WhatsApp team, I think this is still work in progress. It looks like in the future WhatsApp will handle SMS too.
The only way to get more information is by reaching the WhatsApp dev team, what I tried, but I'm still waiting for a response.
Regards!
We released a new library: PySimpleSOAP, that provides support for simple and functional client/server. It goals are: ease of use and flexibility (no classes, autogenerated code or xml is required), WSDL introspection and generation, WS-I standard compliance, compatibility (including Java AXIS, .NET and Jboss WS). It is included into Web2Py to enable full-stack solutions (complementing other supported protocols such as XML_RPC, JSON, AMF-RPC, etc.).
If someone is learning SOAP or want to investigate it, I think it is a good choice to start.
You can switch to shell mode temporarily by:
:! <command>
such as
:! ls
Surely using array_map
and if using a container implementing ArrayAccess
to derive objects is just a smarter, semantic way to go about this?
Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.
For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN()
clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait
cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.
<?php
$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);
vs
<?php
$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
$arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);
If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr
you could always $arr = array_map
and be explicit.
You need to use ScriptManager.RegisterStartupScript for Ajax.
protected void ButtonPP_Click(object sender, EventArgs e) { if (radioBtnACO.SelectedIndex < 0) { string csname1 = "PopupScript"; var cstext1 = new StringBuilder(); cstext1.Append("alert('Please Select Criteria!')"); ScriptManager.RegisterStartupScript(this, GetType(), csname1, cstext1.ToString(), true); } }
I like the SQLite2009 Pro Enterprise Manager suggested by Jfly. However:
The MySQL datatype INT is not converted to SQlite datatype INTEGER (works with DBeaver )
It does not import foreign key constaints from MySQL (I could not find any tool that supports the transfer of foreign key constraints from MySQL to SQlite.)
Converting it to integer worked for me:
int(sub_df.iloc[0])
const a = {
foods: {
dinner: 'Pasta'
}
}
let b = JSON.parse(JSON.stringify(a))
b.foods.dinner = 'Soup'
console.log(b.foods.dinner) // Soup
console.log(a.foods.dinner) // Pasta
Using JSON.stringify
and JSON.parse
is the best way. Because by using the spread operator we will not get the efficient answer when the json object contains another object inside it. we need to manually specify that.
Recurisvely with ls: (-al for include hidden folders)
ftype="jpg"
ls -1R *.${ftype} 2> /dev/null
Just open your repository file and add this new function, then call it inside your controller:
public function distinctCategories(){
return $this->createQueryBuilder('cc')
->where('cc.contenttype = :type')
->setParameter('type', 'blogarticle')
->groupBy('cc.blogarticle')
->getQuery()
->getResult()
;
}
Then within your controller:
public function index(YourRepository $repo)
{
$distinctCategories = $repo->distinctCategories();
return $this->render('your_twig_file.html.twig', [
'distinctCategories' => $distinctCategories
]);
}
Good luck!
I used the RowHeight
property of a range (which means cells as well). If it's zero then it's hidden.
So just loop through all rows as you would normally but in the if
condition check for that property as in If myRange.RowHeight > 0 then DoStuff
where DoStuff
is something you want to do with the visible cells.
PLAIN JAVASCRIPT:
DEMO: http://codepen.io/tazotodua/pen/orhdp
var shownnn = "yes";_x000D_
var dropd = document.getElementById("image-dropdown");_x000D_
_x000D_
function showww() {_x000D_
dropd.style.height = "auto";_x000D_
dropd.style.overflow = "y-scroll";_x000D_
}_x000D_
_x000D_
function hideee() {_x000D_
dropd.style.height = "30px";_x000D_
dropd.style.overflow = "hidden";_x000D_
}_x000D_
//dropd.addEventListener('mouseover', showOrHide, false);_x000D_
//dropd.addEventListener('click',showOrHide , false);_x000D_
_x000D_
_x000D_
function myfuunc(imgParent) {_x000D_
hideee();_x000D_
var mainDIVV = document.getElementById("image-dropdown");_x000D_
imgParent.parentNode.removeChild(imgParent);_x000D_
mainDIVV.insertBefore(imgParent, mainDIVV.childNodes[0]);_x000D_
}
_x000D_
#image-dropdown {_x000D_
display: inline-block;_x000D_
border: 1px solid;_x000D_
}_x000D_
#image-dropdown {_x000D_
height: 30px;_x000D_
overflow: hidden;_x000D_
}_x000D_
/*#image-dropdown:hover {} */_x000D_
_x000D_
#image-dropdown .img_holder {_x000D_
cursor: pointer;_x000D_
}_x000D_
#image-dropdown img.flagimgs {_x000D_
height: 30px;_x000D_
}_x000D_
#image-dropdown span.iTEXT {_x000D_
position: relative;_x000D_
top: -8px;_x000D_
}
_x000D_
<!-- not tested in mobiles -->_x000D_
_x000D_
_x000D_
<div id="image-dropdown" onmouseleave="hideee();">_x000D_
<div class="img_holder" onclick="myfuunc(this);" onmouseover="showww();">_x000D_
<img class="flagimgs first" src="http://www.google.com/tv/images/socialyoutube.png" /> <span class="iTEXT">First</span>_x000D_
</div>_x000D_
<div class="img_holder" onclick="myfuunc(this);" onmouseover="showww();">_x000D_
<img class="flagimgs second" src="http://www.google.com/cloudprint/learn/images/icons/fiabee.png" /> <span class="iTEXT">Second</span>_x000D_
</div>_x000D_
<div class="img_holder" onclick="myfuunc(this);" onmouseover="showww();">_x000D_
<img class="flagimgs second" src="http://www.google.com/tv/images/lplay.png" /> <span class="iTEXT">Third</span>_x000D_
</div>_x000D_
<div class="img_holder" onclick="myfuunc(this);" onmouseover="showww();">_x000D_
<img class="flagimgs second" src="http://www.google.com/cloudprint/learn/images/icons/cloudprintlite.png" /> <span class="iTEXT">Fourth</span>_x000D_
</div>_x000D_
</div>
_x000D_
public class FindTextInLine {
String match = "123woods";
String text = "I will come and meet you at the 123woods";
public void findText () {
if (text.contains(match)) {
System.out.println("Keyword matched the string" );
}
}
}
This other solution for covert datetime to unixtimestampmillis C#.
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long GetCurrentUnixTimestampMillis()
{
DateTime localDateTime, univDateTime;
localDateTime = DateTime.Now;
univDateTime = localDateTime.ToUniversalTime();
return (long)(univDateTime - UnixEpoch).TotalMilliseconds;
}
You could try:
$j('div.contextualError.ckgcellphone').css('display')
As of PostgreSQL 9.4, you can use the ?
operator:
select info->>'name' from rabbits where (info->'food')::jsonb ? 'carrots';
You can even index the ?
query on the "food"
key if you switch to the jsonb type instead:
alter table rabbits alter info type jsonb using info::jsonb;
create index on rabbits using gin ((info->'food'));
select info->>'name' from rabbits where info->'food' ? 'carrots';
Of course, you probably don't have time for that as a full-time rabbit keeper.
Update: Here's a demonstration of the performance improvements on a table of 1,000,000 rabbits where each rabbit likes two foods and 10% of them like carrots:
d=# -- Postgres 9.3 solution
d=# explain analyze select info->>'name' from rabbits where exists (
d(# select 1 from json_array_elements(info->'food') as food
d(# where food::text = '"carrots"'
d(# );
Execution time: 3084.927 ms
d=# -- Postgres 9.4+ solution
d=# explain analyze select info->'name' from rabbits where (info->'food')::jsonb ? 'carrots';
Execution time: 1255.501 ms
d=# alter table rabbits alter info type jsonb using info::jsonb;
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
Execution time: 465.919 ms
d=# create index on rabbits using gin ((info->'food'));
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
Execution time: 256.478 ms
Use n module from npm in order to upgrade node
sudo npm cache clean -f
sudo npm install -g n
sudo n stable
To upgrade to latest version (and not current stable) version, you can use
sudo n latest
Undo :
sudo apt-get install --reinstall nodejs-legacy # fix /usr/bin/node sudo n rm 6.0.0 # replace number with version of Node that was installed sudo npm uninstall -g n
Adding to exebook's response, the mathematics usage of the keyword let also encapsulates well the scoping implications of let
when used in Javascript/ES6. Specifically, just as the following ES6 code is not aware of the assignment in braces of toPrint
when it prints out the value of 'Hello World'
,
let toPrint = 'Hello World.';
{
let toPrint = 'Goodbye World.';
}
console.log(toPrint); // Prints 'Hello World'
let as used in formalized mathematics (especially the writing of proofs) indicates that the current instance of a variable exists only for the scope of that logical idea. In the following example, x immediately gains a new identity upon entering the new idea (usually these are concepts necessary to prove the main idea) and reverts immediately to the old x upon the conclusion of the sub-proof. Of course, just as in coding, this is considered somewhat confusing and so is usually avoided by choosing a different name for the other variable.
Let x be so and so...
Proof stuff
New Idea { Let x be something else ... prove something } Conclude New Idea
Prove main idea with old x
use
window.location.replace("login.php");
or simply window.location("login.php");
It is better than using window.location.href =,
because replace()
does not put the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco. If you want to simulate someone clicking on a link, use location.href
. If you want to simulate an HTTP redirect, use location.replace
.
There isn't one, at least, not unless you are using a "developer" tool of some kind in your browser, e.g. Firebug in Firefox or the Developer tools in Safari. Then you can usually use console.log
.
If I'm doing something in, say, an iOS device, I might add a <div id="debug" />
and then log to it.
You can simply use the ID attribute to the form and attach the <textarea>
tag to the form like this:
<form name="commentform" action="#" method="post" target="_blank" id="1321">
<textarea name="forcom" cols="40" rows="5" form="1321" maxlength="188">
Enter your comment here...
</textarea>
<input type="submit" value="OK">
<input type="reset" value="Clear">
</form>
The password of keystore by default is: "changeit". I functioned to my commands you entered here, for the import of the certificate. I hope you have already solved your problem.
Use Actions -
The user-facing API for emulating complex user gestures.
See Actions#pause method.
Previous answers will strip your decimal point. If you want to save your decimal, you might want to
String str = "My values are : 900.00, 700.00, 650.50";
String[] values = str.split("[^\\d.?\\d]");
// split on wherever they are not digits except the '.' decimal point
// values: { "900.00", "700.00", "650.50"}
In my opinion this is the simplest solution
$orderby = 'name';
$order = 'asc';
$hide_empty = false ;
$cat_args = array(
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
);
$product_categories = get_terms( 'product_cat', $cat_args );
if( !empty($product_categories) ){
echo '
<ul>';
foreach ($product_categories as $key => $category) {
echo '
<li>';
echo '<a href="'.get_term_link($category).'" >';
echo $category->name;
echo '</a>';
echo '</li>';
}
echo '</ul>
';
}
So, if you were looking for command arguments, take a look at Tim's answer. If you just want to read a line from console:
#include <stdio.h>
int main()
{
char string [256];
printf ("Insert your full address: ");
gets (string);
printf ("Your address is: %s\n",string);
return 0;
}
Yes, it is not secure, you can do buffer overrun, it does not check for end of file, it does not support encodings and a lot of other stuff. Actually I didn't even think whether it did ANY of this stuff. I agree I kinda screwed up :) But...when I see a question like "How to read a line from the console in C?", I assume a person needs something simple, like gets() and not 100 lines of code like above. Actually, I think, if you try to write those 100 lines of code in reality, you would do many more mistakes, than you would have done had you chosen gets ;)
I use XSLT to do that. Write up your XSD then pass your data models through a hand written XSLT that outputs SQL commands. Writing an XSLT is way faster and reusable than a custom program /script you may write.
At least thats how I do it at work, and thanks to that I got time to hang out on SO :)
Small variation with Swift 4.2...
On my UITableView I had many sections but I had to avoid the floating header effect so I used a "dummyViewHeight" approach as seen somewhere else here on Stack Overflow... So this is my solution for this problem (it works also for keyboard + toolbar + suggestions):
Declare it as class constant:
let dummyViewHeight: CGFloat = 40.0
Then
override func viewDidLoad() {
super.viewDidLoad()
//... some stuff here, not needed for this example
// Create non floating header
tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: dummyViewHeight))
tableView.contentInset = UIEdgeInsets(top: -dummyViewHeight, left: 0, bottom: 0, right: 0)
addObservers()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
removeObservers()
}
And here all the magic...
@objc func keyboardWillShow(notification: NSNotification) {
if let userInfo = notification.userInfo {
let keyboardHeight = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue.size.height
tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: dummyViewHeight))
tableView.contentInset = UIEdgeInsets(top: -dummyViewHeight, left: 0, bottom: keyboardHeight, right: 0)
}
}
@objc func keyboardWillHide(notification: NSNotification) {
UIView.animate(withDuration: 0.25) {
self.tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: self.dummyViewHeight))
self.tableView.contentInset = UIEdgeInsets(top: -self.dummyViewHeight, left: 0, bottom: 0, right: 0)
}
}
df.T.iloc[-1]
df.T.tail(1)
pd.Series(df.values[:, -1], name=df.columns[-1])
You are missing the std namespace reference in the cc file. You should also call nom.c_str()
because there is no implicit conversion from std::string
to const char *
expected by ifstream
's constructor.
Polygone::Polygone(std::string nom) {
std::ifstream fichier (nom.c_str(), std::ifstream::in);
// ...
}
value_counts work only for series. It won't work for entire DataFrame. Try selecting only one column and using this attribute. For example:
df['accepted'].value_counts()
It also won't work if you have duplicate columns. This is because when you select a particular column, it will also represent the duplicate column and will return dataframe instead of series. At that time remove duplicate column by using
df = df.loc[:,~df.columns.duplicated()]
df['accepted'].value_counts()
If you have a standard code signing certificate, some time will be needed for your application to build trust. Microsoft affirms that an Extended Validation (EV) Code Signing Certificate allows us to skip this period of trust-building. According to Microsoft, extended validation certificates allow the developer to immediately establish a reputation with SmartScreen. Otherwise, the users will see a warning like "Windows Defender SmartScreen prevented an unrecognized app from starting. Running this app might put your PC at risk.", with the two buttons: "Run anyway" and "Don't run".
Another Microsoft resource states the following (quote): "Although not required, programs signed by an EV code signing certificate can immediately establish a reputation with SmartScreen reputation services even if no prior reputation exists for that file or publisher. EV code signing certificates also have a unique identifier which makes it easier to maintain reputation across certificate renewals."
My experience is as follows. Since 2005, we have been using regular (non-EV) code signing certificates to sign .MSI, .EXE and .DLL files with time stamps, and there has never been a problem with SmartScreen until 2018, when there was just one case when it took 3 days for a beta version of our application to build trust since we have released it to beta testers, and it was in the middle of certificate validity period. I don't know what SmartScreen might not like in that specific version of our application, but there have been no SmartScreen complaints since then. Therefore, if your certificate is a non-EV, it is a signed application (such as an .MSI file) that will build trust over time, not a certificate. For example, a certificate can be issued a few months ago and used to sign many files, but for each signed file you publish, it may take a few days for SmartScreen to stop complaining about the file after publishing, as was in our case in 2018.
As a conclusion, to avoid the warning completely, i.e. prevent it from happening even suddenly, you need an Extended Validation (EV) code signing certificate.
Can't comment on accepted answer so I'll add some comments here:
sys.objects
table contains only schema-scoped objects. So to get info about "higher level" objects (i.e. schemas in our case) you need to use sys.schemas
table.[ObjectType]
it's better to use obj.type_desc
only for OBJECT_OR_COLUMN
permission class. For all other cases use perm.[class_desc]
IMPERSONATE
. To get info about impersonations one should LEFT JOIN
with sys.database_principals
on perm.major_id = imp.principal_id
sys.login_token
with sys.server_principals
as it will show also SQL Logins, not only Windows ones'G'
to allowed principal types to allow Windows groupssys
and INFORMATION_SCHEMA
from resulting table, as these users are used only for service I'll post first piece of script with all proposed fixes, other parts should be changed as well:
SELECT
[UserName] = ulogin.[name],
[UserType] = CASE princ.[type]
WHEN 'S' THEN 'SQL User'
WHEN 'U' THEN 'Windows User'
WHEN 'G' THEN 'Windows Group'
END,
[DatabaseUserName] = princ.[name],
[Role] = null,
[PermissionType] = perm.[permission_name],
[PermissionState] = perm.[state_desc],
[ObjectType] = CASE perm.[class]
WHEN 1 THEN obj.type_desc -- Schema-contained objects
ELSE perm.[class_desc] -- Higher-level objects
END,
[ObjectName] = CASE perm.[class]
WHEN 1 THEN OBJECT_NAME(perm.major_id) -- General objects
WHEN 3 THEN schem.[name] -- Schemas
WHEN 4 THEN imp.[name] -- Impersonations
END,
[ColumnName] = col.[name]
FROM
--database user
sys.database_principals princ
LEFT JOIN
--Login accounts
sys.server_principals ulogin on princ.[sid] = ulogin.[sid]
LEFT JOIN
--Permissions
sys.database_permissions perm ON perm.[grantee_principal_id] = princ.[principal_id]
LEFT JOIN
--Table columns
sys.columns col ON col.[object_id] = perm.major_id
AND col.[column_id] = perm.[minor_id]
LEFT JOIN
sys.objects obj ON perm.[major_id] = obj.[object_id]
LEFT JOIN
sys.schemas schem ON schem.[schema_id] = perm.[major_id]
LEFT JOIN
sys.database_principals imp ON imp.[principal_id] = perm.[major_id]
WHERE
princ.[type] IN ('S','U','G') AND
-- No need for these system accounts
princ.[name] NOT IN ('sys', 'INFORMATION_SCHEMA')
This works perfectly! The below answers are too complicated. Don't look at this as dynamic. Set up your store procedure as follows:
(@id as varchar(50))
as
Declare @query as nvarchar(max)
set @query ='
select * from table
where id in('+@id+')'
EXECUTE sp_executesql @query
I think I found it. All you have to do is type in "`n" (WITH THE QUOTATION MARKS!)
Thanks!
Default sorting is ascending, you need to add the keyword DESC to both your orders:
ORDER BY article_rating DESC, article_time DESC
For me maven seems to work off the .mavenrc
file:
echo "export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)" > ~/.mavenrc
I'm sure I picked it up on SO too, just can't remember where.
Based on @dude answer this should return relevant styles in a object, for instance:
.recurly-input {
display: block;
border-radius: 2px;
-webkit-border-radius: 2px;
outline: 0;
box-shadow: none;
border: 1px solid #beb7b3;
padding: 0.6em;
background-color: #f7f7f7;
width:100%;
}
This will return:
backgroundColor:
"rgb(247, 247, 247)"
border
:
"1px solid rgb(190, 183, 179)"
borderBottom
:
"1px solid rgb(190, 183, 179)"
borderBottomColor
:
"rgb(190, 183, 179)"
borderBottomLeftRadius
:
"2px"
borderBottomRightRadius
:
"2px"
borderBottomStyle
:
"solid"
borderBottomWidth
:
"1px"
borderColor
:
"rgb(190, 183, 179)"
borderLeft
:
"1px solid rgb(190, 183, 179)"
borderLeftColor
:
"rgb(190, 183, 179)"
borderLeftStyle
:
"solid"
borderLeftWidth
:
"1px"
borderRadius
:
"2px"
borderRight
:
"1px solid rgb(190, 183, 179)"
borderRightColor
:
"rgb(190, 183, 179)"
borderRightStyle
:
"solid"
borderRightWidth
:
"1px"
borderStyle
:
"solid"
borderTop
:
"1px solid rgb(190, 183, 179)"
borderTopColor
:
"rgb(190, 183, 179)"
borderTopLeftRadius
:
"2px"
borderTopRightRadius
:
"2px"
borderTopStyle
:
"solid"
borderTopWidth
:
"1px"
borderWidth
:
"1px"
boxShadow
:
"none"
display
:
"block"
outline
:
"0px"
outlineWidth
:
"0px"
padding
:
"0.6em"
paddingBottom
:
"0.6em"
paddingLeft
:
"0.6em"
paddingRight
:
"0.6em"
paddingTop
:
"0.6em"
width
:
"100%"
Code:
function getStyle(className_) {
var styleSheets = window.document.styleSheets;
var styleSheetsLength = styleSheets.length;
for(var i = 0; i < styleSheetsLength; i++){
var classes = styleSheets[i].rules || styleSheets[i].cssRules;
if (!classes)
continue;
var classesLength = classes.length;
for (var x = 0; x < classesLength; x++) {
if (classes[x].selectorText == className_) {
return _.pickBy(classes[x].style, (v, k) => isNaN(parseInt(k)) && typeof(v) == 'string' && v && v != 'initial' && k != 'cssText' )
}
}
}
}
public Boolean test() throws InterruptedException {
BlockingQueue<Boolean> booleanHolder = new LinkedBlockingQueue<>();
new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(2);
booleanHolder.put(true);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
return booleanHolder.poll(4, TimeUnit.SECONDS);
}
I'm glad that worked out, so I guess you had to explicitly set 'auto' on IE6 in order for it to mimic other browsers!
I actually recently found another technique for scaling images, again designed for backgrounds. This technique has some interesting features:
The markup relies on a wrapper element:
<div id="wrap"><img src="test.png" /></div>
Given the above markup you then use these rules:
#wrap {
height: 100px;
width: 100px;
}
#wrap img {
min-height: 100%;
min-width: 100%;
}
If you then control the size of wrapper you get the interesting scale effects that I list above.
To be explicit, consider the following base state: A container that is 100x100 and an image that is 10x10. The result is a scaled image of 100x100.
So, in other words, the image is always at least as big as the container, but will scale beyond it to maintain it's aspect ratio.
This probably isn't useful for your site, and it doesn't work in IE6. But, it is useful to get a scaled background for your view port or container.
This will work
$ext = pathinfo($filename, PATHINFO_EXTENSION);
many other people answered your question above. This problen arises when your script don't find the jQuery script and if you are using other framework or cms then maybe there is a conflict between jQuery and other libraries. In my case i used as following- `
<script src="js_directory/jquery.1.7.min.js"></script>
<script>
jQuery.noConflict();
jQuery(document).ready(
function($){
//your other code here
});</script>
`
here might be some syntax error. Please forgive me because i'm writing from my cell phone. Thanks
Having the same problem (with jQuery " done..." strings), but only in Notepad++, I asked, received good friendly replies (that made me understand what I had missed), then spent the time to build a detailed step-by-step explanation, see Finding Line Beginning using Regular expression in Notepad++
Versailles, Tue 27 Apr 2010 22:53:25 +0200
The top voted answer is deprecated in Bootstrap 3.3 and will be removed in v4. Try this instead:
JavaScript:
// Fill modal with content from link href
$("#myModal").on("show.bs.modal", function(e) {
var link = $(e.relatedTarget);
$(this).find(".modal-body").load(link.attr("href"));
});
Html (Based on the official example. Note that for Bootstrap 3.* we set data-remote="false"
to disable the deprecated Bootstrap load function):
<!-- Link trigger modal -->
<a href="remoteContent.html" data-remote="false" data-toggle="modal" data-target="#myModal" class="btn btn-default">
Launch Modal
</a>
<!-- Default bootstrap modal example -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Try it yourself: https://jsfiddle.net/ednon5d1/
package
will add packaged jar
or war
to your target
folder, We can check it when, we empty the target folder (using mvn clean
) and then run mvn package
.
install
will do all the things that package
does, additionally it will add packaged jar
or war
in local repository as well. We can confirm it by checking in your .m2
folder.
Try to install x86 version of XAMPP. The default XAMPP version on their website is x64 (maybe because I'm using x64 Windows 7). download link here
class App extends React.Component {_x000D_
_x000D_
buttonClick(){_x000D_
console.log("came here")_x000D_
_x000D_
}_x000D_
_x000D_
subComponent() {_x000D_
return (<div>Hello World</div>);_x000D_
}_x000D_
_x000D_
render() {_x000D_
return ( _x000D_
<div className="patient-container">_x000D_
<button onClick={this.buttonClick.bind(this)}>Click me</button>_x000D_
{this.subComponent()}_x000D_
</div>_x000D_
)_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App/>, document.getElementById('app'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
it depends on your need, u can use either this.renderIcon()
or bind this.renderIcon.bind(this)
UPDATE
This is how you call a method outside the render.
buttonClick(){
console.log("came here")
}
render() {
return (
<div className="patient-container">
<button onClick={this.buttonClick.bind(this)}>Click me</button>
</div>
);
}
The recommended way is to write a separate component and import it.
I think what you're looking for is !!val==false
which can be turned to !val
(even shorter):
You see:
function checkValue(value) {
console.log(!!value);
}
checkValue(); // false
checkValue(null); // false
checkValue(undefined); // false
checkValue(false); // false
checkValue(""); // false
checkValue(true); // true
checkValue({}); // true
checkValue("any string"); // true
That works by flipping the value by using the !
operator.
If you flip null
once for example like so :
console.log(!null) // that would output --> true
If you flip it twice like so :
console.log(!!null) // that would output --> false
Same with undefined
or false
.
Your code:
if(val==null || val===false){
;
}
would then become:
if(!val) {
;
}
That would work for all cases even when there's a string but it's length is zero.
Now if you want it to also work for the number 0 (which would become false
if it was double flipped) then your if would become:
if(!val && val !== 0) {
// code runs only when val == null, undefined, false, or empty string ""
}
You can use Ctrl + Shift + F which will run your formatter on the file and fix indentations along the way also.
Epoch is the number of seconds since Jan 1, 1970..
So:
String epochString = "1081157732";
long epoch = Long.parseLong( epochString );
Date expiry = new Date( epoch * 1000 );
For more information: http://www.epochconverter.com/
Use the array_count_values function.
$countValues = array_count_values($myArray);
echo $countValues["Ben"];
You haven't specify version in your maven dependency file may be thats why it is not picking the latest jar
As well as you need another deppendency with slf4j-log4j12
artifact id.
Include this in your pom file
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.6</version>
</dependency>
Let me know if error is still not resolved
I also recomend you to see this link
you can use setInterval()
in javascript
<script>
//Call the yourAjaxCall() function every 1000 millisecond
setInterval("yourAjaxCall()",1000);
function yourAjaxCall(){...}
</script>
I have changed the implementation of it to get your problem solved, I made an object to track the old changes and compare it with that. You can use it to solve your issue.
Here I created a method, in which the old value will be stored in a separate variable and, which then will be used in a watch.
new Vue({
methods: {
setValue: function() {
this.$data.oldPeople = _.cloneDeep(this.$data.people);
},
},
mounted() {
this.setValue();
},
el: '#app',
data: {
people: [
{id: 0, name: 'Bob', age: 27},
{id: 1, name: 'Frank', age: 32},
{id: 2, name: 'Joe', age: 38}
],
oldPeople: []
},
watch: {
people: {
handler: function (after, before) {
// Return the object that changed
var vm = this;
let changed = after.filter( function( p, idx ) {
return Object.keys(p).some( function( prop ) {
return p[prop] !== vm.$data.oldPeople[idx][prop];
})
})
// Log it
vm.setValue();
console.log(changed)
},
deep: true,
}
}
})
See the updated codepen
int indexOf()
can be used. It returns -1 if no matching finds
In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198
It's the first result on Google: http://docs.python.org/library/stdtypes.html#string-formatting
See also the new format() function: http://docs.python.org/library/stdtypes.html#str.format
Another option:
=MID(A1,2,LEN(A1)-2)
Or this (for fun):
=RIGHT(LEFT(A1,LEN(A1)-1),LEN(LEFT(A1,LEN(A1)-1))-1)
final is a variable declare with key word final
, example:
final double pi = 3.14 ;
it remains final
through out the program.
effectively final : any local variable or parameter that is assigned a value only once right now(or updated only once). It may not remain effectively final through out the program. so this means that effectively final variable might loose its effectively final property after immediately the time it gets assigned/updated at least one more assignment. example:
class EffectivelyFinal {
public static void main(String[] args) {
calculate(124,53);
}
public static void calculate( int operand1, int operand2){
int rem = 0; // operand1, operand2 and rem are effectively final here
rem = operand1%2 // rem lost its effectively final property here because it gets its second assignment
// operand1, operand2 are still effectively final here
class operators{
void setNum(){
operand1 = operand2%2; // operand1 lost its effectively final property here because it gets its second assignment
}
int add(){
return rem + operand2; // does not compile because rem is not effectively final
}
int multiply(){
return rem * operand1; // does not compile because both rem and operand1 are not effectively final
}
}
}
}
jquery provides val()
function and not value()
. You can check empty string using jquery
if($('#person_data[document_type]').val() != ''){}
$.each(obj, function(index, value) {
$('#looking_for_job_titles').tagsinput('add', value);
console.log(value);
});
I've put together solutions proposed by @Cory Walker with the extensions from @Rafael and the one form @Tex witch was a bit complicated for me and came up with a solution that is hopefully
error-proof with javascript and CSS disabled.
It manipulates with the background-color of the form field to show/hide the label.
<head>
<style type="text/css">
<!--
input {position:relative;background:transparent;}
-->
</style>
<script>
function labelPosition() {
document.getElementById("name").style.position="absolute";
// label is moved behind the textfield using the script,
// so it doesnt apply when javascript disabled
}
</script>
</head>
<body onload="labelPosition()">
<form>
<label id="name">Your name</label>
<input type="text" onblur="if(this.value==''){this.style.background='transparent';}" onfocus="this.style.background='white'">
</form>
</body>
View the script in action: http://mattr.co.uk/work/form_label.html
As pointed out by Max, you can't, but checking files modified or accessed is not all that hard. I wrote a tutorial about this, as late as today. The essence of which is to use -newerXY
and ! -newerXY
:
Example: To find all files modified on the 7th of June, 2007:
$ find . -type f -newermt 2007-06-07 ! -newermt 2007-06-08
To find all files accessed on the 29th of september, 2008:
$ find . -type f -newerat 2008-09-29 ! -newerat 2008-09-30
Or, files which had their permission changed on the same day:
$ find . -type f -newerct 2008-09-29 ! -newerct 2008-09-30
If you don't change permissions on the file, 'c' would normally correspond to the creation date, though.
Resize using helper methods and start-repeat-end handlers like this:
resize(
view1,
1.0f,
0.0f,
1.0f,
0.0f,
0.0f,
0.0f,
150,
null,
null,
null);
return null;
}
Helper methods:
/**
* Resize a view.
*/
public static void resize(
View view,
float fromX,
float toX,
float fromY,
float toY,
float pivotX,
float pivotY,
int duration) {
resize(
view,
fromX,
toX,
fromY,
toY,
pivotX,
pivotY,
duration,
null,
null,
null);
}
/**
* Resize a view with handlers.
*
* @param view A view to resize.
* @param fromX X scale at start.
* @param toX X scale at end.
* @param fromY Y scale at start.
* @param toY Y scale at end.
* @param pivotX Rotate angle at start.
* @param pivotY Rotate angle at end.
* @param duration Animation duration.
* @param start Actions on animation start. Otherwise NULL.
* @param repeat Actions on animation repeat. Otherwise NULL.
* @param end Actions on animation end. Otherwise NULL.
*/
public static void resize(
View view,
float fromX,
float toX,
float fromY,
float toY,
float pivotX,
float pivotY,
int duration,
Callable start,
Callable repeat,
Callable end) {
Animation animation;
animation =
new ScaleAnimation(
fromX,
toX,
fromY,
toY,
Animation.RELATIVE_TO_SELF,
pivotX,
Animation.RELATIVE_TO_SELF,
pivotY);
animation.setDuration(
duration);
animation.setInterpolator(
new AccelerateDecelerateInterpolator());
animation.setFillAfter(true);
view.startAnimation(
animation);
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
if (start != null) {
try {
start.call();
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void onAnimationEnd(Animation animation) {
if (end != null) {
try {
end.call();
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void onAnimationRepeat(
Animation animation) {
if (repeat != null) {
try {
repeat.call();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
This appears to be missing the providerName="System.Data.EntityClient"
bit. Sure you got the whole thing?
cvWaitKey(0)
stops your program until you press a button.
cvWaitKey(10)
doesn't stop your program but wake up and alert to end your program when you press a button. Its used into loops because cvWaitkey
doesn't stop loop.
Normal use
char k;
k=cvWaitKey(0);
if(k == 'ESC')
with k
you can see what key was pressed.
Why not store it as an array of prices instead of object?
prices = []
$(allProducts).each(function () {
var price = parseFloat($(this).data('price'));
prices.push(price);
});
prices.sort(function(a, b) { return a - b }); //this is the magic line which sort the array
That way you can just
prices[0]; // cheapest
prices[prices.length - 1]; // most expensive
Note that you can do shift()
and pop()
to get min and max price respectively, but it will take off the price from the array.
Even better alternative is to use Sergei solution below, by using Math.max
and min
respectively.
EDIT:
I realized that this would be wrong if you have something like [11.5, 3.1, 3.5, 3.7]
as 11.5
is treated as a string, and would come before the 3.x
in dictionary order, you need to pass in custom sort function to make sure they are indeed treated as float:
prices.sort(function(a, b) { return a - b });
You can do this with pure CSS but you will need to hard code the offset scroll amounts, which may not be ideal should you be changing page content- or should dimensions of your content change on say window resize.
You're likely best placed to use e.g. jQuery, specifically:
$('html, body').stop().animate({
scrollTop: element.offset().top
}, 1000);
A complete implementation may be:
$('#up, #down').on('click', function(e){
e.preventDefault();
var target= $(this).get(0).id == 'up' ? $('#down') : $('#up');
$('html, body').stop().animate({
scrollTop: target.offset().top
}, 1000);
});
Where element
is the target element to scroll to and 1000
is the delay in ms before completion.
The benefit being, no matter what changes to your content dimensions, the function will not need to be altered.
Try os.chdir
os.chdir(path)
Change the current working directory to path. Availability: Unix, Windows.
You need to specify the minimum width of the field.
String.format("%" + numberOfSpaces + "s", "");
Why do you want to generate a String of spaces of a certain length.
If you want a column of this length with values then you can do:
String.format("%" + numberOfSpaces + "s", "Hello");
which gives you numberOfSpaces-5 spaces followed by Hello. If you want Hello to appear on the left then add a minus sign in before numberOfSpaces.
With subprocess.run
:
import subprocess
import re
active_process_txt = subprocess.run(['celery', '-A', 'my_proj', 'inspect', 'active'],
stdout=subprocess.PIPE).stdout.decode('utf-8')
return len(re.findall(r'worker_pid', active_process_txt))
Be careful to change my_proj
with your_proj
If you have dynamic classes or don't know what classes could be already applied then this method I believe is the best approach:
// addClass
$('path').attr('class', function(index, classNames) {
return classNames + ' class-name';
});
// removeClass
$('path').attr('class', function(index, classNames) {
return classNames.replace('class-name', '');
});
Contrary to what pointy says, the blur()
method does exist and is a part of the w3c standard. The following exaple will work in every modern browser (including IE):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Javascript test</title>
<script type="text/javascript" language="javascript">
window.onload = function()
{
var field = document.getElementById("field");
var link = document.getElementById("link");
var output = document.getElementById("output");
field.onfocus = function() { output.innerHTML += "<br/>field.onfocus()"; };
field.onblur = function() { output.innerHTML += "<br/>field.onblur()"; };
link.onmouseover = function() { field.blur(); };
};
</script>
</head>
<body>
<form name="MyForm">
<input type="text" name="field" id="field" />
<a href="javascript:void(0);" id="link">Blur field on hover</a>
<div id="output"></div>
</form>
</body>
</html>
Note that I used link.onmouseover
instead of link.onclick
, because otherwise the click itself would have removed the focus.
A slight deviation from the original question however may prove useful for future people landing here wanting to DROP
and CREATE
an index, i.e. in a deployment script.
You can bypass the exists check simply by adding the following to your create statement:
CREATE INDEX IX_IndexName
ON dbo.TableName
WITH (DROP_EXISTING = ON);
Read more here: CREATE INDEX (Transact-SQL) - DROP_EXISTING Clause
N.B. As mentioned in the comments, the index must already exist for this clause to work without throwing an error.
Had the same issue and got it resolved by making sure projects in the solution have the same configuration and platform (in my case it was Debug x64). Somehow the VIsual Studio was missing x64 for part of the projects and I edited the .sln file manually (copied the configurations and platforms from correctly built projects to the projects that were missing the settings I needed). This is what it looks like for one of the projects:
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|x64.ActiveCfg = Debug|x64
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|x64.Build.0 = Debug|x64
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|Any CPU.Build.0 = Release|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|x64.ActiveCfg = Release|x64
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|x64.Build.0 = Release|x64
But then the same error occurred for a project that had a Java file (*.jar) in the dependencies. I had to edit Environment Variables manually to create a record with this value
C:\Program Files\Java\jre1.8.0_171\bin\server
for Java's path, and put it on top of the Path items.
This fixed the issue until I updated Java on my machine. I had to edit the version number in Environment Variables to match the updated folder name.
C:\Program Files\Java\jre1.8.0_181\bin\server
RazorSQL for Linux / Unix.
Here is a method adapted from Jquery 2.1.1 that take a dom element instead of a jquery object (so jquery is not needed). Includes type checks and regex expressions:
function addClass(element, value) {
// Regex terms
var rclass = /[\t\r\n\f]/g,
rnotwhite = (/\S+/g);
var classes,
cur,
curClass,
finalValue,
proceed = typeof value === "string" && value;
if (!proceed) return element;
classes = (value || "").match(rnotwhite) || [];
cur = element.nodeType === 1
&& (element.className
? (" " + element.className + " ").replace(rclass, " ")
: " "
);
if (!cur) return element;
var j = 0;
while ((curClass = classes[j++])) {
if (cur.indexOf(" " + curClass + " ") < 0) {
cur += curClass + " ";
}
}
// only assign if different to avoid unneeded rendering.
finalValue = cur.trim();
if (element.className !== finalValue) {
element.className = finalValue;
}
return element;
};
Depending on which event you actually want to use (textbox change
, or button click
), you can try this:
HTML:
<input id="color" type="text" onchange="changeBackground(this);" />
<br />
<span id="coltext">This text should have the same color as you put in the text box</span>
JS:
function changeBackground(obj) {
document.getElementById("coltext").style.color = obj.value;
}
DEMO: http://jsfiddle.net/6pLUh/
One minor problem with the button was that it was a submit button, in a form. When clicked, that submits the form (which ends up just reloading the page) and any changes from JavaScript are reset. Just using the onchange
allows you to change the color based on the input.
mkdirs()
also creates parent directories in the path this File
represents.
javadocs for mkdirs()
:
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.
javadocs for mkdir()
:
Creates the directory named by this abstract pathname.
Example:
File f = new File("non_existing_dir/someDir");
System.out.println(f.mkdir());
System.out.println(f.mkdirs());
will yield false
for the first [and no dir will be created], and true
for the second, and you will have created non_existing_dir/someDir
Try this:
<SCRIPT LANGUAGE="JavaScript">
function WriteToFile(passForm) {
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("C:\test.txt", True);
s.writeline("HI");
s.writeline("Bye");
s.writeline("-----------------------------");
s.Close();
}
</SCRIPT>
</head>
<body>
<p>To sign up for the Excel workshop please fill out the form below:
</p>
<form onSubmit="WriteToFile(this)">
Type your first name:
<input type="text" name="FirstName" size="20">
<br>Type your last name:
<input type="text" name="LastName" size="20">
<br>
<input type="submit" value="submit">
</form>
This will work only on IE
If your database client connects with TCP/IP and you have ident auth configured in your pg_hba.conf check that you have an identd installed and running. This is mandatory even if you have only local clients connecting to "localhost".
Also beware that nowadays the identd may have to be IPv6 enabled for Postgresql to welcome clients which connect to localhost.
Update: I would now recommend PupeteerSharp over wkhtmltopdf.
Try wkhtmtopdf. It is the best tool I have found so far.
For .NET, you may use this small library to easily invoke wkhtmtopdf command line utility.
you can use RabbitMQ API to get count or messages :
/api/queues/vhost/name/get
Get messages from a queue. (This is not an HTTP GET as it will alter the state of the queue.) You should post a body looking like:
{"count":5,"requeue":true,"encoding":"auto","truncate":50000}
count controls the maximum number of messages to get. You may get fewer messages than this if the queue cannot immediately provide them.
requeue determines whether the messages will be removed from the queue. If requeue is true they will be requeued - but their redelivered flag will be set. encoding must be either "auto" (in which case the payload will be returned as a string if it is valid UTF-8, and base64 encoded otherwise), or "base64" (in which case the payload will always be base64 encoded). If truncate is present it will truncate the message payload if it is larger than the size given (in bytes). truncate is optional; all other keys are mandatory.
Please note that the publish / get paths in the HTTP API are intended for injecting test messages, diagnostics etc - they do not implement reliable delivery and so should be treated as a sysadmin's tool rather than a general API for messaging.
http://hg.rabbitmq.com/rabbitmq-management/raw-file/rabbitmq_v3_1_3/priv/www/api/index.html
Problem:
~$ simple-image-reducer
Traceback (most recent call last):
File "/usr/bin/simple-image-reducer", line 28, in <module>
import Image
**ImportError: No module named Image**
Reason:
Image != image
Solution:
1) make sure it is available
python -m pip install Image
2) where is it available?
sudo find ~ -name image -type d
-->> directory /home/MyHomeDir/.local/lib/python2.7/site-packages/image ->> OK
3) make simple-image-reducer understand via link:
ln -s ~/.local/lib/python2.7/site-packages/image
~/.local/lib/python2.7/site-packages/Image
4)
invoke simple-image-reducer
again.
Works:-)
The other answers in my case did not work. I had to restart windows before I could debug the application again.
The answers that have been given so far will only work the first time that the ng-repeat
gets rendered, but if you have a dynamic ng-repeat
, meaning that you are going to be adding/deleting/filtering items, and you need to be notified every time that the ng-repeat
gets rendered, those solutions won't work for you.
So, if you need to be notified EVERY TIME that the ng-repeat
gets re-rendered and not just the first time, I've found a way to do that, it's quite 'hacky', but it will work fine if you know what you are doing. Use this $filter
in your ng-repeat
before you use any other $filter
:
.filter('ngRepeatFinish', function($timeout){
return function(data){
var me = this;
var flagProperty = '__finishedRendering__';
if(!data[flagProperty]){
Object.defineProperty(
data,
flagProperty,
{enumerable:false, configurable:true, writable: false, value:{}});
$timeout(function(){
delete data[flagProperty];
me.$emit('ngRepeatFinished');
},0,false);
}
return data;
};
})
This will $emit
an event called ngRepeatFinished
every time that the ng-repeat
gets rendered.
<li ng-repeat="item in (items|ngRepeatFinish) | filter:{name:namedFiltered}" >
The ngRepeatFinish
filter needs to be applied directly to an Array
or an Object
defined in your $scope
, you can apply other filters after.
<li ng-repeat="item in (items | filter:{name:namedFiltered}) | ngRepeatFinish" >
Do not apply other filters first and then apply the ngRepeatFinish
filter.
If you want to apply certain css styles into the DOM after the list has finished rendering, because you need to have into account the new dimensions of the DOM elements that have been re-rendered by the ng-repeat
. (BTW: those kind of operations should be done inside a directive)
ngRepeatFinished
event:Do not perform a $scope.$apply
in that function or you will put Angular in an endless loop that Angular won't be able to detect.
Do not use it for making changes in the $scope
properties, because those changes won't be reflected in your view until the next $digest
loop, and since you can't perform an $scope.$apply
they won't be of any use.
No, they are not, this is a hack, if you don't like it don't use it. If you know a better way to accomplish the same thing please let me know it.
This is a hack, and using it in the wrong way is dangerous, use it only for applying styles after the
ng-repeat
has finished rendering and you shouldn't have any issues.
If someone not have reference in .NET . COM (tab) or not have office installed on machine where visual was installed can do :
Add references from:
C:\Program Files (x86)\Microsoft Visual Studio 11.0\Visual Studio Tools for Office\PIA\Office15
This code will do what you're looking for. It's based on examples found here and here.
The autofmt_xdate()
call is particularly useful for making the x-axis labels readable.
import numpy as np
from matplotlib import pyplot as plt
fig = plt.figure()
width = .35
ind = np.arange(len(OY))
plt.bar(ind, OY, width=width)
plt.xticks(ind + width / 2, OX)
fig.autofmt_xdate()
plt.savefig("figure.pdf")
You can achieve this by adding this simple php code block
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
the_content();
endwhile; else: ?>
<p>!Sorry no posts here</p>
<?php endif; ?>
git push --follow-tags
This is a sane option introduced in Git 1.8.3:
git push --follow-tags
It pushes both commits and only tags that are both:
This is sane because:
It is for those reasons that --tags
should be avoided.
Git 2.4 has added the push.followTags
option to turn that flag on by default which you can set with:
git config --global push.followTags true
or by adding followTags = true
to the [push]
section of your ~/.gitconfig
file.
But I wanted to point out that the opinion expressed in the accepted answer is somewhat outdated. According to more recent discussions (django bugs #7634 and #12785), auto_now and auto_now_add are not going anywhere, and even if you go to the original discussion, you'll find strong arguments against the RY (as in DRY) in custom save methods.
A better solution has been offered (custom field types), but didn't gain enough momentum to make it into django. You can write your own in three lines (it's Jacob Kaplan-Moss' suggestion).
from django.db import models
from django.utils import timezone
class AutoDateTimeField(models.DateTimeField):
def pre_save(self, model_instance, add):
return timezone.now()
#usage
created_at = models.DateField(default=timezone.now)
updated_at = models.AutoDateTimeField(default=timezone.now)
You need to follow the steps described in Troubleshooting: Connecting to SQL Server When System Administrators Are Locked Out and add your own Windows user as a member of sysadmin:
-m
and -f
startup parameters (or you can start sqlservr.exe -c -sEXPRESS -m -f
from console)sqlcmd -E -A -S .\EXPRESS
or from SSMS use admin:.\EXPRESS
create login [machinename\username] from windows
to create your Windows login in SQLsp_addsrvrolemember 'machinename\username', 'sysadmin';
to make urself sysadmin member-m -f
Error messages don't get any clearer than this:
"Scripts may close only the windows that were opened by it."
If your script did not initiate opening the window (with something like window.open), then the script in that window is not allowed to close it. Its a security to prevent a website taking control of your browser and closing windows.
Best way to find out is to record the macro and perform the exact steps and see what VBA code it generates. you can then go and replace the bits you want to make generic (i.e. file names and stuff)
SELECT group,subGroup,COUNT(*) FROM tablename GROUP BY group,subgroup
1) Using inline styles
<div [style.color]="myDynamicColor">
2) Use multiple CSS classes mapping to what you want and switch classes like:
/* CSS */
.theme { /* any shared styles */ }
.theme.blue { color: blue; }
.theme.red { color: red; }
/* Template */
<div class="theme" [ngClass]="{blue: isBlue, red: isRed}">
<div class="theme" [class.blue]="isBlue">
Code samples from: https://angular.io/cheatsheet
More info on ngClass directive : https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html
Try to consolidate the syntax in a single line. this will clear the error
Use the Chr or ChrW function, Chr(charNumber)
.
You can use the following script if you just want to use shell scripting without awk or other interpreters:
#!/bin/bash
total=0
for number in `cat files.txt | xargs ls -l | cut -c 23-30`; do
let total=$total+$number
done
echo $total
To compare one object to another, I combine a for in loop (used to loop through objects) and some(). You do not have to worry about an array going out of bounds etc, so that saves some code. Documentation on .some can be found here
var productList = [{id: 'text3'}, {id: 'text2'}, {id: 'text4', product: 'Shampoo'}]; // Example of selected products
var theDatabaseList = [{id: 'text1'}, {id: 'text2'},{id: 'text3'},{id:'text4', product: 'shampoo'}];
var objectsFound = [];
for(let objectNumber in productList){
var currentId = productList[objectNumber].id;
if (theDatabaseList.some(obj => obj.id === currentId)) {
// Do what you need to do with the matching value here
objectsFound.push(currentId);
}
}
console.log(objectsFound);
An alternative way I compare one object to another is to use a nested for loop with Object.keys().length to get the amount of objects in the array. Code below:
var productList = [{id: 'text3'}, {id: 'text2'}, {id: 'text4', product: 'Shampoo'}]; // Example of selected products
var theDatabaseList = [{id: 'text1'}, {id: 'text2'},{id: 'text3'},{id:'text4', product: 'shampoo'}];
var objectsFound = [];
for(var i = 0; i < Object.keys(productList).length; i++){
for(var j = 0; j < Object.keys(theDatabaseList).length; j++){
if(productList[i].id === theDatabaseList[j].id){
objectsFound.push(productList[i].id);
}
}
}
console.log(objectsFound);
To answer your exact question, if are just searching for a value in an object, you can use a single for in loop.
var vendors = [
{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
}
];
for(var ojectNumbers in vendors){
if(vendors[ojectNumbers].Name === 'Magenic'){
console.log('object contains Magenic');
}
}
To expound on Numenor's answer you can do something like, Format(Now(),"HH:mm:ss") using these custom date/time formating options
For everyone who is tempted to downvote this answer please be aware that the question was originally tagged VB and vbscript hence my answer, the VB tag was edited out leaving only the vbscript tag. The OP accepted this answer which I take to mean that it gave him the information that he needed.
I suggest split (not saying that the other answers are invalid, this is just another way to do it):
def findreplace(char, string):
return ''.join(string.split(char))
Splitting by a character removes all the characters and turns it into a list. Then we join the list with the join function. You can see the ipython console test below
In[112]: findreplace('i', 'it is icy')
Out[112]: 't s cy'
And the speed...
In[114]: timeit("findreplace('it is icy','i')", "from __main__ import findreplace")
Out[114]: 0.9927914671134204
Not as fast as replace or translate, but ok.
I know this is an old topic but this may help someone else.
I was able to make the body scroll by making the modal-dialog element position fixed. And since I would never know the exact height of the browser window, I took the information I was sure about, the height of the header and the footer. I was then able to make the modal-body element's top and bottom margins match those heights. This then produced the result I was looking for. I threw together a fiddle to show my work.
also, if you want a full screen dialog just un-comment the width:auto; inside the .modal-dialog.full-screen section.
https://jsfiddle.net/lot224/znrktLej/
And here is the css that I used to modify the bootstrap dialog.
.modal-dialog.full-screen {
position:fixed;
//width:auto; // uncomment to make the width based on the left/right attributes.
margin:auto;
left:0px;
right:0px;
top:0px;
bottom:0px;
}
.modal-dialog.full-screen .modal-content {
position:absolute;
left:10px;
right:10px;
top:10px;
bottom:10px;
}
.modal-dialog.full-screen .modal-content .modal-header {
height:55px; // adjust as needed.
}
.modal-dialog.full-screen .modal-content .modal-body {
overflow-y: auto;
position: absolute;
top: 0;
bottom: 0;
left:0;
right:0;
margin-top: 55px; // .modal-header height
margin-bottom: 80px; // .modal-footer height
}
.modal-dialog.full-screen .modal-content .modal-footer {
height:80px; // adjust as needed.
position:absolute;
bottom:0;
left:0;
right:0;
}
Error Code
FROM
dbo.Category C LEFT OUTER JOIN
dbo.SubCategory SC ON C.categoryID = SC.CategoryID AND C.IsActive = 'True' LEFT OUTER JOIN
dbo.Module M ON SC.subCategoryID = M.subCategoryID AND SC.IsActive = 'True' LEFT OUTER JOIN
dbo.SubModule SM ON M.ModuleID = SM.ModuleID AND M.IsActive = 'True' AND SM.IsActive = 'True' LEFT OUTER JOIN
dbo.trainer ON dbo.trainer.TopicID =dbo.SubModule.subModuleID
Solution Code
FROM
dbo.Category C LEFT OUTER JOIN
dbo.SubCategory SC ON C.categoryID = SC.CategoryID AND C.IsActive = 'True' LEFT OUTER JOIN
dbo.Module M ON SC.subCategoryID = M.subCategoryID AND SC.IsActive = 'True' LEFT OUTER JOIN
dbo.SubModule SM ON M.ModuleID = SM.ModuleID AND M.IsActive = 'True' AND SM.IsActive = 'True' LEFT OUTER JOIN
dbo.trainer ON dbo.trainer.TopicID = SM.subModuleID
as you can see, in error code, dbo.SubModule
is already defined as SM, but I am using dbo.SubModule
in next line, hence there was an error.
use declared name instead of actual name. Problem solved.
In Windows, if you have the shortcut in your taskbar, right-click the "Anaconda Prompt" icon, you'll see:
Right-click on "Anaconda Prompt" again.
Click "Properties"
Add the path you want your anaconda prompt to open up into in the "Start In:" section.
Note - you can also do this by searching for "Anaconda Prompt" in the Start Menu. The directions above are specifically for the shortcut.
You can view this dump from the UNIX console.
The path for the heap dump will be provided as a variable right after where you have placed the mentioned variable.
E.g.:
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${DOMAIN_HOME}/logs/mps"
You can view the dump from the console on the mentioned path.
The more secure option would be to add allowedHosts to your Webpack config like this:
module.exports = {
devServer: {
allowedHosts: [
'host.com',
'subdomain.host.com',
'subdomain2.host.com',
'host2.com'
]
}
};
The array contains all allowed host, you can also specify subdomians. check out more here
You have mentioned Wrong id
alert(document.getElementById("name").value);
if you want to use name
attribute then
alert(document.getElementsByName("username")[0].value);
Updates:
input type="text" id="name" name="username"
id is different from name
This code change the order of DD MM YYYY
function convertDate(format, date) {
let formatArray = format.split('/');
if (formatArray.length != 3) {
console.error('Use a valid Date format');
return;
}
function getType(type) { return type == 'DD' ? d.getDate() : type == 'MM' ? d.getMonth() + 1 : type == 'YYYY' && d.getFullYear(); }
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(date);
return [pad(getType(formatArray[0])), pad(getType(formatArray[1])), getType(formatArray[2])].join('/');
}
In Access, click Create > Module
and paste in the following code
Public Function ConvertMyStringToDateTime(strIn As String) As Date
ConvertMyStringToDateTime = CDate( _
Mid(strIn, 1, 4) & "-" & Mid(strIn, 5, 2) & "-" & Mid(strIn, 7, 2) & " " & _
Mid(strIn, 9, 2) & ":" & Mid(strIn, 11, 2) & ":" & Mid(strIn, 13, 2))
End Function
Hit Ctrl+S and save the module as modDateConversion
.
Now try using a query like
Select * from Events
Where Events.[Date] > ConvertMyStringToDateTime("20130423014854")
--- Edit ---
Alternative solution avoiding user-defined VBA function:
SELECT * FROM Events
WHERE Format(Events.[Date],'yyyyMMddHhNnSs') > '20130423014854'
You can update the value like following
auto itr = m.find('ch');
if (itr != m.end()){
(*itr).second = 98;
}
Just for others (like me) who might have faced the above error. The solution in simple terms.
You might have missed to register your Interface and class (which implements that inteface) registration in your code.
e.g if the error is
"The current type, xyznamespace. Imyinterfacename, is an interface and cannot be constructed. Are you missing a type mapping?"
Then you must register the class which implements the Imyinterfacename in the UnityConfig class in the Register method. using code like below
container.RegisterType<Imyinterfacename, myinterfaceimplclassname>();
target="_blank"
opens a new tab in most browsers.
Created database in MySQL
create database springboot2;
application.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/springboot2
spring.datasource.username = root
spring.datasource.password = root
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
server.port=9192
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
main class
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
model class
package com.First.Try.springboot.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="PRODUCT_TBL1")
public class Product {
@Id
@GeneratedValue
private int id;
private String name;
private int quantity;
private double price;
....
....
....
}
There is another error with the forwars=d slash.
if we get this : def get_x(r): return path/'train'/r['fname']
is the same as def get_x(r): return path + 'train' + r['fname']
the simplest way I found so far is from git official website. It just computed dependencies and downloaded all of the required libraries/tools
http://git-scm.com/book/en/Getting-Started-Installing-Git
The other major way is to install Git via MacPorts (http://www.macports.org). If you have MacPorts installed, install Git via
$ sudo port install git-core +svn +doc +bash_completion +gitweb
Assuming the upper is the upper bound and lower is the lower bound, then you can make a random number, r, between the two bounds with:
int r = (int) (Math.random() * (upper - lower)) + lower;
Use the ieee.numeric_std
library, and the appropriate vector type for the numbers you are working on (unsigned
or signed
).
Then the operators are sla
/sra
for arithmetic shifts (ie fill with sign bit on right shifts and lsb on left shifts) and sll
/srl
for logical shifts (ie fill with '0's).
You pass a parameter to the operator to define the number of bits to shift:
A <= B srl 2; -- logical shift right 2 bits
I have no idea what I was writing above (thanks to Val for pointing that out!)
Of course the correct way to shift signed
and unsigned
types is with the shift_left
and shift_right
functions defined in ieee.numeric_std
.
The shift and rotate operators sll
, ror
etc are for vectors of boolean
, bit
or std_ulogic
, and can have interestingly unexpected behaviour in that the arithmetic shifts duplicate the end-bit even when shifting left.
And much more history can be found here:
http://jdebp.eu./FGA/bit-shifts-in-vhdl.html
However, the answer to the original question is still
sig <= tmp sll number_of_bits;
Use the following selector.
$('#attached_docs [value=123]').remove();
There's an ELSE in the DOS batch language? Back in the days when I did more of this kinda thing, there wasn't.
If my theory is correct and your ELSE is being ignored, you may be better off doing
IF NOT EXIST file GOTO label
...which will also save you a line of code (the one right after your IF).
Second, I vaguely remember some kind of bug with testing for the existence of directories. Life would be easier if you could test for the existence of a file in that directory. If there's no file you can be sure of, something to try (this used to work up to Win95, IIRC) would be to append the device file name NUL
to your directory name, e.g.
IF NOT EXIST C:\dir\NUL GOTO ...
Taking a guess at what it is you're asking for. I'm assuming by millisecond frame timer you're looking for something that acts like the following,
double mticks()
{
struct timeval tv;
gettimeofday(&tv, 0);
return (double) tv.tv_usec / 1000 + tv.tv_sec * 1000;
}
but uses std::chrono
instead,
double mticks()
{
typedef std::chrono::high_resolution_clock clock;
typedef std::chrono::duration<float, std::milli> duration;
static clock::time_point start = clock::now();
duration elapsed = clock::now() - start;
return elapsed.count();
}
Hope this helps.
UPDATE:
If you want to take advantage of Imagick (if it is installed on your server). Note: I didn't use Imagick's nature writeFile
because I was having issues with it on my server. File put contents works just as well.
<?php
/**
*
* Generate Thumbnail using Imagick class
*
* @param string $img
* @param string $width
* @param string $height
* @param int $quality
* @return boolean on true
* @throws Exception
* @throws ImagickException
*/
function generateThumbnail($img, $width, $height, $quality = 90)
{
if (is_file($img)) {
$imagick = new Imagick(realpath($img));
$imagick->setImageFormat('jpeg');
$imagick->setImageCompression(Imagick::COMPRESSION_JPEG);
$imagick->setImageCompressionQuality($quality);
$imagick->thumbnailImage($width, $height, false, false);
$filename_no_ext = reset(explode('.', $img));
if (file_put_contents($filename_no_ext . '_thumb' . '.jpg', $imagick) === false) {
throw new Exception("Could not put contents.");
}
return true;
}
else {
throw new Exception("No valid image provided with {$img}.");
}
}
// example usage
try {
generateThumbnail('test.jpg', 100, 50, 65);
}
catch (ImagickException $e) {
echo $e->getMessage();
}
catch (Exception $e) {
echo $e->getMessage();
}
?>
I have been using this, just execute the function after you store the original image and use that location to create the thumbnail. Edit it to your liking...
function makeThumbnails($updir, $img, $id)
{
$thumbnail_width = 134;
$thumbnail_height = 189;
$thumb_beforeword = "thumb";
$arr_image_details = getimagesize("$updir" . $id . '_' . "$img"); // pass id to thumb name
$original_width = $arr_image_details[0];
$original_height = $arr_image_details[1];
if ($original_width > $original_height) {
$new_width = $thumbnail_width;
$new_height = intval($original_height * $new_width / $original_width);
} else {
$new_height = $thumbnail_height;
$new_width = intval($original_width * $new_height / $original_height);
}
$dest_x = intval(($thumbnail_width - $new_width) / 2);
$dest_y = intval(($thumbnail_height - $new_height) / 2);
if ($arr_image_details[2] == IMAGETYPE_GIF) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
}
if ($arr_image_details[2] == IMAGETYPE_JPEG) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
}
if ($arr_image_details[2] == IMAGETYPE_PNG) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
}
if ($imgt) {
$old_image = $imgcreatefrom("$updir" . $id . '_' . "$img");
$new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imagecopyresized($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
$imgt($new_image, "$updir" . $id . '_' . "$thumb_beforeword" . "$img");
}
}
The above function creates images with a uniform thumbnail size. If the image doesn't have the same dimensions as the specified thumbnail size (proportionally), it just has blackspace on the top and bottom.
Before defining abstract data types, let us considers the different view of system-defined data types. We all know that by default all primitive data types (int, float, etc.) support basic operations such as addition and subtraction. The system provides the implementations for the primitive data types. For user-defined data types, we also need to define operations. The implementation for these operations can be done when we want to actually use them. That means in general, user-defined data types are defined along with their operations.
To simplify the process of solving problems, we combine the data structures with their operations and we call this "Abstract Data Type". (ADT's).
Commonly used ADT'S include: Linked List, Stacks, Queues, Binary Tree, Dictionaries, Disjoint Sets (Union and find), Hash Tables and many others.
ADT's consist of two types:
1. Declaration of data.
2. Declaration of operation.
Did you forget to join some tables? If not then you probably need to use some aliases.
First of all, since Spring doesn't do persistence itself, it cannot specify what readOnly
should exactly mean. This attribute is only a hint to the provider, the behavior depends on, in this case, Hibernate.
If you specify readOnly
as true
, the flush mode will be set as FlushMode.NEVER
in the current Hibernate Session preventing the session from committing the transaction.
Furthermore, setReadOnly(true) will be called on the JDBC Connection, which is also a hint to the underlying database. If your database supports it (most likely it does), this has basically the same effect as FlushMode.NEVER
, but it's stronger since you cannot even flush manually.
Now let's see how transaction propagation works.
If you don't explicitly set readOnly
to true
, you will have read/write transactions. Depending on the transaction attributes (like REQUIRES_NEW
), sometimes your transaction is suspended at some point, a new one is started and eventually committed, and after that the first transaction is resumed.
OK, we're almost there. Let's see what brings readOnly
into this scenario.
If a method in a read/write transaction calls a method that requires a readOnly transaction, the first one should be suspended, because otherwise a flush/commit would happen at the end of the second method.
Conversely, if you call a method from within a readOnly transaction that requires read/write, again, the first one will be suspended, since it cannot be flushed/committed, and the second method needs that.
In the readOnly-to-readOnly, and the read/write-to-read/write cases the outer transaction doesn't need to be suspended (unless you specify propagation otherwise, obviously).
HashMap
is unordered per the second line of the documentation:
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
Perhaps you can do as aix suggests and use a LinkedHashMap
, or another ordered collection. This link can help you find the most appropriate collection to use.
package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.
It describes a single representation of a dependency tree such that teammates, deployments, and continuous integration are guaranteed to install exactly the same dependencies.It contains the following properties.
{
"name": "mobileapp",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@angular-devkit/architect": {
"version": "0.11.4",
"resolved": "https://registry.npmjs.org/@angular- devkit/architect/-/architect-0.11.4.tgz",
"integrity": "sha512-2zi6S9tPlk52vyqNFg==",
"dev": true,
"requires": {
"@angular-devkit/core": "7.1.4",
"rxjs": "6.3.3"
}
},
}
Combining pomber's and avetisk's answers to cover all browsers and not causing warnings:
if (typeof(Event) === 'function') {
// modern browsers
window.dispatchEvent(new Event('resize'));
} else {
// for IE and other old browsers
// causes deprecation warning on modern browsers
var evt = window.document.createEvent('UIEvents');
evt.initUIEvent('resize', true, false, window, 0);
window.dispatchEvent(evt);
}
If you don't know how to enable php_mbstring extension in windows, open your php.ini and remove the semicolon before the extension:
change this
;extension=php_mbstring.dll
to this
extension=php_mbstring.dll
after modification, you need to reset your php server.
OS / mysql version:
$ uname -a
Darwin Raphaels-MacBook-Pro.local 15.6.0 Darwin Kernel Version 15.6.0: Thu Jun 21 20:07:40 PDT 2018; root:xnu-3248.73.11~1/RELEASE_X86_64 x86_64
$ mysql --version
/usr/local/mysql/bin/mysql Ver 14.14 Distrib 5.6.23, for osx10.8 (x86_64) using EditLine wrapper
Adding logging (example, I don't think /var/log/...
is the best path on Mac OS but that worked:
sudo vi ./usr/local/mysql-5.6.23-osx10.8-x86_64/my.cnf
[mysqld]
general_log = on
general_log_file=/var/log/mysql/mysqld_general.log
Restarted Mysql
Result:
$ sudo tail -f /var/log/mysql/mysqld_general.log
181210 9:41:04 21 Connect root@localhost on employees
21 Query /* mysql-connector-java-5.1.47 ( Revision: fe1903b1ecb4a96a917f7ed3190d80c049b1de29 ) */SELECT @@session.auto_increment_increment AS auto_increment_increment, @@character_set_client AS character_set_client, @@character_set_connection AS character_set_connection, @@character_set_results AS character_set_results, @@character_set_server AS character_set_server, @@collation_server AS collation_server, @@collation_connection AS collation_connection, @@init_connect AS init_connect, @@interactive_timeout AS interactive_timeout, @@license AS license, @@lower_case_table_names AS lower_case_table_names, @@max_allowed_packet AS max_allowed_packet, @@net_buffer_length AS net_buffer_length, @@net_write_timeout AS net_write_timeout, @@query_cache_size AS query_cache_size, @@query_cache_type AS query_cache_type, @@sql_mode AS sql_mode, @@system_time_zone AS system_time_zone, @@time_zone AS time_zone, @@tx_isolation AS transaction_isolation, @@wait_timeout AS wait_timeout
21 Query SET NAMES latin1
21 Query SET character_set_results = NULL
21 Query SET autocommit=1
21 Query SELECT USER()
21 Query SELECT USER()
181210 9:41:10 21 Query show tables
181210 9:41:25 21 Query select count(*) from current_dept_emp
In addition to all the great answers here already, I've also used it to walk an item through a series of transformation steps.
If a transformation is implemented as a Func<T,T>
, you can add several transformations to a List<Func<T,T>>
and use Aggregate
to walk an instance of T
through each step.
You want to take a string
value, and walk it through a series of text transformations that could be built programatically.
var transformationPipeLine = new List<Func<string, string>>();
transformationPipeLine.Add((input) => input.Trim());
transformationPipeLine.Add((input) => input.Substring(1));
transformationPipeLine.Add((input) => input.Substring(0, input.Length - 1));
transformationPipeLine.Add((input) => input.ToUpper());
var text = " cat ";
var output = transformationPipeLine.Aggregate(text, (input, transform)=> transform(input));
Console.WriteLine(output);
This will create a chain of transformations: Remove leading and trailing spaces -> remove first character -> remove last character -> convert to upper-case. Steps in this chain can be added, removed, or reordered as needed, to create whatever kind of transformation pipeline is required.
The end result of this specific pipeline, is that " cat "
becomes "A"
.
This can become very powerful once you realize that T
can be anything. This could be used for image transformations, like filters, using BitMap
as an example;
If you want to read CSV file with some lines, so this the solution.
while IFS=, read -ra line
do
test $i -eq 1 && ((i=i+1)) && continue
for col_val in ${line[@]}
do
echo -n "$col_val|"
done
echo
done < "$csvFile"
promise
represents a value that is not yet known deferred
represents work that is not yet finishedA promise is a placeholder for a result which is initially unknown while a deferred represents the computation that results in the value.
Reference
You can run the ant task echoproperties
and look for "java.version" or ant -v
and look for "Java version", e.g. on my machine
ant echoproperties | grep java.version
shows
[echoproperties] java.version=11.0.9.1
and
ant -v | grep -i "java version"
shows
Detected Java version: 11 in: /opt/java/zulu11.43.55-ca-jdk11.0.9.1-linux_x64
Given a csv file with a datetime column in this format: yyyy-mm-dd hh:mm:ss
Excel shows it in this format: dd/mm/yyyy hh:mm
e.g. 2020-05-22 16:40:55 shows as 22/05/2020 16:40
This is evidently determined by the Short date and Short time format selected in Windows; for example, if I change the Short date format in Windows to yyyy-mm-dd, Excel shows 2020-05-22 16:40.
Annoyingly, I can't find any way to make Excel show the seconds automatically (I have to manually format the column in Excel). But if the csv file includes a time column in hh:mm:ss format (e.g. 16:40:55), that's what shows in Excel, including the seconds.
First i tried with this sample code:
$(document).ready(function(){
$('#upload-file').click();
});
It didn't work for me. Then after, tried with this
$(document).ready(function(){
$('#upload-file')[0].click();
});
No change. At last, tried with this
$(document).ready(function(){
$('#upload-file')[0].click(function(){
});
});
Solved my problem. Helpful for anyone.
Robots cannot execute JavaScript so you do something like injecting some kind of hidden element into the page with JavaScript and then detecting it's presence prior to form submission but beware because some of your users will also have JavaScript disabled
Otherwise I think you will be forced to use a form of client proof of "humanness"
Depends ay which point you wish to "catch" the value.
For instance, if you want to catch the value as soon as the user changes the spinner selected item, use the listener approach (provided by jalopaba)
If you rather catch the value when a user performs the final task like clicking a Submit button, or something, then the answer provided by Rich is better.
utf8_bin
compares the bits blindly. No case folding, no accent stripping.utf8_general_ci
compares one byte with one byte. It does case folding and accent stripping, but no 2-character comparisions: ij
is not equal ?
in this collation.utf8_*_ci
is a set of language-specific rules, but otherwise like unicode_ci
. Some special cases: Ç
, C
, ch
, ll
utf8_unicode_ci
follows an old Unicode standard for comparisons. ij
=?
, but ae
!= æ
utf8_unicode_520_ci
follows an newer Unicode standard. ae
= æ
See collation chart for details on what is equal to what in various utf8 collations.
utf8
, as defined by MySQL is limited to the 1- to 3-byte utf8 codes. This leaves out Emoji and some of Chinese. So you should really switch to utf8mb4
if you want to go much beyond Europe.
The above points apply to utf8mb4
, after suitable spelling change. Going forward, utf8mb4
and utf8mb4_unicode_520_ci
are preferred.
This work for me, after that I could convert put my picture in a bytea field in my database.
using (MemoryStream s = new MemoryStream(DirEntry.Properties["thumbnailphoto"].Value as byte[]))
{
return s.ToArray();
}
Solution:
mongoexport --db test --collection traffic --out traffic.json<br><br>
Where:
database -> mock-server
collection name -> api_defs
output file name -> childChoreRequest.json
You could use a nested Any()
for this check which is available on any Enumerable
:
bool hasMatch = myStrings.Any(x => parameters.Any(y => y.source == x));
Faster performing on larger collections would be to project parameters
to source
and then use Intersect
which internally uses a HashSet<T>
so instead of O(n^2) for the first approach (the equivalent of two nested loops) you can do the check in O(n) :
bool hasMatch = parameters.Select(x => x.source)
.Intersect(myStrings)
.Any();
Also as a side comment you should capitalize your class names and property names to conform with the C# style guidelines.
If you need output from Console.WriteLine, and the Redirect All Output Window Text to the Immediate Window does not function and you need to know the output of Tests from the Integrated Test Explorer, using NUnit.Framework our problem is already solved at VS 2017:
Example taken from C# In Depth by Jon Skeet: This produce this output at Text Explorer:
When we click on Blue Output, under Elapsed Time, at right, and it produces this:
Standard Output is our desired Output, produced by Console.WriteLine.
It functions for Console and for Windows Form Applications at VS 2017, but only for Output generated for Test Explorer at Debug or Run; anyway, this is my main need of Console.WriteLine output.
I hit this discussion while trying to figure out how to get a value from a nested map of unknown depth and it helped me come up with the following solution to my problem. It is overkill for the original question but maybe it will be helpful to someone that finds themselves in a situation where you have less knowledge about the map being searched.
private static Object pullNestedVal(
Map<Object, Object> vmap,
Object ... keys) {
if ((keys.length == 0) || (vmap.size() == 0)) {
return null;
} else if (keys.length == 1) {
return vmap.get(keys[0]);
}
Object stageObj = vmap.get(keys[0]);
if (stageObj instanceof Map) {
Map<Object, Object> smap = (Map<Object, Object>) stageObj;
Object[] skeys = Arrays.copyOfRange(keys, 1, keys.length);
return pullNestedVal(smap, skeys);
} else {
return null;
}
}
One way to see the contents would be:
for my_bucket_object in my_bucket.objects.all():
print(my_bucket_object)
Place this on your model:
[DisplayName("Electric Fan")]
public bool ElectricFan { get; set; }
private string electricFanRate;
public string ElectricFanRate
{
get { return electricFanRate ?? (electricFanRate = "$15/month"); }
set { electricFanRate = value; }
}
And this in your cshtml:
<div class="row">
@Html.CheckBoxFor(m => m.ElectricFan, new { @class = "" })
@Html.LabelFor(m => m.ElectricFan, new { @class = "" })
@Html.DisplayTextFor(m => m.ElectricFanRate)
</div>
Which will output this:
If you click on the checkbox or the bold label it will check/uncheck the checkbox
Just write
@section Scripts{
<script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/bundles/jqueryval")"></script>
}
Your code (vector1 == vector2
) is correct C++ syntax. There is an ==
operator for vectors.
If you want to compare short vector with a portion of a longer vector, you can use theequal()
operator for vectors. (documentation here)
Here's an example:
using namespace std;
if( equal(vector1.begin(), vector1.end(), vector2.begin()) )
DoSomething();
Read about the super keyword (Scroll down the Subclass Constructors). If I understand your question, you probably want to call a superclass constructor?
It is worth noting that the Java compiler will automatically put in a no-arg constructor call to the superclass if you do not explicitly invoke a superclass constructor.
Perhaps, you can have them marked as internal, and in this case only classes in your DAL or BL (assuming they are separate dlls) would be able to set it.
You could also supply a constructor that takes the fields and then only exposes them as properties.
Yes, this is a kind of inconsistency in the language.
The "=" in myarray = "abc";
is assignment (which won't work as the array is basically a kind of constant pointer), whereas in char myarray[4] = "abc";
it's an initialization of the array. There's no way for "late initialization".
You should just remember this rule.
check this out https://forum.jquery.com/topic/get-index-of-same-class-element-on-click then http://jsfiddle.net/me2loveit2/d6rFM/2/
var index = $('selector').index(this);
console.log(index)
I had a somehow similar problem working with AFNetworking from a Swift codebase so I'm just leaving this here in the remote case someone is as unlucky as me having to work in such a setup. If you are, I feel you buddy, stay strong!
The operation was failing due to "unacceptable content-type", despite me actually setting the acceptableContentTypes
with a Set
containing the content type value in question.
The solution for me was to tweak the Swift code to be more Objective-C friendly, I guess:
serializer.acceptableContentTypes = NSSet(array: ["application/xml", "text/xml", "text/plain"]) as Set<NSObject>
NSArray *_returnedArguments = [serverOutput componentsSeparatedByString:@":"];
_returnedArguments
is an array of NSStrings
which the UITextField text
property is expecting. No need to convert.
Syntax error:
[_appDelegate loggedIn:usernameField.text:passwordField.text:(int)[[_returnedArguments objectAtIndex:2] intValue]];
If your _appDelegate has a passwordField
property, then you can set the text using the following
[[_appDelegate passwordField] setText:[_returnedArguments objectAtIndex:2]];
Your error is happening because Object
is a module, not a class. So your inheritance is screwy.
Change your import statement to:
from Object import ClassName
and your class definition to:
class Visitor(ClassName):
or
change your class definition to:
class Visitor(Object.ClassName):
etc
how about this solution? I didn't see anything like this in my search. I am trying to avoid division and make solution simpler.
struct timeval cur_time1, cur_time2, tdiff;
gettimeofday(&cur_time1,NULL);
sleep(1);
gettimeofday(&cur_time2,NULL);
tdiff.tv_sec = cur_time2.tv_sec - cur_time1.tv_sec;
tdiff.tv_usec = cur_time2.tv_usec + (1000000 - cur_time1.tv_usec);
while(tdiff.tv_usec > 1000000)
{
tdiff.tv_sec++;
tdiff.tv_usec -= 1000000;
printf("updated tdiff tv_sec:%ld tv_usec:%ld\n",tdiff.tv_sec, tdiff.tv_usec);
}
printf("end tdiff tv_sec:%ld tv_usec:%ld\n",tdiff.tv_sec, tdiff.tv_usec);
ImageIO.write()
will compress the image by default - the compressed image has a smaller size but looks strange sometimes. I use BufferedOutputStream
to save the byte array data - this will keep the original image size.
Here is the code:
import javax.xml.bind.DatatypeConverter;
import java.io.*;
public class ImageTest {
public static void main(String[] args) {
String base64String = "data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAHkAAAB5C...";
String[] strings = base64String.split(",");
String extension;
switch (strings[0]) {//check image's extension
case "data:image/jpeg;base64":
extension = "jpeg";
break;
case "data:image/png;base64":
extension = "png";
break;
default://should write cases for more images types
extension = "jpg";
break;
}
//convert base64 string to binary data
byte[] data = DatatypeConverter.parseBase64Binary(strings[1]);
String path = "C:\\Users\\Ene\\Desktop\\test_image." + extension;
File file = new File(path);
try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))) {
outputStream.write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
From the answer of @DevWL, I got "Undefined offset ..." at
if ($j<($num_fields-1)) { $data.= ','; }
I made some changes to:
class DBbackup {
public $suffix;
public $dirs;
protected $dbInstance;
public function __construct() {
try{
$this->dbInstance = new PDO("mysql:host=".$dbhost.";dbname=".$dbname,
$username, $password);
} catch(Exception $e) {
die("Error ".$e->getMessage());
}
$this->suffix = date('Ymd_His');
}
public function backup($tables = '*'){
$output = "-- database backup - ".date('Y-m-d H:i:s').PHP_EOL;
$output .= "SET NAMES utf8;".PHP_EOL;
$output .= "SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';".PHP_EOL;
$output .= "SET foreign_key_checks = 0;".PHP_EOL;
$output .= "SET AUTOCOMMIT = 0;".PHP_EOL;
$output .= "START TRANSACTION;".PHP_EOL;
//get all table names
if($tables == '*') {
$tables = [];
$query = $this->dbInstance->prepare('SHOW TABLES');
$query->execute();
while($row = $query->fetch(PDO::FETCH_NUM)) {
$tables[] = $row[0];
}
$query->closeCursor();
}
else {
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
foreach($tables as $table) {
$query = $this->dbInstance->prepare("SELECT * FROM `$table`");
$query->execute();
$output .= "DROP TABLE IF EXISTS `$table`;".PHP_EOL;
$query2 = $this->dbInstance->prepare("SHOW CREATE TABLE `$table`");
$query2->execute();
$row2 = $query2->fetch(PDO::FETCH_NUM);
$query2->closeCursor();
$output .= PHP_EOL.$row2[1].";".PHP_EOL;
while($row = $query->fetch(PDO::FETCH_NUM)) {
$output .= "INSERT INTO `$table` VALUES(";
for($j=0; $j<count($row); $j++) {
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n","\\n",$row[$j]);
if (isset($row[$j]))
$output .= "'".$row[$j]."'";
else $output .= "''";
if ($j<(count($row)-1))
$output .= ',';
}
$output .= ");".PHP_EOL;
}
}
$output .= PHP_EOL.PHP_EOL;
$output .= "COMMIT;";
//save filename
$filename = 'db_backup_'.$this->suffix.'.sql';
$this->writeUTF8filename($filename,$output);
}
private function writeUTF8filename($fn,$c){ /* save as utf8 encoding */
$f=fopen($fn,"w+");
# Now UTF-8 - Add byte order mark
fwrite($f, pack("CCC",0xef,0xbb,0xbf));
fwrite($f,$c);
fclose($f);
}
}
And usage example:
$Backup = new DBbackup();
$Backup->backup();
This works great on MySQL 10.1.34-MariaDB , PHP : 7.2.7
I write this additional answer to explain the origins of the diffusion of the spikes when using FFT and especially discuss the scipy.fftpack tutorial with which I disagree at some point.
In this example, the recording time tmax=N*T=0.75
. The signal is sin(50*2*pi*x) + 0.5*sin(80*2*pi*x)
. The frequency signal should contain two spikes at frequencies 50
and 80
with amplitudes 1
and 0.5
. However, if the analysed signal does not have a integer number of periods diffusion can appear due to the truncation of the signal:
50*tmax=37.5
=> frequency 50
is not a multiple of 1/tmax
=> Presence of diffusion due to signal truncation at this frequency.80*tmax=60
=> frequency 80
is a multiple of 1/tmax
=> No diffusion due to signal truncation at this frequency.Here is a code that analyses the same signal as in the tutorial (sin(50*2*pi*x) + 0.5*sin(80*2*pi*x)
), but with the slight differences:
tmax=1.0
instead of 0.75
to avoid truncation diffusion).The code:
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack
# 1. Linspace
N = 600
# Sample spacing
tmax = 3/4
T = tmax / N # =1.0 / 800.0
x1 = np.linspace(0.0, N*T, N)
y1 = np.sin(50.0 * 2.0*np.pi*x1) + 0.5*np.sin(80.0 * 2.0*np.pi*x1)
yf1 = scipy.fftpack.fft(y1)
xf1 = np.linspace(0.0, 1.0/(2.0*T), N//2)
# 2. Integer number of periods
tmax = 1
T = tmax / N # Sample spacing
x2 = np.linspace(0.0, N*T, N)
y2 = np.sin(50.0 * 2.0*np.pi*x2) + 0.5*np.sin(80.0 * 2.0*np.pi*x2)
yf2 = scipy.fftpack.fft(y2)
xf2 = np.linspace(0.0, 1.0/(2.0*T), N//2)
# 3. Correct positioning of dates relatively to FFT theory ('arange' instead of 'linspace')
tmax = 1
T = tmax / N # Sample spacing
x3 = T * np.arange(N)
y3 = np.sin(50.0 * 2.0*np.pi*x3) + 0.5*np.sin(80.0 * 2.0*np.pi*x3)
yf3 = scipy.fftpack.fft(y3)
xf3 = 1/(N*T) * np.arange(N)[:N//2]
fig, ax = plt.subplots()
# Plotting only the left part of the spectrum to not show aliasing
ax.plot(xf1, 2.0/N * np.abs(yf1[:N//2]), label='fftpack tutorial')
ax.plot(xf2, 2.0/N * np.abs(yf2[:N//2]), label='Integer number of periods')
ax.plot(xf3, 2.0/N * np.abs(yf3[:N//2]), label='Correct positioning of dates')
plt.legend()
plt.grid()
plt.show()
Output:
As it can be here, even with using an integer number of periods some diffusion still remains. This behaviour is due to a bad positioning of dates and frequencies in the scipy.fftpack tutorial. Hence, in the theory of discrete Fourier transforms:
t=0,T,...,(N-1)*T
where T is the sampling period and the total duration of the signal is tmax=N*T
. Note that we stop at tmax-T
.f=0,df,...,(N-1)*df
where df=1/tmax=1/(N*T)
is the sampling frequency. All harmonics of the signal should be multiple of the sampling frequency to avoid diffusion.In the example above, you can see that the use of arange
instead of linspace
enables to avoid additional diffusion in the frequency spectrum. Moreover, using the linspace
version also leads to an offset of the spikes that are located at slightly higher frequencies than what they should be as it can be seen in the first picture where the spikes are a little bit at the right of the frequencies 50
and 80
.
I'll just conclude that the example of usage should be replace by the following code (which is less misleading in my opinion):
import numpy as np
from scipy.fftpack import fft
# Number of sample points
N = 600
T = 1.0 / 800.0
x = T*np.arange(N)
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
yf = fft(y)
xf = 1/(N*T)*np.arange(N//2)
import matplotlib.pyplot as plt
plt.plot(xf, 2.0/N * np.abs(yf[0:N//2]))
plt.grid()
plt.show()
Output (the second spike is not diffused anymore):
I think this answer still bring some additional explanations on how to apply correctly discrete Fourier transform. Obviously, my answer is too long and there is always additional things to say (ewerlopes talked briefly about aliasing for instance and a lot can be said about windowing), so I'll stop.
I think that it is very important to understand deeply the principles of discrete Fourier transform when applying it because we all know so much people adding factors here and there when applying it in order to obtain what they want.
I don't know of any JVM that actually checks the JAVA_OPTS
environment variable. Usually this is used in scripts which launch the JVM and they usually just add it to the java
command-line.
The key thing to understand here is that arguments to java
that come before the -jar analyse.jar
bit will only affect the JVM and won't be passed along to your program. So, modifying the java
line in your script to:
java $JAVA_OPTS -jar analyse.jar $*
Should "just work".
If you are just looking for some text and don't need a result set for programming purposes, you could install HeidiSQL for free (I'm using v9.2.0.4947).
Right click any database or table and select "Find text on server".
All the matches are shown in a separate tab for each table - very nice.
Frighteningly useful and saved me hours. Forget messing about with lengthy queries!!
Bootstrap 4 provides the Collapse component for that. It's using JavaScript behind the scenes, but you don't have to write any JavaScript yourself.
This feature works for <button>
and <a>
.
If you use a <button>
, you must set the data-toggle
and data-target
attributes:
<button type="button" data-toggle="collapse" data-target="#collapseExample">
Toggle
</button>
<div class="collapse" id="collapseExample">
Lorem ipsum
</div>
If you use a <a>
, you must use set href
and data-toggle
:
<a data-toggle="collapse" href="#collapseExample">
Toggle
</a>
<div class="collapse" id="collapseExample">
Lorem ipsum
</div>