It may happen after your Linux kernel update, if you entered this error, you can rebuild your nvidia driver using the following command to fix:
dkms
, which can automatically regenerate new modules after kernel version changes.sudo apt-get install dkms
/usr/src
.sudo dkms build -m nvidia -v 440.82
sudo dkms install -m nvidia -v 440.82
Now you can check to see if you can use it by sudo nvidia-smi
.
This is a language that a prof of mine (Dr. Henry Ledgard) tried to sell us on back in undergrad/grad school. (I don't feel bad about giving his name because, as far as I can tell, he's still a big proponent and would welcome the chance to convince some folks it's the best thing since sliced bread). When describing it to people, my best analogy is that it's sort of a bastard child of FORTRAN and COBOL, with some extra bad thrown in. From the only really accessible folder I've found with this material (there's lots more in there that I'm not going to link specifically here):
VSE is built around what they call "The Separation Principle". The idea is that Data and Behavior must be completely segregated. Imagine C's requirement that all variables/data must be declared at the beginning of the function, except now move that declaration into a separate file that other functions can use as well. When other functions use it, they're using the same data, not a local copy of data with the same layout.
Why do things this way? We learn that from The Software Survivors that Variable Scope Rules Are Hard. I'd include a quote but, like most fools, it takes these guys forever to say anything. Search that PDF for "Quagmire Of Scope" and you'll discover some true enlightenment.
They go on to claim that this somehow makes it more suitable for multi-proc environments because it more closely models the underlying hardware implementation. Riiiight.
Another choice theme that comes up frequently:
INCREMENT DAY COUNT BY 7 (or DAY COUNT = DAY COUNT + 7) DECREMENT TOTAL LOSS BY GROUND_LOSS ADD 100.3 TO TOTAL LOSS(LINK_POINTER) SET AIRCRAFT STATE TO ON_THE_GROUND PERCENT BUSY = (TOTAL BUSY CALLS * 100)/TOTAL CALLS
Although not earthshaking, the style of arithmetic reflects ordinary usage, i.e., anyone can read and understand it - without knowing a programming language. In fact, VisiSoft arithmetic is virtually identical to FORTRAN, including embedded complex arithmetic. This puts programmers concerned with their professional status and corresponding job security ill at ease.
Ummm, not that concerned at all, really. One of the key selling points that Bill Cave uses to try to sell VSE is the democratization of programming so that business people don't need to indenture themselves to programmers who use crazy, arcane tools for the sole purpose of job security. He leverages this irrational fear to sell his tool. (And it works-- the federal gov't is his biggest customer). I counted 17 uses of the phrase "job security" in the document. Examples:
- ... and fit only for those desiring artificial job security.
- More false job security?
- Is job security dependent upon ensuring the other guy can't figure out what was done?
- Is job security dependent upon complex code...?
- One of the strongest forces affecting the acceptance of new technology is the perception of one's job security.
He uses this paranoia to drive wedge between the managers holding the purse strings and the technical people who have the knowledge to recognize VSE for the turd that it is. This is how he squeezes it into companies-- "Your technical people are only saying it sucks because they're afraid it will make them obsolete!"
Another consequence of this approach is that data is mapped into memory on a "What You See Is What You Get" basis, and maintained throughout. This allows users to move a complete structure as a string of characters into a template that descrives each individual field. Multiple templates can be redefined for a given storage area. Unlike C and other languages, substructures can be moved without the problems of misalignment due to word boundary alignment standards.
Now, I don't know about you, but I know that a WYSIWYG approach to memory layout is at the top of my priority list when it comes to language choice! Basically, they ignore alignment issues because only old languages that were designed in the '60's and '70's care about word alignment. Or something like that. The reasoning is bogus. It made so little sense to me that I proceeded to forget it almost immediately.
There are no user-defined types in VSE. This is a far-reaching decision that greatly simplifies the language. The gain from a practical point of view is also great. VSE allows the designer and programmer to organize a program along the same lines as a physical system being modeled. VSE allows structures to be built in an easy-to-read, logical attribute hierarchy.
Awesome! User-defined types are lame. Why would I want something like an InputMessage
object when I can have:
LINKS_IN_USE INTEGER
INPUT_MESSAGE
1 ORIGIN INTEGER
1 DESTINATION INTEGER
1 MESSAGE
2 MESSAGE_HEADER CHAR 10
2 MESSAGE_BODY CHAR 24
2 MESSAGE_TRAILER CHAR 10
1 ARRIVAL_TIME INTEGER
1 DURATION INTEGER
1 TYPE CHAR 5
OUTPUT_MESSAGE CHARACTER 50
You might look at that and think, "Oh, that's pretty nicely formatted, if a bit old-school." Old-school is right. Whitespace is significant-- very significant. And redundant! The 1
's must be in column 3. The 1
indicates that it's at the first level of the hierarchy. The Symbol name must be in column 5. You hierarchies are limited to a depth of 9.
Well, ok, but is that so awful? Just wait:
It is well known that for reading text, use of conventional upper/lower case is more readable. VSE uses all upper case (except for comments). Why? The literature in psychology is based on prose. Programs, simply, are not prose. Programs are more like math, accounting, tables. Program fonts (usually Courier) are almost universally fixed-pitch, and for good reason – vertical alignment among related lines of code. Programs in upper case are nicely readable, and, after a time, much better in our opinion
Nothing like enforcing your opinion at the language level! That's right, you cannot use any lower case in VSE unless it's in a comment. Just keep your CAPSLOCK on, it's gonna be stuck there for a while.
VSE subprocedures are called processes. This code sample contains three processes:
PROCESS_MUSIC
EXECUTE INITIALIZE_THE_SCENE
EXECUTE PROCESS_PANEL_WIDGET
INITIALIZE_THE_SCENE
SET TEST_BUTTON PANEL_BUTTON_STATUS TO ON
MOVE ' ' TO TEST_INPUT PANEL_INPUT_TEXT
DISPLAY PANEL PANEL_MUSIC
PROCESS_PANEL_WIDGET
ACCEPT PANEL PANEL_MUSIC
*** CHECK FOR BUTTON CLICK
IF RTG_PANEL_WIDGET_NAME IS EQUAL TO 'TEST_BUTTON'
MOVE 'I LIKE THE BEATLES!' TO TEST_INPUT PANEL_INPUT_TEXT.
DISPLAY PANEL PANEL_MUSIC
All caps as expected. After all, that's easier to read. Note the whitespace. It's significant again. All process names must start in column 0. The initial level of instructions must start on column 4. Deeper levels must be indented exactly 3 spaces. This isn't a big deal, though, because you aren't allowed to do things like nest conditionals. You want a nested conditional? Well just make another process and call it. And note the delicious COBOL-esque syntax!
You want loops? Easy:
EXECUTE NEXT_CALL
EXECUTE NEXT_CALL 5 TIMES
EXECUTE NEXT_CALL TOTAL CALL TIMES
EXECUTE NEXT_CALL UNTIL NO LINES ARE AVAILABLE
EXECUTE NEXT_CALL UNTIL CALLS_ANSWERED ARE EQUAL TO CALLS_WAITING
EXECUTE READ_MESSAGE UNTIL LEAD_CHARACTER IS A DELIMITER
Ugh.
If you don't want to import csv
module for that, you can write a list of lists to a csv file using only Python built-ins
with open("output.csv", "w") as f:
for row in a:
f.write("%s\n" % ','.join(str(col) for col in row))
In the book of Matt Stauffer he suggest to create an array in your config/app.php
to add the variable and then anywhere you reference to it with:
$myvariable = new Namearray(config('fileWhichContainsVariable.array.ConfigKeyVariable'))
Have try this solution? is good ?
2) option : pod update, clean derive data,
There's a simple way to get rid of this restriction by using the datePicker component provided by jQuery.
Include jQuery and jQuery UI libraries (I'm still using an old one)
Use the following snip
$(function() {
$( "#id_of_the_component" ).datepicker({ dateFormat: 'yy-mm-dd'});
});
See jQuery UI DatePicker - Change Date Format if needed.
sudo svn revert filename
this is the better way to revert a single file
One simple solution to this is to replace the item being changed in the ObservableCollection which notifies the collection of the changed item. In the sample code snippet below Artists is the ObservableCollection and artist is an item of the type in the ObservableCollection:
var index = Artists.IndexOf(artist);
Artists.RemoveAt(index);
artist.IsFollowed = true; // change something in the item
Artists.Insert(index, artist);
System.Convert.IsDbNull][1](table.rows[0][0]);
IIRC, the (table.rows[0][0] == null)
won't work, as DbNull.Value != null;
I've noticed that if you set the theme in the AndroidManifest, it seems to get rid of that short time where you can see the action bar. So, try adding this to your manifest:
<android:theme="@android:style/Theme.NoTitleBar">
Just add it to your application
tag to apply it app-wide.
You can change it inside bs-config.json
file as mentioned in the docs https://github.com/johnpapa/lite-server#custom-configuration
For example,
{
"port": 8000,
"files": ["./src/**/*.{html,htm,css,js}"],
"server": { "baseDir": "./src" }
}
With MySql 5.1 (Win7). To recreate DBs (InnoDbs) I've replaced all contents of following dirs (my.ini params):
datadir="C:/ProgramData/MySQL/MySQL Server 5.1/Data/"
innodb_data_home_dir="C:/MySQL Datafiles/"
After that I started MySql Service and all works fine.
I think it's just for your convenience (and the readers of your code)
Your code, and your unit tests should be ideally self documenting which this API helps with,
Think abt what is more clear to read:
AssertTrue(!(a > 3));
or
AssertFalse(a > 3);
When you open your tests after xx months when your tests suddenly fail, it would take you much less time to understand what went wrong in the second case (my opinion). If you disagree, you can always stick with AssertTrue for all cases :)
It is ok for sure. With just few hundred of entries, it will be fast.
You can add an unique id as as primary key (int autoincrement) ans set your coupon_code as unique. So if you need to do request in other tables it's better to use int than varchar
Your java version is 1.5 (you have jdk 1.5). The jar requires java version 1.7 (you should have jdk 1.7). You should download and install the 1.7 jdk from this website:
http://www.oracle.com/technetwork/java/javase/downloads/java-se-jdk-7-download-432154.html
Just for fun, here's a sample with a recursive function which (I hope) should be a bit simpler to understand and to use with your code:
Function Recurse(sPath As String) As String
Dim FSO As New FileSystemObject
Dim myFolder As Folder
Dim mySubFolder As Folder
Set myFolder = FSO.GetFolder(sPath)
For Each mySubFolder In myFolder.SubFolders
Call TestSub(mySubFolder.Path)
Recurse = Recurse(mySubFolder.Path)
Next
End Function
Sub TestR()
Call Recurse("D:\Projets\")
End Sub
Sub TestSub(ByVal s As String)
Debug.Print s
End Sub
Edit: Here's how you can implement this code in your workbook to achieve your objective.
Sub TestSub(ByVal s As String)
Dim FSO As New FileSystemObject
Dim myFolder As Folder
Dim myFile As File
Set myFolder = FSO.GetFolder(s)
For Each myFile In myFolder.Files
If myFile.Name = Range("E1").Value Then
Debug.Print myFile.Name 'Or do whatever you want with the file
End If
Next
End Sub
Here, I just debug the name of the found file, the rest is up to you. ;)
Of course, some would say it's a bit clumsy to call twice the FileSystemObject so you could simply write your code like this (depends on wether you want to compartmentalize or not):
Function Recurse(sPath As String) As String
Dim FSO As New FileSystemObject
Dim myFolder As Folder
Dim mySubFolder As Folder
Dim myFile As File
Set myFolder = FSO.GetFolder(sPath)
For Each mySubFolder In myFolder.SubFolders
For Each myFile In mySubFolder.Files
If myFile.Name = Range("E1").Value Then
Debug.Print myFile.Name & " in " & myFile.Path 'Or do whatever you want with the file
Exit For
End If
Next
Recurse = Recurse(mySubFolder.Path)
Next
End Function
Sub TestR()
Call Recurse("D:\Projets\")
End Sub
Actually, you should use the translate directive for such stuff instead.
<h1 translate="{{pageTitle}}"></h1>
The directive takes care of asynchronous execution and is also clever enough to unwatch translation ids on the scope if the translation has no dynamic values.
However, if there's no way around and you really have to use $translate
service in the controller, you should wrap the call in a $translateChangeSuccess
event using $rootScope
in combination with $translate.instant()
like this:
.controller('foo', function ($rootScope, $scope, $translate) {
$rootScope.$on('$translateChangeSuccess', function () {
$scope.pageTitle = $translate.instant('PAGE.TITLE');
});
})
So why $rootScope
and not $scope
? The reason for that is, that in angular-translate's events are $emit
ed on $rootScope
rather than $broadcast
ed on $scope
because we don't need to broadcast through the entire scope hierarchy.
Why $translate.instant()
and not just async $translate()
? When $translateChangeSuccess
event is fired, it is sure that the needed translation data is there and no asynchronous execution is happening (for example asynchronous loader execution), therefore we can just use $translate.instant()
which is synchronous and just assumes that translations are available.
Since version 2.8.0 there is also $translate.onReady()
, which returns a promise that is resolved as soon as translations are ready. See the changelog.
['foo', 'bar', 'baz'].each_with_index {|j, i| puts "#{i} #{j}"}
The feedback you get on the interactive interpreter uses repr
too. When you type in an expression (let it be expr
), the interpreter basically does result = expr; if result is not None: print repr(result)
. So the second line in your example is formatting the string foo
into the representation you want ('foo'
). And then the interpreter creates the repr
esentation of that, leaving you with double quotes.
Why when I combine %r with double-quote and single quote escapes and print them out, it prints it the way I'd write it in my .py file but not the way I'd like to see it?
I'm not sure what you're asking here. The text single ' and double " quotes
, when run through repr
, includes escapes for one kind of quote. Of course it does, otherwise it wouldn't be a valid string literal by Python rules. That's precisely what you asked for by calling repr
.
Also note that the eval(repr(x)) == x
analogy isn't meant literal. It's an approximation and holds true for most (all?) built-in types, but the main thing is that you get a fairly good idea of the type and logical "value" from looking the the repr
output.
$total=0;
foreach($group as $key=>$value)
{
echo $key. " = " .$value. "<br>";
$total+= $value;
}
echo $total;
If the purpose is to simply print coarse timing information to your program logs, then the easy solution for Java projects is not to write your own stopwatch or timer classes, but just use the org.apache.commons.lang.time.StopWatch
class that is part of Apache Commons Lang.
final StopWatch stopwatch = new StopWatch();
stopwatch.start();
LOGGER.debug("Starting long calculations: {}", stopwatch);
...
LOGGER.debug("Time after key part of calcuation: {}", stopwatch);
...
LOGGER.debug("Finished calculating {}", stopwatch);
Can you pick the appropriate char set in the Constructor:
new InputStreamReader(new FileInputStream(in), "ISO8859_1");
Use this method and pass your array in parameter
Collections.shuffle(arrayList);
This method return void so it will not give you a new list but as we know that array is passed as a reference type in Java so it will shuffle your array and save shuffled values in it. That's why you don't need any return type.
You can now use arraylist which is shuffled.
@kgiannakakis answer is fully correct, but if someone stuck into this problem and uses Java 6 on Linux (by example, Mint 19 Cinnamon), MAXIMIZED_BOTH state is sometimes not applied.
You could try to call pack() method after setting this state.
Code example:
public MainFrame() {
setContentPane(contentPanel); //some JPanel is here
setPreferredSize(new Dimension(1200, 800));
setMinimumSize(new Dimension(1200, 800));
setSize(new Dimension(1200, 800));
setExtendedState(JFrame.MAXIMIZED_BOTH);
pack();
}
This is not necessary if you are using Java 7+ or Java 6 on Windows.
In fact you cannot do it easily right now (at the time I am writing this message). I will try to explain why.
First of all, the glibc is no more, it has been subsumed by the eglibc project. And, the Debian distribution switched to eglibc some time ago (see here and there and even on the glibc source package page). So, you should consider installing the eglibc package through this kind of command:
apt-get install libc6-amd64 libc6-dev libc6-dbg
Replace amd64
by the kind of architecture you want (look at the package list here).
Unfortunately, the eglibc package version is only up to 2.13 in unstable
and testing
. Only the experimental
is providing a 2.17 version of this library. So, if you really want to have it in 2.15 or more, you need to install the package from the experimental version (which is not recommended). Here are the steps to achieve as root:
Add the following line to the file /etc/apt/sources.list
:
deb http://ftp.debian.org/debian experimental main
Update your package database:
apt-get update
Install the eglibc package:
apt-get -t experimental install libc6-amd64 libc6-dev libc6-dbg
Pray...
Well, that's all folks.
I'm making a guess here, but your start
invocation probably looks like this:
start "\Foo\Bar\Path with spaces in it\program.exe"
This will open a new console window, using “\Foo\Bar\Path with spaces in it\program.exe” as its title.
If you use start
with something that is (or needs to be) surrounded by quotes, you need to put empty quotes as the first argument:
start "" "\Foo\Bar\Path with spaces in it\program.exe"
This is because start
interprets the first quoted argument it finds as the window title for a new console window.
I have a method, and while not the most efficient...it works! (and it doesn't involve any fancy modules).
Basically it compares your Variable's ID to globals() Variables' IDs, then returns the match's name.
def getVariableName(variable, globalVariables=globals().copy()):
""" Get Variable Name as String by comparing its ID to globals() Variables' IDs
args:
variable(var): Variable to find name for (Obviously this variable has to exist)
kwargs:
globalVariables(dict): Copy of the globals() dict (Adding to Kwargs allows this function to work properly when imported from another .py)
"""
for globalVariable in globalVariables:
if id(variable) == id(globalVariables[globalVariable]): # If our Variable's ID matches this Global Variable's ID...
return globalVariable # Return its name from the Globals() dict
numba
module for speed up.On big datasets (500k >
) pd.cut
can be quite slow for binning data.
I wrote my own function in numba
with just in time compilation, which is roughly 16x
faster:
from numba import njit
@njit
def cut(arr):
bins = np.empty(arr.shape[0])
for idx, x in enumerate(arr):
if (x >= 0) & (x < 1):
bins[idx] = 1
elif (x >= 1) & (x < 5):
bins[idx] = 2
elif (x >= 5) & (x < 10):
bins[idx] = 3
elif (x >= 10) & (x < 25):
bins[idx] = 4
elif (x >= 25) & (x < 50):
bins[idx] = 5
elif (x >= 50) & (x < 100):
bins[idx] = 6
else:
bins[idx] = 7
return bins
cut(df['percentage'].to_numpy())
# array([5., 5., 7., 5.])
Optional: you can also map it to bins as strings:
a = cut(df['percentage'].to_numpy())
conversion_dict = {1: 'bin1',
2: 'bin2',
3: 'bin3',
4: 'bin4',
5: 'bin5',
6: 'bin6',
7: 'bin7'}
bins = list(map(conversion_dict.get, a))
# ['bin5', 'bin5', 'bin7', 'bin5']
Speed comparison:
# create dataframe of 8 million rows for testing
dfbig = pd.concat([df]*2000000, ignore_index=True)
dfbig.shape
# (8000000, 1)
%%timeit
cut(dfbig['percentage'].to_numpy())
# 38 ms ± 616 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
pd.cut(dfbig['percentage'], bins=bins, labels=labels)
# 215 ms ± 9.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
There is a solution that worked for me, referring to the parent. After getting the url that will redirect to google authentication page, you can try the following code:
var loc = redirect_location;
window.parent.location.replace(loc);
You can get it in a programmatic way via an SSH library (https://code.google.com/p/sshxcute)
public static String getIpAddress() throws TaskExecFailException{
ConnBean cb = new ConnBean(host, username, password);
SSHExec ssh = SSHExec.getInstance(cb);
ssh.connect();
CustomTask sampleTask = new ExecCommand("echo \"${SSH_CLIENT%% *}\"");
String Result = ssh.exec(sampleTask).sysout;
ssh.disconnect();
return Result;
}
Get Autoruns from Mark Russinovich, the Sysinternals guy that discovered the Sony Rootkit... Best software I've ever used for cleaning up things that get started automatically.
Just a recommendation:
I'd recommend using the DOM table implementation, it's very straight forward and easy to use, you really don't need jQuery for this task.
var table = document.getElementById('tblOne');
var rowLength = table.rows.length;
for(var i=0; i<rowLength; i+=1){
var row = table.rows[i];
//your code goes here, looping over every row.
//cells are accessed as easy
var cellLength = row.cells.length;
for(var y=0; y<cellLength; y+=1){
var cell = row.cells[y];
//do something with every cell here
}
}
Here is my version, which provides writelines() and fileno(), too:
class FlushFile(object):
def __init__(self, fd):
self.fd = fd
def write(self, x):
ret = self.fd.write(x)
self.fd.flush()
return ret
def writelines(self, lines):
ret = self.writelines(lines)
self.fd.flush()
return ret
def flush(self):
return self.fd.flush
def close(self):
return self.fd.close()
def fileno(self):
return self.fd.fileno()
imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
I had the same problem but my issue with the @Slauma's solution (although great in certain instances) is that it recommends that I pass the context into the service which implies that the context is available from my controller. It also forces tight coupling between my controller and service layers.
I'm using Dependency Injection to inject the service/repository layers into the controller and as such do not have access to the context from the controller.
My solution was to have the service/repository layers use the same instance of the context - Singleton.
Context Singleton Class:
Reference: http://msdn.microsoft.com/en-us/library/ff650316.aspx
and http://csharpindepth.com/Articles/General/Singleton.aspx
public sealed class MyModelDbContextSingleton
{
private static readonly MyModelDbContext instance = new MyModelDbContext();
static MyModelDbContextSingleton() { }
private MyModelDbContextSingleton() { }
public static MyModelDbContext Instance
{
get
{
return instance;
}
}
}
Repository Class:
public class ProjectRepository : IProjectRepository
{
MyModelDbContext context = MyModelDbContextSingleton.Instance;
[...]
Other solutions do exist such as instantiating the context once and passing it into the constructors of your service/repository layers or another I read about which is implementing the Unit of Work pattern. I'm sure there are more...
As you know this is UK format issue. You can do date conversion indirectly by using function.
CREATE FUNCTION ChangeDateFormatFromUK
(
@DateColumn varchar(10)
)
RETURNS VARCHAR(10)
AS
BEGIN
DECLARE @Year varchar(4), @Month varchar(2), @Day varchar(2), @Result varchar(10)
SET @Year = (SELECT substring(@DateColumn,7,10))
SET @Month = (SELECT substring(@DateColumn,4,5))
SET @Day = (SELECT substring(@DateColumn,1,2))
SET @Result = @Year + '/' @Month + '/' + @Day
RETURN @Result
END
To call this function
SELECT dbo.ChangeDateFormatFromUK([dates]) from table
Convert it normally to datetime
SELECT CONVERT(DATETIME,dbo.ChangeDateFormatFromUK([dates])) from table
In your Case, you can do
SELECT [dates] from table where CONVERT(DATETIME,dbo.ChangeDateFormatFromUK([dates])) > GetDate() -- or any date
I used a trial version of ZOC Terminal Emulator and it worked. It readily accepts the Amazon's *.pem files.
The trick is though, that you need to specify "ec2-user" instead of "root" for the username - despite the example shown in the EC2 console, which is wrong! ;-)
You need to re-factor the code into pieces. This doesn't stop execution, it just puts a delay in between the parts.
function partA() {
...
window.setTimeout(partB,1000);
}
function partB() {
...
}
I'll add XMLSerializer
to the pile. It provides the fastest result without using any object caching (not on the serializer, nor on the Text node).
function serializeTextNode(text) {
return new XMLSerializer().serializeToString(document.createTextNode(text));
}
The added bonus is that it supports attributes which is serialized differently than text nodes:
function serializeAttributeValue(value) {
const attr = document.createAttribute('a');
attr.value = value;
return new XMLSerializer().serializeToString(attr);
}
You can see what it's actually replacing by checking the spec, both for text nodes and for attribute values. The full documentation has more node types, but the concept is the same.
As for performance, it's the fastest when not cached. When you do allow caching, then calling innerHTML
on an HTMLElement with a child Text node is fastest. Regex would be slowest (as proven by other comments). Of course, XMLSerializer could be faster on other browsers, but in my (limited) testing, a innerHTML
is fastest.
Fastest single line:
new XMLSerializer().serializeToString(document.createTextNode(text));
Fastest with caching:
const cachedElementParent = document.createElement('div');
const cachedChildTextNode = document.createTextNode('');
cachedElementParent.appendChild(cachedChildTextNode);
function serializeTextNode(text) {
cachedChildTextNode.nodeValue = text;
return cachedElementParent.innerHTML;
}
Currently there is no way to do this with apps running in WSL2. However there are two work-arounds:
The debug window retains the contents of the WSL shell window that closed.
The window remains open if your application returns a non-zero return code, so you could return non-zero in debug builds for example.
I'm using VS 2019.
if your solution has more than one project / class libraries etc, then you may not see the Web tab when clicking on Solution explorer properties.
Clicking on the MVC project and then checking properties will reveal the web tab where you can change the port.
You just need a binary (with debugging symbols included) that is identical to the one that generated the core dump file. Then you can run gdb path/to/the/binary path/to/the/core/dump/file
to debug it.
When it starts up, you can use bt
(for backtrace) to get a stack trace from the time of the crash. In the backtrace, each function invocation is given a number. You can use frame number
(replacing number with the corresponding number in the stack trace) to select a particular stack frame.
You can then use list
to see code around that function, and info locals
to see the local variables. You can also use print name_of_variable
(replacing "name_of_variable" with a variable name) to see its value.
Typing help
within GDB will give you a prompt that will let you see additional commands.
If you mean "how can I get a reference to all markers on a given map" - then I think the answer is "Sorry, you have to do it yourself". I don't think there is any handy "maps.getMarkers()" type function: you have to keep your own references as the points are created:
var allMarkers = [];
....
// Create some markers
for(var i = 0; i < 10; i++) {
var marker = new google.maps.Marker({...});
allMarkers.push(marker);
}
...
Then you can loop over the allMarkers
array to and do whatever you need to do.
In any case, your code will generate invalid markup: You shouldn't wrap block contents in a link. tags don't work like this. If you want this effect you should use js or create an absolutely positioned link above the content (z-index). More on this here: Make a div into a link.
You should make sure to validate your code when it renders: http://validator.w3.org
FYI, this is probably faster,
SELECT count(1) FROM (SELECT distinct productId WHERE keyword = '$keyword') temp
than this,
SELECT COUNT(DISTINCT productId) WHERE keyword='$keyword'
I want to complete the answer from tchester.
(1) Enable the xp_cmdshell procedure:
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
-- Enable the xp_cmdshell procedure
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE
GO
(2) Create a login 'Domain\TestUser' (windows user) for the non-sysadmin user that has public access to the master database
(3) Grant EXEC permission on the xp_cmdshell stored procedure:
GRANT EXECUTE ON xp_cmdshell TO [Domain\TestUser]
(4) Create a proxy account that xp_cmdshell will be run under using sp_xp_cmdshell_proxy_account
EXEC sp_xp_cmdshell_proxy_account 'Domain\TestUser', 'pwd'
-- Note: pwd means windows password for [Domain\TestUser] account id on the box.
-- Don't include square brackets around Domain\TestUser.
(5) Grant control server permission to user
USE master;
GRANT CONTROL SERVER TO [Domain\TestUser]
GO
Following Snippet will help you
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.vogella.cameara.api"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name="de.vogella.camera.api.MakePhotoActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/captureFront"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="onClick"
android:text="Make Photo" />
</RelativeLayout>
PhotoHandler.java
package org.sample;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
public class PhotoHandler implements PictureCallback {
private final Context context;
public PhotoHandler(Context context) {
this.context = context;
}
@Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFileDir = getDir();
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
Log.d(Constants.DEBUG_TAG, "Can't create directory to save image.");
Toast.makeText(context, "Can't create directory to save image.",
Toast.LENGTH_LONG).show();
return;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "Picture_" + date + ".jpg";
String filename = pictureFileDir.getPath() + File.separator + photoFile;
File pictureFile = new File(filename);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Toast.makeText(context, "New Image saved:" + photoFile,
Toast.LENGTH_LONG).show();
} catch (Exception error) {
Log.d(Constants.DEBUG_TAG, "File" + filename + "not saved: "
+ error.getMessage());
Toast.makeText(context, "Image could not be saved.",
Toast.LENGTH_LONG).show();
}
}
private File getDir() {
File sdDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(sdDir, "CameraAPIDemo");
}
}
MakePhotoActivity.java
package org.sample;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import de.vogella.cameara.api.R;
public class MakePhotoActivity extends Activity {
private final static String DEBUG_TAG = "MakePhotoActivity";
private Camera camera;
private int cameraId = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// do we have a camera?
if (!getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG)
.show();
} else {
cameraId = findFrontFacingCamera();
camera = Camera.open(cameraId);
if (cameraId < 0) {
Toast.makeText(this, "No front facing camera found.",
Toast.LENGTH_LONG).show();
}
}
}
public void onClick(View view) {
camera.takePicture(null, null,
new PhotoHandler(getApplicationContext()));
}
private int findFrontFacingCamera() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
Log.d(DEBUG_TAG, "Camera found");
cameraId = i;
break;
}
}
return cameraId;
}
@Override
protected void onPause() {
if (camera != null) {
camera.release();
camera = null;
}
super.onPause();
}
}
A regex maybe? I think this would work...
\(([a-z]+?)\)
Based on your comment, simple definitions of each is best found at W3Schools The first line of each type gives a brief explanation of the join type
- JOIN: Return rows when there is at least one match in both tables
- LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
- RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
- FULL JOIN: Return rows when there is a match in one of the tables
END EDIT
In a nutshell, the comma separated example you gave of
SELECT * FROM a, b WHERE b.id = a.beeId AND ...
is selecting every record from tables a and b with the commas separating the tables, this can be used also in columns like
SELECT a.beeName,b.* FROM a, b WHERE b.id = a.beeId AND ...
It is then getting the instructed information in the row where the b.id column and a.beeId column have a match in your example. So in your example it will get all information from tables a and b where the b.id equals a.beeId. In my example it will get all of the information from the b table and only information from the a.beeName column when the b.id equals the a.beeId. Note that there is an AND clause also, this will help to refine your results.
For some simple tutorials and explanations on mySQL joins and left joins have a look at Tizag's mySQL tutorials. You can also check out Keith J. Brown's website for more information on joins that is quite good also.
I hope this helps you
If you already have the databinding in place John Myczek answer is complete.
If not you have at least 2 options I know of if you want to specify the source of your data. (However I am not sure whether or not this is in
line with most guidelines, like MVVM)
option 1: like JohnB said. But I think you should use your own defined collection instead of a weakly typed DataTable (no offense, but you can't tell from the code what each column represents)
xaml.cs
DataContext = myCollection;
//myCollection is a `ICollection<YourType>` preferably
`ObservableCollection<YourType>
- option 2) Declare the name of the Datagrid in xaml
<WpfToolkit:DataGrid Name=dataGrid}>
in xaml.cs
CollectionView myCollectionView =
(CollectionView)CollectionViewSource.GetDefaultView(yourCollection);
dataGrid.ItemsSource = myCollectionView;
If your type has a property FirstName defined, you can then do what John Myczek pointed out.
DataGridTextColumn textColumn = new DataGridTextColumn();
dataColumn.Header = "First Name";
dataColumn.Binding = new Binding("FirstName");
dataGrid.Columns.Add(textColumn);
This obviously doesn't work if you don't know properties you will need to show in your dataGrid, but if that is the case you will have more problems to deal with, and I believe that's out of scope here.
I updated @LeonardChallis's solution as it didn't work for me as none of the others. I removed the WHERE
clauses and SET primaryKey = 0
in the temp table so MySQL auto-increments itself the primaryKey
CREATE TEMPORARY TABLE tmptable SELECT * FROM myTable;
UPDATE tmptable SET primaryKey = 0;
INSERT INTO myTable SELECT * FROM tmptable;
This is of course to duplicate all the rows in the table.
Google wrote some code to assist with this. Here are some examples: Example using InfoBubble, Styled markers and Info Window Custom (using OverlayView).
The code in the links above take different routes to achieve similar results. The gist of it is that it is not easy to style InfoWindows directly, and it might be easier to use the additional InfoBubble class instead of InfoWindow, or to override GOverlay. Another option would be to modify the elements of the InfoWindow using javascript (or jQuery), like later ATOzTOA suggested.
Possibly the simplest of these examples is using InfoBubble instead of InfoWindow. InfoBubble is available by importing this file (which you should host yourself): http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobubble/src/infobubble.js
InfoBubble's Github project page.
InfoBubble is very stylable, compared to InfoWindow:
infoBubble = new InfoBubble({
map: map,
content: '<div class="mylabel">The label</div>',
position: new google.maps.LatLng(-32.0, 149.0),
shadowStyle: 1,
padding: 0,
backgroundColor: 'rgb(57,57,57)',
borderRadius: 5,
arrowSize: 10,
borderWidth: 1,
borderColor: '#2c2c2c',
disableAutoPan: true,
hideCloseButton: true,
arrowPosition: 30,
backgroundClassName: 'transparent',
arrowStyle: 2
});
infoBubble.open();
You can also call it with a given map and marker to open on:
infoBubble.open(map, marker);
As another example, the Info Window Custom example extends the GOverlay class from the Google Maps API and uses this as a base for creating a more flexible info window. It first creates the class:
/* An InfoBox is like an info window, but it displays
* under the marker, opens quicker, and has flexible styling.
* @param {GLatLng} latlng Point to place bar at
* @param {Map} map The map on which to display this InfoBox.
* @param {Object} opts Passes configuration options - content,
* offsetVertical, offsetHorizontal, className, height, width
*/
function InfoBox(opts) {
google.maps.OverlayView.call(this);
this.latlng_ = opts.latlng;
this.map_ = opts.map;
this.offsetVertical_ = -195;
this.offsetHorizontal_ = 0;
this.height_ = 165;
this.width_ = 266;
var me = this;
this.boundsChangedListener_ =
google.maps.event.addListener(this.map_, "bounds_changed", function() {
return me.panMap.apply(me);
});
// Once the properties of this OverlayView are initialized, set its map so
// that we can display it. This will trigger calls to panes_changed and
// draw.
this.setMap(this.map_);
}
after which it proceeds to override GOverlay:
InfoBox.prototype = new google.maps.OverlayView();
You should then override the methods you need: createElement
, draw
, remove
and panMap
. It gets rather involved, but in theory you are just drawing a div on the map yourself now, instead of using a normal Info Window.
If you have an x
and y
column that you want to scatterplot, but not all of the cells in one of the columns is populated with meaningful values (i.e. some of them have #DIV/0!
), then insert a new column next to the offending column and type =IFERROR(A2, #N/A)
, where A2 is the value in the offending column.
This will return #N/A
if there is a #DIV/0!
and will return the good value otherwise. Now make your plot with your new column and Excel ignores #N/A
value and will not plot them as zeroes.
Important: do not output "#N/A"
in the formula, just output #N/A
.
Slicing works (and is the preferred approach), but just an alternative if more operations are needed (but then converting to a list wouldn't hurt anyway):
>>> a = '123456789'
>>> b = bytearray(a)
>>> del b[3]
>>> b
bytearray(b'12356789')
>>> str(b)
'12356789'
The simplest solution is probably:
In [10]: ''.join(set('aaabcabccd'))
Out[10]: 'acbd'
Note that this doesn't guarantee the order in which the letters appear in the output, even though the example might suggest otherwise.
You refer to the output as a "list". If a list is what you really want, replace ''.join
with list
:
In [1]: list(set('aaabcabccd'))
Out[1]: ['a', 'c', 'b', 'd']
As far as performance goes, worrying about it at this stage sounds like premature optimization.
For Python users, you can try pyyaml-include.
pip install pyyaml-include
import yaml
from yamlinclude import YamlIncludeConstructor
YamlIncludeConstructor.add_to_loader_class(loader_class=yaml.FullLoader, base_dir='/your/conf/dir')
with open('0.yaml') as f:
data = yaml.load(f, Loader=yaml.FullLoader)
print(data)
Consider we have such YAML files:
+-- 0.yaml
+-- include.d
+-- 1.yaml
+-- 2.yaml
1.yaml
's content:name: "1"
2.yaml
's content:name: "2"
On top level:
If 0.yaml
was:
!include include.d/1.yaml
We'll get:
{"name": "1"}
In mapping:
If 0.yaml
was:
file1: !include include.d/1.yaml
file2: !include include.d/2.yaml
We'll get:
file1:
name: "1"
file2:
name: "2"
In sequence:
If 0.yaml
was:
files:
- !include include.d/1.yaml
- !include include.d/2.yaml
We'll get:
files:
- name: "1"
- name: "2"
? Note:
File name can be either absolute (like
/usr/conf/1.5/Make.yml
) or relative (like../../cfg/img.yml
).
File name can contain shell-style wildcards. Data loaded from the file(s) found by wildcards will be set in a sequence.
If 0.yaml
was:
files: !include include.d/*.yaml
We'll get:
files:
- name: "1"
- name: "2"
? Note:
- For
Python>=3.5
, ifrecursive
argument of!include
YAML tag istrue
, the pattern“**”
will match any files and zero or more directories and subdirectories.- Using the
“**”
pattern in large directory trees may consume an inordinate amount of time because of recursive search.
In order to enable recursive
argument, we shall write the !include
tag in Mapping
or Sequence
mode:
Sequence
mode:!include [tests/data/include.d/**/*.yaml, true]
Mapping
mode:!include {pathname: tests/data/include.d/**/*.yaml, recursive: true}
Not yet, but the New NIO (JSR 203) will have support for these common operations.
In the meantime, there are a few things to keep in mind.
File.renameTo generally works only on the same file system volume. I think of this as the equivalent to a "mv" command. Use it if you can, but for general copy and move support, you'll need to have a fallback.
When a rename doesn't work you will need to actually copy the file (deleting the original with File.delete if it's a "move" operation). To do this with the greatest efficiency, use the FileChannel.transferTo or FileChannel.transferFrom methods. The implementation is platform specific, but in general, when copying from one file to another, implementations avoid transporting data back and forth between kernel and user space, yielding a big boost in efficiency.
You can also use the filter function from the dplyr package which returns rows with matching conditions.
> library(dplyr)
> nrow(filter(aaa, sex == 1 & group1 == 2))
[1] 3
> nrow(filter(aaa, sex == 1 & group2 == "A"))
[1] 2
Somthing like this should workL
SELECT BookingId, StartTime
FROM Booking
WHERE StartTime between dateadd(hour, -1, getdate()) and getdate()
Another approach that is especially useful if you want to store data coming from an external API or a DB would be this:
Create a class that represent your data model
export class Data{
private id:number;
private text: string;
constructor(id,text) {
this.id = id;
this.text = text;
}
In your component class you create an empty array of type Data
and populate this array whenever you get a response from API or whatever data source you are using
export class AppComponent {
private search_key: string;
private dataList: Data[] = [];
getWikiData() {
this.httpService.getDataFromAPI()
.subscribe(data => {
this.parseData(data);
});
}
parseData(jsonData: string) {
//considering you get your data in json arrays
for (let i = 0; i < jsonData[1].length; i++) {
const data = new WikiData(jsonData[1][i], jsonData[2][i]);
this.wikiData.push(data);
}
}
}
Yes! You can Debug Android Application While you are developing them follow these steps.. Make sure that you have PC suite of the mobile manufacturer. For Example:if you are using samsung you should have samsung kies
1.Enable USB debugging on your device:Settings > Applications > Development > USB debugging
2.Enable Unknownresources:Settings>Unknowresoures
3.Connect your device to PC
4.Select your Application Right click it: RunAS>Run configurations>Choose Device>Target Select your device Run.
You can also without using debugging cable.For that you need to install Airdroid in your device.After installing enter the link in your browser and Drag and Drop .apk file.
Happy Coding!
I have a button for a prompt that on click it opens the display dialogue and then I can write what I want to search and it goes to that location on the page. It uses javascript to answer the header.
On the .html file I have:
<button onclick="myFunction()">Load Prompt</button>
<span id="test100"><h4>Hello</h4></span>
On the .js file I have
function myFunction() {
var input = prompt("list or new or quit");
while(input !== "quit") {
if(input ==="test100") {
window.location.hash = 'test100';
return;
// else if(input.indexOf("test100") >= 0) {
// window.location.hash = 'test100';
// return;
// }
}
}
}
When I write test100 into the prompt, then it will go to where I have placed span id="test100" in the html file.
I use Google Chrome.
Note: This idea comes from linking on the same page using
<a href="#test100">Test link</a>
which on click will send to the anchor. For it to work multiple times, from experience need to reload the page.
Credit to the people at stackoverflow (and possibly stackexchange, too) can't remember how I gathered all the bits and pieces. ?
The best way is to check the type, because undefined
/null
/false
are a tricky thing in JS.
So:
if(typeof obj !== "undefined") {
// obj is a valid variable, do something here.
}
Note that typeof
always returns a string, and doesn't generate an error if the variable doesn't exist at all.
An alternative to nvm-windows, which is mentioned in other answers would be Nodist.
I've had some issues with nvm-windows and admin privileges, which Nodist doesn't seem to have.
extended globbing:
rm !(foo|bar)
expands like *
without foo
or bar
:
$ ls
foo
bar
foobar
FOO
$ echo !(foo|bar)
foobar FOO
The registry path for official images (without a slash in the name) is library/<image>
. Try this instead:
docker pull registry.hub.docker.com/library/busybox
For the JS, try
data: {id: the_id}
...
success: function(data) {
alert('the server returned ' + data;
}
and
$the_id = intval($_POST['id']);
in PHP
You can use grep to get the byte-offset of the matching part of a string:
echo $str | grep -b -o str
As per your example:
[user@host ~]$ echo "The cat sat on the mat" | grep -b -o cat
4:cat
you can pipe that to awk if you just want the first part
echo $str | grep -b -o str | awk 'BEGIN {FS=":"}{print $1}'
Try to understand through this below function using python3
def floating_decimals(f_val, dec):
prc = "{:."+str(dec)+"f}" #first cast decimal as str
print(prc) #str format output is {:.3f}
return prc.format(f_val)
print(floating_decimals(50.54187236456456564, 3))
Output is : 50.542
Hope this helps you!
HTML :
<div id="myDiv">
<form id="myForm">
</form>
</div>
jQuery :
var chbx='<input type="checkbox" id="Mumbai" name="Mumbai" value="Mumbai" />Mumbai<br /> <input type="checkbox" id=" Delhi" name=" Delhi" value=" Delhi" /> Delhi<br/><input type="checkbox" id=" Bangalore" name=" Bangalore" value=" Bangalore"/>Bangalore<br />';
$("#myDiv form#myForm").html(chbx);
//to insert dynamically created form
$("#myDiv").html("<form id='dynamicForm'>" +chbx + "'</form>");
If you are using Eclipse then the keyboard shortcut is Ctrl + Shift + / to add a group of code. To make a comment line or select the code, right click -> Source -> Add Block Comment.
To remove the block comment, Ctrl + Shift + \ or right click -> Source -> Remove Block comment.
You need to use view INFORMATION_SCHEMA.COLUMNS
select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = my_table_name AND COLUMN_NAME like 'a%'
TO inline rows you can use PIVOT and for execution EXEC() function.
This is so common but so profoundly wrong. Protobuf data is not string data. It certainly isn't ASCII. You are using the encoding backwards. A text encoding transfers:
You do not have "formatted bytes". You have arbitrary bytes. You need to use something like a base-n (commonly: base-64) encode. This transfers
look at Convert.ToBase64String and Convert. FromBase64String
Something like this might help:
SET Today=%Date:~10,4%%Date:~4,2%%Date:~7,2%
mkdir C:\Test\Backup-%Today%
move C:\Test\Log\*.* C:\Test\Backup-%Today%\
SET Today=
The important part is the first line. It takes the output of the internal DATE
value and parses it into an environmental variable named Today
, in the format CCYYMMDD
, as in '20110407`.
The %Date:~10,4%
says to extract a *substring of the Date
environmental variable 'Thu 04/07/2011' (built in - type echo %Date%
at a command prompt) starting at position 10 for 4 characters (2011
). It then concatenates another substring of Date:
starting at position 4 for 2 chars (04
), and then concats two additional characters starting at position 7 (07
).
*The substring value starting points are 0-based.
You may need to adjust these values depending on the date format in your locale, but this should give you a starting point.
Nowadays with HTML5, it's pretty simple:
<input type="search" placeholder="Search..."/>
Most modern browsers will automatically render a usable clear button in the field by default.
(If you use Bootstrap, you'll have to add an override to your css file to make it show)
input[type=search]::-webkit-search-cancel-button {
-webkit-appearance: searchfield-cancel-button;
}
Safari/WebKit browsers can also provide extra features when using type="search"
, like results=5
and autosave="..."
, but they also override many of your styles (e.g. height, borders) . To prevent those overrides, while still retaining functionality like the X button, you can add this to your css:
input[type=search] {
-webkit-appearance: none;
}
See css-tricks.com for more info about the features provided by type="search"
.
This probably isn't the best approach in Python, but as a Haskeller this lambda/map approach made perfect sense to me and is very short:
anydigit = lambda x: any(map(str.isdigit, x))
Doesn't need to be named of course. Named it could be used like anydigit("abc123")
, which feels like what I was looking for!
The problem may be because you have declared variable as private
.
If you change it to public
, it works.
Better option is to use getter and setter methods for it.
This will solve the issue!
I have faced this issue and I just removed the server from eclipse and re-configured it... And everything started working fine... I have faced it two three times and the same thing worked.
git-bash uses standard unix commands.
ls for directory listing cd for change directory
more here -> http://ss64.com/bash/ Not all of these will work, but the file based ones mostly do.
It's been more than 6 years since the question was asked, but I didn't find any tool to clean up my repository. So I wrote one myself in python to get rid of old jars. Maybe it will be useful for someone:
from os.path import isdir
from os import listdir
import re
import shutil
dry_run = False # change to True to get a log of what will be removed
m2_path = '/home/jb/.m2/repository/' # here comes your repo path
version_regex = '^\d[.\d]*$'
def check_and_clean(path):
files = listdir(path)
for file in files:
if not isdir('/'.join([path, file])):
return
last = check_if_versions(files)
if last is None:
for file in files:
check_and_clean('/'.join([path, file]))
elif len(files) == 1:
return
else:
print('update ' + path.split(m2_path)[1])
for file in files:
if file == last:
continue
print(file + ' (newer version: ' + last + ')')
if not dry_run:
shutil.rmtree('/'.join([path, file]))
def check_if_versions(files):
if len(files) == 0:
return None
last = ''
for file in files:
if re.match(version_regex, file):
if last == '':
last = file
if len(last.split('.')) == len(file.split('.')):
for (current, new) in zip(last.split('.'), file.split('.')):
if int(new) > int(current):
last = file
break
elif int(new) < int(current):
break
else:
return None
else:
return None
return last
check_and_clean(m2_path)
It recursively searches within the .m2
repository and if it finds a catalog where different versions reside it removes all of them but the newest.
Say you have the following tree somewhere in your .m2 repo:
.
+-- antlr
+-- 2.7.2
¦ +-- antlr-2.7.2.jar
¦ +-- antlr-2.7.2.jar.sha1
¦ +-- antlr-2.7.2.pom
¦ +-- antlr-2.7.2.pom.sha1
¦ +-- _remote.repositories
+-- 2.7.7
+-- antlr-2.7.7.jar
+-- antlr-2.7.7.jar.sha1
+-- antlr-2.7.7.pom
+-- antlr-2.7.7.pom.sha1
+-- _remote.repositories
Then the script removes version 2.7.2 of antlr and what is left is:
.
+-- antlr
+-- 2.7.7
+-- antlr-2.7.7.jar
+-- antlr-2.7.7.jar.sha1
+-- antlr-2.7.7.pom
+-- antlr-2.7.7.pom.sha1
+-- _remote.repositories
If any old version, that you actively use, will be removed. It can easily be restored with maven (or other tools that manage dependencies).
You can get a log of what is going to be removed without actually removing it by setting dry_run = False
. The output will go like this:
update /org/projectlombok/lombok
1.18.2 (newer version: 1.18.6)
1.16.20 (newer version: 1.18.6)
This means, that versions 1.16.20 and 1.18.2 of lombok will be removed and 1.18.6 will be left untouched.
The file can be found on my github (the latest version).
Any reason they can't just click on the tab for your sheet when they want it?
I think your problem is that
int selection = scanner.nextInt();
reads just the number, not the end of line or anything after the number. When you declare
String sentence = scanner.nextLine();
This reads the remainder of the line with the number on it (with nothing after the number I suspect)
Try placing a scanner.nextLine(); after each nextInt() if you intend to ignore the rest of the line.
Just adding to the above answer, In a web application
@valid
is used where the bean to be validated is also annotated with validation annotations e.g. @NotNull
, @Email
(hibernate annotation) so when while getting input from user the values can be validated and binding result will have the validation results.
bindingResult.hasErrors()
will tell if any validation failed.
If you just need to set precision quantity and round the value, the right way to do this is use it's own object for this.
BigDecimal value = new BigDecimal("10.0001");
value = value.setScale(4, RoundingMode.HALF_UP);
System.out.println(value); //the return should be "10.0001"
One of the pillars of Oriented Object Programming (OOP) is "encapsulation", this pillar also says that an object should deal with it's own operations, like in this way:
Never, never, never say
if something == True:
Never. It's crazy, since you're redundantly repeating what is redundantly specified as the redundant condition rule for an if-statement.
Worse, still, never, never, never say
if something == False:
You have not
. Feel free to use it.
Finally, doing a == None
is inefficient. Do a is None
. None
is a special singleton object, there can only be one. Just check to see if you have that object.
You have to download the whole project with either "Clone to desktop" button that will use native github program or "Download as zip".
And then search that folder in downloaded project.
Consider:
Function GetFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
This code was adapted from Ozgrid
and as jkf points out, from Mr Excel
Technically a Tier can be a kind of minimum environment required for the code to run.
E.g. hypothetically a 3-tier app can be running on
1 physical machine with 3 virtual machines with no OS.
(That was a 3-(hardware)tier app)
1 physical machine with 3 virtual machines with 3 different/same OSes
(That was a 3-(OS)tier app)
1 physical machine with 1 virtual machine with 1 OS but 3 AppServers
(That was a 3-(AppServer)tier app)
1 physical machine with 1 virtual machine with 1 OS with 1 AppServer but 3 DBMS
(That was a 3-(DBMS)tier app)
1 physical machine with 1 virtual machine with 1 OS with 1 AppServers and 1 DBMS but 3 Excel workbooks.
(That was a 3-(AppServer)tier app)
Excel workbook is the minimum required environment for VBA code to run.
Those 3 workbooks can sit on a single physical computer or multiple.
I have noticed that in practice people mean "OS Tier" when they say "Tier" in the app description context.
That is if an app runs on 3 separate OS then its a 3-Tier app.
So a pedantically correct way describing an app would be
"1-to-3-Tier capable, running on 2 Tiers" app.
:)
Layers are just types of code in respect to the functional separation of duties withing the app (e.g. Presentation, Data , Security etc.)
Number of .parent a
elements that have an id
attribute:
$('.parent a[id]').length
@Gadde - your answer was very helpful. Thank you! I needed a "Maps"-like zoom for a div and was able to produce the feel I needed with your post. My criteria included the need to have the click repeat and continue to zoom out/in with each click. Below is my final result.
var currentZoom = 1.0;
$(document).ready(function () {
$('#btn_ZoomIn').click(
function () {
$('#divName').animate({ 'zoom': currentZoom += .1 }, 'slow');
})
$('#btn_ZoomOut').click(
function () {
$('#divName').animate({ 'zoom': currentZoom -= .1 }, 'slow');
})
$('#btn_ZoomReset').click(
function () {
currentZoom = 1.0
$('#divName').animate({ 'zoom': 1 }, 'slow');
})
});
I had same problem. you can't use left <
arrow in text property like as android:text="< Go back"
in your xml file. Remove any <
arrow from you xml code.
Hope It will helps you.
myArray.sort(
function(a, b) {
if (a.toLowerCase() < b.toLowerCase()) return -1;
if (a.toLowerCase() > b.toLowerCase()) return 1;
return 0;
}
);
EDIT: Please note that I originally wrote this to illustrate the technique rather than having performance in mind. Please also refer to answer @Ivan Krechetov for a more compact solution.
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
public class CollectionsSort {
/**
* @param args
*/`enter code here`
public static void main(String[] args) {
// TODO Auto-generated method stub
CollectionsSort colleciotns = new CollectionsSort();
List<combine> list = new ArrayList<combine>();
HashMap<String, Integer> h = new HashMap<String, Integer>();
h.put("nayanana", 10);
h.put("lohith", 5);
for (Entry<String, Integer> value : h.entrySet()) {
combine a = colleciotns.new combine(value.getValue(),
value.getKey());
list.add(a);
}
Collections.sort(list);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
public class combine implements Comparable<combine> {
public int value;
public String key;
public combine(int value, String key) {
this.value = value;
this.key = key;
}
@Override
public int compareTo(combine arg0) {
// TODO Auto-generated method stub
return this.value > arg0.value ? 1 : this.value < arg0.value ? -1
: 0;
}
public String toString() {
return this.value + " " + this.key;
}
}
}
I had to change both the httpd.conf and httpd-ssl.conf files DocumentRoot properties to get things like relative links (i.e. href="/index.html") and the favicon.ico link to work properly.
The latest Xampp control Panel makes this pretty easy.
From the control panel, there should be Apache in the first row. If it's started, stop it. Then click config and open the httpd.conf file and search for htdocs or documentRoot. Change the path to what you like. Do the same for httpd-ssl.conf. These should be the top 2 files in the list under Config's dropdown.
Then start the server again.
Hope this helps someone. Cheers.
You should use the equals
method since this is implemented to perform the comparison you want. toString()
itself uses an iterator just like equals
but it is a more inefficient approach. Additionally, as @Teepeemm pointed out, toString
is affected by order of elements (basically iterator return order) hence is not guaranteed to provide the same output for 2 different maps (especially if we compare two different maps).
Note/Warning: Your question and my answer assume that classes implementing the map interface respect expected toString
and equals
behavior. The default java classes do so, but a custom map class needs to be examined to verify expected behavior.
See: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html
boolean equals(Object o)
Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.
Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. Have a look at the implementation of AbstractMap
which is used by classes such as HashMap
:
// Comparison and hashing
/**
* Compares the specified object with this map for equality. Returns
* <tt>true</tt> if the given object is also a map and the two maps
* represent the same mappings. More formally, two maps <tt>m1</tt> and
* <tt>m2</tt> represent the same mappings if
* <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the
* <tt>equals</tt> method works properly across different implementations
* of the <tt>Map</tt> interface.
*
* <p>This implementation first checks if the specified object is this map;
* if so it returns <tt>true</tt>. Then, it checks if the specified
* object is a map whose size is identical to the size of this map; if
* not, it returns <tt>false</tt>. If so, it iterates over this map's
* <tt>entrySet</tt> collection, and checks that the specified map
* contains each mapping that this map contains. If the specified map
* fails to contain such a mapping, <tt>false</tt> is returned. If the
* iteration completes, <tt>true</tt> is returned.
*
* @param o object to be compared for equality with this map
* @return <tt>true</tt> if the specified object is equal to this map
*/
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Map))
return false;
Map<K,V> m = (Map<K,V>) o;
if (m.size() != size())
return false;
try {
Iterator<Entry<K,V>> i = entrySet().iterator();
while (i.hasNext()) {
Entry<K,V> e = i.next();
K key = e.getKey();
V value = e.getValue();
if (value == null) {
if (!(m.get(key)==null && m.containsKey(key)))
return false;
} else {
if (!value.equals(m.get(key)))
return false;
}
}
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
return true;
}
toString
fails miserably when comparing a TreeMap
and HashMap
though equals
does compare contents correctly.
Code:
public static void main(String args[]) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("2", "whatever2");
map.put("1", "whatever1");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("2", "whatever2");
map2.put("1", "whatever1");
System.out.println("Are maps equal (using equals):" + map.equals(map2));
System.out.println("Are maps equal (using toString().equals()):"
+ map.toString().equals(map2.toString()));
System.out.println("Map1:"+map.toString());
System.out.println("Map2:"+map2.toString());
}
Output:
Are maps equal (using equals):true
Are maps equal (using toString().equals()):false
Map1:{2=whatever2, 1=whatever1}
Map2:{1=whatever1, 2=whatever2}
I prefer TailMe because of the possibility to watch several log files simultaneously in one window: http://www.dschensky.de/Software/Staff/tailme_en.htm
It seems me there was a network issue. On your side, or on Maven side, or anywhere in the middle. Just try again later.
If the error is permanent, check your network settings. If you are behind a proxy, you need the following in you ~/.m2/settings.xml:
<proxies>
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username>proxyuser</username>
<password>proxypass</password>
<host>proxy.host.net</host>
<port>80</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
</proxies>
In the top level of the IIS Manager (above Sites), you should see the Application Pools tree node. Right click on "Application Pools", choose "Add Application Pool".
Give it a name, choose .NET Framework 4.0 and either Integrated or Classic mode.
When you add or edit a web site, your new application pools will now show up in the list.
Version with exception handling and async task:
AsyncTask<URL, Void, Boolean> asyncTask = new AsyncTask<URL, Void, Boolean>() {
public Bitmap mIcon_val;
public IOException error;
@Override
protected Boolean doInBackground(URL... params) {
try {
mIcon_val = BitmapFactory.decodeStream(params[0].openConnection().getInputStream());
} catch (IOException e) {
this.error = e;
return false;
}
return true;
}
@Override
protected void onPostExecute(Boolean success) {
super.onPostExecute(success);
if (success) {
image.setImageBitmap(mIcon_val);
} else {
image.setImageBitmap(defaultImage);
}
}
};
try {
URL url = new URL(url);
asyncTask.execute(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
Random random = new Random();
double percent = 10.0; //10.0%
if (random.nextDouble() * 100D < percent) {
//do
}
//CSS:
.textarea {
resize: none;
min-width: //-> Integer number of pixels
min-height: //-> Integer number of pixels
max-width: //-> min-width
max-height: //-> min-height
}
above code works on most browsers
//HTML:
<textarea id='textarea' draggable='false'></textarea>
do both for it to work on the maximum number of browsers
There are quite a few ways to work with dynamic arrays in PHP. Initialise an array:
$array = array();
Add to an array:
$array[] = "item"; // for your $arr1
$array[$key] = "item"; // for your $arr2
array_push($array, "item", "another item");
Remove from an array:
$item = array_pop($array);
$item = array_shift($array);
unset($array[$key]);
There are plenty more ways, these are just some examples.
Make sure, under Run > Debug Configurations, that 'Stop in main' is selected, if applicable to your situation.
This should fix a few edge-cases in kobe's answer:
function getQueryParam(url, key) {
var queryStartPos = url.indexOf('?');
if (queryStartPos === -1) {
return;
}
var params = url.substring(queryStartPos + 1).split('&');
for (var i = 0; i < params.length; i++) {
var pairs = params[i].split('=');
if (decodeURIComponent(pairs.shift()) == key) {
return decodeURIComponent(pairs.join('='));
}
}
}
getQueryParam('http://example.com/form_image_edit.php?img_id=33', 'img_id');
// outputs "33"
This is the best explanation I've seen: Understand JavaScripts this with Clarity
The this reference ALWAYS refers to (and holds the value of) an object—a singular object—and it is usually used inside a function or a method, although it can be used outside a function in the global scope. Note that when we use strict mode, this holds the value of undefined in global functions and in anonymous functions that are not bound to any object.
There are Four Scenarios where this can be confusing:
He gives code examples, explanations, and solutions, which I thought was very helpful.
try with sticky jquery plugin
https://github.com/garand/sticky
<script src="jquery.js"></script>_x000D_
<script src="jquery.sticky.js"></script>_x000D_
<script>_x000D_
$(document).ready(function(){_x000D_
$("#sticker").sticky({topSpacing:0});_x000D_
});_x000D_
</script>
_x000D_
Easiest way is to use readline-sync
It process one by one input and out put.
npm i readline-sync
eg:
var firstPrompt = readlineSync.question('Are you sure want to initialize new db? This will drop whole database and create new one, Enter: (yes/no) ');
if (firstPrompt === 'yes') {
console.log('--firstPrompt--', firstPrompt)
startProcess()
} else if (firstPrompt === 'no') {
var secondPrompt = readlineSync.question('Do you want to modify migration?, Enter: (yes/no) ');
console.log('secondPrompt ', secondPrompt)
startAnother()
} else {
console.log('Invalid Input')
process.exit(0)
}
As @sinoroc suggested correct way of installing a package via pip is using separate process since pip may cause closing a thread or may require a restart of interpreter to load new installed package so this is the right way of using the API: subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'SomeProject'])
but since Python allows to access internal API and you know what you're using the API for you may want to use internal API anyway eg. if you're building own GUI package manager with alternative resourcess like https://www.lfd.uci.edu/~gohlke/pythonlibs/
Following soulution is OUT OF DATE, instead of downvoting suggest updates. see https://github.com/pypa/pip/issues/7498 for reference.
get_installed_distributions()
or main
method under import pip
instead use import pip._internal as pip
.
UPDATE ca. v.18 get_installed_distributions()
has been removed. Instead you may use generator freeze
like this:
from pip._internal.operations.freeze import freeze
print([package for package in freeze()])
# eg output ['pip==19.0.3']
import pip
package_names=['selenium', 'requests'] #packages to install
pip.main(['install'] + package_names + ['--upgrade'])
# --upgrade to install or update existing packages
If you need to update every installed package, use following:
import pip
for i in pip.get_installed_distributions():
pip.main(['install', i.key, '--upgrade'])
If you want to stop installing other packages if any installation fails, use it in one single pip.main([])
call:
import pip
package_names = [i.key for i in pip.get_installed_distributions()]
pip.main(['install'] + package_names + ['--upgrade'])
Note: When you install from list in file with -r
/ --requirement
parameter you do NOT need open() function.
pip.main(['install', '-r', 'filename'])
Warning: Some parameters as simple --help
may cause python interpreter to stop.
Curiosity: By using pip.exe
you actually use python interpreter and pip module anyway. If you unpack pip.exe
or pip3.exe
regardless it's python 2.x or 3.x, inside is the SAME single file __main__.py
:
# -*- coding: utf-8 -*-
import re
import sys
from pip import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
For CentOS, RHEL, Amazon Linux: sudo yum install jq
I understand that its been answered already. but I hope this will help someone in future and saves so much time and pain.
complete code is below: This one I did for a textbox to make it Autocomplete in CiviCRM. Hope it helps someone
CRM.$( 'input[id^=custom_78]' ).autocomplete({
autoFill: true,
select: function (event, ui) {
var label = ui.item.label;
var value = ui.item.value;
// Update subject field to add book year and book product
var book_year_value = CRM.$('select[id^=custom_77] option:selected').text().replace('Book Year ','');
//book_year_value.replace('Book Year ','');
var subject_value = book_year_value + '/' + ui.item.label;
CRM.$('#subject').val(subject_value);
CRM.$( 'input[name=product_select_id]' ).val(ui.item.value);
CRM.$('input[id^=custom_78]').val(ui.item.label);
return false;
},
source: function(request, response) {
CRM.$.ajax({
url: productUrl,
data: {
'subCategory' : cj('select[id^=custom_77]').val(),
's': request.term,
},
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
},
success: function(result){
result = jQuery.parseJSON( result);
//console.log(result);
response(CRM.$.map(result, function (val,key) {
//console.log(key);
//console.log(val);
return {
label: val,
value: key
};
}));
}
})
.done(function( data ) {
if ( console && console.log ) {
// console.log( "Sample of dataas:", data.slice( 0, 100 ) );
}
});
}
});
PHP code on how I'm returning data to this jquery ajax call in autocomplete:
/**
* This class contains all product related functions that are called using AJAX (jQuery)
*/
class CRM_Civicrmactivitiesproductlink_Page_AJAX {
static function getProductList() {
$name = CRM_Utils_Array::value( 's', $_GET );
$name = CRM_Utils_Type::escape( $name, 'String' );
$limit = '10';
$strSearch = "description LIKE '%$name%'";
$subCategory = CRM_Utils_Array::value( 'subCategory', $_GET );
$subCategory = CRM_Utils_Type::escape( $subCategory, 'String' );
if (!empty($subCategory))
{
$strSearch .= " AND sub_category = ".$subCategory;
}
$query = "SELECT id , description as data FROM abc_books WHERE $strSearch";
$resultArray = array();
$dao = CRM_Core_DAO::executeQuery( $query );
while ( $dao->fetch( ) ) {
$resultArray[$dao->id] = $dao->data;//creating the array to send id as key and data as value
}
echo json_encode($resultArray);
CRM_Utils_System::civiExit();
}
}
Quoting is an issue if you're running awk from the command line. You'll sometimes need to use \
, e.g. to quote "
, but most of the time you'll use ^
:
w:\srv>dir | grep ".txt" | awk "{ printf(\"echo %s@%s ^> %s.tstamp^\n\", $1, $2, $4); }"
echo 2014-09-07@22:21 > requirements-dev.txt.tstamp
echo 2014-11-28@18:14 > syncspec.txt.tstamp
If yes_ans > no_ans and yes_ans > na_ans
You're using column names in a statement (outside of a query). If you want variables, you must declare and assign them.
Built-in toLocaleDateString()
does the job, but it will remove the leading 0s for the day and month, so we will get something like "1/9/1970", which is not perfect in my opinion. To get a proper format MM/DD/YYYY
we can use something like:
new Date(dateString).toLocaleDateString('en-US', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
})
Though is answered in another stack overflow question Bind a function to Twitter Bootstrap Modal Close but for visual feel here is more detailed answer.
C# generally uses xml-based config files rather than the *.ini-style file like you said, so there's nothing built-in to handle this. However, google returns a number of promising results.
Change the node to and create a file, packages.xsd, in the same folder (and include it in the project) with the following contents:
<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
targetNamespace="urn:packages" xmlns="urn:packages">
<xs:element name="packages">
<xs:complexType>
<xs:sequence>
<xs:element name="package" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="id" type="xs:string" use="required" />
<xs:attribute name="version" type="xs:string" use="required" />
<xs:attribute name="targetFramework" type="xs:string" use="optional" />
<xs:attribute name="allowedVersions" type="xs:string" use="optional" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
void p(String l){
System.out.println(l);
}
Shortest. Go for it.
$itisint=$true
try{
[int]$vartotest
}catch{
"error converting to int"
$itisint=$false
}
this is more universal, because this way you can test also strings (read from a file for example) if they represent number. The other solutions using -is [int] result in false if you would have "123" as string in a variable. This also works on machines with older powershell then 5.1
.modal {
text-align: center;
}
@media screen and (min-width: 768px) {
.modal:before {
display: inline-block;
vertical-align: middle;
content: " ";
height: 100%;
}
}
.modal-dialog {
display: inline-block;
text-align: left;
vertical-align: middle;
}
And adjust a little bit .fade class to make sure it appears out of the top border of window, instead of center
Use json.loads
not json.load
.
(load
loads from a file-like object, loads
from a string. So you could just as well omit the .read()
call instead.)
Basic difference between various options of git reset command are as below.
Wow, there are a lot of examples here. I am providing one that does some error handling. It rebuilds and returns the entire URL with the query-string-param-to-be-removed, removed. It also provides a bonus function that builds the current URL on the fly. Tested, works!
Credit to Mark B for the steps. This is a complete solution to tpow's "strip off this return parameter" original question -- might be handy for beginners, trying to avoid PHP gotchas. :-)
<?php
function currenturl_without_queryparam( $queryparamkey ) {
$current_url = current_url();
$parsed_url = parse_url( $current_url );
if( array_key_exists( 'query', $parsed_url )) {
$query_portion = $parsed_url['query'];
} else {
return $current_url;
}
parse_str( $query_portion, $query_array );
if( array_key_exists( $queryparamkey , $query_array ) ) {
unset( $query_array[$queryparamkey] );
$q = ( count( $query_array ) === 0 ) ? '' : '?';
return $parsed_url['scheme'] . '://' . $parsed_url['host'] . $parsed_url['path'] . $q . http_build_query( $query_array );
} else {
return $current_url;
}
}
function current_url() {
$current_url = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
return $current_url;
}
echo currenturl_without_queryparam( 'key' );
?>
Try this,
$number = 10;
switch ($number%2)
{
case 0:
echo "It's even";
break;
default:
echo "It's odd";
}
Workspaces can only be open in one copy of eclipse at once. Further, you took away your own write access from the looks of it. All the users in question have to have the 'admin' group for what you did to even work a little.
This will disable/enable the options when you select/remove them, respectively.
$("#theSelect").change(function(){
var value = $(this).val();
if (value === '') return;
var theDiv = $(".is" + value);
var option = $("option[value='" + value + "']", this);
option.attr("disabled","disabled");
theDiv.slideDown().removeClass("hidden");
theDiv.find('a').data("option",option);
});
$("div a.remove").click(function () {
$(this).parent().slideUp(function() { $(this).addClass("hidden"); });
$(this).data("option").removeAttr('disabled');
});
Cast the integers to varchar first!
I don't know how stubhub's api works, but generally it should look like this:
s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)
Now your session contains cookies provided by login form. To access cookies of this session simply use
s.cookies
Any further actions like another requests will have this cookie
Watch out!! If there's spaces they will not be considered by the LEN method in T-SQL. Don't let this trick you and use
select max(datalength(Desc)) from table_name
testSpace.Style.Add("display", "none");
This might be better understood if you modified the wording up a bit:
var buttons = {
foo: 'bar',
fiz: 'buz'
};
for ( var property in buttons ) {
console.log( property ); // Outputs: foo, fiz or fiz, foo
}
Note here that you're iterating over the properties of the object, using property
as a reference to each during each subsequent cycle.
MSDN says of for ( variable in [object | array ] )
the following:
Before each iteration of a loop, variable is assigned the next property name of object or the next element index of array. You can then use it in any of the statements inside the loop to reference the property of object or the element of array.
Note also that the property order of an object is not constant, and can change, unlike the index order of an array. That might come in handy.
There's an ongoing effort for a PDCurses port:
Just for information sake, in regards to my need... The answer I was looking for here was:
Mage::app()->getStore()->getGroup()->getName()
That is referenced on the admin page, where one can manage multiple stores... admin/system_store, I wanted to retrieve the store group title...
There's a lot of answers already, but here's another contribution:
Taken directly from the URL
polyfill validity check, use an input
element with type="url"
to take advantage of the browser's built-in validity check:
var inputElement = doc.createElement('input');
inputElement.type = 'url';
inputElement.value = url;
if (!inputElement.checkValidity()) {
throw new TypeError('Invalid URL');
}
It can be done in a single command. You need to set the IDENTITY property for "auto number":
ALTER TABLE MyTable ADD mytableID int NOT NULL IDENTITY (1,1) PRIMARY KEY
More precisely, to set a named table level constraint:
ALTER TABLE MyTable
ADD MytableID int NOT NULL IDENTITY (1,1),
CONSTRAINT PK_MyTable PRIMARY KEY CLUSTERED (MyTableID)
See ALTER TABLE and IDENTITY on MSDN
Convert has a style parameter for date to string conversions.
If there are spaces in the phone2 field from inadvertant data entry, you can ignore those records with the IFNULL and TRIM functions:
SELECT phone, phone2
FROM jewishyellow.users
WHERE phone LIKE '813%'
AND TRIM(IFNULL(phone2,'')) <> '';
mysql.exe can do just that....
To connect,
mysql -u root -p
(press enter)
It should prompt you to enter root password (u = username, p = password)
Then you can use SQL database commands to do pretty much anything....
Set seekbar max and min value
seekbar have method that setmax(int position) and setProgress(int position)
thanks
A slightly cleaner version of DTB's solution.
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var random = new Random();
var list = Enumerable.Repeat(0, 8).Select(x=>chars[random.Next(chars.Length)]);
return string.Join("", list);
Your style preferences may vary.
What is the exact contents you are passing into $html_brand?
If it is has an invalid URL syntax, you will very likely get the HTTP code 0.
There is a setting window.zoom that can enlarge the entire window content including the top menus and side nav tree. Setting this to 1 on a 4k monitor makes the content similar to a 1080p monitor of the same physical size.
There are so many difference exist between Serializable and Externalizable but when we compare difference between custom Serializable(overrided writeObject() & readObject()) and Externalizable then we find that custom implementation is tightly bind with ObjectOutputStream class where as in Externalizable case , we ourself provide an implementation of ObjectOutput which may be ObjectOutputStream class or it could be some other like org.apache.mina.filter.codec.serialization.ObjectSerializationOutputStream
In case of Externalizable interface
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeUTF(key);
out.writeUTF(value);
out.writeObject(emp);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.key = in.readUTF();
this.value = in.readUTF();
this.emp = (Employee) in.readObject();
}
**In case of Serializable interface**
/*
We can comment below two method and use default serialization process as well
Sequence of class attributes in read and write methods MUST BE same.
// below will not work it will not work .
// Exception = java.io.StreamCorruptedException: invalid type code: 00\
private void writeObject(java.io.ObjectOutput stream)
*/
private void writeObject(java.io.ObjectOutputStream Outstream)
throws IOException {
System.out.println("from writeObject()");
/* We can define custom validation or business rules inside read/write methods.
This way our validation methods will be automatically
called by JVM, immediately after default serialization
and deserialization process
happens.
checkTestInfo();
*/
stream.writeUTF(name);
stream.writeInt(age);
stream.writeObject(salary);
stream.writeObject(address);
}
private void readObject(java.io.ObjectInputStream Instream)
throws IOException, ClassNotFoundException {
System.out.println("from readObject()");
name = (String) stream.readUTF();
age = stream.readInt();
salary = (BigDecimal) stream.readObject();
address = (Address) stream.readObject();
// validateTestInfo();
}
I have added sample code to explain better. please check in/out object case of Externalizable. These are not bound to any implementation directly.
Where as Outstream/Instream are tightly bind to classes. We can extends ObjectOutputStream/ObjectInputStream but it will a bit difficult to use.
Alternatively you can use a "." instead of *, as this will take all the files in the working directory, include the folders and subfolders:
FROM ubuntu
COPY . /
RUN ls -la /
you can find how to do it here. In short it is:
public object this[int i]
{
get { return InnerList[i]; }
set { InnerList[i] = value; }
}
If you only need a getter the syntax in answer below can be used as well (starting from C# 6).
import requests
site_request = requests.get("https://abhiunix.in")
site_response = str(site_request.content)
print(site_response)
If your return type is an array then return an empty array otherwise return null.
if 'name' in mydict:
is the preferred, pythonic version. Use of has_key()
is discouraged, and this method has been removed in Python 3.
URL url= new URL("http://example.com/query?q=random word £500 bank $");
URI uri = new URI(url.getProtocol(), url.getUserInfo(), IDN.toASCII(url.getHost()), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
String correctEncodedURL=uri.toASCIIString();
System.out.println(correctEncodedURL);
Prints
http://example.com/query?q=random%20word%20%C2%A3500%20bank%20$
What is happening here?
1. Split URL into structural parts. Use java.net.URL
for it.
2. Encode each structural part properly!
3. Use IDN.toASCII(putDomainNameHere)
to Punycode encode the host name!
4. Use java.net.URI.toASCIIString()
to percent-encode, NFC encoded unicode - (better would be NFKC!). For more info see: How to encode properly this URL
In some cases it is advisable to check if the url is already encoded. Also replace '+' encoded spaces with '%20' encoded spaces.
Here are some examples that will also work properly
{
"in" : "http://???????.com/",
"out" : "http://xn--mgba3gch31f.com/"
},{
"in" : "http://www.example.com/?/foo",
"out" : "http://www.example.com/%E2%80%A5/foo"
},{
"in" : "http://search.barnesandnoble.com/booksearch/first book.pdf",
"out" : "http://search.barnesandnoble.com/booksearch/first%20book.pdf"
}, {
"in" : "http://example.com/query?q=random word £500 bank $",
"out" : "http://example.com/query?q=random%20word%20%C2%A3500%20bank%20$"
}
The solution passes around 100 of the testcases provided by Web Plattform Tests.
Aside from looking into root cause issues like file leaks, etc. in order to do a legitimate increase the "open files" limit and have that persist across reboots, consider editing
/etc/security/limits.conf
by adding something like this
jetty soft nofile 2048
jetty hard nofile 4096
where "jetty" is the username in this case. For more details on limits.conf, see http://linux.die.net/man/5/limits.conf
log off and then log in again and run
ulimit -n
to verify that the change has taken place. New processes by this user should now comply with this change. This link seems to describe how to apply the limit on already running processes but I have not tried it.
The default limit 1024 can be too low for large Java applications.
you can use assertIterableEquals
:
List<String> numbers = Arrays.asList("one", "two", "three");
List<String> numbers2 = Arrays.asList("one", "two", "three");
Assertions.assertIterableEquals(numbers, numbers2);
or assertArrayEquals
and converting lists to arrays :
List<String> numbers = Arrays.asList("one", "two", "three");
List<String> numbers2 = Arrays.asList("one", "two", "three");
Assertions.assertArrayEquals(numbers.toArray(), numbers2.toArray());
More recent and much cleaner: use event.key
. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
People who are still struggling for the simple and best approach, you can use Spread Syntax
for extending object.
var person1 = {_x000D_
name: "Blank",_x000D_
age: 22_x000D_
};_x000D_
_x000D_
var person2 = {_x000D_
name: "Robo",_x000D_
age: 4,_x000D_
height: '6 feet'_x000D_
};_x000D_
// spread syntax_x000D_
let newObj = { ...person1, ...person2 };_x000D_
console.log(newObj.height);
_x000D_
Note: Remember that, the property is farthest to the right will have the priority. In this example, person2
is at right side, so newObj
will have name Robo in it.
Here is how you can do it through JavaScript:
PATH
C:\Program Files\Mozilla Firefox15\Firefox.exe
It will be probably not here - because thats what the error says. How to fix it?
It his does not help then change the constructor like this:
File pathToBinary = new File("C:\\Program Files\\Mozilla Firefox15\\Firefox.exe");
FirefoxBinary ffBinary = new FirefoxBinary(pathToBinary);
FirefoxProfile firefoxProfile = new FirefoxProfile();
FirefoxDriver _driver = new FirefoxDriver(ffBinary,firefoxProfile);
Just add these lines to your <script>
(somewhere after jQuery is loaded but before posting anything):
$.postJSON = function(url, data, func)
{
$.post(url, data, func, 'json');
}
Replace (some/all) $.getJSON
with $.postJSON
and enjoy!
You can use the same Javascript callback functions as with $.getJSON
.
No server-side change is needed. (Well, I always recommend using $_REQUEST
in PHP. http://php.net/manual/en/reserved.variables.request.php, Among $_REQUEST, $_GET and $_POST which one is the fastest?)
This is simpler than @lepe's solution.
You can use filter
too
this.products = array_products.filter((x) => x.Name.includes("ABC"))
All the other responses I see are fine, but C# has support for named groups!
I'd use the following code:
const string input = "Lorem ipsum dolor sit %download%#456 amet, consectetur adipiscing %download%#3434 elit. Duis non nunc nec mauris feugiat porttitor. Sed tincidunt blandit dui a viverra%download%#298. Aenean dapibus nisl %download%#893434 id nibh auctor vel tempor velit blandit.";
static void Main(string[] args)
{
Regex expression = new Regex(@"%download%#(?<Identifier>[0-9]*)");
var results = expression.Matches(input);
foreach (Match match in results)
{
Console.WriteLine(match.Groups["Identifier"].Value);
}
}
The code that reads: (?<Identifier>[0-9]*)
specifies that [0-9]*
's results will be part of a named group that we index as above: match.Groups["Identifier"].Value
using System.Net;
using System.Net.Mail;
using(SmtpClient smtpClient = new SmtpClient())
{
var basicCredential = new NetworkCredential("username", "password");
using(MailMessage message = new MailMessage())
{
MailAddress fromAddress = new MailAddress("[email protected]");
smtpClient.Host = "mail.mydomain.com";
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
message.From = fromAddress;
message.Subject = "your subject";
// Set IsBodyHtml to true means you can send HTML email.
message.IsBodyHtml = true;
message.Body = "<h1>your message body</h1>";
message.To.Add("[email protected]");
try
{
smtpClient.Send(message);
}
catch(Exception ex)
{
//Error, could not send the message
Response.Write(ex.Message);
}
}
}
You may use the above code.
You have to actively choose to install MSYS to get the make.exe. So you should always have at least (the native) mingw32-make.exe if MinGW was installed properly. And if you installed MSYS you will have make.exe (in the MSYS subfolder probably).
Note that many projects require first creating a makefile (e.g. using a configure script or automake .am file) and it is this step that requires MSYS or cygwin. Makes you wonder why they bothered to distribute the native make at all.
Once you have the makefile, it is unclear if the native executable requires a different path separator than the MSYS make (forward slashes vs backward slashes). Any autogenerated makefile is likely to have unix-style paths, assuming the native make can handle those, the compiled output should be the same.
requestDispatcher - forward() method
When we use the
forward
method, the request is transferred to another resource within the same server for further processing.In the case of
forward
, the web container handles all processing internally and the client or browser is not involved.When
forward
is called on therequestDispatcher
object, we pass the request and response objects, so our old request object is present on the new resource which is going to process our request.Visually, we are not able to see the forwarded address, it is transparent.
Using the
forward()
method is faster thansendRedirect
.When we redirect using forward, and we want to use the same data in a new resource, we can use
request.setAttribute()
as we have a request object available.SendRedirect
In case of
sendRedirect
, the request is transferred to another resource, to a different domain, or to a different server for further processing.When you use
sendRedirect
, the container transfers the request to the client or browser, so the URL given inside thesendRedirect
method is visible as a new request to the client.In case of
sendRedirect
call, the old request and response objects are lost because it’s treated as new request by the browser.In the address bar, we are able to see the new redirected address. It’s not transparent.
sendRedirect
is slower because one extra round trip is required, because a completely new request is created and the old request object is lost. Two browser request are required.But in
sendRedirect
, if we want to use the same data for a new resource we have to store the data in session or pass along with the URL.Which one is good?
Its depends upon the scenario for which method is more useful.
If you want control is transfer to new server or context, and it is treated as completely new task, then we go for
sendRedirect
. Generally, a forward should be used if the operation can be safely repeated upon a browser reload of the web page and will not affect the result.
For Firefox Python:
The Firefox Self-signed certificate bug has now been fixed: accept ssl cert with marionette firefox webdrive python splinter
"acceptSslCerts" should be replaced by "acceptInsecureCerts"
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
caps = DesiredCapabilities.FIREFOX.copy()
caps['acceptInsecureCerts'] = True
ff_binary = FirefoxBinary("path to the Nightly binary")
driver = webdriver.Firefox(firefox_binary=ff_binary, capabilities=caps)
driver.get("https://expired.badssl.com")
The floated elements do not add to the height of the container element, and hence if you don't clear them, container height won't increase...
I'll show you visually:
More Explanation:
<div>
<div style="float: left;"></div>
<div style="width: 15px;"></div> <!-- This will shift
besides the top div. Why? Because of the top div
is floated left, making the
rest of the space blank -->
<div style="clear: both;"></div>
<!-- Now in order to prevent the next div from floating beside the top ones,
we use `clear: both;`. This is like a wall, so now none of the div's
will be floated after this point. The container height will now also include the
height of these floated divs -->
<div></div>
</div>
You can also add overflow: hidden;
on container elements, but I would suggest you use clear: both;
instead.
Also if you might like to self-clear an element you can use
.self_clear:after {
content: "";
clear: both;
display: table;
}
The float
property is misunderstood by most beginners. Well, what exactly does float
do? Initially, the float
property was introduced to flow text around images, which are floated left
or right
. Here's another explanation by @Madara Uchicha.
So, is it wrong to use the float
property for placing boxes side by side? The answer is no; there is no problem if you use the float
property in order to set boxes side by side.
Floating an inline
or block
level element will make the element behave like an inline-block
element.
If you float an element left
or right
, the width
of the element will be limited to the content it holds, unless width
is defined explicitly ...
You cannot float
an element center
. This is the biggest issue I've always seen with beginners, using , which is not a valid value for the float: center;
float
property. float
is generally used to float
/move content to the very left or to the very right. There are only four valid values for float
property i.e left
, right
, none
(default) and inherit
.
Parent element collapses, when it contains floated child elements, in order to prevent this, we use clear: both;
property, to clear the floated elements on both the sides, which will prevent the collapsing of the parent element. For more information, you can refer my another answer here.
(Important) Think of it where we have a stack of various elements. When we use float: left;
or float: right;
the element moves above the stack by one. Hence the elements in the normal document flow will hide behind the floated elements because it is on stack level above the normal floated elements. (Please don't relate this to z-index
as that is completely different.)
Taking a case as an example to explain how CSS floats work, assuming we need a simple 2 column layout with a header, footer, and 2 columns, so here is what the blueprint looks like...
In the above example, we will be floating only the red boxes, either you can float
both to the left
, or you can float
on to left
, and another to right
as well, depends on the layout, if it's 3 columns, you may float
2 columns to left
where another one to the right
so depends, though in this example, we have a simplified 2 column layout so will float
one to left
and the other to the right
.
Markup and styles for creating the layout explained further down...
<div class="main_wrap">
<header>Header</header>
<div class="wrapper clear">
<div class="floated_left">
This<br />
is<br />
just<br />
a<br />
left<br />
floated<br />
column<br />
</div>
<div class="floated_right">
This<br />
is<br />
just<br />
a<br />
right<br />
floated<br />
column<br />
</div>
</div>
<footer>Footer</footer>
</div>
* {
-moz-box-sizing: border-box; /* Just for demo purpose */
-webkkit-box-sizing: border-box; /* Just for demo purpose */
box-sizing: border-box; /* Just for demo purpose */
margin: 0;
padding: 0;
}
.main_wrap {
margin: 20px;
border: 3px solid black;
width: 520px;
}
header, footer {
height: 50px;
border: 3px solid silver;
text-align: center;
line-height: 50px;
}
.wrapper {
border: 3px solid green;
}
.floated_left {
float: left;
width: 200px;
border: 3px solid red;
}
.floated_right {
float: right;
width: 300px;
border: 3px solid red;
}
.clear:after {
clear: both;
content: "";
display: table;
}
Let's go step by step with the layout and see how float works..
First of all, we use the main wrapper element, you can just assume that it's your viewport, then we use header
and assign a height
of 50px
so nothing fancy there. It's just a normal non floated block level element which will take up 100%
horizontal space unless it's floated or we assign inline-block
to it.
The first valid value for float
is left
so in our example, we use float: left;
for .floated_left
, so we intend to float a block to the left
of our container element.
And yes, if you see, the parent element, which is .wrapper
is collapsed, the one you see with a green border didn't expand, but it should right? Will come back to that in a while, for now, we have got a column floated to left
.
Coming to the second column, lets it float
this one to the right
Another column floated to the right
Here, we have a 300px
wide column which we float
to the right
, which will sit beside the first column as it's floated to the left
, and since it's floated to the left
, it created empty gutter to the right
, and since there was ample of space on the right
, our right
floated element sat perfectly beside the left
one.
Still, the parent element is collapsed, well, let's fix that now. There are many ways to prevent the parent element from getting collapsed.
clear: both;
before the parent element ends, which holds floated elements, now this one is a cheap solution to clear
your floating elements which will do the job for you but, I would recommend not to use this.Add, <div style="clear: both;"></div>
before the .wrapper
div
ends, like
<div class="wrapper clear">
<!-- Floated columns -->
<div style="clear: both;"></div>
</div>
Well, that fixes very well, no collapsed parent anymore, but it adds unnecessary markup to the DOM, so some suggest, to use overflow: hidden;
on the parent element holding floated child elements which work as intended.
Use overflow: hidden;
on .wrapper
.wrapper {
border: 3px solid green;
overflow: hidden;
}
That saves us an element every time we need to clear
float
but as I tested various cases with this, it failed in one particular one, which uses box-shadow
on the child elements.
Demo (Can't see the shadow on all 4 sides, overflow: hidden;
causes this issue)
So what now? Save an element, no overflow: hidden;
so go for a clear fix hack, use the below snippet in your CSS, and just as you use overflow: hidden;
for the parent element, call the class
below on the parent element to self-clear.
.clear:after {
clear: both;
content: "";
display: table;
}
<div class="wrapper clear">
<!-- Floated Elements -->
</div>
Here, shadow works as intended, also, it self-clears the parent element which prevents to collapse.
And lastly, we use footer after we clear
the floated elements.
When is float: none;
used anyways, as it is the default, so any use to declare float: none;
?
Well, it depends, if you are going for a responsive design, you will use this value a lot of times, when you want your floated elements to render one below another at a certain resolution. For that float: none;
property plays an important role there.
Few real-world examples of how float
is useful.
img
floated inside p
which will enable our content to flow around.Demo (Without floating img
)
Demo 2 (img
floated to the left
)
float
for creating horizontal menu - DemoLast but not the least, I want to explain this particular case where you float
only single element to the left
but you do not float
the other, so what happens?
Suppose if we remove float: right;
from our .floated_right
class
, the div
will be rendered from extreme left
as it isn't floated.
So in this case, either you can float
the to the left
as well
OR
You can use margin-left
which will be equal to the size of the left floated column i.e 200px
wide.
If you are in an interactive environment like Jupyter
or ipython
you might be interested in clearing unwanted var's if they are getting heavy.
The magic-commands reset
and reset_selective
is vailable on interactive python sessions like ipython
and Jupyter
1) reset
reset
Resets the namespace by removing all names defined by the user, if called without arguments.
in
and the out
parameters specify whether you want to flush the in/out caches. The directory history is flushed with the dhist
parameter.
reset in out
Another interesting one is array
that only removes numpy Arrays:
reset array
2) reset_selective
Resets the namespace by removing names defined by the user. Input/Output history are left around in case you need them.
Clean Array Example:
In [1]: import numpy as np
In [2]: littleArray = np.array([1,2,3,4,5])
In [3]: who_ls
Out[3]: ['littleArray', 'np']
In [4]: reset_selective -f littleArray
In [5]: who_ls
Out[5]: ['np']
Source: http://ipython.readthedocs.io/en/stable/interactive/magics.html
It only comes when your list or dictionary not available in the local function.
DATEDIFF but note it returns an integer so if you need fractions of hours use something like this:-
CAST(DATEDIFF(ss, startDate, endDate) AS decimal(precision, scale)) / 3600
I wrote a simple test for all the above.
def eq(a, b)
puts "#{[a, '==', b]} : #{a == b}"
puts "#{[a, '===', b]} : #{a === b}"
puts "#{[a, '.eql?', b]} : #{a.eql?(b)}"
puts "#{[a, '.equal?', b]} : #{a.equal?(b)}"
end
eq("all", "all")
eq(:all, :all)
eq(Object.new, Object.new)
eq(3, 3)
eq(1, 1.0)
There are several ways to try to prevent line breaks, and the phrase “a newer construct” might refer to more than one way—that’s actually the most reasonable interpretation. They probably mostly think of the CSS declaration white-space:nowrap
and possibly the no-break space character. The different ways are not equivalent, far from that, both in theory and especially in practice, though in some given case, different ways might produce the same result.
There is probably nothing real to be gained by switching from the HTML attribute to the somewhat clumsier CSS way, and you would surely lose when style sheets are disabled. But even the nowrap
attribute does no work in all situations. In general, what works most widely is the nobr
markup, which has never made its way to any specifications but is alive and kicking: <td><nobr>...</nobr></td>
.
And of course, the CSS only way for browsers that support nth-child
:
table td:nth-child(2) { display: none; }
This is for IE9 and newer.
For your usecase, you'd need several classes to hide the columns:
.hideCol1 td:nth-child(1) { display: none;}
.hideCol2 td:nth-child(2) { display: none;}
ect...
Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.
Discord supports Markdown and uses highlight.js to highlight code-blocks.
Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.
To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).
```language
message
```
Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).
Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.
Microsoft itself posted a KB article about this, and that article has a service pack that they claim fixes the problem. See below.
http://support.microsoft.com/kb/959417/
It took a while for the associated update to install itself, but once it did, I was able to run the Visual Studio setup successfully from the Add/Remove Programs control panel.
Both pod and container are ephemeral, try to use the following command to stop the specific container and the k8s cluster will restart a new container.
kubectl exec -it [POD_NAME] -c [CONTAINER_NAME] -- /bin/sh -c "kill 1"
This will send a SIGTERM
signal to process 1, which is the main process running in the container. All other processes will be children of process 1, and will be terminated after process 1 exits. See the kill manpage for other signals you can send.
Swift 3.0 code
self.timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector:#selector(fetchAutocompletePlaces(timer:)), userInfo:[textView.text], repeats: true)
func fetchAutocompletePlaces(timer : Timer) {
let keyword = timer.userInfo
}
You can send value in 'userinfo' and use that as parameter in the function.
This will show a model's weights and parameters (but not output shape).
from torch.nn.modules.module import _addindent
import torch
import numpy as np
def torch_summarize(model, show_weights=True, show_parameters=True):
"""Summarizes torch model by showing trainable parameters and weights."""
tmpstr = model.__class__.__name__ + ' (\n'
for key, module in model._modules.items():
# if it contains layers let call it recursively to get params and weights
if type(module) in [
torch.nn.modules.container.Container,
torch.nn.modules.container.Sequential
]:
modstr = torch_summarize(module)
else:
modstr = module.__repr__()
modstr = _addindent(modstr, 2)
params = sum([np.prod(p.size()) for p in module.parameters()])
weights = tuple([tuple(p.size()) for p in module.parameters()])
tmpstr += ' (' + key + '): ' + modstr
if show_weights:
tmpstr += ', weights={}'.format(weights)
if show_parameters:
tmpstr += ', parameters={}'.format(params)
tmpstr += '\n'
tmpstr = tmpstr + ')'
return tmpstr
# Test
import torchvision.models as models
model = models.alexnet()
print(torch_summarize(model))
# # Output
# AlexNet (
# (features): Sequential (
# (0): Conv2d(3, 64, kernel_size=(11, 11), stride=(4, 4), padding=(2, 2)), weights=((64, 3, 11, 11), (64,)), parameters=23296
# (1): ReLU (inplace), weights=(), parameters=0
# (2): MaxPool2d (size=(3, 3), stride=(2, 2), dilation=(1, 1)), weights=(), parameters=0
# (3): Conv2d(64, 192, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2)), weights=((192, 64, 5, 5), (192,)), parameters=307392
# (4): ReLU (inplace), weights=(), parameters=0
# (5): MaxPool2d (size=(3, 3), stride=(2, 2), dilation=(1, 1)), weights=(), parameters=0
# (6): Conv2d(192, 384, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)), weights=((384, 192, 3, 3), (384,)), parameters=663936
# (7): ReLU (inplace), weights=(), parameters=0
# (8): Conv2d(384, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)), weights=((256, 384, 3, 3), (256,)), parameters=884992
# (9): ReLU (inplace), weights=(), parameters=0
# (10): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)), weights=((256, 256, 3, 3), (256,)), parameters=590080
# (11): ReLU (inplace), weights=(), parameters=0
# (12): MaxPool2d (size=(3, 3), stride=(2, 2), dilation=(1, 1)), weights=(), parameters=0
# ), weights=((64, 3, 11, 11), (64,), (192, 64, 5, 5), (192,), (384, 192, 3, 3), (384,), (256, 384, 3, 3), (256,), (256, 256, 3, 3), (256,)), parameters=2469696
# (classifier): Sequential (
# (0): Dropout (p = 0.5), weights=(), parameters=0
# (1): Linear (9216 -> 4096), weights=((4096, 9216), (4096,)), parameters=37752832
# (2): ReLU (inplace), weights=(), parameters=0
# (3): Dropout (p = 0.5), weights=(), parameters=0
# (4): Linear (4096 -> 4096), weights=((4096, 4096), (4096,)), parameters=16781312
# (5): ReLU (inplace), weights=(), parameters=0
# (6): Linear (4096 -> 1000), weights=((1000, 4096), (1000,)), parameters=4097000
# ), weights=((4096, 9216), (4096,), (4096, 4096), (4096,), (1000, 4096), (1000,)), parameters=58631144
# )
Edit: isaykatsman has a pytorch PR to add a model.summary()
that is exactly like keras https://github.com/pytorch/pytorch/pull/3043/files
This is not strictly true as the NTFS filesystem supports paths up to 32k characters. You can use the win32 api and "\\?\
" prefix the path to use greater than 260 characters.
A detailed explanation of long path from the .Net BCL team blog.
A small excerpt highlights the issue with long paths
Another concern is inconsistent behavior that would result by exposing long path support. Long paths with the
\\?\
prefix can be used in most of the file-related Windows APIs, but not all Windows APIs. For example, LoadLibrary, which maps a module into the address of the calling process, fails if the file name is longer than MAX_PATH. So this means MoveFile will let you move a DLL to a location such that its path is longer than 260 characters, but when you try to load the DLL, it would fail. There are similar examples throughout the Windows APIs; some workarounds exist, but they are on a case-by-case basis.
The reason i like below technique because it also help me to identify the section of table.
Add Button in cell cellForRowAtIndexPath:
UIButton *selectTaskBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[selectTaskBtn setFrame:CGRectMake(15, 5, 30, 30.0)];
[selectTaskBtn setTag:indexPath.section]; //Not required but may find useful if you need only section or row (indexpath.row) as suggested by MR.Tarun
[selectTaskBtn addTarget:self action:@selector(addTask:) forControlEvents:UIControlEventTouchDown];
[cell addsubview: selectTaskBtn];
Event addTask:
-(void)addTask:(UIButton*)btn
{
CGPoint buttonPosition = [btn convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
if (indexPath != nil)
{
int currentIndex = indexPath.row;
int tableSection = indexPath.section;
}
}
Hopes this help.
No, because that would open up the floodgates for phishing. The only part of the URI you can change is the fragment (everything after the #
). You can do so by setting window.location.hash
.
<context:annotation-config>
declares support for general annotations such as @Required
, @Autowired
, @PostConstruct
, and so on.
<mvc:annotation-driven />
declares explicit support for annotation-driven MVC controllers (i.e. @RequestMapping
, @Controller
, although support for those is the default behaviour), as well as adding support for declarative validation via @Valid
and message body marshalling with @RequestBody
/ResponseBody
.
You should use a StringBuilder:
StringBuilder contentBuilder = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new FileReader("mypage.html"));
String str;
while ((str = in.readLine()) != null) {
contentBuilder.append(str);
}
in.close();
} catch (IOException e) {
}
String content = contentBuilder.toString();
Use this extension, in case you need to resize width/height only with aspect ratio.
extension UIImage {
func resize(to size: CGSize) -> UIImage {
return UIGraphicsImageRenderer(size: size).image { _ in
draw(in: CGRect(origin: .zero, size: size))
}
}
func resize(width: CGFloat) -> UIImage {
return resize(to: CGSize(width: width, height: width / (size.width / size.height)))
}
func resize(height: CGFloat) -> UIImage {
return resize(to: CGSize(width: height * (size.width / size.height), height: height))
}
}
Dim sSheetName As String
Dim sConnection As String
Dim dtTablesList As DataTable
Dim oleExcelCommand As OleDbCommand
Dim oleExcelReader As OleDbDataReader
Dim oleExcelConnection As OleDbConnection
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Test.xls;Extended Properties=""Excel 12.0;HDR=No;IMEX=1"""
oleExcelConnection = New OleDbConnection(sConnection)
oleExcelConnection.Open()
dtTablesList = oleExcelConnection.GetSchema("Tables")
If dtTablesList.Rows.Count > 0 Then
sSheetName = dtTablesList.Rows(0)("TABLE_NAME").ToString
End If
dtTablesList.Clear()
dtTablesList.Dispose()
If sSheetName <> "" Then
oleExcelCommand = oleExcelConnection.CreateCommand()
oleExcelCommand.CommandText = "Select * From [" & sSheetName & "]"
oleExcelCommand.CommandType = CommandType.Text
oleExcelReader = oleExcelCommand.ExecuteReader
nOutputRow = 0
While oleExcelReader.Read
End While
oleExcelReader.Close()
End If
oleExcelConnection.Close()
Looping the pointer to gain better performance:
#include <ctype.h>
char* toLower(char* s) {
for(char *p=s; *p; p++) *p=tolower(*p);
return s;
}
char* toUpper(char* s) {
for(char *p=s; *p; p++) *p=toupper(*p);
return s;
}
After your insert query, use this command $this->db->insert_id();
to return the last inserted id.
For example:
$this->db->insert('Your_tablename', $your_data);
$last_id = $this->db->insert_id();
echo $last_id // assume that the last id from the table is 1, after the insert query this value will be 2.
If you are willing to use a 3rd party service, auth0.com supports this integration. The auth0 service exchanges a 3rd party SSO service authentication for an AWS temporary session token will limited permissions.
See:
https://github.com/auth0-samples/auth0-s3-sample/
and the auth0 documentation.
You can use Marker With Label option in google-maps-utility-library-v3.
Just refer https://code.google.com/p/google-maps-utility-library-v3/wiki/Libraries
According to OpenCV cheat-sheet this can be done as follows:
IplImage* oldC0 = cvCreateImage(cvSize(320,240),16,1);
Mat newC = cvarrToMat(oldC0);
The cv::cvarrToMat function takes care of the conversion issues.
You can use the Grid CSS properties, is the most clear, clean and intuitive way structure your boxes.
#container{_x000D_
display: grid;_x000D_
grid-template-columns: 100px auto;_x000D_
color:white;_x000D_
}_x000D_
#fixed{_x000D_
background: red;_x000D_
grid-column: 1;_x000D_
}_x000D_
#remaining{_x000D_
background: green;_x000D_
grid-column: 2;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="fixed">Fixed</div>_x000D_
<div id="remaining">Remaining</div>_x000D_
</div>
_x000D_
WCF is a newer technology that is a viable alternative in many instances. ASP is great and works well, but I personally prefer WCF. And you can do it in .Net 4.5.
Create a new project. Right-Click on the project in solution explorer, select "Add Service Reference"
Create a textbox and button in the new application. Below is my click event for the button:
private void btnGo_Click(object sender, EventArgs e)
{
ServiceReference1.Service1Client testClient = new ServiceReference1.Service1Client();
//Add error handling, null checks, etc...
int iValue = int.Parse(txtInput.Text);
string sResult = testClient.GetData(iValue).ToString();
MessageBox.Show(sResult);
}
And you're done.
Javascript String objects have a split function, doesn't really need to be jQuery specific
var str = "nice.test"
var strs = str.split(".")
strs would be
["nice", "test"]
I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed
success: function(data) {
var items = JSON.parse(data)
}
One liner as suggested here
How to determine one year from now in Javascript by JP DeVries
new Date(new Date().setFullYear(new Date().getFullYear() + 1))
Or you can get the number of years from somewhere in a variable:
const nr_years = 3;
new Date(new Date().setFullYear(new Date().getFullYear() + nr_years))
Here is a better way to loop over files as it handles spaces and newlines in file names:
#!/bin/bash
find . -type f -iname "*.txt" -print0 | while IFS= read -r -d $'\0' line; do
echo "$line"
ls -l "$line"
done
Set the touch-action CSS property to none
, which works even with passive event listeners:
touch-action: none;
Applying this property to an element will not trigger the default (scroll) behavior when the event is originating from that element.
By wrapping your comparisons in {}
in your first example you are creating ScriptBlocks; so the PowerShell interpreter views it as Where-Object { <ScriptBlock> -and <ScriptBlock> }
. Since the -and
operator operates on boolean values, PowerShell casts the ScriptBlocks to boolean values. In PowerShell anything that is not empty, zero or null is true. The statement then looks like Where-Object { $true -and $true }
which is always true.
Instead of using {}
, use parentheses ()
.
Also you want to use -eq
instead of -match
since match uses regex and will be true if the pattern is found anywhere in the string (try: 'xlsx' -match 'xls'
).
Invoke-Command -computername SERVERNAME {
Get-ChildItem -path E:\dfsroots\datastore2\public |
Where-Object {($_.extension -eq ".xls" -or $_.extension -eq ".xlk") -and ($_.creationtime -ge "06/01/2014")}
}
A better option is to filter the extensions at the Get-ChildItem
command.
Invoke-Command -computername SERVERNAME {
Get-ChildItem -path E:\dfsroots\datastore2\public\* -Include *.xls, *.xlk |
Where-Object {$_.creationtime -ge "06/01/2014"}
}
There is the possibility of making something really more cool!
# Powershell
$xl = new-object -ComObject excell.application
$doc=$xl.workbooks.open("Filepath")
$doc.Sheets.item(1).rows |
% { ($_.value2 | Select-Object -first 3 | Select-Object -last 2) -join "," }
You will want to use the a ternary operator which acts as a shortened IF/Else statement:
echo '<option value="'.$value.'" '.(($value=='United States')?'selected="selected"':"").'>'.$value.'</option>';
From the JavaDocs of the ArrayList
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.
HTML:
<select class="form-control" id="SecondSelect">
<option>5<option>
<option>10<option>
<option>20<option>
<option>30<option>
</select>
JavaScript:
var value = $('#SecondSelect')[0].value;