Use below command to check outdated or vulnerabilities in your node modules.
npm audit
If any vulnerabilities found, use below command to fix all issues.
npm audit fix
If it doesn't work for you then try
npm audit fix -f
, this command will almost fix all vulnerabilities. Some dependencies or devDependencies are locked in package-lock.json file, so we use-f
flag to force update them.
If you don't want to use force audit fix then you can manually fix your dependencies versions by changing them in package-lock.json and package.json file. Then run
npm update && npm upgrade
We had the same problem. In our case, the browser was blocked by a login popup (Windows authentication), so not returning after 60 seconds. Adding correct access rights to the Windows account Chrome was running under solved the problem.
For generating the publish output provide one more parameter. msbuild example.sln /p:publishprofile=profilename /p:deployonbuild=true /p:configuration=debug/or any
To answer the question of going from an existing python datetime to a pandas Timestamp do the following:
import time, calendar, pandas as pd
from datetime import datetime
def to_posix_ts(d: datetime, utc:bool=True) -> float:
tt=d.timetuple()
return (calendar.timegm(tt) if utc else time.mktime(tt)) + round(d.microsecond/1000000, 0)
def pd_timestamp_from_datetime(d: datetime) -> pd.Timestamp:
return pd.to_datetime(to_posix_ts(d), unit='s')
dt = pd_timestamp_from_datetime(datetime.now())
print('({}) {}'.format(type(dt), dt))
Output:
(<class 'pandas._libs.tslibs.timestamps.Timestamp'>) 2020-09-05 23:38:55
I was hoping for a more elegant way to do this but the to_posix_ts
is already in my standard tool chain so I'm moving on.
When having [FromBody]attribute, the string sent should not be a raw string, but rather a JSON string as it includes the wrapping quotes:
"test"
Similar answer string value is Empty when using FromBody in asp.net web api
I've got this little function:
public static class CoreUtil
{
public static IEnumerable<T> ToEnumerable<T>(params T[] items)
{
return items;
}
}
Since it doesn't prescribe a concrete return type this is so generic that I use it all over the place. Your code would look like
CoreUtil.ToEnumerable("title").ToList();
But of course it also allows
CoreUtil.ToEnumerable("title1", "title2", "title3").ToArray();
I often use it in when I have to append/prepend one item to the output of a LINQ statement. For instance to add a blank item to a selection list:
CoreUtil.ToEnumerable("").Concat(context.TrialTypes.Select(t => t.Name))
Saves a few ToList()
and Add
statements.
(Late answer, but I stumbled upon this oldie and thought this could be helpful)
In NuGet package install Microsoft.AspNetCore.HttpOverrides
Then try:
public class ClientDeviceInfo
{
private readonly IHttpContextAccessor httpAccessor;
public ClientDeviceInfo(IHttpContextAccessor httpAccessor)
{
this.httpAccessor = httpAccessor;
}
public string GetClientLocalIpAddress()
{
return httpAccessor.HttpContext.Connection.LocalIpAddress.ToString();
}
public string GetClientRemoteIpAddress()
{
return httpAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
}
public string GetClientLocalPort()
{
return httpAccessor.HttpContext.Connection.LocalPort.ToString();
}
public string GetClientRemotePort()
{
return httpAccessor.HttpContext.Connection.RemotePort.ToString();
}
}
import Foundation
import CoreLocation
enum Result<T> {
case success(T)
case failure(Error)
}
final class LocationService: NSObject {
private let manager: CLLocationManager
init(manager: CLLocationManager = .init()) {
self.manager = manager
super.init()
manager.delegate = self
}
var newLocation: ((Result<CLLocation>) -> Void)?
var didChangeStatus: ((Bool) -> Void)?
var status: CLAuthorizationStatus {
return CLLocationManager.authorizationStatus()
}
func requestLocationAuthorization() {
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
manager.startUpdatingLocation()
//locationManager.startUpdatingHeading()
}
}
func getLocation() {
manager.requestLocation()
}
deinit {
manager.stopUpdatingLocation()
}
}
extension LocationService: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
newLocation?(.failure(error))
manager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.sorted(by: {$0.timestamp > $1.timestamp}).first {
newLocation?(.success(location))
}
manager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .notDetermined, .restricted, .denied:
didChangeStatus?(false)
default:
didChangeStatus?(true)
}
}
}
Needs to write this code in required ViewController.
//NOTE:: Add permission in info.plist::: NSLocationWhenInUseUsageDescription
let locationService = LocationService()
@IBAction func action_AllowButtonTapped(_ sender: Any) {
didTapAllow()
}
func didTapAllow() {
locationService.requestLocationAuthorization()
}
func getCurrentLocationCoordinates(){
locationService.newLocation = {result in
switch result {
case .success(let location):
print(location.coordinate.latitude, location.coordinate.longitude)
case .failure(let error):
assertionFailure("Error getting the users location \(error)")
}
}
}
func getCurrentLocationCoordinates() {
locationService.newLocation = { result in
switch result {
case .success(let location):
print(location.coordinate.latitude, location.coordinate.longitude)
CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
if error != nil {
print("Reverse geocoder failed with error" + (error?.localizedDescription)!)
return
}
if (placemarks?.count)! > 0 {
print("placemarks", placemarks!)
let pmark = placemarks?[0]
self.displayLocationInfo(pmark)
} else {
print("Problem with the data received from geocoder")
}
})
case .failure(let error):
assertionFailure("Error getting the users location \(error)")
}
}
}
exit
is a helper for the interactive shell - sys.exit
is intended for use in programs.
The
site
module (which is imported automatically during startup, except if the-S
command-line option is given) adds several constants to the built-in namespace (e.g.exit
). They are useful for the interactive interpreter shell and should not be used in programs.
Technically, they do mostly the same: raising SystemExit
. sys.exit
does so in sysmodule.c:
static PyObject *
sys_exit(PyObject *self, PyObject *args)
{
PyObject *exit_code = 0;
if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
return NULL;
/* Raise SystemExit so callers may catch it or clean up. */
PyErr_SetObject(PyExc_SystemExit, exit_code);
return NULL;
}
While exit
is defined in site.py and _sitebuiltins.py, respectively.
class Quitter(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Use %s() or %s to exit' % (self.name, eof)
def __call__(self, code=None):
# Shells like IDLE catch the SystemExit, but listen when their
# stdin wrapper is closed.
try:
sys.stdin.close()
except:
pass
raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')
Note that there is a third exit option, namely os._exit, which exits without calling cleanup handlers, flushing stdio buffers, etc. (and which should normally only be used in the child process after a fork()
).
I was getting exactly same issue, All I have done is to to change the Debug mode to Release while compiling the dll. This has solved my probelm, how/why? I dont know I have already asked a question on SO
In the CSS all you have to do is put url(logical path to the image file)
In my case it happens when i want add view by parent to other view
View root = inflater.inflate(R.layout.single, null);
LinearLayout lyt = root.findViewById(R.id.lytRoot);
lytAll.addView(lyt); // -> crash
you must add parent view like this
View root = inflater.inflate(R.layout.single, null);
LinearLayout lyt = root.findViewById(R.id.lytRoot);
lytAll.addView(root);
Use : '
to open and '
to close.
For example:
: '
This is a
very neat comment
in bash
'
My favorite: Smart::Comments
use Smart::Comments;
# ...
### %hash
That's it.
In laymen's terms, if you use the @Transient annotation on an attribute of an entity: this attribute will be singled out and will not be saved to the database. The rest of the attribute of the object within the entity will still be saved.
Im saving the Object to the database using the jpa repository built in save method as so:
userRoleJoinRepository.save(user2);
width
and height
are used when going the css route.
<!DOCTYPE html>
<html>
<head>
<title>Setting Width and Height on Textareas</title>
<style>
.comments { width: 300px; height: 75px }
</style>
</head>
<body>
<textarea class="comments"></textarea>
</body>
</html>
Absolutely, yes you can. This link contains details about how you can achieve that: https://api.jquery.com/jquery.noconflict/.
I can't say for sure if this is the case, but what appeared to be a problem for me was having .gitignore files in some of the subdirectories. Again, I can't guarantee this, but everything worked after these were deleted.
This does not work, because Chrome forbids any kind of inline code in extensions via Content Security Policy.
Inline JavaScript will not be executed. This restriction bans both inline
<script>
blocks and inline event handlers (e.g.<button onclick="...">
).
If this is indeed the problem, Chrome would produce the following error in the console:
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.
To access a popup's JavaScript console (which is useful for debug in general), right-click your extension's button and select "Inspect popup" from the context menu.
More information on debugging a popup is available here.
One needs to remove all inline JavaScript. There is a guide in Chrome documentation.
Suppose the original looks like:
<a onclick="handler()">Click this</a> <!-- Bad -->
One needs to remove the onclick
attribute and give the element a unique id:
<a id="click-this">Click this</a> <!-- Fixed -->
And then attach the listener from a script (which must be in a .js
file, suppose popup.js
):
// Pure JS:
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("click-this").addEventListener("click", handler);
});
// The handler also must go in a .js file
function handler() {
/* ... */
}
Note the wrapping in a DOMContentLoaded
event. This ensures that the element exists at the time of execution. Now add the script tag, for instance in the <head>
of the document:
<script src="popup.js"></script>
Alternative if you're using jQuery:
// jQuery
$(document).ready(function() {
$("#click-this").click(handler);
});
Q: The error mentions ways to allow inline code. I don't want to / can't change my code, how do I enable inline scripts?
A: Despite what the error says, you cannot enable inline script:
There is no mechanism for relaxing the restriction against executing inline JavaScript. In particular, setting a script policy that includes
'unsafe-inline'
will have no effect.
Update: Since Chrome 46, it's possible to whitelist specific inline code blocks:
As of Chrome 46, inline scripts can be whitelisted by specifying the base64-encoded hash of the source code in the policy. This hash must be prefixed by the used hash algorithm (sha256, sha384 or sha512). See Hash usage for
<script>
elements for an example.
However, I do not readily see a reason to use this, and it will not enable inline attributes like onclick="code"
.
Sure, call the java executable.
Mine is C:\Program Files\Java\jre6\bin\java.exe
, so to run it I would do
C:\Program Files\Java\jre6\bin\java.exe -jar myjarfile.jar
And if you are using google guava, the one line solution would be
List<String> b = Lists.newArrayList(a);
This creates a mutable array list instance.
This is what I went through on Amazon/AWS EMR v5. (Adapted from the previous answers), to have Maven and Java8.
sudo wget https://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo
sudo sed -i s/\$releasever/6/g /etc/yum.repos.d/epel-apache-maven.repo
sudo yum install -y apache-maven
sudo alternatives --config java
pick Java8
sudo alternatives --config javac
pick Java8
Now, if you run:
mvn -version
You should get:
Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T07:58:13Z)
Maven home: /usr/share/apache-maven
Java version: 1.8.0_171, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.171-8.b10.38.amzn1.x86_64/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.14.47-56.37.amzn1.x86_64", arch: "amd64", family: “unix"
You can use Buffer.from()
to convert a string to buffer. More information on this can be found here
var buf = Buffer.from('some string', 'encoding');
for example
var buf = Buffer.from(bStr, 'utf-8');
You can use scriptmanager.registerstartupscript
to call a JavaScript function
.
Inside that function, you can open a new window.
That's one of the few legitimate jobs for cat
:
openssl verify -verbose -CAfile <(cat Intermediate.pem RootCert.pem) UserCert.pem
Update:
As Greg Smethells points out in the comments, this command implicitly trusts Intermediate.pem. I recommend reading the first part of the post Greg references (the second part is specifically about pyOpenSSL and not relevant to this question).
In case the post goes away I'll quote the important paragraphs:
Unfortunately, an "intermediate" cert that is actually a root / self-signed will be treated as a trusted CA when using the recommended command given above:
$ openssl verify -CAfile <(cat geotrust_global_ca.pem rogue_ca.pem) fake_sometechcompany_from_rogue_ca.com.pem fake_sometechcompany_from_rogue_ca.com.pem: OK
It seems openssl will stop verifying the chain as soon as a root certificate is encountered, which may also be Intermediate.pem if it is self-signed. In that case RootCert.pem is not considered. So make sure that Intermediate.pem is coming from a trusted source before relying on the command above.
It's now possible to add a forced line break
with two blank spaces at the end of the line:
line1??
line2
will be formatted as:
line1
line2
Use trigger
to fire your own event. When ever you change class add trigger with name
$("#main").on('click', function () {
$("#chld").addClass("bgcolorRed").trigger("cssFontSet");
});
$('#chld').on('cssFontSet', function () {
alert("Red bg set ");
});
What you want to use is this property:
dt.Columns[0].DataType
The DataType
property will set to one of the following:
Boolean
Byte
Char
DateTime
Decimal
Double
Int16
Int32
Int64
SByte
Single
String
TimeSpan
UInt16
UInt32
UInt64
And if you need authorized user in templates (e.g. JSP) use
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<sec:authentication property="principal.yourCustomField"/>
together with
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring-security.version}</version>
</dependency>
Here is to share something I found on __import__
and importlib
while trying to solve this problem.
I am using Python 3.7.3.
When I try to get to the class d
in module a.b.c
,
mod = __import__('a.b.c')
The mod
variable refer to the top namespace a
.
So to get to the class d
, I need to
mod = getattr(mod, 'b') #mod is now module b
mod = getattr(mod, 'c') #mod is now module c
mod = getattr(mod, 'd') #mod is now class d
If we try to do
mod = __import__('a.b.c')
d = getattr(mod, 'd')
we are actually trying to look for a.d
.
When using importlib
, I suppose the library has done the recursive getattr
for us. So, when we use importlib.import_module
, we actually get a handle on the deepest module.
mod = importlib.import_module('a.b.c') #mod is module c
d = getattr(mod, 'd') #this is a.b.c.d
It's better to use
$('#search-form').setAttribute('action', '/controllerName/actionName');
rather than
$('#search-form').attr('action', '/controllerName/actionName');
So, based on trante's answer we have:
$('#search-form').submit(function() {
var formAction = $("#selectsearch").val() == "people" ? "user" : "content";
$("#search-form").setAttribute("action", "/search/" + formAction);
});
Using setAttribute
can save you a lot of time potentially.
Quite and simple without any "having to specify the first element". CSS is more powerful than most think (e.g. the first-child:before
is great!). But this is by far the cleanest and most proper way to do this, at least in my opinion it is.
#navigation ul
{
margin: 0;
padding: 0;
}
#navigation ul li
{
list-style-type: none;
display: inline;
}
#navigation li:not(:first-child):before {
content: " | ";
}
Now just use a simple unordered list in HTML and it'll populate it for you. HTML should look like this:
<div id="navigation">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Support</a></li>
</ul>
</div><!-- navigation -->
The result will be just like this:
HOME | ABOUT US | SUPPORT
Now you can indefinitely expand and never have to worry about order, changing links, or your first entry. It's all automated and works great!
If you run your commands in a shell you can write something like "java -cp" and add any directories you want separated by ":" if java doesnt find something in one directory it will go try and find them in the other directories, that is what I do.
You can take advantage of CSS3 to do that, by hidding the by-default input radio button with CSS3 rules:
.class-selector input{
margin:0;padding:0;
-webkit-appearance:none;
-moz-appearance:none;
appearance:none;
}
And then using labels for images as the following demos:
Sometimes you want to delete a file whatever the case(whatever the exception occurs ,please do delete the file). For such situations.
public static void DeleteFile(string path)
{
if (!File.Exists(path))
{
return;
}
bool isDeleted = false;
while (!isDeleted)
{
try
{
File.Delete(path);
isDeleted = true;
}
catch (Exception e)
{
}
Thread.Sleep(50);
}
}
Note:An exception is not thrown if the specified file does not exist.
try the below query
DECLARE @Query VARCHAR(max)
SELECT @Query = 'USE ? SELECT ''?'' AS DataBaseName,
sys.columns.name AS ColumnName ,
sys.tables.name AS TableName ,
schema_name (sys.tables.schema_Id) AS schemaName
FROM sys.columns
JOIN sys.tables
ON sys.columns.object_id = sys.tables.object_id
WHERE sys.columns.name = ''id'' '
EXEC SP_MSFOREACHDB @Query
gives list of tables containing ID column from all databases.
Since everybody covered the KeyDown
answers, how about using the IsDefault
on the button?
You can read this tip for a quick howto and what it does: http://www.codeproject.com/Tips/665886/Button-Tip-IsDefault-IsCancel-and-other-usability
Here's an example from the article linked:
<Button IsDefault = "true"
Click = "SaveClicked"
Content = "Save" ... />
'''
Make sure to learn from the padding oracle asp.net vulnerability that just happened (you applied the patch, right? ...) and use protected sections to encrypt the machine key and any other sensitive configuration.
An alternative option is to set it in the machine level web.config, so its not even in the web site folder.
To generate it do it just like the linked article in David's answer.
In Xcode 4.x press
(or click Menubar
> Product
> Scheme
> Edit Scheme
)
select the "Diagnostics" tab and click "Enable Zombie Objects":
This turns released objects into NSZombie instances that print console warnings when used again. This is a debugging aid that increases memory use (no object is really released) but improves error reporting.
A typical case is when you over-release an object and you don't know which one:
-[UITableView release]: message sent to deallocated instance
This Xcode setting is ignored when you archive the application for App Store submission. You don't need to touch anything before releasing your application.
Pressing ??R is the same as selecting Product > Run while keeping the Alt key pressed.
Clicking the "Enable Zombie Objects" checkbox is the same as manually adding "NSZombieEnabled = YES" in the section "Environment Variables" of the tab Arguments.
You're trying to remove index.php from your site URL's, correct?
Try setting your $config['uri_protocol']
to REQUEST_URI
instead of AUTO
.
Embrace the future! Just to be complete, you can also do this the Python 3k way by using the print function:
from __future__ import print_function # Py 2.6+; In Py 3k not needed
mylist = ['10', 12, '14'] # Note that 12 is an int
print(*mylist,sep='\n')
Prints:
10
12
14
Eventually, print
as Python statement will go away... Might as well start to get used to it.
Either:
row.name
inside the apply(..., axis=1)
call:df = pandas.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'], index=['x','y'])
a b c
x 1 2 3
y 4 5 6
df.apply(lambda row: row.name, axis=1)
x x
y y
iterrows()
(slower)DataFrame.iterrows() allows you to iterate over rows, and access their index:
for idx, row in df.iterrows():
...
The correct way to go from C:\...\Admin
to D:\Docs\Java
drive, is the following command :
cd /d d:\Docs\Java
If you're somewhere random on your D:\
drive, and you want to go to the root of your drive, you can use this command :
cd d:\
If you're somewhere random on your D:\
drive, and you want to go to a specific folder on your drive, you can use this command :
cd d:\Docs\Java
If you're on a different drive, and you want to go to the root of your D:\
drive, you can use this command :
cd /d d:\
If you're on a different drive, and you want to go to a specific folder on your D:
drive, you can use this command :
cd /d d:\Docs\Java
If you're on a different drive, and you want to go to the last open folder of you D:
drive, you can use this command :
cd /d d:
As a shorthand for cd /d d:
, you can also use this command :
d:
I dont think adding dual functions inside the toggle function works for a registered click event (Unless I'm missing something)
For example:
$('.btnName').click(function() {
top.$('#panel').toggle(function() {
$(this).animate({
// style change
}, 500);
},
function() {
$(this).animate({
// style change back
}, 500);
});
You can fix this problem by adding "$(ProjectDir)" (or wherever the stdafx.h is) to list of directories under Project->Properties->Configuration Properties->C/C++->General->Additional Include Directories.
If you're did something like accidentally rsync'd to the wrong directory, the above suggestions work to find new files, but for me, the easiest was connecting with an SFTP client like Transmit then ordering by date and deleting.
You need to use ref
if you plan to read and write to the parameter. You need to use out
if you only plan to write. In effect, out
is for when you'd need more than one return value, or when you don't want to use the normal return mechanism for output (but this should be rare).
There are language mechanics that assist these use cases. Ref
parameters must have been initialized before they are passed to a method (putting emphasis on the fact that they are read-write), and out
parameters cannot be read before they are assigned a value, and are guaranteed to have been written to at the end of the method (putting emphasis on the fact that they are write only). Contravening to these principles results in a compile-time error.
int x;
Foo(ref x); // error: x is uninitialized
void Bar(out int x) {} // error: x was not written to
For instance, int.TryParse
returns a bool
and accepts an out int
parameter:
int value;
if (int.TryParse(numericString, out value))
{
/* numericString was parsed into value, now do stuff */
}
else
{
/* numericString couldn't be parsed */
}
This is a clear example of a situation where you need to output two values: the numeric result and whether the conversion was successful or not. The authors of the CLR decided to opt for out
here since they don't care about what the int
could have been before.
For ref
, you can look at Interlocked.Increment
:
int x = 4;
Interlocked.Increment(ref x);
Interlocked.Increment
atomically increments the value of x
. Since you need to read x
to increment it, this is a situation where ref
is more appropriate. You totally care about what x
was before it was passed to Increment
.
In the next version of C#, it will even be possible to declare variable in out
parameters, adding even more emphasis on their output-only nature:
if (int.TryParse(numericString, out int value))
{
// 'value' exists and was declared in the `if` statement
}
else
{
// conversion didn't work, 'value' doesn't exist here
}
It is a accepted standard to have content, layout and behavior separate. So window.onload() will be more suitable to use than <body onload="">
though both do the same work.
My bet:
^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$
Explained:
Domain name is built from segments. Here is one segment (except final):
[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?
It can have 1-63 characters, does not start or end with '-'.
Now append '.' to it and repeat at least one time:
(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+
Then attach final segment, which is 2-63 characters long:
[a-z0-9][a-z0-9-]{0,61}[a-z0-9]
Test it here: http://regexr.com/3au3g
I'm asked this question very frequently, if it's smart to use "Share project..." if a eclipse project has been disconnected from it SVN counterpart in the repository. So, I append my answer to this thread.
The SVN-Team option "Share project ..." is totally fine for projects that exist in SVN and in your Eclipse workspace, even if the Eclipse project is missing the hidden .svn configuration. You can still connect them. Eclipse SVN-implementation (Subclipse/Subversive) will verify if the provided SVN http(s) source is populated. If yes, all existing files will be copied and linked (checked out in SVN terms) to your very personal Eclipse workspace.
Word of caution:
regards, Feder
a.txt
this is line 1
this is line 2
code:
Python 3.4.0 (default, Mar 20 2014, 22:43:40)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']
I'm on Linux, but I guess you just use \r\n
on Windows and it would also work
My two cents:
bool endsWith(std::string str, std::string suffix)
{
return str.find(suffix, str.size() - suffix.size()) != string::npos;
}
FWIW, htpasswd -n username
will output the result directly to stdout, and avoid touching files altogether.
Using MAMP ON Mac, I solve my problem by renaming
/Applications/MAMP/tmp/mysql/mysql.sock.lock
to
/Applications/MAMP/tmp/mysql/mysql.sock
Create file version.properties
MAJOR=1
MINOR=3
PATCH=6
VERSION_CODE=1
Change build.gradle
:
android {
def _versionCode=0
def _major=0
def _minor=0
def _patch=0
def _applicationId = "com.example.test"
def versionPropsFile = file('version.properties')
if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
_patch = versionProps['PATCH'].toInteger() + 1
_major = versionProps['MAJOR'].toInteger()
_minor = versionProps['MINOR'].toInteger()
_versionCode= versionProps['VERSION_CODE'].toInteger()+1
if(_patch==99)
{
_patch=0
_minor=_minor+1
}
if(_major==99){
_major=0
_major=_major+1
}
versionProps['MAJOR']=_major.toString()
versionProps['MINOR']=_minor.toString()
versionProps['PATCH']=_patch.toString()
versionProps['VERSION_CODE']=_versionCode.toString()
versionProps.store(versionPropsFile.newWriter(), null)
}
else {
throw new GradleException("Could not read version.properties!")
}
def _versionName = "${_major}.${_versionCode}.${_minor}.${_patch}"
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId _applicationId
minSdkVersion 11
targetSdkVersion 23
versionCode _versionCode
versionName _versionName
}
}
Output : 1.1.3.6
>>> mydict = {'a':1,'b':3,'c':2}
>>> sorted(mydict, key=lambda key: mydict[key])
['a', 'c', 'b']
There is a hidden cost in removing elements from an ArrayList. Each time you delete an element, you need to move the elements to fill the "hole". On average, this will take N / 2
assignments for a list with N elements.
So removing M elements from an N element ArrayList is O(M * N)
on average. An O(N) solution involves creating a new list. For example.
List data = ...;
List newData = new ArrayList(data.size());
for (Iterator i = data.iterator(); i.hasNext(); ) {
Object element = i.next();
if ((...)) {
newData.add(element);
}
}
If N is large, my guess is that this approach will be faster than the remove
approach for values of M as small as 3 or 4.
But it is important to create newList
large enough to hold all elements in list
to avoid copying the backing array when it is expanded.
input:not([value=""])
This works because we are selecting the input only when there isn't an empty string.
Another problem solved by the rubber duck:
The css is right but you still have to remember that the HTML elements order matters: the div has to come before the header. http://jsfiddle.net/Fq2Na/1/
Change your HTML code to have the div before the header:
<section>
<div><button>button</button></div>
<h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>
</section>
And keep your CSS to the simple div { float: right; }
.
I don't know how you could miss this one, it's pretty basic. That's the syntax for initializing member variables or base class constructors. It works for plain old data types as well as class objects.
I was still confused after reading the other answers and comments. But the answer now seems simpler, so here you go.
Since Pandas version 0.9 (from 2012), you can read your csv with empty cells interpreted as empty strings by simply setting keep_default_na=False
:
pd.read_csv('test.csv', keep_default_na=False)
This issue is more clearly explained in
That was fixed on on Aug 19, 2012 for Pandas version 0.9 in
I've edited Alix Axel's answer to take a third argrument, when setting this third argrument to true
all the files will be added under the main directory rather than directly in the zip folder.
If the zip file exists the file will be deleted as well.
Example:
Zip('/path/to/maindirectory','/path/to/compressed.zip',true);
Third argrument true
zip structure:
maindirectory
--- file 1
--- file 2
--- subdirectory 1
------ file 3
------ file 4
--- subdirectory 2
------ file 5
------ file 6
Third argrument false
or missing zip structure:
file 1
file 2
subdirectory 1
--- file 3
--- file 4
subdirectory 2
--- file 5
--- file 6
Edited code:
function Zip($source, $destination, $include_dir = false)
{
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
if (file_exists($destination)) {
unlink ($destination);
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
if ($include_dir) {
$arr = explode("/",$source);
$maindir = $arr[count($arr)- 1];
$source = "";
for ($i=0; $i < count($arr) - 1; $i++) {
$source .= '/' . $arr[$i];
}
$source = substr($source, 1);
$zip->addEmptyDir($maindir);
}
foreach ($files as $file)
{
$file = str_replace('\\', '/', $file);
// Ignore "." and ".." folders
if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
continue;
$file = realpath($file);
if (is_dir($file) === true)
{
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString(basename($source), file_get_contents($source));
}
return $zip->close();
}
Try to open Services Window, by writing services.msc
into Start->Run and hit Enter.
When window appears, then find SQL Browser service, right click and choose Properties, and then in dropdown list choose Automatic, or Manual, whatever you want, and click OK. Eventually, if not started immediately, you can again press right click on this service and click Start.
To be able to use it like that, you need to return this
. Without the return, fadeOut('slow'), will not get an object to perform that operation on.
I.e.:
$.fn.idle = function(time)
{
var o = $(this);
o.queue(function()
{
setTimeout(function()
{
o.dequeue();
}, time);
});
return this; //****
}
Then do this:
$('.notice').fadeIn().idle(2000).fadeOut('slow');
If someone needs to remove undefined
values from an object with deep search using lodash
then here is the code that I'm using. It's quite simple to modify it to remove all empty values (null
/undefined
).
function omitUndefinedDeep(obj) {
return _.reduce(obj, function(result, value, key) {
if (_.isObject(value)) {
result[key] = omitUndefinedDeep(value);
}
else if (!_.isUndefined(value)) {
result[key] = value;
}
return result;
}, {});
}
I think that it definitely has its place on a resume. Knowledge of HTML is valuable, and there really is a lot to know, what with cross-browser compatibility issues and standards which should be followed.
I wouldn't list HTML under "programming languages" alongside C# or something, but it's worth noting your experience.
Attention!
while (calendar.get(Calendar.DAY_OF_WEEK) > calendar.getFirstDayOfWeek()) {
calendar.add(Calendar.DATE, -1); // Substract 1 day until first day of week.
}
is good idea, but there is some issue: For example, i'm from Ukraine and calendar.getFirstDayOfWeek() in my country is 2 (Monday). And today is 1 (Sunday). In this case calendar.add not called.
So, correct way is change ">" to "!=":
while (calendar.get(Calendar.DAY_OF_WEEK) != calendar.getFirstDayOfWeek()) {...
The recommended approach is:
window.greeting = "Hello World!"
You can then access it within any function:
function foo() {
alert(greeting); // Hello World!
alert(window["greeting"]); // Hello World!
alert(window.greeting); // Hello World! (recommended)
}
This approach is preferred for two reasons.
The intent is explicit. The use of the var
keyword can easily lead to declaring global vars
that were intended to be local or vice versa. This sort of variable scoping is a point of confusion for a lot of Javascript developers. So as a general rule, I make sure all variable declarations are preceded with the keyword var
or the prefix window
.
You standardize this syntax for reading the variables this way as well which means that a locally scoped var
doesn't clobber the global var
or vice versa. For example what happens here is ambiguous:
greeting = "Aloha";
function foo() {
greeting = "Hello"; // overrides global!
}
function bar(greeting) {
alert(greeting);
}
foo();
bar("Howdy"); // does it alert "Hello" or "Howdy" ?
However, this is much cleaner and less error prone (you don't really need to remember all the variable scoping rules):
function foo() {
window.greeting = "Hello";
}
function bar(greeting) {
alert(greeting);
}
foo();
bar("Howdy"); // alerts "Howdy"
Share application with title is you app_name, content is your application link
private static void shareApp(Context context) {
final String appPackageName = BuildConfig.APPLICATION_ID;
final String appName = context.getString(R.string.app_name);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
String shareBodyText = "https://play.google.com/store/apps/details?id=" +
appPackageName;
shareIntent.putExtra(Intent.EXTRA_SUBJECT, appName);
shareIntent.putExtra(Intent.EXTRA_TEXT, shareBodyText);
context.startActivity(Intent.createChooser(shareIntent, context.getString(R.string
.share_with)));
}
Here's the cheat sheet on the commands:
hg update
changes your working copy parent revision and also changes the file content to match this new parent revision. This means that new commits will carry on from the revision you update to.
hg revert
changes the file content only and leaves the working copy parent revision alone. You typically use hg revert
when you decide that you don't want to keep the uncommited changes you've made to a file in your working copy.
hg branch
starts a new named branch. Think of a named branch as a label you assign to the changesets. So if you do hg branch red
, then the following changesets will be marked as belonging on the "red" branch. This can be a nice way to organize changesets, especially when different people work on different branches and you later want to see where a changeset originated from. But you don't want to use it in your situation.
If you use hg update --rev 38
, then changesets 39–45 will be left as a dead end — a dangling head as we call it. You'll get a warning when you push since you will be creating "multiple heads" in the repository you push to. The warning is there since it's kind of impolite to leave such heads around since they suggest that someone needs to do a merge. But in your case you can just go ahead and hg push --force
since you really do want to leave it hanging.
If you have not yet pushed revision 39-45 somewhere else, then you can keep them private. It's very simple: with hg clone --rev 38 foo foo-38
you will get a new local clone that only contains up to revision 38. You can continue working in foo-38
and push the new (good) changesets you create. You'll still have the old (bad) revisions in your foo
clone. (You are free to rename the clones however you want, e.g., foo
to foo-bad
and foo-38
to foo
.)
Finally, you can also use hg revert --all --rev 38
and then commit. This will create a revision 46 which looks identical to revision 38. You'll then continue working from revision 46. This wont create a fork in the history in the same explicit way as hg update
did, but on the other hand you wont get complains about having multiple heads. I would use hg revert
if I were collaborating with others who have already made their own work based on revision 45. Otherwise, hg update
is more explicit.
This does not answer the question fully, but for anyone who is able to calculate the number of days by which they would like to offset an initial date then the following method will work:
myDate.setUTCDate(myDate.getUTCDate() + offsetDays);
offsetDays can be positive or negative and the result will be correct for any given initial date with any given offset.
OnClick is triggered when the user releases the button. But if you still want to use the TouchListener you need to add it in code. It's just:
myView.setOnTouchListener(new View.OnTouchListener()
{
// Implementation;
});
The reason this convention came into practice is because on UNIX-like operating systems a newline character is treated as a line terminator and/or message boundary (this includes piping between processes, line buffering, etc.).
Consider, for example, that a file with just a newline character is treated as a single, empty line. Conversely, a file with a length of zero bytes is actually an empty file with zero lines. This can be confirmed according to the wc -l
command.
Altogether, this behavior is reasonable because there would be no other way to distinguish between an empty text file versus a text file with a single empty line if the \n
character was merely a line-separator rather than a line-terminator. Thus, valid text files should always end with a newline character. The only exception is if the text file is intended to be empty (no lines).
If you have to use a distutils setup.py
script, there are some commandline options for forcing an installation destination. See http://docs.python.org/install/index.html#alternate-installation. If this problem repeats, you can setup a distutils configuration file, see http://docs.python.org/install/index.html#inst-config-files.
Setting the PYTHONPATH variable is described in tihos post.
Sometimes the exception will not stop after you increase the memory in eclipse ini file. then try below option
Go to Window >> Preferences >> MyEclipse >> Java Enterprise Project >> Web Project >> Deployment Tab Under -> Under Library Deployment Policies UnCheck -> Jars from User Libraries
Angular 8
simply use clear()
method on formArrays :
(this.invoiceForm.controls['other_Partners'] as FormArray).clear();
If none of given solutions fixed the error, the issue probably about Google Cloud Billing settings. You must enable Billing on the Google Cloud Project at billing/enable.
{
"error_message" : "You must enable Billing on the Google Cloud Project at https://console.cloud.google.com/project/_/billing/enable Learn more at https://developers.google.com/maps/gmp-get-started",
"results" : [],
"status" : "REQUEST_DENIED"
}
React Native hasn't provided the gradient color yet. But still, you can do it with a nmp package called react-native-linear-gradient
or you can click here for more info
npm install react-native-linear-gradient --save
import LinearGradient from 'react-native-linear-gradient';
in your application file
<LinearGradient colors={['#4c669f', '#3b5998', '#192f6a']}>
<Text>
Your Text Here
</Text>
</LinearGradient>
More complete sample from here and here.
Or you can check out my layout sample. p.s no need to put API key in the map view.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.gms.maps.MapView
android:id="@+id/map_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
/>
<ListView android:id="@+id/nearby_lv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:layout_weight="1"
/>
</LinearLayout>
As mentioned by @Jim, the file organization is described here. Reproduced for ease of discovery:
For Python modules, the typical layout is:
Lib/<module>.py Modules/_<module>.c (if there’s also a C accelerator module) Lib/test/test_<module>.py Doc/library/<module>.rst
For extension-only modules, the typical layout is:
Modules/<module>module.c Lib/test/test_<module>.py Doc/library/<module>.rst
For builtin types, the typical layout is:
Objects/<builtin>object.c Lib/test/test_<builtin>.py Doc/library/stdtypes.rst
For builtin functions, the typical layout is:
Python/bltinmodule.c Lib/test/test_builtin.py Doc/library/functions.rst
Some exceptions:
builtin type int is at Objects/longobject.c builtin type str is at Objects/unicodeobject.c builtin module sys is at Python/sysmodule.c builtin module marshal is at Python/marshal.c Windows-only module winreg is at PC/winreg.c
If you want to split only by newlines, you can use str.splitlines():
Example:
>>> data = """a,b,c
... d,e,f
... g,h,i
... j,k,l"""
>>> data
'a,b,c\nd,e,f\ng,h,i\nj,k,l'
>>> data.splitlines()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']
With str.split() your case also works:
>>> data = """a,b,c
... d,e,f
... g,h,i
... j,k,l"""
>>> data
'a,b,c\nd,e,f\ng,h,i\nj,k,l'
>>> data.split()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']
However if you have spaces (or tabs) it will fail:
>>> data = """
... a, eqw, qwe
... v, ewr, err
... """
>>> data
'\na, eqw, qwe\nv, ewr, err\n'
>>> data.split()
['a,', 'eqw,', 'qwe', 'v,', 'ewr,', 'err']
Using ant debug after building build.xml file :
in your cmd your root should be your project at first then use the ant debug command e.g:
c:\testApp>ant debug
There is a surprisingly effective way that consists of using the easter eggs.
They differ from version to version.
You need to double escape any RegExp characters (once for the slash in the string and once for the regexp):
"$TESTONE $TESTONE".replace( new RegExp("\\$TESTONE","gm"),"foo")
Otherwise, it looks for the end of the line and 'TESTONE' (which it never finds).
Personally, I'm not a big fan of building regexp's using strings for this reason. The level of escaping that's needed could lead you to drink. I'm sure others feel differently though and like drinking when writing regexes.
The functionality of map
and filter
was intentionally changed to return iterators, and reduce was removed from being a built-in and placed in functools.reduce
.
So, for filter
and map
, you can wrap them with list()
to see the results like you did before.
>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> list(filter(f, range(2, 25)))
[5, 7, 11, 13, 17, 19, 23]
>>> def cube(x): return x*x*x
...
>>> list(map(cube, range(1, 11)))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> import functools
>>> def add(x,y): return x+y
...
>>> functools.reduce(add, range(1, 11))
55
>>>
The recommendation now is that you replace your usage of map and filter with generators expressions or list comprehensions. Example:
>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> [i for i in range(2, 25) if f(i)]
[5, 7, 11, 13, 17, 19, 23]
>>> def cube(x): return x*x*x
...
>>> [cube(i) for i in range(1, 11)]
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>>
They say that for loops are 99 percent of the time easier to read than reduce, but I'd just stick with functools.reduce
.
Edit: The 99 percent figure is pulled directly from the What’s New In Python 3.0 page authored by Guido van Rossum.
A few principles:
you have a std::exception base class, you should have your exceptions derive from it. That way general exception handler still have some information.
Don't throw pointers but object, that way memory is handled for you.
Example:
struct MyException : public std::exception
{
std::string s;
MyException(std::string ss) : s(ss) {}
~MyException() throw () {} // Updated
const char* what() const throw() { return s.c_str(); }
};
And then use it in your code:
void Foo::Bar(){
if(!QueryPerformanceTimer(&m_baz)){
throw MyException("it's the end of the world!");
}
}
void Foo::Caller(){
try{
this->Bar();// should throw
}catch(MyException& caught){
std::cout<<"Got "<<caught.what()<<std::endl;
}
}
best to use crypt for password storing in DB
example code :
$crypted_pass = crypt($password);
//$pass_from_login is the user entered password
//$crypted_pass is the encryption
if(crypt($pass_from_login,$crypted_pass)) == $crypted_pass)
{
echo("hello user!")
}
documentation :
As Get-Date
returns a DateTime object you are able to compare them directly. An example:
(get-date 2010-01-02) -lt (get-date 2010-01-01)
will return false.
This worked for me
$("div").css({"left":"2000px"}).animate({"left":"0px"}, "slow");
For MS SQL Server:
select * from information_schema.columns where table_name = 'tableName'
myokyawhtun's solution worked best for me (using PHP 5.4)
You will still get an error though - I resolved using the following:
Line 269 of fpdf_tpl.php - changed the function parameters to:
function Image($file, $x=null, $y=null, $w=0, $h=0, $type='', $link='',$align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0) {
I also made this same change on line 898 of fpdf.php
I have hit this on two types of systems, “shift planning systems (e.g. factory workers)” and “gas depend management systems)…
23 and 25 hour long days are a pain to cope with, so are 8hr shifts that take 7hr or 9hr. The problem is you will find that each customers, or even department of the customer have different rules they have created (often without documenting) on what they do in these special cases.
Some questions are best not asked of the customer’s until after they have paid for your “off the shelf” software. It is very rare to find a customer that thinks about this type of issue up front when buying software.
I think in all cases you should record time in UTC and convert to/from local time before storing the date/time. However even know which take a given time is in can be hard with Daylight saving and time zones.
Instead of having your Test2 class contain a JPanel, you should have it subclass JPanel:
public class Test2 extends JPanel {
Test2(){
...
}
More details:
JPanel is a subclass of Component, so any method that takes a Component as an argument can also take a JPanel as an argument.
Older versions didn't let you add directly to a JFrame; you had to use JFrame.getContentPane().add(Component). If you're using an older version, this might also be an issue. Newer versions of Java do let you call JFrame.add(Component) directly.
It is up to the http server to decide if there is a limit. The product I work on allows the admin to configure the limit.
jQuery get input value after keypress
https://www.tutsmake.com/jquery-keypress-event-detect-enter-key-pressed/
i = 0; _x000D_
$(document).ready(function(){ _x000D_
$("input").keypress(function(){ _x000D_
$("span").text (i += 1); _x000D_
}); _x000D_
});
_x000D_
<!DOCTYPE html> _x000D_
<html> _x000D_
<head> _x000D_
<title>jQuery keyup() Method By Tutsmake Example</title> _x000D_
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>_x000D_
</head> _x000D_
<body> _x000D_
Enter something: <input type="text"> _x000D_
<p>Keypresses val count: <span>0</span></p> _x000D_
</body> _x000D_
</html>
_x000D_
You can use List<T>.RemoveAt
method:
rows.RemoveAt(rows.Count -1);
I not be able to find squid number in sonar 5.6, with this annotation also works:
@SuppressWarnings({"pmd:AvoidCatchingGenericException", "checkstyle:com.puppycrawl.tools.checkstyle.checks.coding.IllegalCatchCheck"})
FileNotFound
is just an unfortunate exception used to indicate that the web server returned a 404.
So many questions here. I see at least two, maybe three:
*args
being used for?The first question is trivially answered in the Python Standard Library reference:
pop(key[, default])
If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.
The second question is covered in the Python Language Reference:
If the form “*identifier” is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form “**identifier” is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary.
In other words, the pop
function takes at least two arguments. The first two get assigned the names self
and key
; and the rest are stuffed into a tuple called args
.
What's happening on the next line when *args
is passed along in the call to self.data.pop
is the inverse of this - the tuple *args
is expanded to of positional parameters which get passed along. This is explained in the Python Language Reference:
If the syntax *expression appears in the function call, expression must evaluate to a sequence. Elements from this sequence are treated as if they were additional positional arguments
In short, a.pop()
wants to be flexible and accept any number of positional parameters, so that it can pass this unknown number of positional parameters on to self.data.pop()
.
This gives you flexibility; data
happens to be a dict
right now, and so self.data.pop()
takes either one or two parameters; but if you changed data
to be a type which took 19 parameters for a call to self.data.pop()
you wouldn't have to change class a
at all. You'd still have to change any code that called a.pop()
to pass the required 19 parameters though.
Strip won't work. It only removes leading and trailing instances, not everything in between: http://docs.python.org/2/library/stdtypes.html#str.strip
Having fun with filter:
import string
asking = "hello! what's your name?"
predicate = lambda x:x not in string.punctuation
filter(predicate, asking)
Try to concatenate the event charCode to the value you get. Here is a sample of my code:
<input type="text" name="price" onkeypress="return (cnum(event,this))" maxlength="10">
<p id="demo"></p>
js:
function cnum(event, str) {
var a = event.charCode;
var ab = str.value + String.fromCharCode(a);
document.getElementById('demo').innerHTML = ab;
}
The value in ab
will get the latest value in the input field.
With SQL Server 2005, I would use this:
select replace(convert(char(10),getdate(),102),'.',' ')
Results: 2015 03 05
Here's an example program that will send myfile.mp3 by streaming it from disk (that is, it doesn't read the whole file into memory before sending the file). The server listens on port 2000.
[Update] As mentioned by @Aftershock in the comments, util.pump
is gone and was replaced with a method on the Stream prototype called pipe
; the code below reflects this.
var http = require('http'),
fileSystem = require('fs'),
path = require('path');
http.createServer(function(request, response) {
var filePath = path.join(__dirname, 'myfile.mp3');
var stat = fileSystem.statSync(filePath);
response.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
var readStream = fileSystem.createReadStream(filePath);
// We replaced all the event handlers with a simple call to readStream.pipe()
readStream.pipe(response);
})
.listen(2000);
Taken from http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/
Because comparison doesn't work that way. 'Y' || 'y'
is a logical-or operator; it returns 1
(true) if either of its arguments is true. Since 'Y'
and 'y'
are both true, you're comparing *answer
with 1.
What you want is if(*answer == 'Y' || *answer == 'y')
or perhaps:
switch (*answer) {
case 'Y':
case 'y':
/* Code for Y */
break;
default:
/* Code for anything else */
}
String taskLatLng = task.getTask_latlng().replaceAll( "\\(","").replaceAll("\\)","").replaceAll("lat/lng:", "").trim();
In your .xml file within Button add this line--
android:textAllCaps="false"
I wish this helps some one
Result
Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:grid="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="item 0x0"
grid:layout_column="0"
grid:layout_columnWeight="1"
grid:layout_gravity="center"
grid:layout_row="0"
grid:layout_rowWeight="1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="item 0x1"
grid:layout_column="1"
grid:layout_columnWeight="1"
grid:layout_gravity="center"
grid:layout_row="0"
grid:layout_rowWeight="1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="item 0x2"
grid:layout_column="2"
grid:layout_columnWeight="1"
grid:layout_gravity="center"
grid:layout_row="0"
grid:layout_rowWeight="1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="item 1x0"
grid:layout_column="0"
grid:layout_columnWeight="1"
grid:layout_gravity="center"
grid:layout_row="1"
grid:layout_rowWeight="1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="item 1x1"
grid:layout_column="1"
grid:layout_columnWeight="1"
grid:layout_gravity="center"
grid:layout_row="1"
grid:layout_rowWeight="1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="item 1x2"
grid:layout_column="2"
grid:layout_columnWeight="1"
grid:layout_gravity="center"
grid:layout_row="1"
grid:layout_rowWeight="1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="item 2x0"
grid:layout_column="0"
grid:layout_columnWeight="1"
grid:layout_gravity="center"
grid:layout_row="2"
grid:layout_rowWeight="1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="item 2x1"
grid:layout_column="1"
grid:layout_columnWeight="1"
grid:layout_gravity="center"
grid:layout_row="2"
grid:layout_rowWeight="1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="item 2x2"
grid:layout_column="2"
grid:layout_columnWeight="1"
grid:layout_gravity="center"
grid:layout_row="2"
grid:layout_rowWeight="1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="item 3x0"
grid:layout_column="0"
grid:layout_columnWeight="1"
grid:layout_gravity="center"
grid:layout_row="3"
grid:layout_rowWeight="1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="item 3x1"
grid:layout_column="1"
grid:layout_columnWeight="1"
grid:layout_gravity="center"
grid:layout_row="3"
grid:layout_rowWeight="1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="item 3x2"
grid:layout_column="2"
grid:layout_columnWeight="1"
grid:layout_gravity="center"
grid:layout_row="3"
grid:layout_rowWeight="1" />
</android.support.v7.widget.GridLayout>
I also found the apache commons IOUtils
class , so :
InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(myString));
It imports once when the function is called for the first time.
I could imagine doing it this way if I had a function in an imported module that is used very seldomly and is the only one requiring the import. Looks rather far-fetched, though...
You can do something like this :
dictionary = {'ab': {object}, 'cd':{object}, 'ef':{object}}
var keys = Object.keys(dictionary);
for(var i = 0; i < keys.length;i++){
//keys[i] for key
//dictionary[keys[i]] for the value
}
The closest you will ever get to doing such thing is a dissasembler, or debug info (Log2Vis.pdb).
This below code just show the very basic use of delegate concept .. you name the variable and class as per your requirement.
First you need to declare a protocol:
Let's call it MyFirstControllerDelegate.h
@protocol MyFirstControllerDelegate
- (void) FunctionOne: (MyDataOne*) dataOne;
- (void) FunctionTwo: (MyDatatwo*) dataTwo;
@end
Import MyFirstControllerDelegate.h file and confirm your FirstController with protocol MyFirstControllerDelegate
#import "MyFirstControllerDelegate.h"
@interface FirstController : UIViewController<MyFirstControllerDelegate>
{
}
@end
In the implementation file, you need to implement both functions of protocol:
@implementation FirstController
- (void) FunctionOne: (MyDataOne*) dataOne
{
//Put your finction code here
}
- (void) FunctionTwo: (MyDatatwo*) dataTwo
{
//Put your finction code here
}
//Call below function from your code
-(void) CreateSecondController
{
SecondController *mySecondController = [SecondController alloc] initWithSomeData:.];
//..... push second controller into navigation stack
mySecondController.delegate = self ;
[mySecondController release];
}
@end
in your SecondController:
@interface SecondController:<UIViewController>
{
id <MyFirstControllerDelegate> delegate;
}
@property (nonatomic,assign) id <MyFirstControllerDelegate> delegate;
@end
In the implementation file of SecondController.
@implementation SecondController
@synthesize delegate;
//Call below two function on self.
-(void) SendOneDataToFirstController
{
[delegate FunctionOne:myDataOne];
}
-(void) SendSecondDataToFirstController
{
[delegate FunctionTwo:myDataSecond];
}
@end
Here is the wiki article on delegate.
When using JetBrains IDE's with Git, "stashing and unstashing actions are supported in addition to shelving and unshelving. These features have much in common; the major difference is in the way patches are generated and applied. Shelve can operate with either individual files or bunch of files, while Stash can only operate with a whole bunch of changed files at once. Here are some more details on the differences between them."
Just cause I don't see this bit of information in the answers above, the reason the code snippet originally posted doesn't work correctly is because the encodedBytes
variable is a byte[]
and not a String
value. If you pass the byte[]
to a new String()
as below, the code snippet works perfectly.
encodedBytes = Base64.encode(authorization.getBytes(), 0);
authorization = "Basic " + new String(encodedBytes);
You could use the Byte conversion methods from Google Guava.
Example:
byte[] bytes = Longs.toByteArray(12345L);
>>> ','.join('{},{}'.format(i, i + 1) for i in range(1, 100, 4))
'1,2,5,6,9,10,13,14,17,18,21,22,25,26,29,30,33,34,37,38,41,42,45,46,49,50,53,54,57,58,61,62,65,66,69,70,73,74,77,78,81,82,85,86,89,90,93,94,97,98'
That was a quick and quite dirty solution.
Now, for a solution that is suitable for different kinds of progression problems:
def deltas():
while True:
yield 1
yield 3
def numbers(start, deltas, max):
i = start
while i <= max:
yield i
i += next(deltas)
print(','.join(str(i) for i in numbers(1, deltas(), 100)))
And here are similar ideas implemented using itertools:
from itertools import cycle, takewhile, accumulate, chain
def numbers(start, deltas, max):
deltas = cycle(deltas)
numbers = accumulate(chain([start], deltas))
return takewhile(lambda x: x <= max, numbers)
print(','.join(str(x) for x in numbers(1, [1, 3], 100)))
If you need a single fadeIn/Out without an explicit user action (like a mouseover/mouseout) you may use a CSS3 animation
: http://codepen.io/anon/pen/bdEpwW
.elementToFadeInAndOut {
animation: fadeinout 4s linear 1 forwards;
}
@keyframes fadeinout {
0% { opacity: 0; }
50% { opacity: 1; }
100% { opacity: 0; }
}
By setting animation-fill-mode: forwards
the animation will retain its last keyframe
By setting animation-iteration-count: 1
the animation will run just once (change this value if you need to repeat the effect more than once)
You can use this repo: GSBorderLabel
It's quite simple:
GSBorderLabel *myLabel = [[GSBorderLabel alloc] initWithTextColor:aColor
andBorderColor:anotherColor
andBorderWidth:2];
See this JSFiddle
input[type="text"]_x000D_
{_x000D_
border: 0;_x000D_
border-bottom: 1px solid red;_x000D_
outline: 0;_x000D_
}
_x000D_
<form>_x000D_
<input type="text" value="See! ONLY BOTTOM BORDER!" />_x000D_
</form>
_x000D_
As of June 2019 this setting can be found through searching 'Panel' - if you want to change the default there is an option for it as shown in the screenshot:
Here is a version that does not rely on spawning a child process - I needed a standalone script which embedded this functionality. It also does a fractional poll interval, so you can poll quicker. timeout would have been preferred - but I'm stuck on an old server
# wait_on_command <timeout> <poll interval> command
wait_on_command()
{
local timeout=$1; shift
local interval=$1; shift
$* &
local child=$!
loops=$(bc <<< "($timeout * (1 / $interval)) + 0.5" | sed 's/\..*//g')
((t = loops))
while ((t > 0)); do
sleep $interval
kill -0 $child &>/dev/null || return
((t -= 1))
done
kill $child &>/dev/null || kill -0 $child &>/dev/null || return
sleep $interval
kill -9 $child &>/dev/null
echo Timed out
}
slow_command()
{
sleep 2
echo Completed normally
}
# wait 1 sec in 0.1 sec increments
wait_on_command 1 0.1 slow_command
# or call an external command
wait_on_command 1 0.1 sleep 10
Docs says the order of events related to the onkeyxxx event:
If you use like below code, it fits with also backspace and enter user interactions. After you can do what you want in onKeyPress or onKeyUp events. Code block trigger event.preventDefault function if the value is not number,backspace or enter.
onInputKeyDown = event => {
const { keyCode } = event;
if (
(keyCode >= 48 && keyCode <= 57) ||
(keyCode >= 96 && keyCode <= 105) ||
keyCode === 8 || //Backspace key
keyCode === 13 //Enter key
) {
} else {
event.preventDefault();
}
};
Yes this is the way:
Right click on your program, select run -> run configuration then on vm argument
-Denv=EnvironmentName -Dcucumber.options="--tags @ifThereisAnyTag"
Then you can apply and close.
git reset HEAD~1
if you don't want your changes to be gone(unstaged changes). Change, commit and push again git push -f [origin] [branch]
One liner using String.protype.matchAll
(ES2020):
[...sourceStr.matchAll(new RegExp(searchStr, 'gi'))].map(a => a.index)
Using your values:
const sourceStr = 'I learned to play the Ukulele in Lebanon.';
const searchStr = 'le';
const indexes = [...sourceStr.matchAll(new RegExp(searchStr, 'gi'))].map(a => a.index);
console.log(indexes); // [2, 25, 27, 33]
If you're worried about doing a spread and a map()
in one line, I ran it with a for...of
loop for a million iterations (using your strings). The one liner averages 1420ms while the for...of
averages 1150ms on my machine. That's not an insignificant difference, but the one liner will work fine if you're only doing a handful of matches.
You likely need to delete the entry from the migrations table too.
Default log location (rhel) are
General messages:
/var/log/messages
Authentication messages:
/var/log/secure
Mail events:
/var/log/maillog
Check your /etc/syslog.conf
or /etc/syslog-ng.conf
(it depends on which of syslog facility you have installed)
Example:
$ cat /etc/syslog.conf
# Log anything (except mail) of level info or higher.
# Don't log private authentication messages!
*.info;mail.none;authpriv.none /var/log/messages
# The authpriv file has restricted access.
authpriv.* /var/log/secure
# Log all the mail messages in one place.
mail.* /var/log/maillog
#For a start, use this simplified approach.
*.* /var/log/messages
I like being able to use foreach, so I made an extension method and a structure:
public struct EnumeratedInstance<T>
{
public long cnt;
public T item;
}
public static IEnumerable<EnumeratedInstance<T>> Enumerate<T>(this IEnumerable<T> collection)
{
long counter = 0;
foreach (var item in collection)
{
yield return new EnumeratedInstance<T>
{
cnt = counter,
item = item
};
counter++;
}
}
and an example use:
foreach (var ii in new string[] { "a", "b", "c" }.Enumerate())
{
Console.WriteLine(ii.item + ii.cnt);
}
One nice thing is that if you are used to the Python syntax, you can still use it:
foreach (var ii in Enumerate(new string[] { "a", "b", "c" }))
You can check the application-specific data in your emulator as follows,
adb shell
in cmd/data/data/
and navigate into your applicationThere you can find the cache data and databases specific to your application
I mostly agree with the accepted answer, but there is a C++11 option that has not been covered in existing answers:
Example:
struct sandwich {
// Factory methods.
static sandwich ham();
static sandwich spam();
// Move constructor.
sandwich(sandwich &&);
// etc.
};
Then you can construct objects on the stack:
sandwich mine{sandwich::ham()};
As subobjects of other things:
auto lunch = std::make_pair(sandwich::spam(), apple{});
Or dynamically allocated:
auto ptr = std::make_shared<sandwich>(sandwich::ham());
When might I use this?
If, on a public constructor, it is not possible to give meaningful initialisers for all class members without some preliminary calculation, then I might convert that constructor to a static method. The static method performs the preliminary calculations, then returns a value result via a private constructor which just does a member-wise initialisation.
I say 'might' because it depends on which approach gives the clearest code without being unnecessarily inefficient.
I just wrote this function to output an array as text:
Should output nicely formatted array.
IMPORTANT NOTE:
Beware of user input.
This script was created for internal use.
If you intend to use this for public use you will need to add some additional data validation to prevent script injection.
This is not fool proof and should be used with trusted data only.
The following function will output something like:
$var = array(
'primarykey' => array(
'test' => array(
'var' => array(
1 => 99,
2 => 500,
),
),
'abc' => 'd',
),
);
here is the function (note: function is currently formatted for oop implementation.)
public function outArray($array, $lvl=0){
$sub = $lvl+1;
$return = "";
if($lvl==null){
$return = "\t\$var = array(\n";
}
foreach($array as $key => $mixed){
$key = trim($key);
if(!is_array($mixed)){
$mixed = trim($mixed);
}
if(empty($key) && empty($mixed)){continue;}
if(!is_numeric($key) && !empty($key)){
if($key == "[]"){
$key = null;
} else {
$key = "'".addslashes($key)."'";
}
}
if($mixed === null){
$mixed = 'null';
} elseif($mixed === false){
$mixed = 'false';
} elseif($mixed === true){
$mixed = 'true';
} elseif($mixed === ""){
$mixed = "''";
}
//CONVERT STRINGS 'true', 'false' and 'null' TO true, false and null
//uncomment if needed
//elseif(!is_numeric($mixed) && !is_array($mixed) && !empty($mixed)){
// if($mixed != 'false' && $mixed != 'true' && $mixed != 'null'){
// $mixed = "'".addslashes($mixed)."'";
// }
//}
if(is_array($mixed)){
if($key !== null){
$return .= "\t".str_repeat("\t", $sub)."$key => array(\n";
$return .= $this->outArray($mixed, $sub);
$return .= "\t".str_repeat("\t", $sub)."),\n";
} else {
$return .= "\t".str_repeat("\t", $sub)."array(\n";
$return .= $this->outArray($mixed, $sub);
$return .= "\t".str_repeat("\t", $sub)."),\n";
}
} else {
if($key !== null){
$return .= "\t".str_repeat("\t", $sub)."$key => $mixed,\n";
} else {
$return .= "\t".str_repeat("\t", $sub).$mixed.",\n";
}
}
}
if($lvl==null){
$return .= "\t);\n";
}
return $return;
}
Alternately you can use this script I also wrote a while ago:
This one is nice to copy and paste parts of an array.
( Would be near impossible to do that with serialized output )
Not the cleanest function but it gets the job done.
This one will output as follows:
$array['key']['key2'] = 'value';
$array['key']['key3'] = 'value2';
$array['x'] = 7;
$array['y']['z'] = 'abc';
Also take care for user input. Here is the code.
public static function prArray($array, $path=false, $top=true) {
$data = "";
$delimiter = "~~|~~";
$p = null;
if(is_array($array)){
foreach($array as $key => $a){
if(!is_array($a) || empty($a)){
if(is_array($a)){
$data .= $path."['{$key}'] = array();".$delimiter;
} else {
$data .= $path."['{$key}'] = \"".htmlentities(addslashes($a))."\";".$delimiter;
}
} else {
$data .= self::prArray($a, $path."['{$key}']", false);
}
}
}
if($top){
$return = "";
foreach(explode($delimiter, $data) as $value){
if(!empty($value)){
$return .= '$array'.$value."<br>";
}
};
echo $return;
}
return $data;
}
just Disable the Firewall and start again. it worked for me
You can use position:absolute;
to absolutely position an element within a parent div.
When using position:absolute;
the element will be positioned absolutely from the first positioned parent div, if it can't find one it will position absolutely from the window so you will need to make sure the content div is positioned.
To make the content div positioned, all position
values that aren't static will work, but relative
is the easiest since it doesn't change the divs positioning by itself.
So add position:relative;
to the content div, remove the float from the button and add the following css to the button:
position: absolute;
right: 0;
bottom: 0;
1- Just open https://developer.android.com/studio/index.html
2- scroll down to the bottom of that page
3- download last version of tools for your OS (for example tools_r25.2.3-windows.zip)
4- Unzip it
5- Delete folder tools from previous Android Sdk folder
6- Copy new folder tools to Android SDK Folder like this image:
md5=$(md5sum < $file | tr -d ' -')
You should not throw an ArithmeticException. Since the error is in the supplied arguments, throw an IllegalArgumentException
. As the documentation says:
Thrown to indicate that a method has been passed an illegal or inappropriate argument.
Which is exactly what is going on here.
if (divisor == 0) {
throw new IllegalArgumentException("Argument 'divisor' is 0");
}
unsafe.park is pretty much the same as thread.wait, except that it's using architecture specific code (thus the reason it's 'unsafe'). unsafe is not made available publicly, but is used within java internal libraries where architecture specific code would offer significant optimization benefits. It's used a lot for thread pooling.
So, to answer your question, all the thread is doing is waiting for something, it's not really using any CPU. Considering that your original stack trace shows that you're using a lock I would assume a deadlock is going on in your case.
Yes I know you have almost certainly already solved this issue by now. However, you're one of the top results if someone googles sun.misc.unsafe.park. I figure answering the question may help others trying to understand what this method that seems to be using all their CPU is.
I am the author of PowerShell GAC. With PowerShell GAC you can extract assemblies from the GAC without depending on GAC internals like changing folder structures.
Get-GacAssembly SomeCompany* | Get-GacAssemblyFile | Copy-Item -Dest C:\Temp\SomeCompany
Try using batch file
php -S localhost:8000
.bat
extension, server.bat
server.bat
file your server is ready on http://localhost:8000
if you got error php not recognize any internal or external command
then goto environment variable and edit path to php.exe
"C:\wamp\bin\php\php5.4.3"
I wouldn't try to temporarily enable a deprecated feature. According to the MDN documentation for showModalDialog, there's already a polyfill available on Github.
I just used that to add windows.showModalDialog
to a legacy enterprise application as a userscript, but you can obviously also add it in the head of the HTML if you have access to the source.
Try using float: left
(or right
) instead of display: inline
. Inline display replaces list-item display, which is what adds the bullet points.
I was intrigued by this, I ran this random word generator on a dictionary word list. Range: Integer.MIN_VALUE to Integer.MAX_VALUE
I got 15131 hits.
int[] arrInt = {-2146926310, -1885533740, -274140519,
-2145247212, -1845077092, -2143584283,
-2147483454, -2138225126, -2147375969};
for(int seed : arrInt){
System.out.print(randomString(seed) + " ");
}
Prints
the quick browny fox jumps over a lazy dog
Forking creates an entirely new repository from existing repository (simply doing git clone on gitHub/bitbucket)
Forks are best used: when the intent of the ‘split’ is to create a logically independent project, which may never reunite with its parent.
Branch strategy creates a new branch over the existing/working repository
Branches are best used: when they are created as temporary places to work through a feature, with the intent to merge the branch with the origin.
More Specific :- In open source projects it is the owner of the repository who decides who can push to the repository. However, the idea of open source is that everybody can contribute to the project.
This problem is solved by forks: any time a developer wants to change something in an open source project, they don’t clone the official repository directly. Instead, they fork it to create a copy. When the work is finished, they make a pull request so that the owner of the repository can review the changes and decide whether to merge them to his project.
At its core forking is similar to feature branching, but instead of creating branches a fork of the repository is made, and instead of doing a merge request you create a pull request.
The below links provide the difference in a well-explained manner :
https://blog.gitprime.com/the-definitive-guide-to-forks-and-branches-in-git/
If your IN
clause is too big for MSSQL to handle, you can use a TableValueParameter with Dapper pretty easily.
Create your TVP type in MSSQL:
CREATE TYPE [dbo].[MyTVP] AS TABLE([ProviderId] [int] NOT NULL)
Create a DataTable
with the same column(s) as the TVP and populate it with values
var tvpTable = new DataTable();
tvpTable.Columns.Add(new DataColumn("ProviderId", typeof(int)));
// fill the data table however you wish
Modify your Dapper query to do an INNER JOIN
on the TVP table:
var query = @"SELECT * FROM Providers P
INNER JOIN @tvp t ON p.ProviderId = t.ProviderId";
Pass the DataTable in your Dapper query call
sqlConn.Query(query, new {tvp = tvpTable.AsTableValuedParameter("dbo.MyTVP")});
This also works fantastically when you want to do a mass update of multiple columns - simply build a TVP and do an UPDATE
with an inner join to the TVP.
You can try like this:
<input type="number" name="input">
<input type="submit" value="Next" formnovalidate="formnovalidate">
But be careful: If your input contains something other than a number, it will not be transmitted to the server.
you can unpack your tuples and get only the first element using a list comprehension:
l = [(1, u'abc'), (2, u'def')]
[f for f, *_ in l]
output:
[1, 2]
this will work no matter how many elements you have in a tuple:
l = [(1, u'abc'), (2, u'def', 2, 4, 5, 6, 7)]
[f for f, *_ in l]
output:
[1, 2]
I uninstalled ASP.NET MVC 4 using the Windows Control Panel, then reinstalled it by running AspNetMVC4Setup.exe
(which I got from https://www.microsoft.com/en-us/download/details.aspx?id=30683), and that fixed the issue for me.
In other words, I didn't need to use Nuget or Visual Studio.
if (Enum.IsDefined(typeof(foo), value))
{
return (Foo)Enum.Parse(typeof(foo), value);
}
Hope this helps
Edit This answer got down voted as value in my example is a string, where as the question asked for an int. My applogies; the following should be a bit clearer :-)
Type fooType = typeof(foo);
if (Enum.IsDefined(fooType , value.ToString()))
{
return (Foo)Enum.Parse(fooType , value.ToString());
}
openssl x509 -outform der -in your-cert.pem -out your-cert.crt
Well, I would check if any of your columns are set as ReadOnly
. I have never had to use BeginEdit, but maybe there is some legitimate use. Once you have done dataGridView1.Columns[".."].ReadOnly = False;
, the fields that are not ReadOnly
should be editable. You can use the DataGridView CellEnter
event to determine what cell was entered and then turn on editing on those cells after you have passed editing from the first two columns to the next set of columns and turn off editing on the last two columns.
You want to create an alias by simply typing:
c:\>alias kgs kubectl get svc
Created alias for kgs=kubectl get svc
And use the alias as follows:
c:\>kgs alfresco-svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
alfresco-svc ClusterIP 10.7.249.219 <none> 80/TCP 8d
Just add the following alias.bat
file to you path. It simply creates additional batch files in the same directory as itself.
@echo off
echo.
for /f "tokens=1,* delims= " %%a in ("%*") do set ALL_BUT_FIRST=%%b
echo @echo off > C:\Development\alias-script\%1.bat
echo echo. >> C:\Development\alias-script\%1.bat
echo %ALL_BUT_FIRST% %%* >> C:\Development\alias-script\%1.bat
echo Created alias for %1=%ALL_BUT_FIRST%
An example of the batch file this created called kgs.bat
is:
@echo off
echo.
kubectl get svc %*
Watch your trailing slashes too. I found that including images/*
in my ignore setting file did not ignore ./images/
. When I ran svn status -u
it still showed ? images
. So, I just changed the ignore setting to just images
, no slashes. Ran a status check and that cleared it out.
The FolderBrowserDialog class is the best option.
If you add and remove the innerHTML, all javascript, css and more will be loaded twice, and the events will fire twice (happened to me), is better hide content, using jQuery and css like this:
function printDiv(selector) {
$('body .site-container').css({display:'none'});
var content = $(selector).clone();
$('body .site-container').before(content);
window.print();
$(selector).first().remove();
$('body .site-container').css({display:''});
}
The div "site-container" contain all site, so you can call the function like:
printDiv('.someDiv');
From the previous answers just adding code sample.
class Program
{
static void Main(string[] args)
{
int enumlen = Enum.GetNames(typeof(myenum)).Length;
Console.Write(enumlen);
Console.Read();
}
public enum myenum
{
value1,
value2
}
}
Yes, it's built in to jQuery. See the docs at jquery documentation.
ajaxError may be what you want.
Use the Node.js console.time()
and console.timeEnd()
:
var i;
console.time("dbsave");
for(i = 1; i < LIMIT; i++){
db.users.save({id : i, name : "MongoUser [" + i + "]"}, end);
}
end = function(err, saved) {
console.log(( err || !saved )?"Error":"Saved");
if(--i === 1){console.timeEnd("dbsave");}
};
Of course you can sample each row:
sapply (1:4, function (row) df1[row,]<<-sample(df1[row,]))
will shuffle the rows itself, so the number of 1
's in each row doesn't change. Small changes and it also works great with columns, but this is a exercise for the reader :-P
Makes sure when running junit test cases, you have the log4j.properties or log4j.xml file in your test/resources folder.
You can use the CellMouseEnter and CellMouseLeave to track the row number that the mouse is currently hovering over.
Then use a ContextMenu object to display you popup menu, customised for the current row.
Here's a quick and dirty example of what I mean...
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
ContextMenu m = new ContextMenu();
m.MenuItems.Add(new MenuItem("Cut"));
m.MenuItems.Add(new MenuItem("Copy"));
m.MenuItems.Add(new MenuItem("Paste"));
int currentMouseOverRow = dataGridView1.HitTest(e.X,e.Y).RowIndex;
if (currentMouseOverRow >= 0)
{
m.MenuItems.Add(new MenuItem(string.Format("Do something to row {0}", currentMouseOverRow.ToString())));
}
m.Show(dataGridView1, new Point(e.X, e.Y));
}
}
starts with file:///
and ends with filename
should work:
<img src="file:///C:/Users/91860/Desktop/snow.jpg" alt="Snow" style="width:100%;">
This JSFiddle project could help you to understand how modulus work: http://jsfiddle.net/elazar170/7hhnagrj
The modulus function works something like this:
function modulus(x,y){
var m = Math.floor(x / y);
var r = m * y;
return x - r;
}
If, like me, you don't like to rely on JavaScript for links on buttons. You can also use a anchor and style it like your buttons using CSS.
<a href="/Controller/View" class="Button">Text</a>
one url to the same view! like so!
urls.py
url(r'^$', views.landing.as_view(), name = 'landing'),
views.py
class landing(View):
template_name = '/home.html'
form_class1 = forms.pynamehere1
form_class2 = forms.pynamehere2
def get(self, request):
form1 = self.form_class1(None)
form2 = self.form_class2(None)
return render(request, self.template_name, { 'register':form1, 'login':form2,})
def post(self, request):
if request.method=='POST' and 'htmlsubmitbutton1' in request.POST:
## do what ever you want to do for first function ####
if request.method=='POST' and 'htmlsubmitbutton2' in request.POST:
## do what ever you want to do for second function ####
## return def post###
return render(request, self.template_name, {'form':form,})
/home.html
<!-- #### form 1 #### -->
<form action="" method="POST" >
{% csrf_token %}
{{ register.as_p }}
<button type="submit" name="htmlsubmitbutton1">Login</button>
</form>
<!--#### form 2 #### -->
<form action="" method="POST" >
{% csrf_token %}
{{ login.as_p }}
<button type="submit" name="htmlsubmitbutton2">Login</button>
</form>
//Note: This resolves as true even if all $_POST values are empty strings
if (!empty($_POST))
{
// handle post data
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
if (isset($_POST['fromPerson']) )
{
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
The answers are working fine with xls format but, in my case, it didn't work for xlsx format. Thus I added some code here. it works both xls and xlsx format.
I took the sample from the official sample link.
Hope it may help !
function fileReader(oEvent) {
var oFile = oEvent.target.files[0];
var sFilename = oFile.name;
var reader = new FileReader();
var result = {};
reader.onload = function (e) {
var data = e.target.result;
data = new Uint8Array(data);
var workbook = XLSX.read(data, {type: 'array'});
console.log(workbook);
var result = {};
workbook.SheetNames.forEach(function (sheetName) {
var roa = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {header: 1});
if (roa.length) result[sheetName] = roa;
});
// see the result, caution: it works after reader event is done.
console.log(result);
};
reader.readAsArrayBuffer(oFile);
}
// Add your id of "File Input"
$('#fileUpload').change(function(ev) {
// Do something
fileReader(ev);
}
To add rows to existing DataTable in Dataset:
DataRow drPartMtl = DSPartMtl.Tables[0].NewRow();
drPartMtl["Group"] = "Group";
drPartMtl["BOMPart"] = "BOMPart";
DSPartMtl.Tables[0].Rows.Add(drPartMtl);
You're declaring a virtual
function and not defining it:
virtual void calculateCredits();
Either define it or declare it as:
virtual void calculateCredits() = 0;
Or simply:
virtual void calculateCredits() { };
Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table
You are indeed passing the first data item to the each function.
Pass data.programs to the each function instead. Change the code to as below:
<script>
$(document).ready(function() {
var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };
$.each(data.programs, function(key,val) {
alert(key+val);
});
});
</script>
click: WAMP icon->Apache->Apache modules->chose rewrite_module
and do restart for all services.
I already found it:
SELECT grantee, privilege_type
FROM information_schema.role_table_grants
WHERE table_name='mytable'
I had the error
Error: could not find function
some.function
happen when doing R CMD check of a package I was making with RStudio. I found adding
exportPattern(".")
to the NAMESPACE file did the trick. As a sidenote, I had initially configured RStudio to use ROxygen to make the documentation -- and selected the configuration where ROxygen would write my NAMESPACE file for me, which kept erasing my edits. So, in my instance I unchecked NAMESPACE from the Roxygen configuration and added exportPattern(".") to NAMESPACE to solve this error.
history.go(-1) this is a possible solution to the problem but it does not work in incognito mode as history is not maintained by the browser in this mode.
I happened to come up with a solution very similar to @Andrew, only DRY
class MetaFoo(type):
def __new__(mc1, name, bases, nmspc):
nmspc.update({'thingy': MetaFoo.thingy})
return super(MetaFoo, mc1).__new__(mc1, name, bases, nmspc)
@property
def thingy(cls):
if not inspect.isclass(cls):
cls = type(cls)
return cls._thingy
@thingy.setter
def thingy(cls, value):
if not inspect.isclass(cls):
cls = type(cls)
cls._thingy = value
class Foo(metaclass=MetaFoo):
_thingy = 23
class Bar(Foo)
_thingy = 12
This has the best of all answers:
The "metaproperty" is added to the class, so that it will still be a property of the instance
In my case, I actually customized _thingy
to be different for every child, without defining it in each class (and without a default value) by:
def __new__(mc1, name, bases, nmspc):
nmspc.update({'thingy': MetaFoo.services, '_thingy': None})
return super(MetaFoo, mc1).__new__(mc1, name, bases, nmspc)
It happens to me only when modifying the XML files on the project. If you rebuild the entire project before running (Build > Rebuild Project) it doesn't show up anymore.
I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.
What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;
If you do go down the inline-block route then you may have to consider my favorite IE hack.
width:100px;
display:inline-block;
zoom:1; //IE only
*display:inline; //IE only
Happy Coding :)
This is my answer
- (IBAction)Result:(id)sender
{
self.statusLabel.text = DataSource[[pickerViewTool selectedRowInComponent:0]];
}
This was done with PyCharm Community 2019.1
Take a look at the documentation for HttpServletRequest
.
In order to build the URL in your example you will need to use:
getScheme()
getServerName()
getServerPort()
getContextPath()
Here is a method that will return your example:
public static String getURLWithContextPath(HttpServletRequest request) {
return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
}
The problem is that simple console can't edit the registry. No need to edit the registry by hand, just launch the groovysh
once with administrative priveleges. All subsequent launches work without error.
I adapted the SetTags() search function above (which should be replaced by the equivalent set tags+=./tags;/
) to work for cscope. Seems to work!
"cscope file-searching alternative
function SetCscope()
let curdir = getcwd()
while !filereadable("cscope.out") && getcwd() != "/"
cd ..
endwhile
if filereadable("cscope.out")
execute "cs add " . getcwd() . "/cscope.out"
endif
execute "cd " . curdir
endfunction
call SetCscope()
This can also be a file that contains images or charts, see this: http://kb.tableausoftware.com/articles/knowledgebase/resolving-error-external-table-is-not-in-expected-format
The recommendation is to save as Excel 2003
Specify the /FA switch for the cl compiler. Depending on the value of the switch either only assembly code or high-level code and assembly code is integrated. The filename gets .asm file extension. Here are the supported values:
How can one test existence of an item in localStorage
?
this method works in internet explorer.
<script>
try{
localStorage.getItem("username");
}catch(e){
alert("we are in catch "+e.print);
}
</script>
1.Add a new folder to your project
2.Copy the form into that
3.Change the name in properties as well as change the file name
4.Check each form for their class name (they shouldn't be same)
In Mysql, you can not update one table by subquery the same table.
You can separate the query in two parts, or do
UPDATE TABLE_A AS A INNER JOIN TABLE_A AS B ON A.field1 = B.field1 SET field2 = ?
>>> u"\u00b0"
u'\xb0'
>>> print _
°
BTW, all I did was search "unicode degree" on Google. This brings up two results: "Degree sign U+00B0" and "Degree Celsius U+2103", which are actually different:
>>> u"\u2103"
u'\u2103'
>>> print _
?
Bootstrap 2
If you want to change the caret/arrow as well, do the following:
.red-tooltip + .tooltip > .tooltip-inner {background-color: #f00;}
.red-tooltip + .tooltip > .tooltip-arrow {border-bottom-color: #f00;}
or
.red-tooltip + .tooltip > .tooltip-inner, .red-tooltip + .tooltip > .tooltip-arrow {background-color: #f00;}
jsFiddle: http://jsfiddle.net/technotarek/2htZe/
UPDATE: Bootstrap 3
You have to be specific for the direction of the tooltip in Bootstrap 3. For example:
.tooltip.top .tooltip-inner {
background-color:red;
}
.tooltip.top .tooltip-arrow {
border-top-color: red;
}
jsFiddle for all tooltip directions using Bootstrap 3: http://jsfiddle.net/technotarek/L2rLE/
We can use this "WHERE id IN" clause if we filter the input array properly. Something like this:
$galleries = array();
foreach ($_REQUEST['gallery_id'] as $key => $val) {
$galleries[$key] = filter_var($val, FILTER_SANITIZE_NUMBER_INT);
}
Like the example below:
$galleryIds = implode(',', $galleries);
I.e. now you should safely use $query = "SELECT * FROM galleries WHERE id IN ({$galleryIds})";
Setup https://docs.djangoproject.com/en/dev/topics/logging/ and then these error's will echo where you point them. By default they tend to go off in the weeds so I always start off with a good logging setup before anything else.
Here is a really good example for a basic setup: https://ian.pizza/b/2013/04/16/getting-started-with-django-logging-in-5-minutes/
Edit: The new link is moved to: https://github.com/ianalexander/ianalexander/blob/master/content/blog/getting-started-with-django-logging-in-5-minutes.html
You should get the value of the current date to get the date with (ms) and add (30 * 60 *1000) to it. Now you have (current date + 30 min) with ms
console.log('with ms', Date.now() + (30 * 60 * 1000))_x000D_
console.log('new Date', new Date(Date.now() + (30 * 60 * 1000)))
_x000D_
Use decode
:
print(curses.version.decode())
# 2.2
You can use \t
to create a tab in a file.
Assuming MySQL (EDIT: posted before the SQL variant was supplied):
ALTER TABLE myTable ADD myNewColumn VARCHAR(255) AFTER myOtherColumn
The AFTER keyword tells MySQL where to place the new column. You can also use FIRST to flag the new column as the first column in the table.
I know this isn't the best way to do it, but right click the button in question, events, key, key typed. This is a simple way to do it, but reacts to any key
The query execution happens on all get methods like
$this->db->get('table_name');
$this->db->get_where('table_name',$array);
While last_query contains the last query which was run
$this->db->last_query();
If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now you can write query and get it in a variable
$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();
Now reset query so if you want to write another query the object will be cleared.
$this->db->_reset_select();
And the thing is done. Cheers!!! Note : While using this way you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
Check that All Files are Included in Your Project:
I had this same error pop up after I updated cLion. After hours of tinkering, I noticed one of my files was not included in the project target. After I added it back to the active project, I stopped getting the undefined reference to winmain16, and the code compiled.
Edit: It's also worthwhile to check the build settings within your IDE.
(Not sure if this error is related to having recently updated the IDE - could be causal or simply correlative. Feel free to comment with any insight on that factor!)
If you're using an implementation of System.Collections.IEnumerable
you can do like following to convert it to a List
. The following uses Enumerable.Cast method to convert IEnumberable
to a Generic List
.
//ArrayList Implements IEnumerable interface
ArrayList _provinces = new System.Collections.ArrayList();
_provinces.Add("Western");
_provinces.Add("Eastern");
List<string> provinces = _provinces.Cast<string>().ToList();
If you're using Generic version IEnumerable<T>
, The conversion is straight forward. Since both are generics, you can do like below,
IEnumerable<int> values = Enumerable.Range(1, 10);
List<int> valueList = values.ToList();
But if the IEnumerable
is null, when you try to convert it to a List
, you'll get
ArgumentNullException
saying Value cannot be null.
IEnumerable<int> values2 = null;
List<int> valueList2 = values2.ToList();
Therefore as mentioned in the other answer, remember to do a null
check before converting it to a List
.
Use atof()
But this is deprecated, use this instead:
const char* flt = "4.0800";
float f;
sscanf(flt, "%f", &f);
http://www.cplusplus.com/reference/clibrary/cstdlib/atof/
atof()
returns 0
for both failure and on conversion of 0.0
, best to not use it.
It should be understood that from a performance standpoint there are no differences between @temp tables and #temp tables that favor variables. They reside in the same place (tempdb) and are implemented the same way. All the differences appear in additional features. See this amazingly complete writeup: https://dba.stackexchange.com/questions/16385/whats-the-difference-between-a-temp-table-and-table-variable-in-sql-server/16386#16386
Although there are cases where a temp table can't be used such as in table or scalar functions, for most other cases prior to v2016 (where even filtered indexes can be added to a table variable) you can simply use a #temp table.
The drawback to using named indexes (or constraints) in tempdb is that the names can then clash. Not just theoretically with other procedures but often quite easily with other instances of the procedure itself which would try to put the same index on its copy of the #temp table.
To avoid name clashes, something like this usually works:
declare @cmd varchar(500)='CREATE NONCLUSTERED INDEX [ix_temp'+cast(newid() as varchar(40))+'] ON #temp (NonUniqueIndexNeeded);';
exec (@cmd);
This insures the name is always unique even between simultaneous executions of the same procedure.
just write it yourself using simple recursion:
public List<File> addFiles(List<File> files, File dir)
{
if (files == null)
files = new LinkedList<File>();
if (!dir.isDirectory())
{
files.add(dir);
return files;
}
for (File file : dir.listFiles())
addFiles(files, file);
return files;
}