I created a working CodePen example demonstrating how to do this the correct way in AngularJS. The Angular $window service should be used to access any global objects since directly accessing window
makes testing more difficult.
HTML:
<section ng-app="myapp" ng-controller="MainCtrl">
Value of global variable read by AngularJS: {{variable1}}
</section>
JavaScript:
// global variable outside angular
var variable1 = true;
var app = angular.module('myapp', []);
app.controller('MainCtrl', ['$scope', '$window', function($scope, $window) {
$scope.variable1 = $window.variable1;
}]);
If you want a real timer you need to use the date object.
Calculate the difference.
Format your string.
window.onload=function(){
var start=Date.now(),r=document.getElementById('r');
(function f(){
var diff=Date.now()-start,ns=(((3e5-diff)/1e3)>>0),m=(ns/60)>>0,s=ns-m*60;
r.textContent="Registration closes in "+m+':'+((''+s).length>1?'':'0')+s;
if(diff>3e5){
start=Date.now()
}
setTimeout(f,1e3);
})();
}
Example
not so precise timer
var time=5*60,r=document.getElementById('r'),tmp=time;
setInterval(function(){
var c=tmp--,m=(c/60)>>0,s=(c-m*60)+'';
r.textContent='Registration closes in '+m+':'+(s.length>1?'':'0')+s
tmp!=0||(tmp=time);
},1000);
If you know the list of ids try this query:
SELECT * FROM `Buses` WHERE BusId IN (`list of busIds`)
or if you pull them from another table list of busIds
could be another subquery:
SELECT * FROM `Buses` WHERE BusId IN (SELECT SomeId from OtherTable WHERE something = somethingElse)
If you need to compare to another table you need a join:
SELECT * FROM `Buses` JOIN OtheTable on Buses.BusesId = OtehrTable.BusesId
The issue is because you have a bean of type SuggestionService created through @Component annotation and also through the XML config . As explained by JB Nizet, this will lead to the creation of a bean with name 'suggestionService' created via @Component and another with name 'SuggestionService' created through XML .
When you refer SuggestionService by @Autowired, in your controller, Spring autowires "by type" by default and find two beans of type 'SuggestionService'
You could do the following
Remove @Component from your Service and depend on mapping via XML - Easiest
Remove SuggestionService from XML and autowire the dependencies - use util:map to inject the indexSearchers map.
Use @Resource instead of @Autowired to pick the bean by its name .
@Resource(name="suggestionService")
private SuggestionService service;
or
@Resource(name="SuggestionService")
private SuggestionService service;
both should work.The third is a dirty fix and it's best to resolve the bean conflict through other ways.
Compact form for short commands (no 'echo'):
IF "%ID%"=="0" ( ... & ... & ... ) ELSE ^
IF "%ID%"=="1" ( ... ) ELSE ^
IF "%ID%"=="2" ( ... ) ELSE ^
REM default case...
After ^
must be an immediate line end, no spaces.
This is the functional programming method. It lifts the tuple expansion feature out of syntax sugar:
apply_tuple = lambda f, t: f(*t)
Redefine apply_tuple
via curry
to save a lot of partial
calls in the long run:
from toolz import curry
apply_tuple = curry(apply_tuple)
Example usage:
from operator import add, eq
from toolz import thread_last
thread_last(
[(1,2), (3,4)],
(map, apply_tuple(add)),
list,
(eq, [3, 7])
)
# Prints 'True'
you can use raiserror
. Read more details here
--from MSDN
BEGIN TRY
-- RAISERROR with severity 11-19 will cause execution to
-- jump to the CATCH block.
RAISERROR ('Error raised in TRY block.', -- Message text.
16, -- Severity.
1 -- State.
);
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
-- Use RAISERROR inside the CATCH block to return error
-- information about the original error that caused
-- execution to jump to the CATCH block.
RAISERROR (@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
);
END CATCH;
EDIT
If you are using SQL Server 2012+ you can use throw
clause. Here are the details.
For example: To go My folder project on source, i need to up two folder. I make this algorim to 2 days week and into four hour
public static void LimpiarArchivosViejos()
{
DayOfWeek today = DateTime.Today.DayOfWeek;
int hora = DateTime.Now.Hour;
if(today == DayOfWeek.Monday || today == DayOfWeek.Tuesday && hora < 12 && hora > 8)
{
CleanPdfOlds();
CleanExcelsOlds();
}
}
private static void CleanPdfOlds(){
string[] files = Directory.GetFiles("../../Users/Maxi/Source/Repos/13-12-2017_config_pdfListados/ApplicaAccWeb/Uploads/Reports");
foreach (string file in files)
{
FileInfo fi = new FileInfo(file);
if (fi.CreationTime < DateTime.Now.AddDays(-7))
fi.Delete();
}
}
private static void CleanExcelsOlds()
{
string[] files2 = Directory.GetFiles("../../Users/Maxi/Source/Repos/13-12-2017_config_pdfListados/ApplicaAccWeb/Uploads/Excels");
foreach (string file in files2)
{
FileInfo fi = new FileInfo(file);
if (fi.CreationTime < DateTime.Now.AddDays(-7))
fi.Delete();
}
}
As others have said, you could use Object.keys()
, but who cares about older browsers, right?
Well, I do.
Try this. array_keys
from PHPJS ports PHP's handy array_keys
function, so it can be used in JavaScript.
At a glance, it uses Object.keys
if supported, but it handles the case where it isn't very easily. It even includes filtering the keys based on values you might be looking for (optional) and a toggle for whether or not to use strict comparison ===
versus typecasting comparison ==
(optional).
I was facing with this problem some time ago and I found java.util.LinkedList
is best for my case. It has several methods, with different namings, but they're doing what is needed:
push() -> LinkedList.addLast(); // Or just LinkedList.add();
pop() -> LinkedList.pollLast();
shift() -> LinkedList.pollFirst();
unshift() -> LinkedList.addFirst();
Do you have something against splitting it up?
...FROM <blah>
WHERE
(fieldA LIKE '%THIS%' OR fieldA LIKE '%THAT%')
AND something = else
I know I'm resurrecting an ancient question, but I was trying to solve this problem today and have an alternate solution. Toggling caching when I want to test was not really acceptable for me, and as others mentioned, hard refreshing (ctrl+shift+r) doesn't always work.
Instead, I opted to put the following in my vhost.conf file (can also be done in .htaccess) on my dev environment:
<FilesMatch "\.(js|css)$">
FileETag None
<IfModule mod_headers.c>
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</IfModule>
</FilesMatch>
On my dev environment, this ensures that js and css are always retrieved. Additionally it doesn't affect the rest of my browsing, and it also works for all browsers, so testing in chrome / ie etc is also easy.
Found the snippet here, some other handy apache tricks as well: http://www.askapache.com/htaccess/using-http-headers-with-htaccess.html#prevent-caching-with-htaccess
To make sure that my clients always see the latest version on production, we increment the query string on the js include on each update, ie
jquery.somefile.js?v=0.5
This forces my clients' browsers to update their local cache when they see a new querystring, but then caches the new copy until the file is updated again
If you are using Python3 with pathlib
you can access os.stat()
information using the Path.stat()
method, which has the attribute st_size
(file size in bytes):
>>> from pathlib import Path
>>> mypath = Path("path/to/my/file")
>>> mypath.stat().st_size == 0 # True if empty
type "syso" and then press ctrl + space
OR
type "sysout" and then press ctrl + space
My issue was with my Android Studio install.
I am building out a new CI server and although I installed Android Studio and hooked up the SDK, etc., I did not open the studio with the project -- instead just went to the command line to build. When I subsequently opened the project in the studio, it started prompting for all sorts of updates. Followed the bouncing-ball and then I was able to reach my USB tethered device.
Hopefully, this is helpful for Build Master and DevOps as a "got-cha" to avoid.
I ended up doing something similar to what mark dibe did, but I needed to figure out the spacing for a slightly different manner.
The col-x
classes in bootstrap can be an absolute lifesaver. I ended up doing something similar to this:
<div class="row col-12">
<div class="col-3">Title</div>
</div>
<div class="row col-12">
<div class="col-3">Bootstrap Switch</div>
<div>
This allowed me to align titles and input switches in a nicely spaced manner. The same idea can be applied to the buttons and allow you to stop the buttons from touching.
(Side note: I wanted this to be a comment on the above link, but my reputation is not high enough)
Enabling delayed variable expansion solves you problem, the script produces "hi":
setlocal EnableDelayedExpansion
set var1=A
set var2=B
set AB=hi
set newvar=!%var1%%var2%!
echo %newvar%
You're storing the .Text
properties of the textboxes directly into the database, this doesn't work. The .Text
properties are String
s (i.e. simple text) and not typed as DateTime
instances. Do the conversion first, then it will work.
Do this for each date parameter:
Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) )
Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse
or DateTime.TryParseExact
, but implementing that is an exercise for the reader.
As your query string is a literal, and assuming your dates are properly stored as DATE
you should use date literals:
SELECT * FROM OrderArchive
WHERE OrderDate <= DATE '2015-12-31'
If you want to use TO_DATE
(because, for example, your query value is not a literal), I suggest you to explicitly set the NLS_DATE_LANGUAGE parameter as you are using US abbreviated month names. That way, it won't break on some localized Oracle Installation:
SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014', 'DD MON YYYY',
'NLS_DATE_LANGUAGE = American');
Eloquent uses the query builder internally, so you can do:
$users = User::orderBy('name', 'desc')
->groupBy('count')
->having('count', '>', 100)
->get();
Using file extension and getimagesize
function to detect if uploaded file has right format is just the entry level check and it can simply bypass by uploading a file with true extension and some byte of an image header but wrong content.
for being secure and safe you may make thumbnail/resize (even with original image sizes) the uploaded picture and save this version instead the uploaded one.
Also its possible to get uploaded file content and search it for special character like <?php
to find the file is image or not.
set myDIR=LOG
IF not exist %myDIR% (mkdir %myDIR%)
For Eclipse, modify project.properties
like this: (your path please)
android.library.reference.1=../../../../workspace/appcompat_v7_22
And remove android-support-v4.jar
file in your project's libs
folder.
Application.Exit
is for Windows Forms applications - it informs all message pumps that they should terminate, waits for them to finish processing events and then terminates the application. Note that it doesn't necessarily force the application to exit.
Environment.Exit
is applicable for all Windows applications, however it is mainly intended for use in console applications. It immediately terminates the process with the given exit code.
In general you should use Application.Exit
in Windows Forms applications and Environment.Exit
in console applications, (although I prefer to let the Main
method / entry point run to completion rather than call Environment.Exit
in console applications).
For more detail see the MSDN documentation.
As far as I know List<T>
implements IEnumerable<T>
. It means that you do not have to convert or cast anything.
Eclipse by default does not know about your external Maven installation and uses the embedded one. Therefore in order for Eclipse to use your global settings you need to set it in menu Settings ? Maven ? Installations.
Fromthe Javadoc of Method.invoke():
If the underlying method is static, then the specified obj argument is ignored. It may be null.
What happens when you
Class klass = ...; Method m = klass.getDeclaredMethod(methodName, paramtypes); m.invoke(null, args)
var attr = $(this).attr('name');
// For some browsers, `attr` is undefined; for others,
// `attr` is false. Check for both.
if (typeof attr !== typeof undefined && attr !== false) {
// ...
}
change type="number" to type="tel"
(eclipse-workspace)\.metadata\.plugins\org.eclipse.wst.server.core
and delete all tmp folders.Install brew
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Update and verify you are good with
brew update
brew doctor
Install mongodb with
brew install mongodb
Create folder for mongo data files:
mkdir -p /data/db
Set permissions
sudo chown -R `id -un` /data/db
Open another terminal window & run and keep running a mongo server/daemon
mongod
Return to previous terminal and run a mongodb shell to access data
mongo
The Shell:
quit()
The Server
ctrl-c
UIImage*image = [UIImage imageNamed:@"logo"];
float targetHeight = self.navigationController.navigationBar.frame.size.height;
float logoRatio = image.size.width / image.size.height;
float targetWidth = targetHeight * logoRatio;
UIImageView*logoView = [[UIImageView alloc] initWithImage:image];
// X or Y position can not be manipulated because autolayout handles positions.
//[logoView setFrame:CGRectMake((self.navigationController.navigationBar.frame.size.width - targetWidth) / 2 , (self.navigationController.navigationBar.frame.size.height - targetHeight) / 2 , targetWidth, targetHeight)];
[logoView setFrame:CGRectMake(0, 0, targetWidth, targetHeight)];
self.navigationItem.titleView = logoView;
// How much you pull out the strings and struts, with autolayout, your image will fill the width on navigation bar. So setting only height and content mode is enough/
[logoView setContentMode:UIViewContentModeScaleAspectFit];
/* Autolayout constraints also can not be manipulated since navigation bar has immutable constraints
self.navigationItem.titleView.translatesAutoresizingMaskIntoConstraints = false;
NSDictionary*metricsArray = @{@"width":[NSNumber numberWithFloat:targetWidth],@"height":[NSNumber numberWithFloat:targetHeight],@"margin":[NSNumber numberWithFloat:20]};
NSDictionary*viewsArray = @{@"titleView":self.navigationItem.titleView};
[self.navigationItem.titleView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-(>margin=)-H:[titleView(width)]-(>margin=)-|" options:NSLayoutFormatAlignAllCenterX metrics:metricsArray views:viewsArray]];
[self.navigationItem.titleView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[titleView(height)]" options:0 metrics:metricsArray views:viewsArray]];
NSLog(@"%f", self.navigationItem.titleView.width );
*/
So all we actually need is
UIImage*image = [UIImage imageNamed:@"logo"];
UIImageView*logoView = [[UIImageView alloc] initWithImage:image];
float targetHeight = self.navigationController.navigationBar.frame.size.height;
[logoView setFrame:CGRectMake(0, 0, 0, targetHeight)];
[logoView setContentMode:UIViewContentModeScaleAspectFit];
self.navigationItem.titleView = logoView;
if you are using dynamic ip just grant access to 192.168.2.% so now you dont have to worry about granting access to your ip address every time.
For those using the context menu api
, the docs are not immediately clear on how to obtain tab information.
chrome.contextMenus.onClicked.addListener(function(info, tab) {
console.log(info);
return console.log(tab);
});
For Google chrome it is not Ctrl+F5. It's Shift+F5 to clear the current cache! It works for me !
On a current netcat (v0.7.1) you have a -c switch:
-c, --close close connection on EOF from stdin
Hence,
echo "hi" | nc -cu localhost 8000
should do the trick.
'L' means wchar_t
, which, as opposed to a normal character, requires 16-bits of storage rather than 8-bits. Here's an example:
"A" = 41
"ABC" = 41 42 43
L"A" = 00 41
L"ABC" = 00 41 00 42 00 43
A wchar_t
is twice big as a simple char. In daily use you don't need to use wchar_t, but if you are using windows.h you are going to need it.
so I have a solution that isn't perfect but it worked for me. Use the polygon example from Google, and use the pinpoint on Google Maps to get lat & long locations.
I used what I call "ocular copy & paste" where you look at the screen and then write in the numbers you want ;-)
<style>
#map {
height: 500px;
}
</style>
<script>
// This example creates a simple polygon representing the host city of the
// Greatest Outdoor Show On Earth.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 9,
center: {lat: 51.039, lng: -114.204},
mapTypeId: 'terrain'
});
// Define the LatLng coordinates for the polygon's path.
var triangleCoords = [
{lat: 51.183, lng: -114.234},
{lat: 51.154, lng: -114.235},
{lat: 51.156, lng: -114.261},
{lat: 51.104, lng: -114.259},
{lat: 51.106, lng: -114.261},
{lat: 51.102, lng: -114.272},
{lat: 51.081, lng: -114.271},
{lat: 51.081, lng: -114.234},
{lat: 51.009, lng: -114.236},
{lat: 51.008, lng: -114.141},
{lat: 50.995, lng: -114.142},
{lat: 50.998, lng: -114.160},
{lat: 50.984, lng: -114.163},
{lat: 50.987, lng: -114.141},
{lat: 50.979, lng: -114.141},
{lat: 50.921, lng: -114.141},
{lat: 50.921, lng: -114.210},
{lat: 50.893, lng: -114.210},
{lat: 50.892, lng: -114.140},
{lat: 50.888, lng: -114.139},
{lat: 50.878, lng: -114.094},
{lat: 50.878, lng: -113.994},
{lat: 50.840, lng: -113.954},
{lat: 50.854, lng: -113.905},
{lat: 50.922, lng: -113.906},
{lat: 50.935, lng: -113.877},
{lat: 50.943, lng: -113.877},
{lat: 50.955, lng: -113.912},
{lat: 51.183, lng: -113.910}
];
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
}
</script>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/jskey=YOUR_API_KEY&callback=initMap">
</script>
This gets you the outline for Calgary. I've attached an image here.
To get al installed apps you can use Package Manager..
List<PackageInfo> apps = getPackageManager().getInstalledPackages(0);
To run you can use package name
Intent launchApp = getPackageManager().getLaunchIntentForPackage(“package name”)
startActivity(launchApp);
For more detail you can read this blog http://codebucket.co.in/android-get-list-of-all-installed-apps/
I would suggest defining your own package based on the following tex code; this gives you complete freedom. http://ubuntuforums.org/archive/index.php/t-331602.html
As noted in a prior answer, although git merge-base
works,
$ git merge-base myfeature develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2
If myfeature
is the current branch, as is common, you can use --fork-point
:
$ git merge-base --fork-point develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2
This argument works only in sufficiently recent versions of git. Unfortunately it doesn't always work, however, and it is not clear why. Please refer to the limitations noted toward the end of this answer.
For full commit info, consider:
$ git log -1 $(git merge-base --fork-point develop)
Ok, I'm probably late to the party, BUT...
THERE'S NO NEED TO RESIZE THE COLUMN IN YOUR CASE!
Postgres, unlike some other databases, is smart enough to only use just enough space to fit the string (even using compression for longer strings), so even if your column is declared as VARCHAR(255) - if you store 40-character strings in the column, the space usage will be 40 bytes + 1 byte of overhead.
The storage requirement for a short string (up to 126 bytes) is 1 byte plus the actual string, which includes the space padding in the case of character. Longer strings have 4 bytes of overhead instead of 1. Long strings are compressed by the system automatically, so the physical requirement on disk might be less. Very long values are also stored in background tables so that they do not interfere with rapid access to shorter column values.
(http://www.postgresql.org/docs/9.0/interactive/datatype-character.html)
The size specification in VARCHAR is only used to check the size of the values which are inserted, it does not affect the disk layout. In fact, VARCHAR and TEXT fields are stored in the same way in Postgres.
You need to use sqlite's prepared statements interface. Basically, the idea is that you prepare a statement with a placeholder for your blob, then use one of the bind calls to "bind" your data...
If you got php5.6 using the ppa repository http://ppa.launchpad.net/ondrej/php/ubuntu,
then you should install the package using:
sudo apt install php5.6-pgsql
Finally, if you use apache2, restart it:
sudo service apache2 restart
There is an analog solution to this also. There's an android app called "Timeout Blocker" that vibrates at a set interval and you put your mouse on it. https://play.google.com/store/apps/details?id=com.isomerprogramming.application.timeoutblocker&hl=en
sudo apt-get -y -f install php7.0-mysql
you can filter the waypoints by passing the user to the form init
class waypointForm(forms.Form):
def __init__(self, user, *args, **kwargs):
super(waypointForm, self).__init__(*args, **kwargs)
self.fields['waypoints'] = forms.ChoiceField(
choices=[(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
)
from your view while initiating the form pass the user
form = waypointForm(user)
in case of model form
class waypointForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(waypointForm, self).__init__(*args, **kwargs)
self.fields['waypoints'] = forms.ModelChoiceField(
queryset=Waypoint.objects.filter(user=user)
)
class Meta:
model = Waypoint
To change even less on your original query, you can turn your join into a RIGHT
join
SELECT person.person_id, COUNT(appointment.person_id) AS "number_of_appointments"
FROM appointment
RIGHT JOIN person ON person.person_id = appointment.person_id
GROUP BY person.person_id;
This just builds on the selected answer, but as the outer join is in the RIGHT
direction, only one word needs to be added and less changes. - Just remember that it's there and can sometimes make queries more readable and require less rebuilding.
Here you have two links for MD5 hashing and other hash methods:
Javadoc API: https://docs.oracle.com/javase/1.5.0/docs/api/java/security/MessageDigest.html
Because GETs are purely URLs, they can be cached by the web browser and may be better used for things like consistently generated images. (Set an Expiry time)
One example from the gravatar page: http://www.gravatar.com/avatar/4c3be63a4c2f539b013787725dfce802?d=monsterid
GET may yeild marginally better performance, some webservers write POST contents to a temporary file before invoking the handler.
Another thing to consider is the size limit. GETs are capped by the size of the URL, 1024 bytes by the standard, though browsers may support more.
Transferring more data than that should use a POST to get better browser compatibility.
Even less than that limit is a problem, as another poster wrote, anything in the URL could end up in other parts of the brower's UI, like history.
As many others have mentioned, selector:focus {outline: none;}
will remove that border but that border is a key accessibility feature that allows for keyboard users to find the button and shouldn't be removed.
Since your concern seems to be an aesthetic one, you should know that you can change the color, style, and width of the outline, making it fit into your site styling better.
selector:focus {
outline-width: 1px;
outline-style: dashed;
outline-color: red;
}
Shorthand:
selector:focus {
outline: 1px dashed red;
}
Well in the way this is a single page application, the solution used was:
load the content with AJAX, like any other controller, and then call:
angular.bootstrap($('#your_div_loaded_in_ajax'),["myApp","other_module"]);
You can check if it can be converted to decimal. If yes, then its a number
from decimal import Decimal
def is_number(value):
try:
value = Decimal(value)
return True
except:
return False
print is_number(None) // False
print is_number(0) // True
print is_number(2.3) // True
print is_number('2.3') // True (caveat!)
A vector
is functionally same as an array. But, to the language vector
is a type, and int
is also a type. To a function argument, an array of any type (including vector[]
) is treated as pointer. A vector<int>
is not same as int[]
(to the compiler). vector<int>
is non-array, non-reference, and non-pointer - it is being passed by value, and hence it will call copy-constructor.
So, you must use vector<int>&
(preferably with const
, if function isn't modifying it) to pass it as a reference.
Your @Entity
class has a String
type for its @Id
field, so it can't generate ids for you.
If you change it to an auto increment in the DB and a Long
in java, and add the @GeneratedValue
annotation:
@Id
@Column(name="U_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long U_id;
it will handle incrementing id generation for you.
Please refer to this question if you want to use UPSERT/MERGE command in Oracle. Otherwise, just resolve your issue on the client side by doing a count(1)
first and then deciding whether to insert or update.
On a linux system, you can modify terminal behaviour using the stty
command. By default, the terminal will buffer all information until Enter is pressed, before even sending it to the C program.
A quick, dirty, and not-particularly-portable example to change the behaviour from within the program itself:
#include<stdio.h>
#include<stdlib.h>
int main(void){
int c;
/* use system call to make terminal send all keystrokes directly to stdin */
system ("/bin/stty raw");
while((c=getchar())!= '.') {
/* type a period to break out of the loop, since CTRL-D won't work raw */
putchar(c);
}
/* use system call to set terminal behaviour to more normal behaviour */
system ("/bin/stty cooked");
return 0;
}
Please note that this isn't really optimal, since it just sort of assumes that stty cooked
is the behaviour you want when the program exits, rather than checking what the original terminal settings were. Also, since all special processing is skipped in raw mode, many key sequences (such as CTRL-C or CTRL-D) won't actually work as you expect them to without explicitly processing them in the program.
You can man stty
for more control over the terminal behaviour, depending exactly on what you want to achieve.
I'm afraid your posted example is not working, since X and Y aren't defined. So instead of pcolormesh
let's use imshow
:
import numpy as np
import matplotlib.pyplot as plt
H = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]) # added some commas and array creation code
fig = plt.figure(figsize=(6, 3.2))
ax = fig.add_subplot(111)
ax.set_title('colorMap')
plt.imshow(H)
ax.set_aspect('equal')
cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()
You have to be clear on what you mean by "JSON".
Some people use the term JSON incorrectly to refer to a plain old JavaScript object, such as [{a: 1}]
. This one happens to be an array. If you want to add a new element to the array, just push
it, as in
var arr = [{a: 1}];
arr.push({b: 2});
< [{a: 1}, {b: 2}]
The word JSON may also be used to refer to a string which is encoded in JSON format:
var json = '[{"a": 1}]';
Note the (single) quotation marks indicating that this is a string. If you have such a string that you obtained from somewhere, you need to first parse it into a JavaScript object, using JSON.parse
:
var obj = JSON.parse(json);
Now you can manipulate the object any way you want, including push
as shown above. If you then want to put it back into a JSON string, then you use JSON.stringify
:
var new_json = JSON.stringify(obj.push({b: 2}));
'[{"a": 1}, {"b": 1}]'
JSON is also used as a common way to format data for transmission of data to and from a server, where it can be saved (persisted). This is where ajax comes in. Ajax is used both to obtain data, often in JSON format, from a server, and/or to send data in JSON format up to to the server. If you received a response from an ajax request which is JSON format, you may need to JSON.parse
it as described above. Then you can manipulate the object, put it back into JSON format with JSON.stringify
, and use another ajax call to send the data to the server for storage or other manipulation.
You use the term "JSON file". Normally, the word "file" is used to refer to a physical file on some device (not a string you are dealing with in your code, or a JavaScript object). The browser has no access to physical files on your machine. It cannot read or write them. Actually, the browser does not even really have the notion of a "file". Thus, you cannot just read or write some JSON file on your local machine. If you are sending JSON to and from a server, then of course, the server might be storing the JSON as a file, but more likely the server would be constructing the JSON based on some ajax request, based on data it retrieves from a database, or decoding the JSON in some ajax request, and then storing the relevant data back into its database.
Do you really have a "JSON file", and if so, where does it exist and where did you get it from? Do you have a JSON-format string, that you need to parse, mainpulate, and turn back into a new JSON-format string? Do you need to get JSON from the server, and modify it and then send it back to the server? Or is your "JSON file" actually just a JavaScript object, that you simply need to manipulate with normal JavaScript logic?
To add my 2 cents. To mock specific http request methods either Get or Post. This worked for me.
mockHttpMessageHandler.Protected().Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.Is<HttpRequestMessage>(a => a.Method == HttpMethod.Get), ItExpr.IsAny<CancellationToken>())
.Returns(Task.FromResult(new HttpResponseMessage()
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(""),
})).Verifiable();
One thing to note is that the two are actually very related. Linear SVMs are equivalent to single-layer NN's (i.e., perceptrons), and multi-layer NNs can be expressed in terms of SVMs. See here for some details.
You need to use the document.getElementsByClassName('class_name');
and dont forget that the returned value is an array of elements so if you want the first one use:
document.getElementsByClassName('class_name')[0]
UPDATE
Now you can use:
document.querySelector(".class_name")
to get the first element with the class_name
CSS class (null
will be returned if non of the elements on the page has this class name)
or document.querySelectorAll(".class_name")
to get a NodeList of elements with the class_name
css class (empty NodeList will be returned if non of. the elements on the the page has this class name).
You can use PowerShell job cmdlets to achieve your goals.
There are 6 job related cmdlets available in PowerShell.
If interesting about it, you can download the sample How to create background job in PowerShell
[OOT]
A bit OOT, but this question is the most closest topic with my question.
Here is an example if you want to show Event where ALL participant meet certain requirement. Let's say, event where ALL the participant has fully paid. So, it WILL NOT return events which having one or more participants that haven't fully paid .
Simply use the whereDoesntHave
of the others 2 statuses.
Let's say the statuses are haven't paid at all [eq:1], paid some of it [eq:2], and fully paid [eq:3]
Event::whereDoesntHave('participants', function ($query) {
return $query->whereRaw('payment = 1 or payment = 2');
})->get();
Tested on Laravel 5.8 - 7.x
Select Top 1* FROM test_table WHERE user_id = value order by Date_Added Desc
You can also set a Java property, i.e. environment variable, on the command line and easily use it anywhere in your code.
The command line would be done this way:
c:/> java -jar -Dmyvar=enwiki-20111007-pages-articles.xml wiki2txt
and the java code accesses the value like this:
String context = System.getProperty("myvar");
See this question about argument passing in Java.
You can use fstat() to get the file's inode by struct stat. Then, using readdir() you can compare the inode you found with those that exist (struct dirent) in a directory (assuming that you know the directory, otherwise you'll have to search the whole filesystem) and find the corresponding file name. Nasty?
Your "scary" solution does not appear scary to me. Calling shuffle()
for two sequences of the same length results in the same number of calls to the random number generator, and these are the only "random" elements in the shuffle algorithm. By resetting the state, you ensure that the calls to the random number generator will give the same results in the second call to shuffle()
, so the whole algorithm will generate the same permutation.
If you don't like this, a different solution would be to store your data in one array instead of two right from the beginning, and create two views into this single array simulating the two arrays you have now. You can use the single array for shuffling and the views for all other purposes.
Example: Let's assume the arrays a
and b
look like this:
a = numpy.array([[[ 0., 1., 2.],
[ 3., 4., 5.]],
[[ 6., 7., 8.],
[ 9., 10., 11.]],
[[ 12., 13., 14.],
[ 15., 16., 17.]]])
b = numpy.array([[ 0., 1.],
[ 2., 3.],
[ 4., 5.]])
We can now construct a single array containing all the data:
c = numpy.c_[a.reshape(len(a), -1), b.reshape(len(b), -1)]
# array([[ 0., 1., 2., 3., 4., 5., 0., 1.],
# [ 6., 7., 8., 9., 10., 11., 2., 3.],
# [ 12., 13., 14., 15., 16., 17., 4., 5.]])
Now we create views simulating the original a
and b
:
a2 = c[:, :a.size//len(a)].reshape(a.shape)
b2 = c[:, a.size//len(a):].reshape(b.shape)
The data of a2
and b2
is shared with c
. To shuffle both arrays simultaneously, use numpy.random.shuffle(c)
.
In production code, you would of course try to avoid creating the original a
and b
at all and right away create c
, a2
and b2
.
This solution could be adapted to the case that a
and b
have different dtypes.
A slight variation on Jack's answer to add support for PHP < 7:
// Get an RFC-4122 compliant globaly unique identifier
function get_guid() {
$data = PHP_MAJOR_VERSION < 7 ? openssl_random_pseudo_bytes(16) : random_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // Set version to 0100
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // Set bits 6-7 to 10
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
A supplement to h4xxr's answer in the above, an easier way to adjust the height of the UITextField is to select square border style in the attribute inspectors->Text Field. (By default, the border style of a UITextfield is ellipse.)
Reference: Answered Brian in here : How to set UITextField height?
Simple Answer: NO
Well, at least a naming convention as such encouraged by Oracle or community, no, however, basically you have to be aware of following the rules and limits for identifiers, such as indicated in MySQL documentation: https://dev.mysql.com/doc/refman/8.0/en/identifiers.html
About the naming convention you follow, I think it is ok, just the number 5 is a little bit unnecesary, I think most visual tools for managing databases offer a option for sorting column names (I use DBeaver, and it have it), so if the purpouse is having a nice visual presentation of your table you can use this option I mention.
By personal experience, I would recommed this:
lower_case_table_names
is not correctly configured and your server start throwing errors just by simply unrecognizing your camelCase or PascalCase standard (case sensitivity problem).And what about the "Plural vs Singular" naming? Well, this is most a situation of personal preferences. In my case I try to use plural names for tables because I think a table as a collection of elements or a package containig elements, so a plural name make sense for me; and singular names for columns because I see columns as attributes that describe singularly to those table elements.
Sometimes it occurs when some installations are not completed correctly, the process is stuck, or a file is still opened. So, when you try to run the installation again and the installation requires deleting, you can see the aforementioned error. In my case, shutting down the python processes and command prompt utilization helped.
No there isn't. If you watch the http traffic and dump the page source you can see that there is an API below the covers, but it's not published nor available for 3rd party apps.
Check this link: https://developers.google.com/gsuite/products for updates.
However, there is an unofficial Python API under active development: https://github.com/kiwiz/gkeepapi
If you mean the array indexer,, You overload that just by writing an indexer property.. And you can overload, (write as many as you want) indexer properties as long as each one has a different parameter signature
public class EmployeeCollection: List<Employee>
{
public Employee this[int employeeId]
{
get
{
foreach(var emp in this)
{
if (emp.EmployeeId == employeeId)
return emp;
}
return null;
}
}
public Employee this[string employeeName]
{
get
{
foreach(var emp in this)
{
if (emp.Name == employeeName)
return emp;
}
return null;
}
}
}
Using Java 8 use can define the Comparator
in one line using Comparator.comparing()
Use any of the following way:
Option 1:
listToBeSorted.sort(Comparator.comparing(CustomObject::getStartDate));
Option 2:
Collections.sort(listToBeSorted, Comparator.comparing(CustomObject::getStartDate));
I run into this frequently for some reason, and I can't fathom why this solution hasn't been mentioned:
Click View ? Output (or just hold Ctrl and hit W > O)
Console output then appears where your Error List, Locals, and Watch windows are.
Note: I'm using Visual Studio 2015.
Use the std::vector
class from the standard library.
MSYS has not been updated a long time, MSYS2 is more active, you can download from MSYS2, it has both mingw
and cygwin fork
package.
To install the MinGW-w64 toolchain (Reference):
pacman -Sy pacman
to update the package databasepacman -Syu
to update the package database and core system packagespacman -Su
to update the restpacman -S mingw-w64-i686-toolchain
pacman -S mingw-w64-x86_64-toolchain
make
, run pacman -S make
Put them into a list
and use merge
with Reduce
Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
# id v1 v2 v3
# 1 1 1 NA NA
# 2 10 4 NA NA
# 3 2 3 4 NA
# 4 43 5 NA NA
# 5 73 2 NA NA
# 6 23 NA 2 1
# 7 57 NA 3 NA
# 8 62 NA 5 2
# 9 7 NA 1 NA
# 10 96 NA 6 NA
You can also use this more concise version:
Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))
I had the same problem.
The solution from depa is absolutely correct.
Just make sure that u have a user configured to use PostgreSQL.
Check the file:
$ ls /etc/postgresql/9.1/main/pg_hba.conf -l
The permission of this file should be given to the user you have registered your psql with.
Further. If you are good till now..
Update as per @depa's instructions.
i.e.
$ sudo nano /etc/postgresql/9.1/main/pg_hba.conf
and then make changes.
You could use the undocumented
DBCC LOG(databasename, typeofoutput)
where typeofoutput:
0: Return only the minimum of information for each operation -- the operation, its context and the transaction ID. (Default)
1: As 0, but also retrieve any flags and the log record length.
2: As 1, but also retrieve the object name, index name, page ID and slot ID.
3: Full informational dump of each operation.
4: As 3 but includes a hex dump of the current transaction log row.
For example, DBCC LOG(database, 1)
You could also try fn_dblog.
For rolling back a transaction using the transaction log I would take a look at Stack Overflow post Rollback transaction using transaction log.
You just need to get selenium package imported, that you can do from command prompt using the command
pip install selenium
When you have to use it in any IDE just import this package, no other documentation required to be imported
For Eg :
import selenium
print(selenium.__filepath__)
This is just a general command you may use in starting to check the filepath of selenium
Add the class hide to the modal
<!-- Modal Demo -->
<div class="modal hide" id ="myModal" aria-hidden="true" >
Javascript Code
<!-- Use this to hide the modal necessary for loading and closing the modal-->
<script>
$(function(){
$('#closeModal').click(function(){
$('#myModal').modal('hide');
});
});
</script>
<!-- Use this to load the modal necessary for loading and closing the modal-->
<script>
$(function () {
$('#myModal').modal('show');
});
</script>
This worked for my purposes. Pretty basic and simple, but it did what I needed (which was to get a personal photo of mine onto the internet so I could use its URL).
Go to photos.google.com and open any image that you wish to embed in your website.
Tap the Share Icon and then choose "Get Link" to generate a shareable link for that image.
Go to j.mp/EmbedGooglePhotos, paste that link and it will instantly generate the embed code for that picture.
Open your website template, paste the generated code and save. The image will now serve directly from your Google Photos account.
Check this video tutorial out if you have trouble.
Under OSX, to avoid this issue and avoid other problems with developing on a case-insensitive filesystem, you can use Disk Utility to create a case sensitive virtual drive / disk image.
Run disk utility, create new disk image, and use the following settings (or change as you like, but keep it case sensitive):
Make sure to tell git it is now on a case sensitive FS:
git config core.ignorecase false
There are open source scripts on Detect Mobile Browser that do this in Apache, ASP, ColdFusion, JavaScript and PHP.
Unrecognized option: - Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit.
I was getting this Error due to incorrect syntax using in the terminal. I was using java - version. But its actually is java -version. there is no space between - and version. you can also cross check by using java -help.
i hope this will help.
set TEXT_T="myfile.txt"
set /a c=1
FOR /F "tokens=1 usebackq" %%i in (%TEXT_T%) do (
set /a c+=1
set OUTPUT_FILE_NAME=output_%c%.txt
echo Output file is %OUTPUT_FILE_NAME%
echo %%i, %c%
)
Just create your own button on:
Cheers
Just define the variable as a variant, and make them equal:
Dim DirArray As Variant
DirArray = Range("a1:a5").Value
No need for the Array command.
Using CSS text-transform: uppercase
does not change the actual input but only changes its look.
If you send the input data to a server it is still going to lowercase or however you entered it. To actually transform the input value you need to add javascript code as below:
document.querySelector("input").addEventListener("input", function(event) {_x000D_
event.target.value = event.target.value.toLocaleUpperCase()_x000D_
})
_x000D_
<input>
_x000D_
Here I am using toLocaleUpperCase()
to convert input
value to uppercase.
It works fine until you need to edit what you had entered, e.g. if you had entered ABCXYZ and now you try to change it to ABCLMNXYZ, it will become ABCLXYZMN because after every input the cursor jumps to the end.
To overcome this jumping of the cursor, we have to make following changes in our function:
document.querySelector("input").addEventListener("input", function(event) {_x000D_
var input = event.target;_x000D_
var start = input.selectionStart;_x000D_
var end = input.selectionEnd;_x000D_
input.value = input.value.toLocaleUpperCase();_x000D_
input.setSelectionRange(start, end);_x000D_
})
_x000D_
<input>
_x000D_
Now everything works as expected, but if you have slow PC you may see text jumping from lowercase to uppercase as you type. If this annoys you, this is the time to use CSS, apply input: {text-transform: uppercase;}
to CSS file and everything will be fine.
Your code is correct. Just test to ensure it is being called like:
<script>
function doIt(){
alert("here i am!");
__doPostBack('ctl00$ctl00$bLogout','')
}
</script>
<iframe onload="doIt()"></iframe>
You can use nodebrew. It can switch node versions too.
Implementation with Guzzle library:
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
$httpClient = new Client();
$response = $httpClient->post(
'https://postman-echo.com/post',
[
RequestOptions::BODY => 'POST raw request content',
RequestOptions::HEADERS => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
]
);
echo(
$response->getBody()->getContents()
);
PHP CURL extension:
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://postman-echo.com/post',
CURLOPT_RETURNTRANSFER => true,
/**
* Specify POST method
*/
CURLOPT_POST => true,
/**
* Specify request content
*/
CURLOPT_POSTFIELDS => 'POST raw request content',
]);
$response = curl_exec($curlHandler);
curl_close($curlHandler);
echo($response);
from sklearn.model_selection import train_test_split
import numpy
with open("datafile.txt", "rb") as f:
data = f.read().split('\n')
data = numpy.array(data) #convert array to numpy type array
x_train ,x_test = train_test_split(data,test_size=0.5) #test_size=0.5(whole_data)
Stumbled onto this, was strangely hard to find again later. Putting here for posterity:
sudo yum install nodejs npm --enablerepo=epel
EDIT 3: As of July 2016, EDIT 1 no longer works for nodejs 4 (and EDIT 2 neither). This answer (https://stackoverflow.com/a/35165401/78935) gives a true one-liner.
EDIT 1: If you're looking for nodejs 4, please try the EPEL testing repo:
sudo yum install nodejs --enablerepo=epel-testing
EDIT 2: To upgrade from nodejs 0.12 installed through the EPEL repo using the command above, to nodejs 4 from the EPEL testing repo, please follow these steps:
sudo yum rm nodejs
sudo rm -f /usr/local/bin/node
sudo yum install nodejs --enablerepo=epel-testing
The newer packages put the node binaries in /usr/bin
, instead of /usr/local/bin
.
And some background:
The option --enablerepo=epel
causes yum
to search for the packages in the EPEL repository.
EPEL (Extra Packages for Enterprise Linux) is open source and free community based repository project from Fedora team which provides 100% high quality add-on software packages for Linux distribution including RHEL (Red Hat Enterprise Linux), CentOS, and Scientific Linux. Epel project is not a part of RHEL/Cent OS but it is designed for major Linux distributions by providing lots of open source packages like networking, sys admin, programming, monitoring and so on. Most of the epel packages are maintained by Fedora repo.
Via http://www.tecmint.com/how-to-enable-epel-repository-for-rhel-centos-6-5/
The substitute command can be applied to a visual selection. Make a visual block over the lines that you want to change, and type :, and notice that the command-line is initialized like this: :'<,'>
. This means that the substitute command will operate on the visual selection, like so:
:'<,'>s/$/,/
And this is a substitution that should work for your example, assuming that you really want the comma at the end of each line as you've mentioned. If there are trailing spaces, then you may need to adjust the command accordingly:
:'<,'>s/\s*$/,/
This will replace any amount of whitespace preceding the end of the line with a comma, effectively removing trailing whitespace.
The same commands can operate on a range of lines, e.g. for the next 5 lines: :,+5s/$/,/
, or for the entire buffer: :%s/$/,/
.
With VS 2013 Express this key does not exist. What I see is HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\12.0 and there is no mention of Text Editor under that.
(\d+)\s+(\(.*?\))?\s?Z
Note the escaped parentheses, and the ?
(zero or once) quantifiers. Any of the groups you don't want to capture can be (?:
non-capture groups).
I agree about the spaces. \s
is a better option there. I also changed the quantifier to insure there are digits at the beginning. As far as newlines, that would depend on context: if the file is parsed line by line it won't be a problem. Another option is to anchor the start and end of the line (add a ^
at the front and a $
at the end).
my_hash = {:a => 5}
my_hash[:key] = "value"
I know one aspect: Although CBC gives better security by changing the IV for each block, it's not applicable to randomly accessed encrypted content (like an encrypted hard disk).
So, use CBC (and the other sequential modes) for sequential streams and ECB for random access.
The code you posted is wrong.
You shouldn't make multiple calls to DateTime.Today
. If you happen to run that code just as the date changes you could get completely wrong results. For example if you ran it on December 31st 2011 you might get "2011-1-1".
Use a single call to DateTime.Today
then use ToString
with an appropriate format string to format the date as you desire.
string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
your markup was a bit messed up. Here's the styles you need and proper html
CSS:
.navbar-brand,
.navbar-nav li a {
line-height: 150px;
height: 150px;
padding-top: 0;
}
HTML:
<nav class="navbar navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><img src="img/logo.png" /></a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="">Portfolio</a></li>
<li><a href="">Blog</a></li>
<li><a href="">Contact</a></li>
</ul>
</div>
</nav>
Or check out the fiddle at: http://jsfiddle.net/TP5V8/1/
I always just use sc.exe (see http://support.microsoft.com/kb/251192). It should be installed on XP from SP1, and if it's not in your flavor of Vista, you can download load it with the Vista resource kit.
I haven't done anything too complicated with Java, but using either a fully qualified command line argument (x:\java.exe ....) or creating a script with Ant to include depencies and set parameters works fine for me.
You can use query string to pass value from one page to another..
1.pass the value using querystring
Response.Redirect("Default3.aspx?value=" + txt.Text + "& number="+n);
2.Retrive the value in the page u want by using any of these methods..
Method1:
string v = Request.QueryString["value"];
string n=Request.QueryString["number"];
Method2:
NameValueCollection v = Request.QueryString;
if (v.HasKeys())
{
string k = v.GetKey(0);
string n = v.Get(0);
if (k == "value")
{
lbltext.Text = n.ToString();
}
if (k == "value1")
{
lbltext.Text = "error occured";
}
}
NOTE:Method 2 is the fastest method.
This is a simple way that is inefficient, but it's quite reasonable when you don't need anything too complex or you don't have many objects.
Otherwise there are many different algorithms, but most of them are quite complex to implement.
For example, you can use a divide et impera approach in which you cluster objects hierarchically according to their distance and you give to every cluster a bounding box that contains all the items of the cluster. Then you can check which clusters collide and avoid checking pairs of object that belong to clusters that are not colliding/overlapped.
Otherwise, you can figure out a generic space partitioning algorithm to split up in a similar way the objects to avoid useless checks. These kind of algorithms split the collision detection in two phases: a coarse one in which you see what objects maybe colliding and a fine one in which you effectively check single objects. For example, you can use a QuadTree (Wikipedia) to work out an easy solution...
Take a look at the Wikipedia page. It can give you some hints.
var a= [1, 2, 3, '3'];
var b = [1, 2, 3];
var c = a.filter(function (i) { return ! ~b.indexOf(i); });
alert(c.length);
We can do something like this
DateTime date_temp_from = DateTime.Parse(from.Value); //from.value" is input by user (dd/MM/yyyy)
DateTime date_temp_to = DateTime.Parse(to.Value); //to.value" is input by user (dd/MM/yyyy)
string date_from = date_temp_from.ToString("yyyy/MM/dd HH:mm");
string date_to = date_temp_to.ToString("yyyy/MM/dd HH:mm");
Thank you
Below pattern perfectly works in case of leap year and as well as with normal dates. The date format is : YYYY-MM-DD
<input type="text" placeholder="YYYY-MM-DD" pattern="(?:19|20)(?:(?:[13579][26]|[02468][048])-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))|(?:[0-9]{2}-(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:29|30))|(?:(?:0[13578]|1[02])-31)))" class="form-control " name="eventDate" id="" required autofocus autocomplete="nope">
I got this solution from http://html5pattern.com/Dates. Hope it may help someone.
mysqlclient is a fork of MySQLdb and can serve as a drop-in replacement with Python 3.4 support. If you have trouble building it on Windows, you can download it from Christoph Gohlke's Unofficial Windows Binaries for Python Extension Packages
Have you considered lsof
(list open files)?
Its easy go to File - Data Modeler - Import - Data Dictionary - DB connection - OK
Try Request.Url.Query
if you want the raw querystring as a string.
var pdf = MyPdf.pdf;
window.open(pdf);
This will open the pdf document in a full window from JavaScript
A function to open windows would look like this:
function openPDF(pdf){
window.open(pdf);
return false;
}
You should've kept that DOM ready function
$(function() {
$("#projectKey").change(function() {
alert( $('option:selected', this).text() );
});
});
The document isn't ready if you added the javascript before the elements in the DOM, you have to either use a DOM ready function or add the javascript after the elements, the usual place is right before the </body>
tag
For correct work your shape should be with selector and item tags
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#ffffff" />
<stroke android:width="1dp"
android:color="@color/shape_border_active"/>
</shape>
</item>
</selector>
The solution discussed here worked well for me. This solution uses built-in cuda functions and is very simple to implement.
The relevant code is copied below:
#include <stdio.h>
#include <stdlib.h>
__global__ void foo(int *ptr)
{
*ptr = 7;
}
int main(void)
{
foo<<<1,1>>>(0);
// make the host block until the device is finished with foo
cudaDeviceSynchronize();
// check for error
cudaError_t error = cudaGetLastError();
if(error != cudaSuccess)
{
// print the CUDA error message and exit
printf("CUDA error: %s\n", cudaGetErrorString(error));
exit(-1);
}
return 0;
}
I know this is old but this answer still applies to newer Core releases.
If by chance your DbContext
implementation is in a different project than your startup project and you run ef migrations
, you'll see this error because the command will not be able to invoke the application's startup code leaving your database provider without a configuration. To fix it, you have to let ef migrations
know where they're at.
dotnet ef migrations add MyMigration [-p <relative path to DbContext project>, -s <relative path to startup project>]
Both -s
and -p
are optionals that default to the current folder.
Use align-items: flex-start
on the container, or align-self: flex-start
on the flex items.
No need for display: inline-flex
.
An initial setting of a flex container is align-items: stretch
. This means that flex items will expand to cover the full length of the container along the cross axis.
The align-self
property does the same thing as align-items
, except that align-self
applies to flex items while align-items
applies to the flex container.
By default, align-self
inherits the value of align-items
.
Since your container is flex-direction: column
, the cross axis is horizontal, and align-items: stretch
is expanding the child element's width as much as it can.
You can override the default with align-items: flex-start
on the container (which is inherited by all flex items) or align-self: flex-start
on the item (which is confined to the single item).
Learn more about flex alignment along the cross axis here:
Learn more about flex alignment along the main axis here:
yourLabel.intrinsicContentSize.width
for Objective-C / Swift
Unless your functions are very slow, you're going to need a very high-resolution timer. The most accurate one I know is QueryPerformanceCounter
. Google it for more info. Try pushing the following into a class, call it CTimer
say, then you can make an instance somewhere global and just call .StartCounter
and .TimeElapsed
Option Explicit
Private Type LARGE_INTEGER
lowpart As Long
highpart As Long
End Type
Private Declare Function QueryPerformanceCounter Lib "kernel32" (lpPerformanceCount As LARGE_INTEGER) As Long
Private Declare Function QueryPerformanceFrequency Lib "kernel32" (lpFrequency As LARGE_INTEGER) As Long
Private m_CounterStart As LARGE_INTEGER
Private m_CounterEnd As LARGE_INTEGER
Private m_crFrequency As Double
Private Const TWO_32 = 4294967296# ' = 256# * 256# * 256# * 256#
Private Function LI2Double(LI As LARGE_INTEGER) As Double
Dim Low As Double
Low = LI.lowpart
If Low < 0 Then
Low = Low + TWO_32
End If
LI2Double = LI.highpart * TWO_32 + Low
End Function
Private Sub Class_Initialize()
Dim PerfFrequency As LARGE_INTEGER
QueryPerformanceFrequency PerfFrequency
m_crFrequency = LI2Double(PerfFrequency)
End Sub
Public Sub StartCounter()
QueryPerformanceCounter m_CounterStart
End Sub
Property Get TimeElapsed() As Double
Dim crStart As Double
Dim crStop As Double
QueryPerformanceCounter m_CounterEnd
crStart = LI2Double(m_CounterStart)
crStop = LI2Double(m_CounterEnd)
TimeElapsed = 1000# * (crStop - crStart) / m_crFrequency
End Property
The specificity is calculated based on the amount of id, class and tag selectors in your rule. Id has the highest specificity, then class, then tag. Your first rule is now more specific than the second one, since they both have a class selector, but the first one also has two tag selectors.
To make the second one override the first one, you can make more specific by adding information of it's parents:
table.rule1 tr td.rule2 {
background-color: #ffff00;
}
Here is a nice article for more information on selector precedence.
Updated answer
Here is how to change the box model used by the input/textarea/select elements so that they all behave the same way. You need to use the box-sizing
property which is implemented with a prefix for each browser
-ms-box-sizing:content-box;
-moz-box-sizing:content-box;
-webkit-box-sizing:content-box;
box-sizing:content-box;
This means that the 2px difference we mentioned earlier does not exist..
example at http://www.jsfiddle.net/gaby/WaxTS/5/
note: On IE it works from version 8 and upwards..
Original
if you reset their borders then the select
element will always be 2 pixels less than the input
elements..
Just wanted to post my piece of PHP code, because I think the way I collect the columns is a bit cleaner in code than the previous examples. Also this shows how you could easily alter an field, in this case adding a string. But you could also replace a foreign key field with the newly added record, in case you want to copy some child records as well.
// Read columns, unset the PK (always the first field in my case)
$stmt = $conn->prepare('SHOW COLUMNS FROM template');
$stmt->execute();
$columns = $stmt->fetchAll();
$columns = array_map(function ($element) { return $element['Field']; }, $columns);
unset($columns[0]);
// Insert record in the database. Add string COPY to the name field.
$sql = "INSERT INTO `template` (".implode(",", $columns).")";
if ($key = array_search('name', $columns))
$columns[$key] = "CONCAT(name, ' COPY')";
$sql .= " SELECT ".implode(",", $columns)." FROM `template` WHERE `id` = ".$id;
$stmt = $conn->prepare($sql);
$stmt->execute();
You need spaces inside the [
and ]
brackets:
#!/bin/bash
if [ ! -d /home/mlzboy/b2c2/shared/db ]
then
mkdir -p /home/mlzboy/b2c2/shared/db
fi
You can check the version of CUDA using
nvcc -V
or you can use
nvcc --version
or You can check the location of where the CUDA is using
whereis cuda
and then do
cat location/of/cuda/you/got/from/above/command
Just for completeness - in SQL 2008 you would use the plus +
operator to perform string concatenation.
Take a look at the MSDN reference with sample code. Starting with SQL 2012, you may wish to use the new CONCAT function.
I came across this issue when not using async/await on a asynchronous function (api call). Hence adding them / using the promise handlers properly cleared the error.
Simply divide the Variable containing Numbers as a string by 1. PowerShell automatically convert the result to an integer.
$a = 15; $b = 2; $a + $b --> 152
But if you divide it before:
$a/1 + $b/1 --> 17
In JPA 2.1 you need to do the following
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.Table;
@Entity(name="TEST_PERSON")
@Table(
name="TEST_PERSON",
indexes = {
@Index(name = "PERSON_INDX_0", columnList = "age"),
@Index(name = "PERSON_INDX_1", columnList = "fName"),
@Index(name = "PERSON_INDX_1", columnList = "sName") })
public class TestPerson {
@Column(name = "age", nullable = false)
private int age;
@Column(name = "fName", nullable = false)
private String firstName;
@Column(name = "sName", nullable = false)
private String secondName;
@Id
private long id;
public TestPerson() {
}
}
In the above example the table TEST_PERSON will have 3 indexes:
unique index on the primary key ID
index on AGE
compound index on FNAME, SNAME
Note 1: You get the compound index by having two @Index annotations with the same name
Note 2: You specify the column name in the columnList not the fieldName
To analyze a query you already have entered into the Query editor, you need to choose "Include Actual Execution Plan" (7th toggle button to the right of the "! Execute" button). After executing the query, you need to click on the "Execution Plan" tab in the results pane at the bottom (above the results of the query).
In command mode (press Esc if you are not sure) you can use:
In case you use fastlane, additional flags can be passed with
gradle(
...
flags: "{your flags}"
)
More information here
I've tested all combinations of pre-allocating/not pre-allocating, counting up/down, and for/while loops in IE 6/7/8, Firefox 3.5, Chrome, and Opera.
The functions below was consistently the fastest or extremely close in Firefox, Chrome, and IE8, and not much slower than the fastest in Opera and IE 6. It's also the simplest and clearest in my opinion. I've found several browsers where the while loop version is slightly faster, so I'm including it too for reference.
function newFilledArray(length, val) {
var array = [];
for (var i = 0; i < length; i++) {
array[i] = val;
}
return array;
}
or
function newFilledArray(length, val) {
var array = [];
var i = 0;
while (i < length) {
array[i++] = val;
}
return array;
}
{
"/api": {
"target": "http://targetIP:targetPort",
"secure": false,
"pathRewrite": {"^/api" : targeturl/api},
"changeOrigin": true,
"logLevel": "debug"
}
}
in package.json, make
"start": "ng serve --proxy-config proxy.conf.json"
in code let url = "/api/clnsIt/dev/78"; this url will be translated to http://targetIP:targetPort/api/clnsIt/dev/78.
You can also force rewrite by filling the pathRewrite. This is the link for details cmd/NPM console will log something like "Rewriting path from "/api/..." to "http://targeturl:targetPort/api/..", while browser console will log "http://loclahost/api"
real life example, notify Airbrake API about new deployment via NetHttps
require 'uri'
require 'net/https'
require 'json'
class MakeHttpsRequest
def call(url, hash_json)
uri = URI.parse(url)
req = Net::HTTP::Post.new(uri.to_s)
req.body = hash_json.to_json
req['Content-Type'] = 'application/json'
# ... set more request headers
response = https(uri).request(req)
response.body
end
private
def https(uri)
Net::HTTP.new(uri.host, uri.port).tap do |http|
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
end
end
project_id = 'yyyyyy'
project_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
url = "https://airbrake.io/api/v4/projects/#{project_id}/deploys?key=#{project_key}"
body_hash = {
"environment":"production",
"username":"tomas",
"repository":"https://github.com/equivalent/scrapbook2",
"revision":"live-20160905_0001",
"version":"v2.0"
}
puts MakeHttpsRequest.new.call(url, body_hash)
Notes:
in case you doing authentication via Authorisation header set header req['Authorization'] = "Token xxxxxxxxxxxx"
or http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html
Sometimes .concat() is better than .push() since .concat() returns the new array whereas .push() returns the length of the array.
Therefore, if you are setting a variable equal to the result, use .concat().
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
newArray = items.push({'id':5})
In this case, newArray will return 5 (the length of the array).
newArray = items.concat({'id': 5})
However, here newArray will return [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 5}].
Quoted from http://maven.apache.org/settings.html:
There are two locations where a settings.xml file may live:
The Maven install: $M2_HOME/conf/settings.xml
A user's install: ${user.home}/.m2/settings.xml
So, usually for a specific user you edit
/home/*username*/.m2/settings.xml
To set environment for all local users, you might think about changing the first path.
Build solution only builds those projects which have changed in the solution, and does not effect assemblies that have not changed,
ReBuild first cleans, all the assemblies from the solution and then builds entire solution regardless of changes done.
Clean, simply cleans the solution.
Also if you want to do something like ClassB.Run("thing");
, make sure the Method Run();
is static
or you could call it like this: thing.Run("thing");
.
You need to call self.a()
to invoke a
from b
. a
is not a global function, it is a method on the class.
You may want to read through the Python tutorial on classes some more to get the finer details down.
hbn's answer won't work out of the box if the file to load is in a subdirectory or is named with dashes.
In such a case you may consider this alternative :
exec open(myconfig.py).read()
Or the simpler but deprecated in python3 :
execfile(myconfig.py)
I guess Stephan202's warning applies to both options, though, and maybe the loop on lines is safer.
I think you can get this error if your database model is not correct and the underlying data contains a null which the model is attempting to map to a non-null object.
For example, some auto-generated models can attempt to map nvarchar(1) columns to char rather than string and hence if this column contains nulls it will throw an error when you attempt to access the data.
Note, LinqPad has a compatibility option if you want it to generate a model like that, but probably doesn't do this by default, which might explain it doesn't give you the error.
use #undef UNICODE
at the top of your main file.
If your cron job is running on Mac OS X only, you may want to use launchd instead.
From Scheduling Timed Jobs (official Apple docs):
Note: Although it is still supported, cron is not a recommended solution. It has been deprecated in favor of launchd.
You can find additional information (such as the launchd Wikipedia page) with a simple web search.
Have you tried using a view model instead of ViewData? Strongly typed helpers that end with For
and take a lambda expression cannot work with weakly typed structures such as ViewData
.
Personally I don't use ViewData/ViewBag. I define view models and have my controller actions pass those view models to my views.
For example in your case I would define a view model:
public class MyViewModel
{
[HiddenInput(DisplayValue = false)]
public string CRN { get; set; }
}
have my controller action populate this view model:
public ActionResult Index()
{
var model = new MyViewModel
{
CRN = "foo bar"
};
return View(model);
}
and then have my strongly typed view simply use an EditorFor
helper:
@model MyViewModel
@Html.EditorFor(x => x.CRN)
which would generate me:
<input id="CRN" name="CRN" type="hidden" value="foo bar" />
in the resulting HTML.
the symbol ? after the int means that it can be nullable.
The ? symbol is usually used in situations whereby the variable can accept a null or an integer or alternatively, return an integer or null.
Hope the context of usage helps. In this way you are not restricted to solely dealing with integers.
I used the jQuery.click function to get the desired output:
$('input[name=rate]').click(function(){
console.log('Hey you clicked this: ' + this.value);
if(this.value == 'Fixed Rate'){
rate_value = $('#r1').value;
} else if(this.value =='Variable Rate'){
rate_value = $('#r2').value;
} else if(this.value =='Multi Rate'){
rate_value = $('#r3').value;
}
$('#results').innerHTML = rate_value;
});
Hope it helps.
Bind to the change
event instead of click
. However, you will probably still need to check whether or not the checkbox is checked:
$(".checkbox").change(function() {
if(this.checked) {
//Do stuff
}
});
The main benefit of binding to the Redacted in commentschange
event over the click
event is that not all clicks on a checkbox will cause it to change state. If you only want to capture events that cause the checkbox to change state, you want the aptly-named change
event.
Also note that I've used this.checked
instead of wrapping the element in a jQuery object and using jQuery methods, simply because it's shorter and faster to access the property of the DOM element directly.
Edit (see comments)
To get all checkboxes you have a couple of options. You can use the :checkbox
pseudo-selector:
$(":checkbox")
Or you could use an attribute equals selector:
$("input[type='checkbox']")
All you need is to make an ajax request to your pythoncode. You can do this with jquery http://api.jquery.com/jQuery.ajax/, or use just javascript
$.ajax({
type: "POST",
url: "~/pythoncode.py",
data: { param: text}
}).done(function( o ) {
// do something
});
An alternative to the answer from sergey_mo is to create multiple ssh keys on the jenkins server.
(Though as the first commenter to sergey_mo's answer said, this may end up being more painful than managing a single key-pair.)
You were almost there : just add theme(legend.title=element_blank())
ggplot(df, aes(x, y, colour=g)) +
geom_line(stat="identity") +
theme(legend.position="bottom") +
theme(legend.title=element_blank())
This page on Cookbook for R gives plenty of details on how to customize legends.
In the "root" __init__.py
you can also do a
import sys
sys.path.insert(1, '.')
which should make both modules importable.
Change column type to LONGTEXT
javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean
This literally means that the mentioned class com.example.Bean
doesn't have a public (non-static!) getter method for the mentioned property foo
. Note that the field itself is irrelevant here!
The public getter method name must start with get
, followed by the property name which is capitalized at only the first letter of the property name as in Foo
.
public Foo getFoo() {
return foo;
}
You thus need to make sure that there is a getter method matching exactly the property name, and that the method is public
(non-static
) and that the method does not take any arguments and that it returns non-void
. If you have one and it still doesn't work, then chances are that you were busy editing code forth and back without firmly cleaning the build, rebuilding the code and redeploying/restarting the application. You need to make sure that you have done so.
For boolean
(not Boolean
!) properties, the getter method name must start with is
instead of get
.
public boolean isFoo() {
return foo;
}
Regardless of the type, the presence of the foo
field itself is thus not relevant. It can have a different name, or be completely absent, or even be static
. All of below should still be accessible by ${bean.foo}
.
public Foo getFoo() {
return bar;
}
public Foo getFoo() {
return new Foo("foo");
}
public Foo getFoo() {
return FOO_CONSTANT;
}
You see, the field is not what counts, but the getter method itself. Note that the property name itself should not be capitalized in EL. In other words, ${bean.Foo}
won't ever work, it should be ${bean.foo}
.
import { ActivatedRoute } from '@angular/router';_x000D_
_x000D_
export class ClassName {_x000D_
_x000D_
private router = ActivatedRoute;_x000D_
_x000D_
constructor(r: ActivatedRoute) {_x000D_
this.router =r;_x000D_
}_x000D_
_x000D_
onSuccess() {_x000D_
this.router.navigate(['/user_invitation'],_x000D_
{queryParams: {email: loginEmail, code: userCode}});_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
Get this values:_x000D_
---------------_x000D_
_x000D_
ngOnInit() {_x000D_
this.route_x000D_
.queryParams_x000D_
.subscribe(params => {_x000D_
let code = params['code'];_x000D_
let userEmail = params['email'];_x000D_
});_x000D_
}
_x000D_
Ref: https://angular.io/docs/ts/latest/api/router/index/NavigationExtras-interface.html
I was looking for simple solution to remove views from viewpager (no fragments) dynamically. So, if you have some info, that your pages belongs to, you can set it to View as tag. Just like that (adapter code):
@Override
public Object instantiateItem(ViewGroup collection, int position)
{
ImageView iv = new ImageView(mContext);
MediaMessage msg = mMessages.get(position);
...
iv.setTag(media);
return iv;
}
@Override
public int getItemPosition (Object object)
{
View o = (View) object;
int index = mMessages.indexOf(o.getTag());
if (index == -1)
return POSITION_NONE;
else
return index;
}
You just need remove your info from mMessages, and then call notifyDataSetChanged()
for your adapter. Bad news there is no animation in this case.
For those who can't rely on Chronometer, I made a utility class out of one of the suggestions:
public class TimerTextHelper implements Runnable {
private final Handler handler = new Handler();
private final TextView textView;
private volatile long startTime;
private volatile long elapsedTime;
public TimerTextHelper(TextView textView) {
this.textView = textView;
}
@Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
textView.setText(String.format("%d:%02d", minutes, seconds));
if (elapsedTime == -1) {
handler.postDelayed(this, 500);
}
}
public void start() {
this.startTime = System.currentTimeMillis();
this.elapsedTime = -1;
handler.post(this);
}
public void stop() {
this.elapsedTime = System.currentTimeMillis() - startTime;
handler.removeCallbacks(this);
}
public long getElapsedTime() {
return elapsedTime;
}
}
to use..just do:
TimerTextHelper timerTextHelper = new TimerTextHelper(textView);
timerTextHelper.start();
.....
timerTextHelper.stop();
long elapsedTime = timerTextHelper.getElapsedTime();
There are several of this same question (1, 2). One way of doing it is using canvas. Here's a working solution. Here you can see some working examples of using this library.
It is always preferred to use a virtual environment ,Create your virtual environment using :
python -m venv <name_of_virtualenv>
go to your environment directory and activate your environment using below command on windows:
env_name\Scripts\activate.bat
then simply use
pip install package_name
Well another way :)
md5=`md5sum ${my_iso_file} | awk '{ print $1 }'`
You can simply create extra conditions which match the fields you require in the same function. For example, using your code above...
$(document).ready(function () {
$('#form').validate({
errorPlacement: function(error, element) {
//Custom position: first name
if (element.attr("name") == "first" ) {
$("#errNm1").text(error);
}
//Custom position: second name
else if (element.attr("name") == "second" ) {
$("#errNm2").text(error);
}
// Default position: if no match is met (other fields)
else {
error.append($('.errorTxt span'));
}
},
rules
});
Hope that helps!
re> |(?<=\w)/.+(?=\.\w+$)| Compile time 0.0011 milliseconds Memory allocation (code space): 32 Study time 0.0002 milliseconds Capturing subpattern count = 0 No options First char = '/' No need char Max lookbehind = 1 Subject length lower bound = 2 No set of starting bytes data> http://php.net/manual/en/function.preg-match.php Execute time 0.0007 milliseconds 0: /manual/en/function.preg-match
re> |//[^/]*(.*)\.\w+$| Compile time 0.0010 milliseconds Memory allocation (code space): 28 Study time 0.0002 milliseconds Capturing subpattern count = 1 No options First char = '/' Need char = '.' Subject length lower bound = 4 No set of starting bytes data> http://php.net/manual/en/function.preg-match.php Execute time 0.0005 milliseconds 0: //php.net/manual/en/function.preg-match.php 1: /manual/en/function.preg-match
re> |/[^/]+(.*)\.| Compile time 0.0008 milliseconds Memory allocation (code space): 23 Study time 0.0002 milliseconds Capturing subpattern count = 1 No options First char = '/' Need char = '.' Subject length lower bound = 3 No set of starting bytes data> http://php.net/manual/en/function.preg-match.php Execute time 0.0005 milliseconds 0: /php.net/manual/en/function.preg-match. 1: /manual/en/function.preg-match
re> |/[^/]+\K.*(?=\.)| Compile time 0.0009 milliseconds Memory allocation (code space): 22 Study time 0.0002 milliseconds Capturing subpattern count = 0 No options First char = '/' No need char Subject length lower bound = 2 No set of starting bytes data> http://php.net/manual/en/function.preg-match.php Execute time 0.0005 milliseconds 0: /manual/en/function.preg-match
re> |\w+\K/.*(?=\.)| Compile time 0.0009 milliseconds Memory allocation (code space): 22 Study time 0.0003 milliseconds Capturing subpattern count = 0 No options No first char Need char = '/' Subject length lower bound = 2 Starting byte set: 0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ a b c d e f g h i j k l m n o p q r s t u v w x y z data> http://php.net/manual/en/function.preg-match.php Execute time 0.0011 milliseconds 0: /manual/en/function.preg-match
As a slight improvement over the other answers, you can do the mkdir
and chmod
as a single operation using mkdir
's -m
switch.
$ mkdir -m 700 ${HOME}/.ssh
From a Linux system
$ mkdir --help
Usage: mkdir [OPTION]... DIRECTORY...
Create the DIRECTORY(ies), if they do not already exist.
Mandatory arguments to long options are mandatory for short options too.
-m, --mode=MODE set file mode (as in chmod), not a=rwx - umask
...
...
A little late here, but I've found this to be a common problem worth a custom directive to handle. Here's how that might look:
.directive('toggleOnHover', function(){
return {
restrict: 'A',
link: link
};
function link(scope, elem, attrs){
elem.on('mouseenter', applyToggleExp);
elem.on('mouseleave', applyToggleExp);
function applyToggleExp(){
scope.$apply(attrs.toggleOnHover);
}
}
});
You can use it like this:
<li toggle-on-hover="editableProp = !editableProp">edit</li>
Use the DATE function:
SELECT DATE(orders.date_purchased) AS date
The error is clear, isn't it?
You've not added the path where sqljdbc_auth.dll is present. Find out in the system where the DLL is and add that to your classpath.
And if that also doesn't work, add the folder where the DLL is present (I'm assuming \Microsoft SQL Server JDBC Driver 3.0\sqljdbc_3.0\enu\auth\x86) to your PATH variable.
Again if you're going via ant or cmd you have to explicitly mention the path using -Djava.library.path=[path to MS_SQL_AUTH_DLL]
You are trying to use the string as a function:
"Your new price is: $"(float(price) * 0.1)
Because there is nothing between the string literal and the (..)
parenthesis, Python interprets that as an instruction to treat the string as a callable and invoke it with one argument:
>>> "Hello World!"(42)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
Seems you forgot to concatenate (and call str()
):
easygui.msgbox("Your new price is: $" + str(float(price) * 0.1))
The next line needs fixing as well:
easygui.msgbox("Your new price is: $" + str(float(price) * 0.2))
Alternatively, use string formatting with str.format()
:
easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.1))
easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.2))
where {:02.2f}
will be replaced by your price calculation, formatting the floating point value as a value with 2 decimals.
If you are using word2vec, you need to calculate the average vector for all words in every sentence/document and use cosine similarity between vectors:
import numpy as np
from scipy import spatial
index2word_set = set(model.wv.index2word)
def avg_feature_vector(sentence, model, num_features, index2word_set):
words = sentence.split()
feature_vec = np.zeros((num_features, ), dtype='float32')
n_words = 0
for word in words:
if word in index2word_set:
n_words += 1
feature_vec = np.add(feature_vec, model[word])
if (n_words > 0):
feature_vec = np.divide(feature_vec, n_words)
return feature_vec
Calculate similarity:
s1_afv = avg_feature_vector('this is a sentence', model=model, num_features=300, index2word_set=index2word_set)
s2_afv = avg_feature_vector('this is also sentence', model=model, num_features=300, index2word_set=index2word_set)
sim = 1 - spatial.distance.cosine(s1_afv, s2_afv)
print(sim)
> 0.915479828613
like Paul said, use
conda create --prefix=/users/.../yourEnvName python=x.x
if you are located in the folder in which you want to create your virtual environment, just omit the path and use
conda create --prefix=yourEnvName python=x.x
conda only keep track of the environments included in the folder envs inside the anaconda folder. The next time you will need to activate your new env, move to the folder where you created it and activate it with
source activate yourEnvName
Try something like this:
public class test
{
public static void main(String a[])
{
long tmp = 1346524199000;
Date d = new Date(tmp);
System.out.println(d);
}
}
Both perform shallow copies as @PatrickDesjardins said (despite the many misled souls who think that CopyTo
does a deep copy).
However, CopyTo
allows you to copy one array to a specified index in the destination array, giving it significantly more flexibility.
You can try
<form action="product.php" method="get" name="frmProduct" id="frmProduct" enctype="multipart/form-data">
<input onclick="submitAction(this)" id="submit_value" type="button" name="submit_value" value="">
</form>
<script type="text/javascript">
function submitAction(element)
{
element.form.submit();
}
</script>
Don't you have more than one form with the same name ?
You are mixing razor and aspx syntax,if your view engine is razor just do this:
<button class="btn btn-info" type="button" id="addressSearch"
onclick="location.href='@Url.Action("List", "Search")'">
For non-preemptive system,
waitingTime = startTime - arrivalTime
turnaroundTime = burstTime + waitingTime = finishTime- arrivalTime
startTime = Time at which the process started executing
finishTime = Time at which the process finished executing
You can keep track of the current time elapsed in the system(timeElapsed
). Assign all processors to a process in the beginning, and execute until the shortest process is done executing. Then assign this processor which is free to the next process in the queue. Do this until the queue is empty and all processes are done executing. Also, whenever a process starts executing, recored its startTime
, when finishes, record its finishTime
(both same as timeElapsed
). That way you can calculate what you need.
is(':visible')
checks the display
property of an element, you can use css
method.
if (!$("#singlechatpanel-1").css('visibility') === 'hidden') {
// ...
}
If you set the display
property of the element to none
then your if
statement returns true
.
You can change the default location of .m2 directory in m2.conf file. It resides in your maven installation directory.
add modify this line in
m2.conf
set maven.home C:\Users\me\.m2
Wget currently only supports x-www-form-urlencoded data. --post-file
is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example
.
--post-data
and --post-file
work the same way: the only difference is that --post-data
allows you to specify the data in the command line, while --post-file
allows you to specify the path of the file that contain the data to send.
Here's the documentation:
--post-data=string
--post-file=file
Use POST as the method for all HTTP requests and send the specified data
in the request body. --post-data sends string as data, whereas
--post-file sends the contents of file. Other than that, they work in
exactly the same way. In particular, they both expect content of the
form "key1=value1&key2=value2", with percent-encoding for special
characters; the only difference is that one expects its content as a
command-line parameter and the other accepts its content from a file. In
particular, --post-file is not for transmitting files as form
attachments: those must appear as "key=value" data (with appropriate
percent-coding) just like everything else. Wget does not currently
support "multipart/form-data" for transmitting POST data; only
"application/x-www-form-urlencoded". Only one of --post-data and
--post-file should be specified.
Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.
Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN
.
wget --post-data 'user=foo&password=bar' http://example.com/auth.php
Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.
From Wikipedia:
UTC does not change with a change of seasons, but local time or civil time may change if a time zone jurisdiction observes daylight saving time (summer time). For example, local time on the east coast of the United States is five hours behind UTC during winter, but four hours behind while daylight saving is observed there.
So this is my code:
TimeSpan span = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0,DateTimeKind.Utc));
double unixTime = span.TotalSeconds;
It's 2020 and chances are the API has already a promise-based version that works with await. However, some interfaces, especially event emitters will require this workaround:
// doesn't wait
let value;
someEventEmitter.once((e) => { value = e.value; });
// waits
let value = await new Promise((resolve) => {
someEventEmitter.once('event', (e) => { resolve(e.value); });
});
In this particular case it would be:
let response = await new Promise((resolve) => {
myAPI.exec('SomeCommand', (response) => { resolve(response); });
});
Await has been in new Node.js releases for the past 3 years (since v7.6).
CASE might help you out:
SELECT t.first_name,
t.last_name,
t.employid,
t.status
FROM employeetable t
WHERE t.status = (CASE WHEN status_flag = STATUS_ACTIVE THEN 'A'
WHEN status_flag = STATUS_INACTIVE THEN 'T'
ELSE null END)
AND t.business_unit = (CASE WHEN source_flag = SOURCE_FUNCTION THEN 'production'
WHEN source_flag = SOURCE_USER THEN 'users'
ELSE null END)
AND t.first_name LIKE firstname
AND t.last_name LIKE lastname
AND t.employid LIKE employeeid;
The CASE statement evaluates multiple conditions to produce a single value. So, in the first usage, I check the value of status_flag, returning 'A', 'T' or null depending on what it's value is, and compare that to t.status. I do the same for the business_unit column with a second CASE statement.
You may debug using two ways:
Press CTRL+U to view page Source . Press CTRL+F to find "mystyles.css" in source . click on mystyles.css link and check if it is not showing "404 not found".
You can INSPECT ELEMENT IN FIRBUG and set path to Image ,Set Image height and width because sometimes image doesnt show up.
Hope this may works !!.
If you know x
and y
are both strings, using ===
is not strictly necessary, but is still good practice.
Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string
rather than an actual string, which may complicate things.
Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===
. Just go with that.
My solution: Installing libffi-dev with apt-get didn't help. But this helped: Installing libffi from source and then installing Python 3.8 from source.
My configuration: Ubuntu 16.04 LTS Python 3.8.2
Step by step:
I got the error message "ModuleNotFoundError: No module named '_ctypes'" when starting the debugger from Visual Studio Code, and when running python3 -c "import sklearn; sklearn.show_versions()"
.
sudo apt-get install libtool
The file README.md from libffi mentions that autoconf and automake are also necessary. They were already installed on my system../configure --disable-docs
make check
sudo make install
./configure
make
make test
make install
After that my python installation could find _ctypes.
I have added line
$this->_productCollection->addAttributeToSelect('releasedate');
in
app/code/core/Mage/Catalog/Block/Product/List.php on line 95
in function _getProductCollection()
and then call it in
app/design/frontend/default/hellopress/template/catalog/product/list.phtml
By writing code
<div><?php echo $this->__('Release Date: %s', $this->dateFormat($_product->getReleasedate())) ?>
</div>
Now it is working in Magento 1.4.x
try using concatenation of string
Statistics(string date)
{
this->date += date;
}
acually this was a part of a class..
The middle one writes to the pipeline. Write-Host
and Out-Host
writes to the console. 'echo' is an alias for Write-Output
which writes to the pipeline as well. The best way to write to the console would be using the Write-Host
cmdlet.
When an object is written to the pipeline it can be consumed by other commands in the chain. For example:
"hello world" | Do-Something
but this won't work since Write-Host
writes to the console, not to the pipeline (Do-Something will not get the string):
Write-Host "hello world" | Do-Something
As original question was - how to ignore the cert error, here is solution for those using SpringBoot and RestTemplate
@Service
public class SomeService {
private final RestTemplate restTemplate;
private final ObjectMapper objectMapper;
private static HttpComponentsClientHttpRequestFactory createRequestFactory() {
try {
SSLContextBuilder sslContext = new SSLContextBuilder();
sslContext.loadTrustMaterial(null, new TrustAllStrategy());
CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext.build()).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(client);
return requestFactory;
} catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException var3) {
throw new IllegalStateException("Couldn't create HTTP Request factory ignore SSL cert validity: ", var3);
}
}
@Autowired
public SomeService(RestTemplate restTemplate, ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
this.dimetorURL = dimetorURL;
restTemplate.setRequestFactory(createRequestFactory());
}
public ResponseEntity<ResponseObject> sendRequest(RequestObject requestObject) {
//...
return restTemplate.exchange(url, HttpMethod.GET, ResponseObject.class);
//...
}
}
Although its an old question let me give my input on it as well.
abstract class: Inside abstract class we can declare instance variables, which are required to the child class
Interface: Inside interface every variables is always public static and final we cannot declare instance variables
abstract class: Abstract class can talk about state of object
Interface: Interface can never talk about state of object
abstract class: Inside Abstract class we can declare constructors
Interface: Inside interface we cannot declare constructors as purpose of
constructors is to initialize instance variables. So what
is the need of constructor there if we cannot have instance
variables in interfaces.
abstract class: Inside abstract class we can declare instance and static blocks
Interface: Interfaces cannot have instance and static blocks.
abstract class: Abstract class cannot refer lambda expression
Interfaces: Interfaces with single abstract method can refer lambda expression
abstract class: Inside abstract class we can override OBJECT CLASS methods
Interfaces: We cannot override OBJECT CLASS methods inside interfaces.
I will end on the note that:
Default method concepts/static method concepts in interface came just to save implementation classes but not to provide meaningful useful implementation. Default methods/static methods are kind of dummy implementation, "if you want you can use them or you can override them (in case of default methods) in implementation class" Thus saving us from implementing new methods in implementation classes whenever new methods in interfaces are added. Therefore interfaces can never be equal to abstract classes.
Try this if your code lies in a form:
Graphics g = this.CreateGraphics();
points = pixels * 72 / g.DpiX;
g.Dispose();
Referring to answer of @Chris,
We can also go to parent directory of batch file and run commands using following
cd /d %~dp0..
<OTHER_BATCH_COMMANDS>
cmd.exe
To understand working of command cd /d %~dp0..
please refer below link
var formData = new FormData;
var alphaArray = ['A', 'B', 'C','D','E'];
for (var i = 0; i < alphaArray.length; i++) {
formData.append('listOfAlphabet', alphaArray [i]);
}
And In your request you will get array of alphabets.
Taken From www.regular-expressions.info
Greediness: Greedy quantifiers first tries to repeat the token as many times as possible, and gradually gives up matches as the engine backtracks to find an overall match.
Laziness: Lazy quantifier first repeats the token as few times as required, and gradually expands the match as the engine backtracks through the regex to find an overall match.
Just use plt.tight_layout()
before plt.show()
. It works well.
You can use an array of pointer to (homogeneous) member data to enable a dual, named-member (i.e. x.data) and array-subscript (i.e. x[idx]) interface.
#include <cassert>
#include <cstddef>
struct vector3 {
float x;
float y;
float z;
float& operator[](std::size_t idx) {
static float vector3::*component[3] = {
&vector3::x, &vector3::y, &vector3::z
};
return this->*component[idx];
}
};
int main()
{
vector3 v = { 0.0f, 1.0f, 2.0f };
assert(&v[0] == &v.x);
assert(&v[1] == &v.y);
assert(&v[2] == &v.z);
for (std::size_t i = 0; i < 3; ++i) {
v[i] += 1.0f;
}
assert(v.x == 1.0f);
assert(v.y == 2.0f);
assert(v.z == 3.0f);
return 0;
}
The common wisdom that floating-point numbers cannot be compared for equality is inaccurate. Floating-point numbers are no different from integers: If you evaluate "a == b", you will get true if they are identical numbers and false otherwise (with the understanding that two NaNs are of course not identical numbers).
The actual problem is this: If I have done some calculations and am not sure the two numbers I have to compare are exactly correct, then what? This problem is the same for floating-point as it is for integers. If you evaluate the integer expression "7/3*3", it will not compare equal to "7*3/3".
So suppose we asked "How do I compare integers for equality?" in such a situation. There is no single answer; what you should do depends on the specific situation, notably what sort of errors you have and what you want to achieve.
Here are some possible choices.
If you want to get a "true" result if the mathematically exact numbers would be equal, then you might try to use the properties of the calculations you perform to prove that you get the same errors in the two numbers. If that is feasible, and you compare two numbers that result from expressions that would give equal numbers if computed exactly, then you will get "true" from the comparison. Another approach is that you might analyze the properties of the calculations and prove that the error never exceeds a certain amount, perhaps an absolute amount or an amount relative to one of the inputs or one of the outputs. In that case, you can ask whether the two calculated numbers differ by at most that amount, and return "true" if they are within the interval. If you cannot prove an error bound, you might guess and hope for the best. One way of guessing is to evaluate many random samples and see what sort of distribution you get in the results.
Of course, since we only set the requirement that you get "true" if the mathematically exact results are equal, we left open the possibility that you get "true" even if they are unequal. (In fact, we can satisfy the requirement by always returning "true". This makes the calculation simple but is generally undesirable, so I will discuss improving the situation below.)
If you want to get a "false" result if the mathematically exact numbers would be unequal, you need to prove that your evaluation of the numbers yields different numbers if the mathematically exact numbers would be unequal. This may be impossible for practical purposes in many common situations. So let us consider an alternative.
A useful requirement might be that we get a "false" result if the mathematically exact numbers differ by more than a certain amount. For example, perhaps we are going to calculate where a ball thrown in a computer game traveled, and we want to know whether it struck a bat. In this case, we certainly want to get "true" if the ball strikes the bat, and we want to get "false" if the ball is far from the bat, and we can accept an incorrect "true" answer if the ball in a mathematically exact simulation missed the bat but is within a millimeter of hitting the bat. In that case, we need to prove (or guess/estimate) that our calculation of the ball's position and the bat's position have a combined error of at most one millimeter (for all positions of interest). This would allow us to always return "false" if the ball and bat are more than a millimeter apart, to return "true" if they touch, and to return "true" if they are close enough to be acceptable.
So, how you decide what to return when comparing floating-point numbers depends very much on your specific situation.
As to how you go about proving error bounds for calculations, that can be a complicated subject. Any floating-point implementation using the IEEE 754 standard in round-to-nearest mode returns the floating-point number nearest to the exact result for any basic operation (notably multiplication, division, addition, subtraction, square root). (In case of tie, round so the low bit is even.) (Be particularly careful about square root and division; your language implementation might use methods that do not conform to IEEE 754 for those.) Because of this requirement, we know the error in a single result is at most 1/2 of the value of the least significant bit. (If it were more, the rounding would have gone to a different number that is within 1/2 the value.)
Going on from there gets substantially more complicated; the next step is performing an operation where one of the inputs already has some error. For simple expressions, these errors can be followed through the calculations to reach a bound on the final error. In practice, this is only done in a few situations, such as working on a high-quality mathematics library. And, of course, you need precise control over exactly which operations are performed. High-level languages often give the compiler a lot of slack, so you might not know in which order operations are performed.
There is much more that could be (and is) written about this topic, but I have to stop there. In summary, the answer is: There is no library routine for this comparison because there is no single solution that fits most needs that is worth putting into a library routine. (If comparing with a relative or absolute error interval suffices for you, you can do it simply without a library routine.)
A slight modification beyond @udondan's answer. I like to reuse the registered variable names with the set_fact
to help keep the clutter to a minimum.
So if I were to register using the variable, psk
, I'd use that same variable name with creating the set_fact
.
- name: generate PSK
shell: openssl rand -base64 48
register: psk
delegate_to: 127.0.0.1
run_once: true
- set_fact:
psk={{ psk.stdout }}
- debug: var=psk
run_once: true
Then when I run it:
$ ansible-playbook -i inventory setup_ipsec.yml
PLAY [all] *************************************************************************************************************************************************************************
TASK [Gathering Facts] *************************************************************************************************************************************************************
ok: [hostc.mydom.com]
ok: [hostb.mydom.com]
ok: [hosta.mydom.com]
TASK [libreswan : generate PSK] ****************************************************************************************************************************************************
changed: [hosta.mydom.com -> 127.0.0.1]
TASK [libreswan : set_fact] ********************************************************************************************************************************************************
ok: [hosta.mydom.com]
ok: [hostb.mydom.com]
ok: [hostc.mydom.com]
TASK [libreswan : debug] ***********************************************************************************************************************************************************
ok: [hosta.mydom.com] => {
"psk": "6Tx/4CPBa1xmQ9A6yKi7ifONgoYAXfbo50WXPc1kGcird7u/pVso/vQtz+WdBIvo"
}
PLAY RECAP *************************************************************************************************************************************************************************
hosta.mydom.com : ok=4 changed=1 unreachable=0 failed=0
hostb.mydom.com : ok=2 changed=0 unreachable=0 failed=0
hostc.mydom.com : ok=2 changed=0 unreachable=0 failed=0