There is a download for the Google API Python Client library that contains the library and all of its dependencies, named something like google-api-python-client-gae-<version>.zip in the downloads section of the project. Just unzip this into your App Engine project.
Just in case you don't know the type of uploaded image, and you just you need to remove its base64
header:
var imageParts = model.ImageAsString.Split(',').ToList<string>();
//Exclude the header from base64 by taking second element in List.
byte[] Image = Convert.FromBase64String(imageParts[1]);
I had the same issue. I'm running a java rest app on a jboss server. But I think the solution is similar on an ASP .NET webapp.
Firefox makes a pre call to your server / rest url to check which options are allowed. That is the "OPTIONS" request which your server doesn't reply to accordingly. If this OPTIONS call is replied correct a second call is performed which is the actual "POST" request with json content.
This only happens when performing a cross-domain call. In your case calling 'http://localhost:16329/Hello
' instead of calling a url path under the same domain '/Hello'
If you intend to make a cross domain call you have to enhance your rest service class with an annotated method the supports a "OPTIONS" http request. This is the according java implementation:
@Path("/rest")
public class RestfulService {
@POST
@Path("/Hello")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public string HelloWorld(string name)
{
return "hello, " + name;
}
//THIS NEEDS TO BE ADDED ADDITIONALLY IF MAKING CROSS-DOMAIN CALLS
@OPTIONS
@Path("/Hello")
@Produces(MediaType.TEXT_PLAIN+ ";charset=utf-8")
public Response checkOptions(){
return Response.status(200)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "Content-Type")
.header("Access-Control-Allow-Methods", "POST, OPTIONS") //CAN BE ENHANCED WITH OTHER HTTP CALL METHODS
.build();
}
}
So I guess in .NET you have to add an additional method annotated with
[WebInvoke(
Method = "OPTIONS",
UriTemplate = "Hello",
ResponseFormat = WebMessageFormat.)]
where the following headers are set
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "Content-Type")
.header("Access-Control-Allow-Methods", "POST, OPTIONS")
Check if any other program is using that port.
If an instance of the same program is still active, kill that process.
None of the above examples worked for my personal needs. The below is what I ended up doing.
public class ContainsConstraint : IHttpRouteConstraint
{
public string[] array { get; set; }
public bool match { get; set; }
/// <summary>
/// Check if param contains any of values listed in array.
/// </summary>
/// <param name="param">The param to test.</param>
/// <param name="array">The items to compare against.</param>
/// <param name="match">Whether we are matching or NOT matching.</param>
public ContainsConstraint(string[] array, bool match)
{
this.array = array;
this.match = match;
}
public bool Match(System.Net.Http.HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
{
if (values == null) // shouldn't ever hit this.
return true;
if (!values.ContainsKey(parameterName)) // make sure the parameter is there.
return true;
if (string.IsNullOrEmpty(values[parameterName].ToString())) // if the param key is empty in this case "action" add the method so it doesn't hit other methods like "GetStatus"
values[parameterName] = request.Method.ToString();
bool contains = array.Contains(values[parameterName]); // this is an extension but all we are doing here is check if string array contains value you can create exten like this or use LINQ or whatever u like.
if (contains == match) // checking if we want it to match or we don't want it to match
return true;
return false;
}
To use the above in your route use:
config.Routes.MapHttpRoute("Default", "{controller}/{action}/{id}", new { action = RouteParameter.Optional, id = RouteParameter.Optional}, new { action = new ContainsConstraint( new string[] { "GET", "PUT", "DELETE", "POST" }, true) });
What happens is the constraint kind of fakes in the method so that this route will only match the default GET, POST, PUT and DELETE methods. The "true" there says we want to check for a match of the items in array. If it were false you'd be saying exclude those in the strYou can then use routes above this default method like:
config.Routes.MapHttpRoute("GetStatus", "{controller}/status/{status}", new { action = "GetStatus" });
In the above it is essentially looking for the following URL => http://www.domain.com/Account/Status/Active
or something like that.
Beyond the above I'm not sure I'd get too crazy. At the end of the day it should be per resource. But I do see a need to map friendly urls for various reasons. I'm feeling pretty certain as Web Api evolves there will be some sort of provision. If time I'll build a more permanent solution and post.
If you want to call function without form you can use my ngEnter directive:
Javascript:
angular.module('yourModuleName').directive('ngEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if(event.which === 13) {
scope.$apply(function(){
scope.$eval(attrs.ngEnter, {'event': event});
});
event.preventDefault();
}
});
};
});
HTML:
<div ng-app="" ng-controller="MainCtrl">
<input type="text" ng-enter="doSomething()">
</div>
I submit others awesome directives on my twitter and my gist account.
just use the core https module with the https.request function. Example for a POST
request (GET
would be similar):
var https = require('https');
var options = {
host: 'www.google.com',
port: 443,
path: '/upload',
method: 'POST'
};
var req = https.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
This error also occurs if you did not upload the various rsl/swc/flash-library that your swf file might expect. You may upload this RSL or missing swc or tweak your compiler options cf. http://help.adobe.com/en_US/flashbuilder/using/WSe4e4b720da9dedb5-1a92eab212e75b9d8b2-7ffe.html#WSe4e4b720da9dedb5-1a92eab212e75b9d8b2-7ff5
You just need to set the userTrackingMode of the MKMapView. If you only want to display and track the user location and implement the same behaviour as the Apple Maps app uses, there is no reason for writing additional code.
mapView.userTrackingMode = .follow
See more at https://developer.apple.com/documentation/mapkit/mkmapview/1616208-usertrackingmode .
Java Escape Sequences:
\u{0000-FFFF} /* Unicode [Basic Multilingual Plane only, see below] hex value
does not handle unicode values higher than 0xFFFF (65535),
the high surrogate has to be separate: \uD852\uDF62
Four hex characters only (no variable width) */
\b /* \u0008: backspace (BS) */
\t /* \u0009: horizontal tab (HT) */
\n /* \u000a: linefeed (LF) */
\f /* \u000c: form feed (FF) */
\r /* \u000d: carriage return (CR) */
\" /* \u0022: double quote (") */
\' /* \u0027: single quote (') */
\\ /* \u005c: backslash (\) */
\{0-377} /* \u0000 to \u00ff: from octal value
1 to 3 octal digits (variable width) */
The Basic Multilingual Plane is the unicode values from 0x0000 - 0xFFFF (0 - 65535). Additional planes can only be specified in Java by multiple characters: the egyptian heiroglyph A054 (laying down dude) is U+1303F
/ 𓀿
and would have to be broken into "\uD80C\uDC3F"
(UTF-16) for Java strings. Some other languages support higher planes with "\U0001303F"
.
Using Android default libraries like AppCompat, you can convert all the PDF pages into images. This way is very fast and optimized. The below code is for getting separate images of a PDF page. It is very fast and quick.
ParcelFileDescriptor fileDescriptor = ParcelFileDescriptor.open(new File("pdfFilePath.pdf"), MODE_READ_ONLY);
PdfRenderer renderer = new PdfRenderer(fileDescriptor);
final int pageCount = renderer.getPageCount();
for (int i = 0; i < pageCount; i++) {
PdfRenderer.Page page = renderer.openPage(i);
Bitmap bitmap = Bitmap.createBitmap(page.getWidth(), page.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(bitmap, 0, 0, null);
page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
page.close();
if (bitmap == null)
return null;
if (bitmapIsBlankOrWhite(bitmap))
return null;
String root = Environment.getExternalStorageDirectory().toString();
File file = new File(root + filename + ".png");
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
Log.v("Saved Image - ", file.getAbsolutePath());
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
=======================================================
private static boolean bitmapIsBlankOrWhite(Bitmap bitmap) {
if (bitmap == null)
return true;
int w = bitmap.getWidth();
int h = bitmap.getHeight();
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
int pixel = bitmap.getPixel(i, j);
if (pixel != Color.WHITE) {
return false;
}
}
}
return true;
}
I suggest to not only store a boolean flag, but the complete version code. This way you can also query at the beginning if it is the first start in a new version. You can use this information to display a "Whats new" dialog, for example.
The following code should work from any android class that "is a context" (activities, services, ...). If you prefer to have it in a separate (POJO) class, you could consider using a "static context", as described here for example.
/**
* Distinguishes different kinds of app starts: <li>
* <ul>
* First start ever ({@link #FIRST_TIME})
* </ul>
* <ul>
* First start in this version ({@link #FIRST_TIME_VERSION})
* </ul>
* <ul>
* Normal app start ({@link #NORMAL})
* </ul>
*
* @author schnatterer
*
*/
public enum AppStart {
FIRST_TIME, FIRST_TIME_VERSION, NORMAL;
}
/**
* The app version code (not the version name!) that was used on the last
* start of the app.
*/
private static final String LAST_APP_VERSION = "last_app_version";
/**
* Finds out started for the first time (ever or in the current version).<br/>
* <br/>
* Note: This method is <b>not idempotent</b> only the first call will
* determine the proper result. Any subsequent calls will only return
* {@link AppStart#NORMAL} until the app is started again. So you might want
* to consider caching the result!
*
* @return the type of app start
*/
public AppStart checkAppStart() {
PackageInfo pInfo;
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
AppStart appStart = AppStart.NORMAL;
try {
pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
int lastVersionCode = sharedPreferences
.getInt(LAST_APP_VERSION, -1);
int currentVersionCode = pInfo.versionCode;
appStart = checkAppStart(currentVersionCode, lastVersionCode);
// Update version in preferences
sharedPreferences.edit()
.putInt(LAST_APP_VERSION, currentVersionCode).commit();
} catch (NameNotFoundException e) {
Log.w(Constants.LOG,
"Unable to determine current app version from pacakge manager. Defenisvely assuming normal app start.");
}
return appStart;
}
public AppStart checkAppStart(int currentVersionCode, int lastVersionCode) {
if (lastVersionCode == -1) {
return AppStart.FIRST_TIME;
} else if (lastVersionCode < currentVersionCode) {
return AppStart.FIRST_TIME_VERSION;
} else if (lastVersionCode > currentVersionCode) {
Log.w(Constants.LOG, "Current version code (" + currentVersionCode
+ ") is less then the one recognized on last startup ("
+ lastVersionCode
+ "). Defenisvely assuming normal app start.");
return AppStart.NORMAL;
} else {
return AppStart.NORMAL;
}
}
It could be used from an activity like this:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
switch (checkAppStart()) {
case NORMAL:
// We don't want to get on the user's nerves
break;
case FIRST_TIME_VERSION:
// TODO show what's new
break;
case FIRST_TIME:
// TODO show a tutorial
break;
default:
break;
}
// ...
}
// ...
}
The basic logic can be verified using this JUnit test:
public void testCheckAppStart() {
// First start
int oldVersion = -1;
int newVersion = 1;
assertEquals("Unexpected result", AppStart.FIRST_TIME,
service.checkAppStart(newVersion, oldVersion));
// First start this version
oldVersion = 1;
newVersion = 2;
assertEquals("Unexpected result", AppStart.FIRST_TIME_VERSION,
service.checkAppStart(newVersion, oldVersion));
// Normal start
oldVersion = 2;
newVersion = 2;
assertEquals("Unexpected result", AppStart.NORMAL,
service.checkAppStart(newVersion, oldVersion));
}
With a bit more effort you could probably test the android related stuff (PackageManager and SharedPreferences) as well. Anyone interested in writing the test? :)
Note that the above code will only work properly if you don't mess around with your android:versionCode
in AndroidManifest.xml!
The onclick
property is all lower-case, and accepts a function, not a string.
document.getElementById("test").onclick = foo2;
See also addEventListener
.
You will first need to update the local formulas by doing
brew update
and then upgrade the package by doing
brew upgrade formula-name
An example would be if i wanted to upgrade mongodb, i would do something like this, assuming mongodb was already installed :
brew update && brew upgrade mongodb && brew cleanup mongodb
Here is another solution
Set a hidden scope variable in your html then you can use it from your controller:
<span style="display:none" >{{ formValid = myForm.$valid}}</span>
Here is the full working example:
angular.module('App', [])_x000D_
.controller('myController', function($scope) {_x000D_
$scope.userType = 'guest';_x000D_
$scope.formValid = false;_x000D_
console.info('Ctrl init, no form.');_x000D_
_x000D_
$scope.$watch('myForm', function() {_x000D_
console.info('myForm watch');_x000D_
console.log($scope.formValid);_x000D_
});_x000D_
_x000D_
$scope.isFormValid = function() {_x000D_
//test the new scope variable_x000D_
console.log('form valid?: ', $scope.formValid);_x000D_
};_x000D_
});
_x000D_
<!doctype html>_x000D_
<html ng-app="App">_x000D_
<head>_x000D_
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<form name="myForm" ng-controller="myController">_x000D_
userType: <input name="input" ng-model="userType" required>_x000D_
<span class="error" ng-show="myForm.input.$error.required">Required!</span><br>_x000D_
<tt>userType = {{userType}}</tt><br>_x000D_
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>_x000D_
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>_x000D_
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>_x000D_
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>_x000D_
_x000D_
_x000D_
/*-- Hidden Variable formValid to use in your controller --*/_x000D_
<span style="display:none" >{{ formValid = myForm.$valid}}</span>_x000D_
_x000D_
_x000D_
<br/>_x000D_
<button ng-click="isFormValid()">Check Valid</button>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
use this command php artisan migrate --path=/database/migrations/my_migration.php
it worked for me..
You missed the closing tag for the input fields, and you can choose any one of the events, ex: onload, onclick etc.
(a) Onload event:
<script type="text/javascript">
$(document).ready(function(){
$('#frm1').submit();
});
</script>
(b) Onclick Event:
<form name="frm1" id="frm1" action="../somePage" method="post">
Please Waite...
<input type="hidden" name="uname" id="uname" value=<?php echo $uname;?> />
<input type="hidden" name="price" id="price" value=<?php echo $price;?> />
<input type="text" name="submit" id="submit" value="submit">
</form>
<script type="text/javascript">
$('#submit').click(function(){
$('#frm1').submit();
});
</script>
Later versions of Safari allow you to Disable Cross-Origin Restrictions. Just enable the developer menu from Preferences >> Advanced, and select "Disable Cross-Origin Restrictions" from the develop menu.
If you want local only, then you only need to enable the developer menu, and select "Disable local file restrictions" from the develop menu.
I used friedmud's answer. I looked into this for a while, and it seems to be a good way to get started. This solution also has a well defined method of adding compiler flags. I answered again, because I made changes to make it work in my environment, Ubuntu and g++. More working examples are the best teacher, sometimes.
appname := myapp
CXX := g++
CXXFLAGS := -Wall -g
srcfiles := $(shell find . -maxdepth 1 -name "*.cpp")
objects := $(patsubst %.cpp, %.o, $(srcfiles))
all: $(appname)
$(appname): $(objects)
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $(appname) $(objects) $(LDLIBS)
depend: .depend
.depend: $(srcfiles)
rm -f ./.depend
$(CXX) $(CXXFLAGS) -MM $^>>./.depend;
clean:
rm -f $(objects)
dist-clean: clean
rm -f *~ .depend
include .depend
Makefiles seem to be very complex. I was using one, but it was generating an error related to not linking in g++ libraries. This configuration solved that problem.
You can download a custom version of bootstrap and set @navbarBackground to the color you want.
Your browser's default font-family will be inherited for that case.
You can check the browser default font in chrome: Settings > Web content > Customize fonts...
Edit This will create a link with Edit after clicking on editing a function name as edit will be called.
cd to sessions directory and then:
1) View sessions older than 40 min:
find . -amin +40 -exec stat -c "%n %y" {} \;
2) Remove sessions older than 40 min:
find . -amin +40 -exec rm {} \;
This happened to me also, while i was reading text containing Hebrew from a .txt
file.
I clicked: file -> save as
and I saved this file as a UTF-8
encoding
I just wanted to add one more solution for those having issues installing setuptools from Windows 64-bit. The issue is discussed in this bug on python.org and is still unresolved as of the date of this comment. A simple workaround is mentioned and it works flawlessly. One registry change did the trick for me.
Link: http://bugs.python.org/issue6792#
Solution that worked for me...:
Add this registry setting for 2.6+ versions of Python:
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.6\InstallPath]
@="C:\\Python26\\"
This is most likely the registry setting you will already have for Python 2.6+:
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath]
@="C:\\Python26\\"
Clearly, you will need to replace the 2.6 version with whatever version of Python you are running.
This is how I do it in Laravel 5
return Response::json(['hello' => $value],201);
Or using a helper function:
return response()->json(['hello' => $value], 201);
If I understood you correctly:
var hash = {};
hash['bob'] = 123;
hash['joe'] = 456;
var sum = 0;
for (var name in hash) {
sum += hash[name];
}
alert(sum); // 579
You could try a different approach like read the file line by line instead of dealing with all this nl2br / explode stuff.
$fh = fopen("employees.txt", "r"); if ($fh) { while (($line = fgets($fh)) !== false) { $line = trim($line); echo "<option value='".$line."'>".$line."</option>"; } } else { // error opening the file, do something }
Also maybe just doing a trim (remove whitespace from beginning/end of string) is your issue?
And maybe people are just misunderstanding what you mean by "submitting results to a spreadsheet" -- are you doing this with code? or a copy/paste from an HTML page into a spreadsheet? Maybe you can explain that in more detail. The delimiter for which you split the lines of the file shouldn't be displaying in the output anyway unless you have unexpected output for some other reason.
Here's what worked for me:
select visits, activations, simulations, simulations/activations
as sims_per_visit, activations/visits*100
as adoption_rate, simulations/activations*100
as completion_rate, duration/60
as minutes, m1 as month, Wk1 as week, Yr1 as year
from
(
(select count(*) as visits, year(stamp) as Yr1, week(stamp) as Wk1, month(stamp)
as m1 from sessions group by week(stamp), year(stamp)) as t3
join
(select count(*) as activations, year(stamp) as Yr2, week(stamp) as Wk2,
month(stamp) as m2 from sessions where activated='1' group by week(stamp),
year(stamp)) as t4
join
(select count(*) as simulations, year(stamp) as Yr3 , week(stamp) as Wk3,
month(stamp) as m3 from sessions where simulations>'0' group by week(stamp),
year(stamp)) as t5
join
(select avg(duration) as duration, year(stamp) as Yr4 , week(stamp) as Wk4,
month(stamp) as m4 from sessions where activated='1' group by week(stamp),
year(stamp)) as t6
)
where Yr1=Yr2 and Wk1=Wk2 and Wk1=Wk3 and Yr1=Yr3 and Yr1=Yr4 and Wk1=Wk4
I used joins, not unions (I needed different columns for each query, a join puts it all in the same column) and I dropped the quotation marks (compared to what Liam was doing) because they were giving me errors.
Thanks! I couldn't have pulled that off without this page! PS: Sorry I don't know how you're getting your statements formatted with colors. etc.
Define the variables at the beginning of the function so if there are no records, the variables exist and you won't get the error. Check for null values in the returned array.
$hn = null;
$pid = null;
$datereg = null;
$prefix = null;
$fname = null;
$lname = null;
$age = null;
$sex = null;
This helped me to resolve the problem (one line - split for readability / copy-ability):
C:\Windows\System32\inetsrv\appcmd set config "YOUR_WEBSITE_NAME"
-section:system.webServer/serverRuntime /uploadReadAheadSize:"2147483647"
/commit:apphost
What this means is that your web page is referring to content which is in the folder one level up from your page, but your page is already in the website's root folder, so the relative path is invalid. Judging by your exception message it looks like an image control is causing the problem.
You must have something like:
<asp:Image ImageUrl="..\foo.jpg" />
But since the page itself is in the root folder of the website, it cannot refer to content one level up, which is what the leading ..\
is doing.
Send the data from the form:
$("#change_section_type").live "change", ->
url = $(this).attr("data-url")
postData = $(this).parents("#contract_setting_form").serializeArray()
$.ajax
type: "PUT"
url: url
dataType: "script"
data: postData
The error is:
Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])
In JSON, platforms
look like this:
"platforms": [
{
"platform": "iphone"
},
{
"platform": "ipad"
},
{
"platform": "android_phone"
},
{
"platform": "android_tablet"
}
]
So try change your pojo to something like this:
private List platforms;
public List getPlatforms(){
return this.platforms;
}
public void setPlatforms(List platforms){
this.platforms = platforms;
}
EDIT: you will need change mobile_networks
too. Will look like this:
private List mobile_networks;
public List getMobile_networks() {
return mobile_networks;
}
public void setMobile_networks(List mobile_networks) {
this.mobile_networks = mobile_networks;
}
I have written some code to implement the trim functionality.
LTRIM (trim left):
function ltrim(s)
{
var l=0;
while(l < s.length && s[l] == ' ')
{ l++; }
return s.substring(l, s.length);
}
RTRIM (trim right):
function rtrim(s)
{
var r=s.length -1;
while(r > 0 && s[r] == ' ')
{ r-=1; }
return s.substring(0, r+1);
}
TRIM (trim both sides):
function trim(s)
{
return rtrim(ltrim(s));
}
OR
Regular expression is also available which we can use.
function trimStr(str) {
return str.replace(/^\s+|\s+$/g, '');
}
Maybe you can run this regex first to see if the line is all caps:
^[A-Z \d\W]+$
That will match only if it's a line like THING P1 MUST CONNECT TO X2.
Otherwise, you should be able to pull out the individual uppercase phrases with this:
[A-Z][A-Z\d]+
That should match "P1" and "J236" in The thing P1 must connect to the J236 thing in the Foo position.
First go (pre-OP-edit): Use sets:
mylist = [1,2,3,4,5,6,7]
goodvals = [1,3,7,8,9]
myset = set(mylist)
goodset = set(goodvals)
print list(myset.intersection(goodset)) # [1, 3, 7]
print list(myset.difference(goodset)) # [2, 4, 5, 6]
That's good for both readability (IMHO) and performance.
Second go (post-OP-edit):
Create your list of good extensions as a set:
IMAGE_TYPES = set(['.jpg','.jpeg','.gif','.bmp','.png'])
and that will increase performance. Otherwise, what you have looks fine to me.
Import the file itself. Assuming the file is called test.py:
import test
if __name__=='__main__':
test.func()
else:
def func():
print('Func worked')
Remember.. inherits is case sensitive for C# (not so for vb.net)
Found that out the hard way.
The other answers here have demonstrated how to define structs inside of classes. There’s another way to do this, and that’s to declare the struct inside the class, but define it outside. This can be useful, for example, if the struct is decently complex and likely to be used standalone in a way that would benefit from being described in detail somewhere else.
The syntax for this is as follows:
class Container {
...
struct Inner; // Declare, but not define, the struct.
...
};
struct Container::Inner {
/* Define the struct here. */
};
You more commonly would see this in the context of defining nested classes rather than structs (a common example would be defining an iterator type for a collection class), but I thought for completeness it would be worth showing off here.
Go to Build Settings, under Code Signing, set Code Signing Identity as iOS Developer & Provisioning Profile as Automatic.
Select your device (now visible) from drop down list and run your app.
l =['abc' , 'cd' , 'xy' , 'ba' , 'dc']
l.sort()
print(l1)
Result
['abc', 'ba', 'cd', 'dc', 'xy']
Use the matplotlib savefig
function with the keyword argument transparent=True
to save the image as a png file.
In [30]: x = np.linspace(0,6,31)
In [31]: y = np.exp(-0.5*x) * np.sin(x)
In [32]: plot(x, y, 'bo-')
Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>]
In [33]: savefig('demo.png', transparent=True)
Result:
Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display
command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.
To answer your main question, you want to use the subplot command. I think changing plt.figure(i)
to plt.subplot(4,4,i+1)
should work.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendMail1 {
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "valid email to address";
// Sender's email ID needs to be mentioned
String from = "valid email from address";
// Get system properties
Properties properties = System.getProperties();
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
Authenticator authenticator = new Authenticator () {
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("userid","password");//userid and password for "from" email address
}
};
Session session = Session.getDefaultInstance( properties , authenticator);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
To remove bullet from UL
you can simply use list-style: none;
or list-style-type: none;
If still not works then i guess there is an issue of priority CSS. May be globally UL already defined. So best way add a class/ID to that particular UL and add your CSS there. Hope it will works.
osascript -e 'display notification "hello world!"'
osascript -e 'display notification "hello world!" with title "This is the title"'
osascript -e 'display notification "hello world!" with title "Greeting" sound name "Submarine"'
osascript -e 'display notification "'"$TR_TORRENT_NAME has finished downloading!"'" with title " ? Transmission-daemon"'
credits: https://code-maven.com/display-notification-from-the-mac-command-line
My solution is similar to the one of lolo above. However, I insert the HTML code via JavaScript's document.write instead of using jQuery:
a.html:
<html>
<body>
<h1>Put your HTML content before insertion of b.js.</h1>
...
<script src="b.js"></script>
...
<p>And whatever content you want afterwards.</p>
</body>
</html>
b.js:
document.write('\
\
<h1>Add your HTML code here</h1>\
\
<p>Notice however, that you have to escape LF's with a '\', just like\
demonstrated in this code listing.\
</p>\
\
');
The reason for me against using jQuery is that jQuery.js is ~90kb in size, and I want to keep the amount of data to load as small as possible.
In order to get the properly escaped JavaScript file without much work, you can use the following sed command:
sed 's/\\/\\\\/g;s/^.*$/&\\/g;s/'\''/\\'\''/g' b.html > escapedB.html
Or just use the following handy bash script published as a Gist on Github, that automates all necessary work, converting b.html
to b.js
:
https://gist.github.com/Tafkadasoh/334881e18cbb7fc2a5c033bfa03f6ee6
Credits to Greg Minshall for the improved sed command that also escapes back slashes and single quotes, which my original sed command did not consider.
Alternatively for browsers that support template literals the following also works:
b.js:
document.write(`
<h1>Add your HTML code here</h1>
<p>Notice, you do not have to escape LF's with a '\',
like demonstrated in the above code listing.
</p>
`);
If you are looking for easy one liners to sort 2d array, then here you go.
Sort String[][] arr in ascending order by first column
Arrays.sort(arr, (a, b) -> a[0].compareTo(b[0]);
Sort String[][] arr in descending order by first column
Arrays.sort(arr, (a, b) -> b[0].compareTo(a[0]);
Sort String[][] arr in ascending order by second column
Arrays.sort(arr, (a, b) -> a[1].compareTo(b[1]);
Sort String[][] arr in descending order by second column
Arrays.sort(arr, (a, b) -> b[1].compareTo(a[1]);
Sort int[][] arr in ascending order by first column
Arrays.sort(arr, (a, b) -> Integer.compare(a[0], b[0]));
or
Arrays.sort(arr, (a, b) -> a[0] - b[0]);
Sort int[][] arr in descending order by first column
Arrays.sort(arr, (a, b) -> Integer.compare(b[0], a[0]));
or
Arrays.sort(arr, (a, b) -> b[0] - a[0]);
Sort int[][] arr in ascending order by second column
Arrays.sort(arr, (a, b) -> Integer.compare(a[1], b[1]));
or
Arrays.sort(arr, (a, b) -> a[1] - b[1]);
Sort int[][] arr in descending order by second column
Arrays.sort(arr, (a, b) -> Integer.compare(b[1], a[1]));
or
Arrays.sort(arr, (a, b) -> b[1] - a[1]);
This seems to work for Ionic5 on iphone 6 Plus on iOS 12.4.2
.large_player {
float: left;
bottom: 0;
width: 100%;
position: fixed;
background-color: white;
border-top: black 1px solid;
height: 14rem;
z-index: 100;
transform: translate3d(0,0,0);
}
The transform
tag makes it work, but it also seems a little clunky in how the scroll works, it is seems to redraw the 'on top' element after it's all moved and sort of resets and makes it jump a little.
Or, you could also use this tag option as well, position: -webkit-sticky;
, but then you won't get, or may run in to trouble with WPA/browser or Android builds while having to do version checking and have multiple CSS tags.
.large_player {
float: left;
bottom: 0;
width: 100%;
position: -webkit-sticky;
background-color: white;
border-top: black 1px solid;
height: 14rem;
z-index: 100;
}
I don't know at what point it was fixed, but later iOS phones work without the transform tag. I don't know if it's the iOS version, or the phone.
As most iOS devices are usually on the most recent iOS version, it's pretty safe with go with a weird work around - such as using the transform
tag, rather than building in a quirky detection routine for the sake of less than 1% of users.
Update:
After thinking about this answer further, this is just another way of doing this by platform for ionic5+:
.TS
import {Platform } from '@ionic/angular';
constructor(
public platform: Platform
)
{
// This next bit is so that the CSS is shown correctly for each platform
platform.ready().then(() => {
if (this.platform.is('android')) {
console.log("running on Android device!");
this.css_iOS = false;
}
if (this.platform.is('ios')) {
console.log("running on iOS device!");
this.css_iOS = true;
}
if (this.platform.is('ipad')) {
console.log("running on iOS device!");
this.css_iOS = true;
}
});
}
css_iOS: boolean = false;
.HTML
<style *ngIf="css_iOS">
.small_player {
position: -webkit-sticky !important;
}
.large_player {
position: -webkit-sticky !important;
}
</style>
<style>
.small_player {
float: left;
bottom: 0;
width: 100%;
position: fixed;
background-color: white;
border-top: black 1px solid;
height: 4rem;
z-index: 100;
/*transform: translate3d(0,0,0);*/
}
.large_player {
float: left;
bottom: 0;
width: 100%;
position: fixed;
background-color: white;
border-top: black 1px solid;
height: 14rem;
z-index: 100;
/*transform: translate3d(0,0,0);*/
}
</style>
.android
check this folder in
C:\Users\user
its have an issue and fix it then restart android studio.
I got this error because I was using a wrong CSS selector with the Selenium WebDriver Node.js function By.css()
.
You can check if your selector is correct by using it in the web console of your web browser (Ctrl+Shift+K shortcut), with the JavaScript function document.querySelectorAll()
.
This code will check whether the alert is present or not.
public static void isAlertPresent(){
try{
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText()+" Alert is Displayed");
}
catch(NoAlertPresentException ex){
System.out.println("Alert is NOT Displayed");
}
}
Below conf works for me:
JAVA_HOME=/JDK1.7.51-64/jdk1.7.0_51/
PATH=/JDK1.7.51-64/jdk1.7.0_51/bin:$PATH
export PATH
export JAVA_HOME
JVM_ARGS="-d64 -Xms1024m -Xmx15360m -server"
/JDK1.7.51-64/jdk1.7.0_51/bin/java $JVM_ARGS -jar `dirname $0`/ApacheJMeter.jar "$@"
Jonathon's answer is better, but to let you know somelist[-1]
is one of the LastIndexOf
notations available.
As krusty.ar mentioned somelist.last
apparently is too.
irb(main):003:0* f = 'C:\\path\\file.txt'
irb(main):007:0> f.split('\\')
=> ["C:", "path", "file.txt"]
irb(main):008:0> f.split('\\')[-1]
=> "file.txt"
Simply use String.ElementAt()
. It's quite similar to java's String.charAt()
. Have fun coding!
I had a similar issue while doing AOT angular build. Following commands helped me.
npm install -g increase-memory-limit
increase-memory-limit
Source: https://geeklearning.io/angular-aot-webpack-memory-trick/
text/javascript
is obsolete, and application/x-javascript
was experimental (hence the x-
prefix) for a transitional period until application/javascript
could be standardised.
You should use application/javascript
. This is documented in the RFC.
As far a browsers are concerned, there is no difference (at least in HTTP headers). This was just a change so that the text/*
and application/*
MIME type groups had a consistent meaning where possible. (text/*
MIME types are intended for human readable content, JavaScript is not designed to directly convey meaning to humans).
Note that using application/javascript
in the type
attribute of a script element will cause the script to be ignored (as being in an unknown language) in some older browsers. Either continue to use text/javascript
there or omit the attribute entirely (which is permitted in HTML 5).
This isn't a problem in HTTP headers as browsers universally (as far as I'm aware) either ignore the HTTP content-type of scripts entirely, or are modern enough to recognise application/javascript
.
even simpler, adding up to String[]
,
use built-in filter filter(StringUtils::isNotEmpty)
of org.apache.commons.lang3
import org.apache.commons.lang3.StringUtils;
String test = "a\nb\n\nc\n";
String[] lines = test.split("\\n", -1);
String[] result = Arrays.stream(lines).filter(StringUtils::isNotEmpty).toArray(String[]::new);
System.out.println(Arrays.toString(lines));
System.out.println(Arrays.toString(result));
and output:
[a, b, , c, ]
[a, b, c]
An int (or any other data type for that matter) is already stored as bytes in memory. So why not just copy the memory directly?
memcpy(arrayOfByte, &x, sizeof x);
A simple elegant one liner that will also work with any other data type.
If you need the bytes reversed you can use std::reverse
memcpy(arrayOfByte, &x, sizeof x);
std::reverse(arrayOfByte, arrayOfByte + sizeof x);
or better yet, just copy the bytes in reverse to begin with
BYTE* p = (BYTE*) &x;
std::reverse_copy(p, p + sizeof x, arrayOfByte);
If you don't want to make a copy of the data at all, and just have its byte representation
BYTE* bytes = (BYTE*) &x;
There's a write-up here that may be of use: Set Focus to First Input on Web Page
None of these answers worked for me. This is how I did it.
position: relative;
left: 50%;
-webkit-transform: translateX(-50%);
-ms-transform: translateX(-50%);
transform: translateX(-50%);
I just got around to doing this myself, so the following is where I am so far in terms of a CentOS init.d service controller script. It's working quite nicely so far, but I'm no leet Bash hacker, so I'm sure there's room for improvement, so thoughts on improving it are welcome.
First of all, I have a short config script /data/svcmgmt/conf/my-spring-boot-api.sh
for each service, which sets up environment variables.
#!/bin/bash
export JAVA_HOME=/opt/jdk1.8.0_05/jre
export APP_HOME=/data/apps/my-spring-boot-api
export APP_NAME=my-spring-boot-api
export APP_PORT=40001
I'm using CentOS, so to ensure that my services are started after a server restart, I have a service control script in /etc/init.d/my-spring-boot-api
:
#!/bin/bash
# description: my-spring-boot-api start stop restart
# processname: my-spring-boot-api
# chkconfig: 234 20 80
. /data/svcmgmt/conf/my-spring-boot-api.sh
/data/svcmgmt/bin/spring-boot-service.sh $1
exit 0
As you can see, that calls the initial config script to set up environment variables and then calls a shared script which I use for restarting all of my Spring Boot services. That shared script is where the meat of it all can be found:
#!/bin/bash
echo "Service [$APP_NAME] - [$1]"
echo " JAVA_HOME=$JAVA_HOME"
echo " APP_HOME=$APP_HOME"
echo " APP_NAME=$APP_NAME"
echo " APP_PORT=$APP_PORT"
function start {
if pkill -0 -f $APP_NAME.jar > /dev/null 2>&1
then
echo "Service [$APP_NAME] is already running. Ignoring startup request."
exit 1
fi
echo "Starting application..."
nohup $JAVA_HOME/bin/java -jar $APP_HOME/$APP_NAME.jar \
--spring.config.location=file:$APP_HOME/config/ \
< /dev/null > $APP_HOME/logs/app.log 2>&1 &
}
function stop {
if ! pkill -0 -f $APP_NAME.jar > /dev/null 2>&1
then
echo "Service [$APP_NAME] is not running. Ignoring shutdown request."
exit 1
fi
# First, we will try to trigger a controlled shutdown using
# spring-boot-actuator
curl -X POST http://localhost:$APP_PORT/shutdown < /dev/null > /dev/null 2>&1
# Wait until the server process has shut down
attempts=0
while pkill -0 -f $APP_NAME.jar > /dev/null 2>&1
do
attempts=$[$attempts + 1]
if [ $attempts -gt 5 ]
then
# We have waited too long. Kill it.
pkill -f $APP_NAME.jar > /dev/null 2>&1
fi
sleep 1s
done
}
case $1 in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
esac
exit 0
When stopping, it will attempt to use Spring Boot Actuator to perform a controlled shutdown. However, in case Actuator is not configured or fails to shut down within a reasonable time frame (I give it 5 seconds, which is a bit short really), the process will be killed.
Also, the script makes the assumption that the java process running the appllication will be the only one with "my-spring-boot-api.jar" in the text of the process details. This is a safe assumption in my environment and means that I don't need to keep track of PIDs.
You can simply use background
CSS property as follows:
tr:hover{
background: #F1F1F2;
}
You don't have to use Javascript to do this. Using plain-old css:
div.blah {
position:absolute;
top: 0; /*[wherever you want it]*/
left:0; /*[wherever you want it]*/
}
If you feel you must use javascript, or are trying to do this dynamically Using JQuery, this affects all divs of class "blah":
var blahclass = $('.blah');
blahclass.css('position', 'absolute');
blahclass.css('top', 0); //or wherever you want it
blahclass.css('left', 0); //or wherever you want it
Alternatively, if you must use regular old-javascript you can grab by id
var domElement = document.getElementById('myElement');// don't go to to DOM every time you need it. Instead store in a variable and manipulate.
domElement.style.position = "absolute";
domElement.style.top = 0; //or whatever
domElement.style.left = 0; // or whatever
It looks as if you were on the right track. You just need to add the else statement after the ";" following the "then" statement. Also I would split the first line from the second line with a semicolon instead of joining it with "&&".
maxline='cat journald.conf | grep "#SystemMaxUse="'; if [ $maxline == "#SystemMaxUse=" ]; then sed 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf > journald.conf2 && mv journald.conf2 journald.conf; else echo "This file has been edited. You'll need to do it manually."; fi
Also in your original script, when declaring maxline you used back-ticks "`" instead of single quotes "'" which might cause problems.
You can also declare 'x' with the keyword var:
var x = new
{
driver = new
{
firstName = "john",
lastName = "walter"
},
car = new
{
brand = "BMW"
}
};
This will allow you to declare your x object inline, but you will have to name your 2 anonymous objects, in order to access them. You can have an array of "x" :
x.driver.firstName // "john"
x.car.brand // "BMW"
var y = new[] { x, x, x, x };
y[1].car.brand; // "BMW"
In Rails 3, I don't know anything fancier. However, I'm not sure if you're aware, your not equal condition does not match for (user_id) NULL values. If you want that, you'll have to do something like this:
GroupUser.where("user_id != ? OR user_id IS NULL", me)
in json everything is string between double quote ", so you need escape " if it happen in value (only in direct writing) use backslash \
and everything in json file wrapped in {} change your json to
{_x000D_
[_x000D_
{_x000D_
"id": "services.html",_x000D_
"img": "img/SolutionInnerbananer.jpg",_x000D_
"html": "<h2 class=\"fg-white\">AboutUs</h2><p class=\"fg-white\">developing and supporting complex IT solutions.Touching millions of lives world wide by bringing in innovative technology</p>"_x000D_
}_x000D_
]_x000D_
}
_x000D_
string CurrentMonth = String.Format("{0:MMMM}", DateTime.Now)
You seem to be aware already, but I'll just restate it anyway; It's a bad sign, if you need to test protected methods. The aim of a unit test, is to test the interface of a class, and protected methods are implementation details. That said, there are cases where it makes sense. If you use inheritance, you can see a superclass as providing an interface for the subclass. So here, you would have to test the protected method (But never a private one). The solution to this, is to create a subclass for testing purpose, and use this to expose the methods. Eg.:
class Foo {
protected function stuff() {
// secret stuff, you want to test
}
}
class SubFoo extends Foo {
public function exposedStuff() {
return $this->stuff();
}
}
Note that you can always replace inheritance with composition. When testing code, it's usually a lot easier to deal with code that uses this pattern, so you may want to consider that option.
You can try with mentioning "Accept: application/json" in your rest client header as well, if you are expecting your object as JSON in response.
Try this
if(name.getText() != null && name.getText().equals(""))
{
loginbt.setEnabled(false);
}
else
{
loginbt.setEnabled(true);
}
My gut feeling is that this is (again) a mac/OSX-thing: the front end and the back end assume a different location for the unix-domain socket (which functions as a rendezvous point).
Checklist:
ps aux | grep postgres | grep -v grep
should do the trickfind / -name .s.PGSQL.5432 -ls
(the socket used to be in /tmp; you could start looking there)If postgres is running, and the socket actually exists, you could use:
psql -h /the/directory/where/the/socket/was/found mydbname
(which attempts to connect to the unix-domain socket)
; you should now get the psql prompt: try \d
and then \q
to quit. You could also
try:
psql -h localhost mydbname
.(which attempts to connect to localhost (127.0.0.1)
If these attempts fail because of insufficient authorisation, you could alter pg_hba.conf (and SIGHUP or restart) In this case: also check the logs.
A similar question: Can't get Postgres started
Note: If you can get to the psql prompt, the quick fix to this problem is just to change your config/database.yml
, add:
host: localhost
or you could try adding:
host: /the/directory/where/the/socket/was/found
In my case, host: /tmp
You can also define a variable directly in the PowerShell command line and then execute the script. The variable will be defined there, too. This helped me in a case where I couldn't modify a signed script.
Example:
PS C:\temp> $stepsize = 30
PS C:\temp> .\itunesForward.ps1
with iTunesForward.ps1 being
$iTunes = New-Object -ComObject iTunes.Application
if ($iTunes.playerstate -eq 1)
{
$iTunes.PlayerPosition = $iTunes.PlayerPosition + $stepsize
}
I'd just like to add to Jon's example. To get a reference to your own assembly, you can use:
Assembly myAssembly = Assembly.GetExecutingAssembly();
System.Reflection
namespace.
If you want to examine an assembly that you have no reference to, you can use either of these:
Assembly assembly = Assembly.ReflectionOnlyLoad(fullAssemblyName);
Assembly assembly = Assembly.ReflectionOnlyLoadFrom(fileName);
If you intend to instantiate your type once you've found it:
Assembly assembly = Assembly.Load(fullAssemblyName);
Assembly assembly = Assembly.LoadFrom(fileName);
See the Assembly class documentation for more information.
Once you have the reference to the Assembly
object, you can use assembly.GetTypes()
like Jon already demonstrated.
As Yanflea mentioned, there is a way to go around this.
In Maven 3.5.0 you can use the following way of transferring the version down from the parent project:
<project ...>
<modelVersion>4.0.0</modelVersion>
<groupId>com.mydomain</groupId>
<artifactId>myprojectparent</artifactId>
<packaging>pom</packaging>
<version>${myversion}</version>
<name>MyProjectParent</name>
<properties>
<myversion>0.1-SNAPSHOT</myversion>
</properties>
<modules>
<module>modulefolder</module>
</modules>
...
</project>
<project ...>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.mydomain</groupId>
<artifactId>myprojectmodule</artifactId>
<version>${myversion}</version> <!-- This still needs to be set, but you can use properties from parent -->
</parent>
<groupId>se.car_o_liner</groupId>
<artifactId>vinno</artifactId>
<packaging>war</packaging>
<name>Vinno</name>
<!-- Note that there's no version specified; it's inherited from parent -->
...
</project>
You are free to change myversion
to whatever you want that isn't a reserved property.
WHERE t.date >= DATE_ADD(CURDATE(), INTERVAL '-3' DAY);
use quotes on the -3 value
8.833333333339
(or 8.833333333333334
, the result of 106.00/12
) properly rounded to two decimal places is 8.83
. Mathematically it sounds like what you want is a ceiling function. The one in Python's math
module is named ceil
:
import math
v = 8.8333333333333339
print(math.ceil(v*100)/100) # -> 8.84
Respectively, the floor and ceiling functions generally map a real number to the largest previous or smallest following integer which has zero decimal places — so to use them for 2 decimal places the number is first multiplied by 102 (or 100) to shift the decimal point and is then divided by it afterwards to compensate.
If you don't want to use the math
module for some reason, you can use this (minimally tested) implementation I just wrote:
def ceiling(x):
n = int(x)
return n if n-1 < x <= n else n+1
From the sample output it appears that they rounded up the monthly payment, which is what many call the effect of the ceiling function. This means that each month a little more than 1/12 of the total amount is being paid. That made the final payment a little smaller than usual — leaving a remaining unpaid balance of only 8.76
.
It would have been equally valid to use normal rounding producing a monthly payment of 8.83
and a slightly higher final payment of 8.87
. However, in the real world people generally don't like to have their payments go up, so rounding up each payment is the common practice — it also returns the money to the lender more quickly.
I believe you want to find the current region of A1 and surrounding cells - not necessarily all cells on the sheet. If so - simply use... Range("A1").CurrentRegion
I had the same problem and I found out that if you add the URL param ?v=3
you won't get the warning message anymore:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3"></script>
As pointed out in the comments by @Zia Ul Rehman Mughal
Turns out specifying this means you are referring to old frozen version 3.0 not the latest version. Frozen old versions are not updated with bug fixes or anything. But this is good to mention though. https://developers.google.com/maps/documentation/javascript/versions#the-frozen-version
This solution doesn't work anymore.
In the source header you can declare:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
....
It is described in the PEP 0263:
Then you can use UTF-8 in strings:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
u = 'idzie waz waska drózka'
uu = u.decode('utf8')
s = uu.encode('cp1250')
print(s)
This declaration is not needed in Python 3 as UTF-8 is the default source encoding (see PEP 3120).
In addition, it may be worth verifying that your text editor properly encodes your code in UTF-8. Otherwise, you may have invisible characters that are not interpreted as UTF-8.
You should need to convert your PHP array to javascript array using PHP syntax json_encode. json_encode convert PHP array to JSON string
Single Dimension PHP array to javascript array
<?php
var $itemsarray= array("Apple", "Bear", "Cat", "Dog");
?>
<script>
var items= <?php echo json_encode($itemsarray); ?>;
console.log(items[2]); // Output: Bear
// OR
alert(items[0]); // Output: Apple
</script>
Multi Dimension PHP array to javascript array
<?php
var $itemsarray= array(
array('name'='Apple', 'price'=>'12345'),
array('name'='Bear', 'price'=>'13344'),
array('name'='Potato', 'price'=>'00440')
);
?>
<script>
var items= <?php echo json_encode($itemsarray); ?>;
console.log(items[1][name]); // Output: Bear
// OR
alert(items[0][price]); // Output: Apple
</script>
For more detail, you can also check php array to javascript array
If you take a look at the source code of Spring Data JPA, and particularly the PartTreeJpaQuery
class, you will see that is tries to instantiate PartTree
.
Inside that class the following regular expression
private static final Pattern PREFIX_TEMPLATE = Pattern.compile("^(find|read|get|count|query)(\\p{Lu}.*?)??By")
should indicate what is allowed and what's not.
Of course if you try to add such a method you will actually see that is does not work and you get the full stacktrace.
I should note that I was using looking at version 1.5.0.RELEASE
of Spring Data JPA
As mentioned in this Jakob Nielsen article, drop down lists should be avoided for data that is well known to the user:
Menus of data well known to users, such as the month and year of their birth. Such information is often hardwired into users' fingers, and having to select such options from a menu breaks the standard paradigm for entering information and can even create more work for users.
The ideal solution is likely something like follows:
EDIT: Here is how we implemented our DOB picker: Masked text input field with HTML5 regex to force the numeric keyboard on iOS devices.
I provided a couple of reasonably interesting answers to this question:
Nlog - Generating Header Section for a log file
Adding a Header:
The question wanted to know how to add a header to the log file. Using config entries like this allow you to define the header format separately from the format of the rest of the log entries. Use a single logger, perhaps called "headerlogger" to log a single message at the start of the application and you get your header:
Define the header and file layouts:
<variable name="HeaderLayout" value="This is the header. Start time = ${longdate} Machine = ${machinename} Product version = ${gdc:item=version}"/>
<variable name="FileLayout" value="${longdate} | ${logger} | ${level} | ${message}" />
Define the targets using the layouts:
<target name="fileHeader" xsi:type="File" fileName="xxx.log" layout="${HeaderLayout}" />
<target name="file" xsi:type="File" fileName="xxx.log" layout="${InfoLayout}" />
Define the loggers:
<rules>
<logger name="headerlogger" minlevel="Trace" writeTo="fileHeader" final="true" />
<logger name="*" minlevel="Trace" writeTo="file" />
</rules>
Write the header, probably early in the program:
GlobalDiagnosticsContext.Set("version", "01.00.00.25");
LogManager.GetLogger("headerlogger").Info("It doesn't matter what this is because the header format does not include the message, although it could");
This is largely just another version of the "Treating exceptions differently" idea.
Log each log level with a different layout
Similarly, the poster wanted to know how to change the format per logging level. It wasn't clear to me what the end goal was (and whether it could be achieved in a "better" way), but I was able to provide a configuration that did what he asked:
<variable name="TraceLayout" value="This is a TRACE - ${longdate} | ${logger} | ${level} | ${message}"/>
<variable name="DebugLayout" value="This is a DEBUG - ${longdate} | ${logger} | ${level} | ${message}"/>
<variable name="InfoLayout" value="This is an INFO - ${longdate} | ${logger} | ${level} | ${message}"/>
<variable name="WarnLayout" value="This is a WARN - ${longdate} | ${logger} | ${level} | ${message}"/>
<variable name="ErrorLayout" value="This is an ERROR - ${longdate} | ${logger} | ${level} | ${message}"/>
<variable name="FatalLayout" value="This is a FATAL - ${longdate} | ${logger} | ${level} | ${message}"/>
<targets>
<target name="fileAsTrace" xsi:type="FilteringWrapper" condition="level==LogLevel.Trace">
<target xsi:type="File" fileName="xxx.log" layout="${TraceLayout}" />
</target>
<target name="fileAsDebug" xsi:type="FilteringWrapper" condition="level==LogLevel.Debug">
<target xsi:type="File" fileName="xxx.log" layout="${DebugLayout}" />
</target>
<target name="fileAsInfo" xsi:type="FilteringWrapper" condition="level==LogLevel.Info">
<target xsi:type="File" fileName="xxx.log" layout="${InfoLayout}" />
</target>
<target name="fileAsWarn" xsi:type="FilteringWrapper" condition="level==LogLevel.Warn">
<target xsi:type="File" fileName="xxx.log" layout="${WarnLayout}" />
</target>
<target name="fileAsError" xsi:type="FilteringWrapper" condition="level==LogLevel.Error">
<target xsi:type="File" fileName="xxx.log" layout="${ErrorLayout}" />
</target>
<target name="fileAsFatal" xsi:type="FilteringWrapper" condition="level==LogLevel.Fatal">
<target xsi:type="File" fileName="xxx.log" layout="${FatalLayout}" />
</target>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="fileAsTrace,fileAsDebug,fileAsInfo,fileAsWarn,fileAsError,fileAsFatal" />
<logger name="*" minlevel="Info" writeTo="dbg" />
</rules>
Again, very similar to Treating exceptions differently.
You can turn a stash into a branch if you feel it's important enough:
git stash branch <branchname> [<stash>]
from the man page:
This creates and checks out a new branch named <branchname>
starting from the commit at which the <stash>
was originally created, applies the changes recorded in <stash>
to the new working tree and index, then drops the <stash>
if that completes successfully. When no <stash>
is given, applies the latest one.
This is useful if the branch on which you ran git stash save
has changed enough that git stash apply fails due to conflicts. Since the stash is applied on top of the commit that was HEAD at the time git stash was run, it restores the originally stashed state with no conflicts.
You can later rebase this new branch to some other place that's a descendent of where you were when you stashed.
#!/usr/bin/python
import sys
col = int(sys.argv[1]) - 1
for line in sys.stdin:
columns = line.split()
try:
print(columns[col])
except IndexError:
# ignore
pass
Then, supposing you name the script as co, say, do something like this to get the sizes of files (the example assumes you're using Linux, but the script itself is OS-independent) :-
ls -lh | co 5
Here is the server Open a stream to the file and send it overnetwork
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleFileServer {
public final static int SOCKET_PORT = 5501;
public final static String FILE_TO_SEND = "file.txt";
public static void main (String [] args ) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock = null;
try {
servsock = new ServerSocket(SOCKET_PORT);
while (true) {
System.out.println("Waiting...");
try {
sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// send file
File myFile = new File (FILE_TO_SEND);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = sock.getOutputStream();
System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
os.flush();
System.out.println("Done.");
} catch (IOException ex) {
System.out.println(ex.getMessage()+": An Inbound Connection Was Not Resolved");
}
}finally {
if (bis != null) bis.close();
if (os != null) os.close();
if (sock!=null) sock.close();
}
}
}
finally {
if (servsock != null)
servsock.close();
}
}
}
Here is the client Recive the file being sent overnetwork
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class SimpleFileClient {
public final static int SOCKET_PORT = 5501;
public final static String SERVER = "127.0.0.1";
public final static String
FILE_TO_RECEIVED = "file-rec.txt";
public final static int FILE_SIZE = Integer.MAX_VALUE;
public static void main (String [] args ) throws IOException {
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Socket sock = null;
try {
sock = new Socket(SERVER, SOCKET_PORT);
System.out.println("Connecting...");
// receive file
byte [] mybytearray = new byte [FILE_SIZE];
InputStream is = sock.getInputStream();
fos = new FileOutputStream(FILE_TO_RECEIVED);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
System.out.println("File " + FILE_TO_RECEIVED
+ " downloaded (" + current + " bytes read)");
}
finally {
if (fos != null) fos.close();
if (bos != null) bos.close();
if (sock != null) sock.close();
}
}
}
// I would make it a little bit more simple
var products = new List<List<product>> {item1, item2, item3 }.SelectMany(id => id).ToList();
This way it is a multi dimensional List and the .SelectMany() will flatten it into a IEnumerable of product then I use the .ToList() method after.
You are most likely pushing a string 'NULL'
to the table, rather then an actual NULL
, but other things may be going on as well, an illustration:
mysql> CREATE TABLE date_test (pdd DATE NOT NULL);
Query OK, 0 rows affected (0.11 sec)
mysql> INSERT INTO date_test VALUES (NULL);
ERROR 1048 (23000): Column 'pdd' cannot be null
mysql> INSERT INTO date_test VALUES ('NULL');
Query OK, 1 row affected, 1 warning (0.05 sec)
mysql> show warnings;
+---------+------+------------------------------------------+
| Level | Code | Message |
+---------+------+------------------------------------------+
| Warning | 1265 | Data truncated for column 'pdd' at row 1 |
+---------+------+------------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT * FROM date_test;
+------------+
| pdd |
+------------+
| 0000-00-00 |
+------------+
1 row in set (0.00 sec)
mysql> ALTER TABLE date_test MODIFY COLUMN pdd DATE NULL;
Query OK, 1 row affected (0.15 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> INSERT INTO date_test VALUES (NULL);
Query OK, 1 row affected (0.06 sec)
mysql> SELECT * FROM date_test;
+------------+
| pdd |
+------------+
| 0000-00-00 |
| NULL |
+------------+
2 rows in set (0.00 sec)
The opensource framework Dynamitey has a static method that does late binding using DLR including cast conversion among others.
dynamic Cast(object obj, Type castTo){
return Dynamic.InvokeConvert(obj, castTo, explict:true);
}
The advantage of this over a Cast<T>
called using reflection, is that this will also work for any IDynamicMetaObjectProvider
that has dynamic conversion operators, ie. TryConvert on DynamicObject
.
If you decorate the User
class with the XmlType
to match the required capitalization:
[XmlType("user")]
public class User
{
...
}
Then the XmlRootAttribute
on the XmlSerializer
ctor can provide the desired root and allow direct reading into List<>:
// e.g. my test to create a file
using (var writer = new FileStream("users.xml", FileMode.Create))
{
XmlSerializer ser = new XmlSerializer(typeof(List<User>),
new XmlRootAttribute("user_list"));
List<User> list = new List<User>();
list.Add(new User { Id = 1, Name = "Joe" });
list.Add(new User { Id = 2, Name = "John" });
list.Add(new User { Id = 3, Name = "June" });
ser.Serialize(writer, list);
}
...
// read file
List<User> users;
using (var reader = new StreamReader("users.xml"))
{
XmlSerializer deserializer = new XmlSerializer(typeof(List<User>),
new XmlRootAttribute("user_list"));
users = (List<User>)deserializer.Deserialize(reader);
}
HEAD
is (direct or indirect, i.e. symbolic) reference to the current commit. It is a commit that you have checked in the working directory (unless you made some changes, or equivalent), and it is a commit on top of which "git commit" would make a new one. Usually HEAD
is symbolic reference to some other named branch; this branch is currently checked out branch, or current branch. HEAD
can also point directly to a commit; this state is called "detached HEAD", and can be understood as being on unnamed, anonymous branch.
And @
alone is a shortcut for HEAD
, since Git 1.8.5
ORIG_HEAD
is previous state of HEAD
, set by commands that have possibly dangerous behavior, to be easy to revert them. It is less useful now that Git has reflog: HEAD@{1}
is roughly equivalent to ORIG_HEAD
(HEAD@{1}
is always last value of HEAD
, ORIG_HEAD
is last value of HEAD
before dangerous operation).
For more information read git(1) manpage / [gitrevisions(7) manpage][git-revisions], Git User's Manual, the Git Community Book and Git Glossary
Addition to what @KennyTM said:
-ms
-moz
-webkit
1) On February 12 2013 Opera (version 15+) announces they moving away from their own engine Presto to WebKit named Blink.
2) On April 3 2013 Google (Chrome version 28+) announces they are going to use the WebKit-based Blink engine.
3) On December 6 2018 Microsoft (Microsoft Edge 79+ stable) announces they are going to use the WebKit-based Blink engine.
Here's a version of the SQL that returns the correct records:
select distinct u.*
from Users u, CompanyRolesToUsers c
where u.Id = c.UserId --join just specified here, perfectly fine
and u.firstname like '%amy%'
and c.CompanyRoleId in (2,3,4)
Also, note that (2,3,4) is a list selected from a checkbox list by the web app user, and I forgot to mention that I just hardcoded that for simplicity. Really it's an array of CompanyRoleId values, so it could be (1) or (2,5) or (1,2,3,4,6,7,99).
Also the other thing that I should specify more clearly, is that the PredicateExtensions are used to dynamically add predicate clauses to the Where for the query, depending on which form fields the web app user has filled in. So the tricky part for me is how to transform the working query into a LINQ Expression that I can attach to the dynamic list of expressions.
I'll give some of the sample LINQ queries a shot and see if I can integrate them with our code, and then get post my results. Thanks!
marcel
nullptr
is always a pointer type. 0
(aka. C's NULL bridged over into C++) could cause ambiguity in overloaded function resolution, among other things:
f(int);
f(foo *);
From the documentation about ASP.NET Web Project Folder Structure in MSDN:
You can keep your Web project's files in any folder structure that is convenient for your application. To make it easier to work with your application, ASP.NET reserves certain file and folder names that you can use for specific types of content.
App_Data contains application data files including .mdf database files, XML files, and other data store files. The App_Data folder is used by ASP.NET to store an application's local database, such as the database for maintaining membership and role information. For more information, see Introduction to Membership and Understanding Role Management.
I had the same problem and resolved it by changing the character set of the column. Even though your database has a default character set of utf-8
I think it's possible for database columns to have a different character set in MySQL. Here's the SQL QUERY I used:
ALTER TABLE database.table MODIFY COLUMN col VARCHAR(255)
CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;
::-webkit-search-cancel-button {
height: 10px;
width: 10px;
display: inline-block;
/*background-color: #0e1d3033;*/
content: "&#f00d;";
font-family: FontAwesome;
font-weight: 900;
-webkit-appearance: searchfield-cancel-button !important;
}
input#searchInput {
-webkit-appearance: searchfield !important;
}
<input data-type="search" type="search" id="searchInput" class="form-control">
since iterating over a string it will render an item for each char:
<li ng-repeat = "k in 'aaaa' track by $index">
{{$index}} //THIS DOESN'T ANSWER OP'S QUESTION. Read below.
</li>
we can use this ugly but no-code workaround using the number|n decimal places
native filter.
<li ng-repeat="k in (0|number:mynumber -2 ) track by $index">
{{$index}}
</li>
this way we'll have mynumber
elements with no extra code. Say '0.000'
.
We use mynumber - 2
to compensate 0.
It won't work for numbers below 3, but might be useful in some cases.
This code prints out all the directories and files in my documents directory:
Some modification of your function:
func listFilesFromDocumentsFolder() -> [String]
{
let dirs = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)
if dirs != [] {
let dir = dirs[0]
let fileList = try! FileManager.default.contentsOfDirectory(atPath: dir)
return fileList
}else{
let fileList = [""]
return fileList
}
}
Which gets called by:
let fileManager:FileManager = FileManager.default
let fileList = listFilesFromDocumentsFolder()
let count = fileList.count
for i in 0..<count
{
if fileManager.fileExists(atPath: fileList[i]) != true
{
print("File is \(fileList[i])")
}
}
EDIT: There is now a queuecomplete
event that you can use for exactly that purpose.
Previous answer:
Paul B.'s answer works, but an easier way to do so, is by checking if there are still files in the queue or uploading whenever a file completes. This way you don't have to keep track of the files yourself:
Dropzone.options.filedrop = {
init: function () {
this.on("complete", function (file) {
if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
doSomething();
}
});
}
};
Simply give them the same name:
<input type="radio" name="radAnswer" />
You are getting this message because getBean returns an Object reference and you are casting it to the correct type. Java 1.5 gives you a warning. That's the nature of using Java 1.5 or better with code that works like this. Spring has the typesafe version
someMap=getApplicationContext().getBean<HashMap<String, String>>("someMap");
on its todo list.
You would need to manage the referential constraint across databases using a Trigger.
Basically you create an insert, update trigger to verify the existence of the Key in the Primary key table. If the key does not exist then revert the insert or update and then handle the exception.
Example:
Create Trigger dbo.MyTableTrigger ON dbo.MyTable, After Insert, Update
As
Begin
If NOT Exists(select PK from OtherDB.dbo.TableName where PK in (Select FK from inserted) BEGIN
-- Handle the Referential Error Here
END
END
Edited: Just to clarify. This is not the best approach with enforcing referential integrity. Ideally you would want both tables in the same db but if that is not possible. Then the above is a potential work around for you.
Swift 4.2 version of SwiftArchitect's solution above (works great):
// Usage: insert view.fadeTransition right before changing content
extension UIView {
func fadeTransition(_ duration:CFTimeInterval) {
let animation = CATransition()
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
animation.type = CATransitionType.fade
animation.duration = duration
layer.add(animation, forKey: CATransitionType.fade.rawValue)
}
}
Invocation:
// This will fade
aLabel.fadeTransition(0.4)
aLabel.text = "text"
Using 1=1 is actually not a very good idea as this can cause full table scans by itself.
See this--> T-SQL 1=1 Performance Hit
If you want to create a small dots, just use icon from font awesome.
fa fa-circle
You can also add underscore.js to your project and will be able to do it in one line:
_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})
I used the following approach for determining the frame of the keyboard in iOS 7.1.
In the init method of my view controller, I registered for the UIKeyboardDidShowNotification
:
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(keyboardOnScreen:) name:UIKeyboardDidShowNotification object:nil];
Then, I used the following code in keyboardOnScreen:
to gain access to the frame of the keyboard. This code gets the userInfo
dictionary from the notification and then accesses the NSValue
associated with UIKeyboardFrameEndUserInfoKey
. You can then access the CGRect and convert it to the coordinates of the view of your view controller. From there, you can perform any calculations you need based on that frame.
-(void)keyboardOnScreen:(NSNotification *)notification
{
NSDictionary *info = notification.userInfo;
NSValue *value = info[UIKeyboardFrameEndUserInfoKey];
CGRect rawFrame = [value CGRectValue];
CGRect keyboardFrame = [self.view convertRect:rawFrame fromView:nil];
NSLog(@"keyboardFrame: %@", NSStringFromCGRect(keyboardFrame));
}
Swift
And the equivalent implementation with Swift:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name: UIResponder.keyboardDidShowNotification, object: nil)
@objc
func keyboardDidShow(notification: Notification) {
guard let info = notification.userInfo else { return }
guard let frameInfo = info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
let keyboardFrame = frameInfo.cgRectValue
print("keyboardFrame: \(keyboardFrame)")
}
The method used for all previous answers to this question suggest changing the url which is not necessary, and I think readers should be aware of an alternative solution. I use ui-router and $stateProvider to associate a state value with a templateUrl which points to the html file for your view. Then it is just a matter of injecting the $state into your controller and calling $state.go('state-value') to update your view.
What is the difference between angular-route and angular-ui-router?
Steve's reply is definitely the correct technique but it should be refactored so that your installpath variable is in a separate environment script where all such declarations are made.
Then all scripts source that script and should installpath change, you only need to change it in one location. Makes things more, er, futureproof. God I hate that word! (-:
BTW You should really refer to the variable using ${installpath} when using it in the way shown in your example:
. ${installpath}/incl.sh
If the braces are left out, some shells will try and expand the variable "installpath/incl.sh"!
I know this is a way late, but I thought I'd add yet another way of doing this.
You can take advantage of the fact that the Text property can be set using "Runs", so you can set up multiple bindings using a Run for each one. This is useful if you don't have access to MultiBinding (which I didn't find when developing for Windows Phone)
<TextBlock>
<Run Text="Name = "/>
<Run Text="{Binding Name}"/>
<Run Text=", Id ="/>
<Run Text="{Binding Id}"/>
</TextBlock>
No. Regular expressions in Python are handled by the re
module.
article = re.sub(r'(?is)</html>.+', '</html>', article)
In general:
text_after = re.sub(regex_search_term, regex_replacement, text_before)
The following code works fine for me, using the StreamReader
class:
using (var reader = new StreamReader(fileName, defaultEncodingIfNoBom, true))
{
reader.Peek(); // you need this!
var encoding = reader.CurrentEncoding;
}
The trick is to use the Peek
call, otherwise, .NET has not done anything (and it hasn't read the preamble, the BOM). Of course, if you use any other ReadXXX
call before checking the encoding, it works too.
If the file has no BOM, then the defaultEncodingIfNoBom
encoding will be used. There is also a StreamReader without this overload method (in this case, the Default (ANSI) encoding will be used as defaultEncodingIfNoBom), but I recommand to define what you consider the default encoding in your context.
I have tested this successfully with files with BOM for UTF8, UTF16/Unicode (LE & BE) and UTF32 (LE & BE). It does not work for UTF7.
Yes, sort of.
Here you go by example :
void printA(int a){
printf("Hello world from printA : %d\n",a);
}
void printB(const char *buff){
printf("Hello world from printB : %s\n",buff);
}
#define Max_ITEMS() 6, 5, 4, 3, 2, 1, 0
#define __VA_ARG_N(_1, _2, _3, _4, _5, _6, N, ...) N
#define _Num_ARGS_(...) __VA_ARG_N(__VA_ARGS__)
#define NUM_ARGS(...) (_Num_ARGS_(_0, ## __VA_ARGS__, Max_ITEMS()) - 1)
#define CHECK_ARGS_MAX_LIMIT(t) if(NUM_ARGS(args)>t)
#define CHECK_ARGS_MIN_LIMIT(t) if(NUM_ARGS(args)
#define print(x , args ...) \
CHECK_ARGS_MIN_LIMIT(1) printf("error");fflush(stdout); \
CHECK_ARGS_MAX_LIMIT(4) printf("error");fflush(stdout); \
({ \
if (__builtin_types_compatible_p (typeof (x), int)) \
printA(x, ##args); \
else \
printB (x,##args); \
})
int main(int argc, char** argv) {
int a=0;
print(a);
print("hello");
return (EXIT_SUCCESS);
}
It will output 0 and hello .. from printA and printB.
I'm using GIMP 2.8.1. I hope this will work for you:
Open the "Windows" menu and select "Single-Window Mode".
Simple ;)
If one uses the tool Linqpad, after one connects to a target database from the connections one can get a connection string to use.
Properties
Advanced
Copy Full Connection String to Clipboard
Result: Data Source=.\jabberwocky;Integrated Security=SSPI;Initial Catalog=Rasa;app=LINQPad
Remove the app=LinqPad
depending on the drivers and other items such as Server
instead of source, you may need to adjust the driver to suit the target operation; but it gives one a launching pad.
You can save some homemade factorial functions on a separate module, utils.py, and then import them and compare the performance with the predefinite one, in scipy, numpy and math using timeit. In this case I used as external method the last proposed by Stefan Gruenwald:
import numpy as np
def factorial(n):
return reduce((lambda x,y: x*y),range(1,n+1))
Main code (I used a framework proposed by JoshAdel in another post, look for how-can-i-get-an-array-of-alternating-values-in-python):
from timeit import Timer
from utils import factorial
import scipy
n = 100
# test the time for the factorial function obtained in different ways:
if __name__ == '__main__':
setupstr="""
import scipy, numpy, math
from utils import factorial
n = 100
"""
method1="""
factorial(n)
"""
method2="""
scipy.math.factorial(n) # same algo as numpy.math.factorial, math.factorial
"""
nl = 1000
t1 = Timer(method1, setupstr).timeit(nl)
t2 = Timer(method2, setupstr).timeit(nl)
print 'method1', t1
print 'method2', t2
print factorial(n)
print scipy.math.factorial(n)
Which provides:
method1 0.0195569992065
method2 0.00638914108276
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
Process finished with exit code 0
The proper way to do it is using the ng-options
directive. The HTML would look like this.
<select ng-model="selectedTestAccount"
ng-options="item.Id as item.Name for item in testAccounts">
<option value="">Select Account</option>
</select>
JavaScript:
angular.module('test', []).controller('DemoCtrl', function ($scope, $http) {
$scope.selectedTestAccount = null;
$scope.testAccounts = [];
$http({
method: 'GET',
url: '/Admin/GetTestAccounts',
data: { applicationId: 3 }
}).success(function (result) {
$scope.testAccounts = result;
});
});
You'll also need to ensure angular is run on your html and that your module is loaded.
<html ng-app="test">
<body ng-controller="DemoCtrl">
....
</body>
</html>
Take a look into jQuery's .load() function:
<script>
$(function(){
$('#siteloader').load('http://www.somesitehere.com');
});
</script>
However, this only works on the same domain of the JS file.
the default encoding of a HTTP POST is ISO-8859-1.
else you have to look at the Content-Type header that will then look like
Content-Type: application/x-www-form-urlencoded ; charset=UTF-8
You can maybe declare your form with
<form enctype="application/x-www-form-urlencoded;charset=UTF-8">
or
<form accept-charset="UTF-8">
to force the encoding.
Some references :
Oddly enough, the issue for me was I was trying to open 2012 SQL Server Integration Services on SSMS 2008 R2. When I opened the same in SSMS 2012, it connected right away.
You can't remove hidden without also removing system.
You want:
cd mydir
attrib -H -S /D /S
That will remove the hidden and system attributes from all the files/folders inside of your current directory.
With an HTML form like:
<input type="submit" name="btnSubmit" value="Save Changes" />
<input type="submit" name="btnDelete" value="Delete" />
The PHP code to use would look like:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Something posted
if (isset($_POST['btnDelete'])) {
// btnDelete
} else {
// Assume btnSubmit
}
}
You should always assume or default to the first submit button to appear in the form HTML source code. In practice, the various browsers reliably send the name/value of a submit button with the post data when:
Other ways to submit a form exist, and some browsers/versions decide not to send the name/value of any submit buttons in some of these situations. For example, many users submit forms by pressing the Enter key when the cursor/focus is on a text field. Forms can also be submitted via JavaScript, as well as some more obscure methods.
It's important to pay attention to this detail, otherwise you can really frustrate your users when they submit a form, yet "nothing happens" and their data is lost, because your code failed to detect a form submission, because you did not anticipate the fact that the name/value of a submit button may not be sent with the post data.
Also, the above advice should be used for forms with a single submit button too because you should always assume a default submit button.
I'm aware that the Internet is filled with tons of form-handler tutorials, and almost of all them do nothing more than check for the name and value of a submit button. But, they're just plain wrong!
Since web.config file is xml file you can open web.config using xmldocument class. Get the node from that xml file that you want to update and then save xml file.
here is URL that explains in more detail how you can update web.config file programmatically.
http://patelshailesh.com/index.php/update-web-config-programmatically
Note: if you make any changes to web.config, ASP.NET detects that changes and it will reload your application(recycle application pool) and effect of that is data kept in Session, Application, and Cache will be lost (assuming session state is InProc and not using a state server or database).
players
is a list which needs to be indexed by integers. You seem to be using it like a dictionary. Maybe you could use unpacking -- Something like:
name, score = player
(if the player
list is always a constant length).
There's not much more advice we can give you without knowing what query
is and how it works.
It's worth pointing out that the entire code you posted doesn't make a whole lot of sense. There's an IndentationError
on the second line. Also, your function is looping over some iterable, but unconditionally returning during the first iteration which isn't usually what you actually want to do.
Just remove the break. since it is already inside first if it will not execute else. It will exit anyway.
Select
is used for projecting some or all fields of a dataframe
. It won't give you an value
as an output but a new dataframe
. Its a transformation
.
Before initializing map check for is the map is already initiated or not
var container = L.DomUtil.get('map');
if(container != null){
container._leaflet_id = null;
}
It works for me
.g-recaptcha{
-moz-transform:scale(1.1);
-ms-transform:scale(1.1);
-o-transform:scale(1.1);
-moz-transform-origin:0;
-ms-transform-origin:0;
-o-transform-origin:0;
-webkit-transform:scale(1.1);
transform:scale(1.1);
-webkit-transform-origin:0 0;
transform-origin:0;
filter: progid:DXImageTransform.Microsoft.Matrix(M11=1.1,M12=0,M21=0,M22=1.1,SizingMethod='auto expand');
}
Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.
Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .
if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .
if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .
after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).
if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.
If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.
If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.
If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property.
if you further face any difficulty then you need to provide more information about your web site and sql server .
This comment syntax should work for you:
@* enter comments here *@
Here is a very simple one ...
public class FluentHashMap<K, V> extends java.util.HashMap<K, V> {
public FluentHashMap<K, V> with(K key, V value) {
put(key, value);
return this;
}
public static <K, V> FluentHashMap<K, V> map(K key, V value) {
return new FluentHashMap<K, V>().with(key, value);
}
}
then
import static FluentHashMap.map;
HashMap<String, Integer> m = map("a", 1).with("b", 2);
See https://gist.github.com/culmat/a3bcc646fa4401641ac6eb01f3719065
Make sure you take into account that adding this tag,
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
may only allow compatibility with the latest versions. It all depends on your libraries
To show more than one inputs inline without using "form-inline" class you can use the next code:
<div class="input-group">
<input type="text" class="form-control" value="First input" />
<span class="input-group-btn"></span>
<input type="text" class="form-control" value="Second input" />
</div>
Then using CSS selectors:
/* To remove space between text inputs */
.input-group > .input-group-btn:empty {
width: 0px;
}
Basically you have to insert an empty span tag with "input-group-btn" class between input tags.
If you want to see more examples of input groups and bootstrap-select groups take a look at this URL: http://jsfiddle.net/vkhusnulina/gze0Lcm0
You can put them in the Application:
Application["GlobalVar"] = 1234;
They are only global within the current IIS / Virtual applicition. This means, on a webfarm they are local to the server, and within the virtual directory that is the root of the application.
Webkit scrollbar doesnt support on most of the browers.
Supports on CHROME
Here is a demo for webkit scrollbar Webkit Scrollbar DEMO
If you are looking for more examples Check this More Examples
Another Method is Jquery Scroll Bar Plugin
It supports on all browsers and easy to apply
Download the plugin from Download Here
How to use and for more options CHECK THIS
In my case and while installing VS 2015 on Windows7 64x SP1, I experienced the same so tried to cancel and download/install the KBKB2999226 separately and for some reason the standalone update installer also get stuck searching for updates.
A MD5 hash is 128 bits, so you can't represent it in hex with less than 32 characters...
If the both DBs(from & to) are password protected, in that scenario terminal won't ask for the password for both the DBs, password prompt will appear only once. So, to fix this, pass the password along with the commands.
PGPASSWORD=<password> pg_dump -h <hostIpAddress> -U <hostDbUserName> -t <hostTable> > <hostDatabase> | PGPASSWORD=<pwd> psql -h <toHostIpAddress> -d <toDatabase> -U <toDbUser>
<form name="input" action="some.php" method="post">
<input type="text" name="user" id="mytext">
<input type="submit" value="Submit">
</form>
<script>
var w = someValue;
document.getElementById("mytext").value = w;
</script>
//php on some.php page
echo $_POST['user'];
I'm going to take a guess. I think the column name that contains "Number"
is something like " Number"
or "Number "
. Notice that I'm assuming you might have a residual space in the column name somewhere. Do me a favor and run print "<{}>".format(data.columns[1])
and see what you get. Is it something like < Number>
? If so, then my guess was correct. You should be able to fix it with this:
data.columns = data.columns.str.strip()
See the defaultValue property of a text input, it's also used when you reset the form by clicking an <input type="reset"/>
button (http://www.w3schools.com/jsref/prop_text_defaultvalue.asp )
btw, defaultValue and placeholder text are different concepts, you need to see which one better fits your needs
Global working tested solution.
getSupportFragmentManager()
keeps the null reference some times and View pager does not create new since it find reference to same fragment. So to over come this use getChildFragmentManager()
solves problem in simple way.
Don't do this:
new PagerAdapter(getSupportFragmentManager(), fragments);
Do this:
new PagerAdapter(getChildFragmentManager() , fragments);
The highest (Deepak Goel) answer didn't work well for me. Somehow the tag wasn't added properly.
I ended up just sending the ID of the fragment through the flow (using intents) and retrieving it directly from fragment manager.
I'm using the followin code. Note: It's made for an AnyCPU project.
public static bool Is32bitProcess(Process proc) {
if (!IsThis64bitProcess()) return true; // We're in 32-bit mode, so all are 32-bit.
foreach (ProcessModule module in proc.Modules) {
try {
string fname = Path.GetFileName(module.FileName).ToLowerInvariant();
if (fname.Contains("wow64")) {
return true;
}
} catch {
// What on earth is going on here?
}
}
return false;
}
public static bool Is64bitProcess(Process proc) {
return !Is32bitProcess(proc);
}
public static bool IsThis64bitProcess() {
return (IntPtr.Size == 8);
}
Do you have to use Bootstrap for this? Here's a basic HTML/CSS example for obtaining this look that doesn't use any Bootstrap:
HTML:
<div class="bottom">
<div class="box-content right">Rich Media Ad Production</div>
<div class="box-content right">Web Design & Development</div>
<div class="box-content right">Mobile Apps Development</div>
<div class="box-content">Creative Design</div>
</div>
<div>
<div class="box-content right">Web Analytics</div>
<div class="box-content right">Search Engine Marketing</div>
<div class="box-content right">Social Media</div>
<div class="box-content">Quality Assurance</div>
</div>
CSS:
.box-content {
display: inline-block;
width: 200px;
padding: 10px;
}
.bottom {
border-bottom: 1px solid #ccc;
}
.right {
border-right: 1px solid #ccc;
}
Here is the working Fiddle.
If you must use Bootstrap, here is a semi-responsive example that achieves the same effect, although you may need to write a few additional media queries.
HTML:
<div class="row">
<div class="col-xs-3">Rich Media Ad Production</div>
<div class="col-xs-3">Web Design & Development</div>
<div class="col-xs-3">Mobile Apps Development</div>
<div class="col-xs-3">Creative Design</div>
</div>
<div class="row">
<div class="col-xs-3">Web Analytics</div>
<div class="col-xs-3">Search Engine Marketing</div>
<div class="col-xs-3">Social Media</div>
<div class="col-xs-3">Quality Assurance</div>
</div>
CSS:
.row:not(:last-child) {
border-bottom: 1px solid #ccc;
}
.col-xs-3:not(:last-child) {
border-right: 1px solid #ccc;
}
Here is another working Fiddle.
Note:
Note that you may also use the <hr>
element to insert a horizontal divider in Bootstrap as well if you'd like.
The approach of @AzharShaikh works fine.
android:ellipsize="end"
android:maxLines="1"
But I realize a trouble that TextView will be truncated by word (in default). Show if we have a text like:
test long_line_without_any_space_abcdefgh
the TextView will display:
test...
And I found solution to handle this trouble, replace spaces with the unicode no-break space character, it makes TextView wrap on characters instead of words:
yourString.replace(" ", "\u00A0");
The result:
test long_line_without_any_space_abc...
Not much mention of unannotated tags vs annotated ones here. 'describe' works on annotated tags and ignores unannotated ones.
This is ugly but does the job requested and it will not find any tags on other branches (and not on the one specified in the command: master in the example below)
The filtering should prob be optimized (consolidated), but again, this seems to the the job.
git log --decorate --tags master |grep '^commit'|grep 'tag:.*)$'|awk '{print $NF}'|sed 's/)$//'|head -n 1
Critiques welcome as I am going now to put this to use :)
You can convert your number to string and use list slicing like this:
int(str(number)[:2])
Output:
>>> number = 1520
>>> int(str(number)[:2])
15
DateTime
structure stores only one value, not range of values. MinValue
and MaxValue
are static fields, which hold range of possible values for instances of DateTime
structure. These fields are static and do not relate to particular instance of DateTime
. They relate to DateTime
type itself.
Suggested reading: static (C# Reference)
UPDATE: Getting month range:
DateTime date = ...
var firstDayOfMonth = new DateTime(date.Year, date.Month, 1);
var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);
url-pattern
is used in web.xml
to map your servlet
to specific URL. Please see below xml code, similar code you may find in your web.xml
configuration file.
<servlet>
<servlet-name>AddPhotoServlet</servlet-name> //servlet name
<servlet-class>upload.AddPhotoServlet</servlet-class> //servlet class
</servlet>
<servlet-mapping>
<servlet-name>AddPhotoServlet</servlet-name> //servlet name
<url-pattern>/AddPhotoServlet</url-pattern> //how it should appear
</servlet-mapping>
If you change url-pattern
of AddPhotoServlet
from /AddPhotoServlet
to /MyUrl
. Then, AddPhotoServlet
servlet can be accessible by using /MyUrl
. Good for the security reason, where you want to hide your actual page URL.
Java Servlet url-pattern
Specification:
- A string beginning with a '/' character and ending with a '/*' suffix is used for path mapping.
- A string beginning with a '*.' prefix is used as an extension mapping.
- A string containing only the '/' character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
- All other strings are used for exact matches only.
Reference : Java Servlet Specification
You may also read this Basics of Java Servlet
Use an onsubmit attribute on the form tag rather than onclick on the submit.
When you want to merge three or more projects in a single commit, do the steps as described in the other answers (remote add -f
, merge
). Then, (soft) reset the index to old head (where no merge happened). Add all files (git add -A
) and commit them (message "Merging projects A, B, C, and D into one project). This is now the commit-id of master.
Now, create .git/info/grafts
with following content:
<commit-id of master> <list of commit ids of all parents>
Run git filter-branch -- head^..head head^2..head head^3..head
. If you have more than three branches, just add as much head^n..head
as you have branches. To update tags, append --tag-name-filter cat
. Do not always add that, because this might cause a rewrite of some commits. For details see man page of filter-branch, search for "grafts".
Now, your last commit has the right parents associated.
use default convertation class: Convert.ToDecimal(Double)
If you are using jQuery you can use $('#mydiv').append('html content')
and it will keep the existing content.
PERIOD_DIFF calculates months between two dates.
For example, to calculate the difference between now() and a time column in your_table:
select period_diff(date_format(now(), '%Y%m'), date_format(time, '%Y%m')) as months from your_table;
Another way to download file is to write the stream content to the response's body directly:
[HttpGet("pdfstream/{id}")]
public async Task GetFile(long id)
{
var stream = GetStream(id);
Response.StatusCode = (int)HttpStatusCode.OK;
Response.Headers.Add( HeaderNames.ContentDisposition, $"attachment; filename=\"{Guid.NewGuid()}.pdf\"" );
Response.Headers.Add( HeaderNames.ContentType, "application/pdf" );
await stream.CopyToAsync(Response.Body);
await Response.Body.FlushAsync();
}
Well you can simply use Math.pow(a,b)
as you have used earlier and just convert its value by using (int)
before it. Below could be used as an example to it.
int x = (int) Math.pow(a,b);
where a
and b
could be double
or int
values as you want.
This will simply convert its output to an integer value as you required.
You say you've had problems with Navicat. For the record, I use Navicat and I haven't experienced the issue you describe. You might want to dig around, see if there's a reason for your problem and/or a solution, because given the question asked, my first recommendation would have been Navicat.
But if you want alternative suggestions, here are a few that I know of and have used:
MySQL has its own tool which you can download for free, called MySQL Workbench. Download it from here: http://wb.mysql.com/. My experience is that it's powerful, but I didn't really like the UI. But that's just my personal taste.
Another free program you might want to try is HeidiSQL. It's more similar to Navicat than MySQL Workbench. A colleague of mine loves it.
(interesting to note, by the way, that MariaDB (the forked version of MySQL) is currently shipped with HeidiSQL as its GUI tool)
Finally, if you're running a web server on your machine, there's always the option of a browser-based tool like PHPMyAdmin. It's actually a surprisingly powerful piece of software.
Here is a simple threading example for Android. It's very basic but it should help you to get a perspective.
Android code - Main.java
package test12.tt;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Test12Activity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView txt1 = (TextView) findViewById(R.id.sm);
new Thread(new Runnable() {
public void run(){
txt1.setText("Thread!!");
}
}).start();
}
}
Android application xml - main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id = "@+id/sm"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"/>
</LinearLayout>
https://jsfiddle.net/bm3Lfcod/1/
For those seeking for a solution that works within a flexible parent container with a children that is flexible in both dimensions. eg. navbar buttons.
//the parent (example of what it may be)
div {
display:flex;
width: 100%;
}
//The children
a {
display: inline-block;
}
//text wrapper
span {
display: table-caption;
}
Please try the following:
import re
name = ["A1B1", "djdd", "B2C4", "C2H2", "jdoi","1A4V"]
# Match names.
for element in name:
m = re.match("(^[A-Z]\d[A-Z]\d)", element)
if m:
print(m.groups())
You may be able to use the built-in function dir()
to produce similar behavior to PHP's isset()
, something like:
if 'foo' in dir(): # returns False, foo is not defined yet.
pass
foo = 'b'
if 'foo' in dir(): # returns True, foo is now defined and in scope.
pass
dir()
returns a list of the names in the current scope, more information can be found here: http://docs.python.org/library/functions.html#dir.
Another important module that needs reconfiguring before PUT and DELETE will work is the options verb
<modules>
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="OPTIONSVerbHandler" />
<remove name="WebDAV" />
<add name="OPTIONSVerbHandler" path="*" verb="*" modules="ProtocolSupportModule" resourceType="Unspecified" requireAccess="Script" />
</handlers>
Also see this post: https://stackoverflow.com/a/22018750/9376681
For those looking for an example of how to pass the OAuth2 authorization (access token) in the header (as opposed to using a request or body parameter), here is how it's done:
Authorization: Bearer 0b79bab50daca910b000d4f1a2b675d604257e42
Complete reference is not available for the mentioned files, as they are extensible by various plug-ins.
Basically, .project files store project-settings, such as builder and project nature settings, while .classpath files define the classpath to use during running. The classpath files contains src and target entries that correspond with folders in the project; the con entries are used to describe some kind of "virtual" entries, such as the JVM libs or in case of eclipse plug-ins dependencies (normal Java project dependencies are displayed differently, using a special src entry).
if(mas[i].indexOf("bird") == 0)
//there is bird
You.can read about indexOf here: http://www.w3schools.com/jsref/jsref_indexof.asp
Delete the file(index.php) from your xampp folder, you will get the list of directories and files from htdocs folder.
Then apart from these 4, we have
foldByKey which is same as reduceByKey but with a user defined Zero Value.
AggregateByKey takes 3 parameters as input and uses 2 functions for merging(one for merging on same partitions and another to merge values across partition. The first parameter is ZeroValue)
whereas
ReduceBykey takes 1 parameter only which is a function for merging.
CombineByKey takes 3 parameter and all 3 are functions. Similar to aggregateBykey except it can have a function for ZeroValue.
GroupByKey takes no parameter and groups everything. Also, it is an overhead for data transfer across partitions.
Take a look at the System
log in Windows EventViewer (eventvwr
from the command line).
You should see entries with source as 'Service Control Manager'. e.g. on my WinXP machine,
Event Type: Information
Event Source: Service Control Manager
Event Category: None
Event ID: 7036
Date: 7/1/2009
Time: 12:09:43 PM
User: N/A
Computer: MyMachine
Description:
The Background Intelligent Transfer Service service entered the running state.
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
Use the Font Class to set the control's font and styles.
Try Font Constructor (String, Single)
Label lab = new Label();
lab.Text ="Font Bold at 24";
lab.Font = new Font("Arial", 20);
or
lab.Font = new Font(FontFamily.GenericSansSerif,
12.0F, FontStyle.Bold);
To get installed fonts refer this - .NET System.Drawing.Font - Get Available Sizes and Styles
If you want to plot a set of circles, you might want to see this post or this gist(a bit newer). The post offered a function named circles
.
The function circles
works like scatter
, but the sizes of plotted circles are in data unit.
Here's an example:
from pylab import *
figure(figsize=(8,8))
ax=subplot(aspect='equal')
#plot one circle (the biggest one on bottom-right)
circles(1, 0, 0.5, 'r', alpha=0.2, lw=5, edgecolor='b', transform=ax.transAxes)
#plot a set of circles (circles in diagonal)
a=arange(11)
out = circles(a, a, a*0.2, c=a, alpha=0.5, edgecolor='none')
colorbar(out)
xlim(0,10)
ylim(0,10)
try this:
width:360px;
height:360px;
top: 50%; left: 50%;
margin-top: -160px; /* ( ( width / 2 ) * -1 ) */
margin-left: -160px; /* ( ( height / 2 ) * -1 ) */
position:absolute;
From what I understand, you can branch the current branch into an existing branch. In essence, this will overwrite master
with whatever you have in the current branch:
git branch -f master HEAD
Once you've done that, you can normally push your local master
branch, possibly requiring the force parameter here as well:
git push -f origin master
No merges, no long commands. Simply branch
and push
— but, yes, this will rewrite history of the master
branch, so if you work in a team you have got to know what you're doing.
Alternatively, I found that you can push any branch to the any remote branch, so:
# This will force push the current branch to the remote master
git push -f origin HEAD:master
# Switch current branch to master
git checkout master
# Reset the local master branch to what's on the remote
git reset --hard origin/master
You can remove the time part from java.util.Date by setting the hour, minute, second and millisecond values to zero.
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
public static Date removeTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
}
document.getElementById("myspan").textContent="newtext";
this will select dom-node with id myspan
and change it text content to new text
First save all IDs and alter them programmatically to the values you wan't, then remove them from database and then insert them again using something similar:
use [Name.Database]
go
set identity_insert [Test] ON
insert into [dbo].[Test]
([Id])
VALUES
(2)
set identity_insert [Test] OFF
For bulk insert use:
use [Name.Database]
go
set identity_insert [Test] ON
BULK INSERT [Test]
FROM 'C:\Users\Oscar\file.csv'
WITH (FIELDTERMINATOR = ';',
ROWTERMINATOR = '\n',
KEEPIDENTITY)
set identity_insert [Test] OFF
Sample data from file.csv:
2;
3;
4;
5;
6;
If you don't set identity_insert
to off you will get the following error:
Cannot insert explicit value for identity column in table 'Test' when IDENTITY_INSERT is set to OFF.
let imageDataDict:[String: UIImage] = ["image": image]
// Post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
// `default` is now a property, not a method call
// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
// Handle notification
func showSpinningWheel(_ notification: NSNotification) {
print(notification.userInfo ?? "")
if let dict = notification.userInfo as NSDictionary? {
if let id = dict["image"] as? UIImage {
// Do something with your image
}
}
}
let imageDataDict:[String: UIImage] = ["image": image]
// Post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
// `default` is now a property, not a method call
// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
// Handle notification
@objc func showSpinningWheel(_ notification: NSNotification) {
print(notification.userInfo ?? "")
if let dict = notification.userInfo as NSDictionary? {
if let id = dict["image"] as? UIImage {
// Do something with your image
}
}
}
by default <UL/>
contains default padding
therefore try adding style to padding:0px
in css class or inline css
Assert does throw an AssertionError if you run your app with assertions turned on.
int a = 42;
assert a >= 0 && d <= 10;
If you run this with, say: java -ea -jar peiska.jar
It shall throw an java.lang.AssertionError
If you want to write all in one line try
new Select (driver.findElement(By.id("designation"))).selectByVisibleText("Programmer ");
There is a nice library for reading all tables, ridona
$database = new ridona\Database('mysql:dbname=database_name;host=127.0.0.1', 'db_user','db_pass');
foreach ($database->tables()->by_entire() as $row) {
....do
}
The ViewPager doesn't remove your fragments with the code above because it loads several views (or fragments in your case) into memory. In addition to the visible view, it also loads the view to either side of the visible one. This provides the smooth scrolling from view to view that makes the ViewPager so cool.
To achieve the effect you want, you need to do a couple of things.
Change the FragmentPagerAdapter to a FragmentStatePagerAdapter. The reason for this is that the FragmentPagerAdapter will keep all the views that it loads into memory forever. Where the FragmentStatePagerAdapter disposes of views that fall outside the current and traversable views.
Override the adapter method getItemPosition (shown below). When we call mAdapter.notifyDataSetChanged();
the ViewPager interrogates the adapter to determine what has changed in terms of positioning. We use this method to say that everything has changed so reprocess all your view positioning.
And here's the code...
private class MyPagerAdapter extends FragmentStatePagerAdapter {
//... your existing code
@Override
public int getItemPosition(Object object){
return PagerAdapter.POSITION_NONE;
}
}
I'm surprised not a lot of people know about the download attribute for a elements. Please help spread the word about it! You can have a hidden html link, and fake a click on it. If the html link has the download attribute it downloads the file, not views it, no matter what. Here's the code. It will download a cat picture if it can find it.
document.getElementById('download').click();
_x000D_
<a href="https://docs.google.com/uc?id=0B0jH18Lft7ypSmRjdWg1c082Y2M" download id="download" hidden></a>
_x000D_
Note: This is not supported on all browsers: http://www.w3schools.com/tags/att_a_download.asp
Spring have the IoC container which carry the Bag of Bean ; creation maintain and deletion are the responsibilities of Spring Container. We can put the bean in to Spring by Wiring and Auto Wiring. Wiring mean we manually configure it into the XML file and "Auto Wiring" mean we put the annotations in the Java file then Spring automatically scan the root-context where java configuration file, make it and put into the bag of Spring.
Here is the detail URI where you got more information about Beans
According to this documentation, the find method will search down through the tree of elements until it finds the element in the selector parameters. So $(parentSelector).find(childSelector)
is the fastest and most efficient way to do this.
Use the CATALINA_OPTS
environment variable.
This code should work:
var connect = require("connect");
var app = connect.createServer().use(connect.static(__dirname + '/public'));
app.listen(8180);
Also in connect 2.0 .createServer() method deprecated. Use connect() instead.
var connect = require("connect");
var app = connect().use(connect.static(__dirname + '/public'));
app.listen(8180);
You can use the Select method if you have a datasource: http://msdn.microsoft.com/en-us/library/b51xae2y%28v=vs.71%29.aspx
Or use linq if you have objects in you datasource
One more difference I found with respect to both is that it is fairly easy to connect to multiple databases
with mongodb native driver
while you have to use work arounds in mongoose
which still have some drawbacks.
So if you wanna go for a multitenant application, go for mongodb native driver.
Oracle will throw ORA-00904
if executing user does not have proper permissions on objects involved in the query.
You can just use the pipe on its own:
"string1|string2"
for example:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));
Output:
blah, blah, string3
The main reason to use parentheses is to limit the scope of the alternatives:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));
has the same output. but if you just do this:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));
you get:
blah, stringblah, string3
because you've said "string1" or "2".
If you don't want to capture that part of the expression use ?:
:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));
As discussed somewhat in the question comments, this is one way you could do it:
<input ... ng-model="$parent.storeDefault" value="{{location.id}}">
The above assumes that each location has a field (e.g., id) that holds a unique value.
Note that $parent.storeDefault is used because ng-repeat creates a child scope, and we want to manipulate the storeDefault parameter on the parent scope.
i have same problem what i did i just downloaded 32-bit dll and added it to my bin folder this is solved my problem
Have you tried Cell[0]
? Remember indexes start at 0, not 1.
.
matches any character. Used in conjunction with the curly braces already mentioned:
$: cat > test
========
============================
oo
ooooooooooooooooooooooo
$: grep -E '(.)\1{10}' test
============================
ooooooooooooooooooooooo
This worked for me:
grep "\bsearch_word\b" text_file > output.txt ## \b indicates boundaries. This is much faster.
or,
grep -w "search_word" text_file > output.txt
Shutdown hooks execute in all cases where the VM is not forcibly killed. So, if you were to issue a "standard" kill (SIGTERM
from a kill command) then they will execute. Similarly, they will execute after calling System.exit(int)
.
However a hard kill (kill -9
or kill -SIGKILL
) then they won't execute. Similarly (and obviously) they won't execute if you pull the power from the computer, drop it into a vat of boiling lava, or beat the CPU into pieces with a sledgehammer. You probably already knew that, though.
Finalizers really should run as well, but it's best not to rely on that for shutdown cleanup, but rather rely on your shutdown hooks to stop things cleanly. And, as always, be careful with deadlocks (I've seen far too many shutdown hooks hang the entire process)!
Not sure is this could help, but I solved the pinch / zoom problem (I wanted to avoid users to do zooming on my webapp) using angular hammer module:
In my app.component.html I added:
<div id="app" (pinchin)="pinchin();">
and in my app.component.ts:
pinchin() {
//console.log('pinch in');
}