Use pd.MultiIndex.from_product
as an index in an otherwise empty dataframe, then reset its index, and you're done.
a = [1, 2, 3]
b = ["a", "b", "c"]
index = pd.MultiIndex.from_product([a, b], names = ["a", "b"])
pd.DataFrame(index = index).reset_index()
out:
a b
0 1 a
1 1 b
2 1 c
3 2 a
4 2 b
5 2 c
6 3 a
7 3 b
8 3 c
<TextBlock Text="{Binding Date, StringFormat='{}{0:MM/dd/yyyy a\\t h:mm tt}'}" />
will return you
04/07/2011 at 1:28 PM (-04)
fetchTimeout (url,options,timeout=3000) {
return new Promise( (resolve, reject) => {
fetch(url, options)
.then(resolve,reject)
setTimeout(reject,timeout);
})
}
loop { begin Bar.new rescue SystemExit p $! #: #<SystemExit: exit> end }
This will print #<SystemExit: exit>
in an infinite loop, without ever exiting.
As a general rule, converting a Web Forms or MVC5 application to ASP.NET Core will require a significant amount of refactoring.
HttpContext.Current
was removed in ASP.NET Core. Accessing the current HTTP context from a separate class library is the type of messy architecture that ASP.NET Core tries to avoid. There are a few ways to re-architect this in ASP.NET Core.
You can access the current HTTP context via the HttpContext
property on any controller. The closest thing to your original code sample would be to pass HttpContext
into the method you are calling:
public class HomeController : Controller
{
public IActionResult Index()
{
MyMethod(HttpContext);
// Other code
}
}
public void MyMethod(Microsoft.AspNetCore.Http.HttpContext context)
{
var host = $"{context.Request.Scheme}://{context.Request.Host}";
// Other code
}
If you're writing custom middleware for the ASP.NET Core pipeline, the current request's HttpContext
is passed into your Invoke
method automatically:
public Task Invoke(HttpContext context)
{
// Do something with the current HTTP context...
}
Finally, you can use the IHttpContextAccessor
helper service to get the HTTP context in any class that is managed by the ASP.NET Core dependency injection system. This is useful when you have a common service that is used by your controllers.
Request this interface in your constructor:
public MyMiddleware(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
You can then access the current HTTP context in a safe way:
var context = _httpContextAccessor.HttpContext;
// Do something with the current HTTP context...
IHttpContextAccessor
isn't always added to the service container by default, so register it in ConfigureServices
just to be safe:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
// if < .NET Core 2.2 use this
//services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Other code...
}
Third solution:
I would set ws
to a sheet of workbook wb
as the use of Sheet("name")
always refers to the active workbook, which might change as your code develops.
sub kl()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ActiveWorkbook
'be aware as this might produce an error, if Shet "name" does not exist
Set ws = wb.Sheets("name")
' if wb is other than the active workbook
wb.activate
ws.Select
End Sub
For those of you landing here but searching how to break out of a loop that contains an include statement use return instead of break or continue.
<?php
for ($i=0; $i < 100; $i++) {
if (i%2 == 0) {
include(do_this_for_even.php);
}
else {
include(do_this_for_odd.php);
}
}
?>
If you want to break when being inside do_this_for_even.php you need to use return. Using break or continue will return this error: Cannot break/continue 1 level. I found more details here
This was my solution:
this.myForm = this._formBuilder.group({
socDate: [[{ value: '', disabled: true }], Validators.required],
...
)}
<input fxFlex [matDatepicker]="picker" placeholder="Select Date" formControlName="socDate" [attr.disabled]="true" />
Already everyone has provided enough good answer for your problem. Now from the all suggestions, you need to decided which will fit your requirement. There are two types of collection which you need to know. One is unmodified collection and other one collection which will allow you to modify the object later.
So, Here I will give short example for two use cases.
Immutable collection creation :: When you don't want to modify the collection object after creation
List<Element> elementList = Arrays.asList(array)
Mutable collection creation :: When you may want to modify the created collection object after creation.
List<Element> elementList = new ArrayList<Element>(Arrays.asList(array));
May be helpful for late comers.
#include "stdafx.h"
#include "cv.h"
#include "highgui.h"
using namespace cv;
using namespace std;
int main(int argc, char *argv[])
{
if (argc != 2) {
cout << "Usage: display_Image ImageToLoadandDisplay" << endl;
return -1;
}else{
Mat image;
Mat grayImage;
image = imread(argv[1], IMREAD_COLOR);
if (!image.data) {
cout << "Could not open the image file" << endl;
return -1;
}
else {
int height = image.rows;
int width = image.cols;
cvtColor(image, grayImage, CV_BGR2GRAY);
namedWindow("Display window", WINDOW_AUTOSIZE);
imshow("Display window", image);
namedWindow("Gray Image", WINDOW_AUTOSIZE);
imshow("Gray Image", grayImage);
cvWaitKey(0);
image.release();
grayImage.release();
return 0;
}
}
}
var obj = [
{"name": "Afghanistan", "code": "AF"},
{"name": "Åland Islands", "code": "AX"},
{"name": "Albania", "code": "AL"},
{"name": "Algeria", "code": "DZ"}
];
// the code you're looking for
var needle = 'AL';
// iterate over each element in the array
for (var i = 0; i < obj.length; i++){
// look for the entry with a matching `code` value
if (obj[i].code == needle){
// we found it
// obj[i].name is the matched result
}
}
function Do-SendKeys {
param (
$SENDKEYS,
$WINDOWTITLE
)
$wshell = New-Object -ComObject wscript.shell;
IF ($WINDOWTITLE) {$wshell.AppActivate($WINDOWTITLE)}
Sleep 1
IF ($SENDKEYS) {$wshell.SendKeys($SENDKEYS)}
}
Do-SendKeys -WINDOWTITLE Print -SENDKEYS '{TAB}{TAB}'
Do-SendKeys -WINDOWTITLE Print
Do-SendKeys -SENDKEYS '%{f4}'
Try this CSS:
h1 {
left: 0;
line-height: 200px;
margin-top: -100px;
position: absolute;
text-align: center;
top: 50%;
width: 100%;
}
jsFiddle: http://jsfiddle.net/wprw3/
Lots of great answers here but they might be superseded by this CMake support in Visual Studio (Oct 5 2016)
First create a DataGridTemplateColumn
to contain the button:
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Click="ShowHideDetails">Details</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
When the button is clicked, update the containing DataGridRow
's DetailsVisibility
:
void ShowHideDetails(object sender, RoutedEventArgs e)
{
for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
if (vis is DataGridRow)
{
var row = (DataGridRow)vis;
row.DetailsVisibility =
row.DetailsVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
break;
}
}
In this case we are assuming that we have two tables:
SMPPMsgLog
and SMSService
with common column serviceid
:
SELECT sp.SMS,ss.CMD
FROM vas.SMPPMsgLog AS sp,vas.SMSService AS ss
WHERE sp.serviceid=5431
AND ss.ServiceID = 5431
AND Receiver ="232700000"
AND date(TimeStamp) <='2013-08-07'
AND date(TimeStamp) >='2013-08-06' \G;
Building on @xQbert's answer's, you can avoid the subquery AND make it generic enough to filter by any ID
SELECT id, signin, signout
FROM dTable
INNER JOIN(
SELECT id, MAX(signin) AS signin
FROM dTable
GROUP BY id
) AS t1 USING(id, signin)
el.innerHTML='';
el.appendChild(document.createTextNode("yo"));
If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE
Edit: On the model overview it's under Physical Schemata
Screenshot:
So if you want a solution that can cope with dynamic html pages, as you already include it you should use jQuery's live to set the handler on all elements that are now and in future in the dom or get removed.
I use
$(document).on("click", "[data-hide-closest]", function(e) {_x000D_
e.preventDefault();_x000D_
var $this = $(this);_x000D_
$this.closest($this.attr("data-hide-closest")).hide();_x000D_
});
_x000D_
.alert-success {_x000D_
background-color: #dff0d8;_x000D_
border-color: #d6e9c6;_x000D_
color: #3c763d;_x000D_
}_x000D_
.alert {_x000D_
border: 1px solid transparent;_x000D_
border-radius: 4px;_x000D_
margin-bottom: 20px;_x000D_
padding: 15px;_x000D_
}_x000D_
.close {_x000D_
color: #000;_x000D_
float: right;_x000D_
font-size: 21px;_x000D_
font-weight: bold;_x000D_
line-height: 1;_x000D_
opacity: 0.2;_x000D_
text-shadow: 0 1px 0 #fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="alert alert-success">_x000D_
<a class="close" data-hide-closest=".alert">×</a>_x000D_
<strong>Success!</strong> Your entries were saved._x000D_
</div>
_x000D_
This is code for executing stored procedures with and with out parameters via reflection. Do note that the objects property names need to match the parameters of the stored procedure.
private static string ConnString = ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString;
private SqlConnection Conn = new SqlConnection(ConnString);
public void ExecuteStoredProcedure(string procedureName)
{
SqlConnection sqlConnObj = new SqlConnection(ConnString);
SqlCommand sqlCmd = new SqlCommand(procedureName, sqlConnObj);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlConnObj.Open();
sqlCmd.ExecuteNonQuery();
sqlConnObj.Close();
}
public void ExecuteStoredProcedure(string procedureName, object model)
{
var parameters = GenerateSQLParameters(model);
SqlConnection sqlConnObj = new SqlConnection(ConnString);
SqlCommand sqlCmd = new SqlCommand(procedureName, sqlConnObj);
sqlCmd.CommandType = CommandType.StoredProcedure;
foreach (var param in parameters)
{
sqlCmd.Parameters.Add(param);
}
sqlConnObj.Open();
sqlCmd.ExecuteNonQuery();
sqlConnObj.Close();
}
private List<SqlParameter> GenerateSQLParameters(object model)
{
var paramList = new List<SqlParameter>();
Type modelType = model.GetType();
var properties = modelType.GetProperties();
foreach (var property in properties)
{
if (property.GetValue(model) == null)
{
paramList.Add(new SqlParameter(property.Name, DBNull.Value));
}
else
{
paramList.Add(new SqlParameter(property.Name, property.GetValue(model)));
}
}
return paramList;
}
jQuery has a function that can do this:
include the following script in your head:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
(or just download the jQuery.js file online and include it locally)
use this script to toggle the check box when the input is clicked:
var toggle = false;
$("#INPUTNAMEHERE").click(function() {
$("input[type=checkbox]").attr("checked",!toggle);
toggle = !toggle;
});
That should do what you want if I understood what you were trying to do.
The following steps work fine on macOS Sierra 10.12.4. Note that after brew installs Docker, the docker
command (symbolic link) is not available at /usr/local/bin
. Running the Docker app for the first time creates this symbolic link. See the detailed steps below.
Install Docker.
brew cask install docker
Launch Docker.
Docker
to launch Docker.When Docker is launched in this manner, a Docker whale icon appears in the status menu. As soon as the whale icon appears, the symbolic links for docker
, docker-compose
, docker-credential-osxkeychain
and docker-machine
are created in /usr/local/bin
.
$ ls -l /usr/local/bin/docker*
lrwxr-xr-x 1 susam domain Users 67 Apr 12 14:14 /usr/local/bin/docker -> /Users/susam/Library/Group Containers/group.com.docker/bin/docker
lrwxr-xr-x 1 susam domain Users 75 Apr 12 14:14 /usr/local/bin/docker-compose -> /Users/susam/Library/Group Containers/group.com.docker/bin/docker-compose
lrwxr-xr-x 1 susam domain Users 90 Apr 12 14:14 /usr/local/bin/docker-credential-osxkeychain -> /Users/susam/Library/Group Containers/group.com.docker/bin/docker-credential-osxkeychain
lrwxr-xr-x 1 susam domain Users 75 Apr 12 14:14 /usr/local/bin/docker-machine -> /Users/susam/Library/Group Containers/group.com.docker/bin/docker-machine
Click on the docker whale icon in the status menu and wait for it to show Docker is running.
Test that docker works fine.
$ docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
78445dd45222: Pull complete
Digest: sha256:c5515758d4c5e1e838e9cd307f6c6a0d620b5e07e6f927b07d05f6d12a1ac8d7
Status: Downloaded newer image for hello-world:latest
Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
3. The Docker daemon created a new container from that image which runs the
executable that produces the output you are currently reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
to your terminal.
To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash
Share images, automate workflows, and more with a free Docker ID:
https://cloud.docker.com/
For more examples and ideas, visit:
https://docs.docker.com/engine/userguide/
$ docker version
Client:
Version: 17.03.1-ce
API version: 1.27
Go version: go1.7.5
Git commit: c6d412e
Built: Tue Mar 28 00:40:02 2017
OS/Arch: darwin/amd64
Server:
Version: 17.03.1-ce
API version: 1.27 (minimum version 1.12)
Go version: go1.7.5
Git commit: c6d412e
Built: Fri Mar 24 00:00:50 2017
OS/Arch: linux/amd64
Experimental: true
If you are going to use docker-machine
to create virtual machines, install VirtualBox.
brew cask install virtualbox
Note that if VirtualBox is not installed, then docker-machine
fails with the following error.
$ docker-machine create manager
Running pre-create checks...
Error with pre-create check: "VBoxManage not found. Make sure VirtualBox is installed and VBoxManage is in the path"
The real problem is that the variable line always has a value. The test for "no matches found" is whether there is a match so the code "if line == None:" should be replaced with "else:"
Another free option is jmeld: http://keeskuip.home.xs4all.nl/jmeld/
It's a java tool and could therefore be used on several platforms.
But (as Preet mentioned in his answer), free is not always the best option. The best diff/merge tool I ever came across is Araxis Merge. Standard edition is available for 99 EUR which is not that much.
They also provide a documentation for how to integrate Araxis with msysGit.
If you want to stick to a free tool, JMeld comes pretty close to Araxis.
Run below command into the current branch folder to merge from this <commit-id>
to current branch, --no-commit
do not make a new commit automatically
git merge --no-commit <commit-id>
git merge --continue
can only be run after the merge has resulted in conflicts.
git merge --abort
Abort the current conflict resolution process, and try to reconstruct the pre-merge state.
Try this approach using the newer str.format
syntax:
line_new = '{:>12} {:>12} {:>12}'.format(word[0], word[1], word[2])
And here's how to do it using the old %
syntax (useful for older versions of Python that don't support str.format
):
line_new = '%12s %12s %12s' % (word[0], word[1], word[2])
A really simple way to do this...
// create the option
var opt = $("<option>").val("myvalue").text("my text");
//append option to the select element
$(#my-select).append(opt);
This could be done in lots of ways, even in a single line if really you want to.
Had a directory by the same name as the file i was trying to write, so people can look out for that as well.
Check for a local or environment variables for a variable called LOL in Bash:
el@server /home/el $ set | grep LOL
el@server /home/el $
el@server /home/el $ env | grep LOL
el@server /home/el $
Sanity check, no local or environment variable called LOL.
Set a local variable called LOL in local, but not environment. So set it:
el@server /home/el $ LOL="so wow much code"
el@server /home/el $ set | grep LOL
LOL='so wow much code'
el@server /home/el $ env | grep LOL
el@server /home/el $
Variable 'LOL' exists in local variables, but not environment variables. LOL will disappear if you restart the terminal, logout/login or run exec bash
.
Set a local variable, and then clear out all local variables in Bash
el@server /home/el $ LOL="so wow much code"
el@server /home/el $ set | grep LOL
LOL='so wow much code'
el@server /home/el $ exec bash
el@server /home/el $ set | grep LOL
el@server /home/el $
You could also just unset the one variable:
el@server /home/el $ LOL="so wow much code"
el@server /home/el $ set | grep LOL
LOL='so wow much code'
el@server /home/el $ unset LOL
el@server /home/el $ set | grep LOL
el@server /home/el $
Local variable LOL is gone.
Promote a local variable to an environment variable:
el@server /home/el $ DOGE="such variable"
el@server /home/el $ export DOGE
el@server /home/el $ set | grep DOGE
DOGE='such variable'
el@server /home/el $ env | grep DOGE
DOGE=such variable
Note that exporting makes it show up as both a local variable and an environment variable.
Exported variable DOGE above survives a Bash reset:
el@server /home/el $ exec bash
el@server /home/el $ env | grep DOGE
DOGE=such variable
el@server /home/el $ set | grep DOGE
DOGE='such variable'
Unset all environment variables:
You have to pull out a can of Chuck Norris to reset all environment variables without a logout/login:
el@server /home/el $ export CAN="chuck norris"
el@server /home/el $ env | grep CAN
CAN=chuck norris
el@server /home/el $ set | grep CAN
CAN='chuck norris'
el@server /home/el $ env -i bash
el@server /home/el $ set | grep CAN
el@server /home/el $ env | grep CAN
You created an environment variable, and then reset the terminal to get rid of them.
Or you could set and unset an environment variable manually like this:
el@server /home/el $ export FOO="bar"
el@server /home/el $ env | grep FOO
FOO=bar
el@server /home/el $ unset FOO
el@server /home/el $ env | grep FOO
el@server /home/el $
Another strange thing. You wont see the libs folder in Android Studio, unless you have at least 1 file in the folder. So, I had to go to the libs folder using File Explorer, and then place the jar file there. Then, it showed up in Android Studio.
With the help of GoogleApiClient's LocationServices API we can get the current location of the user/device in specific time interval. This can be added into a background service which updates the Activity when onLocationChanged callbacks
The background service will keep running as long as the application exists in the memory and sticks to the notification drawer. The service handles the following functionalities,
Service With Location Listener
public class LocationMonitoringService extends Service implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
LocationListener {
...
...
...
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mLocationClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest.setInterval(10000); //10 secs
mLocationRequest.setFastestInterval(5000); //5 secs
int priority = LocationRequest.PRIORITY_HIGH_ACCURACY; //by default
//PRIORITY_BALANCED_POWER_ACCURACY, PRIORITY_LOW_POWER, PRIORITY_NO_POWER are the other priority modes
mLocationRequest.setPriority(priority);
mLocationClient.connect();
//Make it stick to the notification panel so it is less prone to get cancelled by the Operating System.
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
/*
* LOCATION CALLBACKS
*/
@Override
public void onConnected(Bundle dataBundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
Log.d(TAG, "== Error On onConnected() Permission not granted");
//Permission not granted by user so cancel the further execution.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest, this);
Log.d(TAG, "Connected to Google API");
}
/*
* Called by Location Services if the connection to the
* location client drops because of an error.
*/
@Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "Connection suspended");
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Failed to connect to Google API");
}
//to get the location change
@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Location changed");
if (location != null) {
//Do something with the location details,
if (location != null) {
//call your API
callAPI(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
}
}
}
}
See Complete Tutorial With source code and explanation in detail >>
Another reason why you should avoid converting the column to varchar(max) is because you cannot create an index on a varchar(max) column.
The following code snippet resolved my issue. Thought this might be useful to others.
var strEnc = this.$.txtSearch.value.replace(/\s/g, "-");_x000D_
strEnc = strEnc.replace(/-/g, " ");
_x000D_
Rather using default encodeURIComponent
my first line of code is converting all spaces
into hyphens
using regex pattern /\s\g
and the following line just does the reverse, i.e. converts all hyphens
back to spaces
using another regex pattern /-/g
. Here /g
is actually responsible for finding all
matching characters.
When I am sending this value to my Ajax call, it traverses as normal spaces
or simply %20
and thus gets rid of double-encoding
.
name
attribute in IE, please add ID to the element if you want to use getElementByIdA great alternative is
All
- it is a collection. The [0] will get the elements of the first form on the page. The "form" is a valid CSS selectorIn all of the above, the .elements
can be replaced by for example .querySelectorAll("[type=text]")
to get all text elements
This is just a supplement to the other answers. I will not repeat them (now four years later).
There are situations where a const
and a non-const have different semantics. For example:
const int y = 42;
static void Main()
{
short x = 42;
Console.WriteLine(x.Equals(y));
}
prints out True
, whereas:
static readonly int y = 42;
static void Main()
{
short x = 42;
Console.WriteLine(x.Equals(y));
}
writes False
.
The reason is that the method x.Equals
has two overloads, one that takes in a short
(System.Int16
) and one that takes an object
(System.Object
). Now the question is whether one or both apply with my y
argument.
When y
is a compile-time constant (literal), the const
case, it becomes important that there does exist an implicit conversion from int
to short
provided that the int
is a constant, and provided that the C# compiler verifies that its value is within the range of a short
(which 42
is). See Implicit constant expression conversions in the C# Language Specification. So both overloads have to be considered. The overload Equals(short)
is preferred (any short
is an object
, but not all object
are short
). So y
is converted to short
, and that overload is used. Then Equals
compares two short
of identical value, and that gives true
.
When y
is not a constant, no implicit conversion from int
to short
exists. That's because in general an int
may be too huge to fit into a short
. (An explicit conversion does exist, but I didn't say Equals((short)y)
, so that's not relevant.) We see that only one overload applies, the Equals(object)
one. So y
is boxed to object
. Then Equals
is going to compare a System.Int16
to a System.Int32
, and since the run-time types do not even agree, that will yield false
.
We conclude that in some (rare) cases, changing a const
type member to a static readonly
field (or the other way, when that is possible) can change the behavior of the program.
No need of use addition CSS/JS (Tested)
data-toggle="dropdown"
- for Clickable (can use Mobile as well web)data-hover="dropdown"
- for Hover (web only, because mobile doesn't have feature HOVER
)data-toggle="dropdown"
)/*!
* this CSS code just for snippet preview purpose. Please omit when using it.
*/
#bs-example-navbar-collapse-1 ul li {
float: left;
}
#bs-example-navbar-collapse-1 ul li ul li {
float: none !important;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
<a class="" href="">Home</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
subnav1
</a>
<ul class="dropdown-menu">
<li><a href="">Sub1</a></li>
<li><a href="">Sub2</a></li>
<li><a href="">Sub3</a></li>
<li><a href="">Sub4</a></li>
<li><a href="">Sub5</a></li>
<li><a href="">Sub6</a></li>
</ul>
<div class="clear"></div>
</li>
<li class="dropdown">
<a href="" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true">
subnav2
</a>
<ul class="dropdown-menu">
<li><a href="">Sub1</a></li>
<li><a href="">Sub2</a></li>
<li><a href="">Sub3</a></li>
<li><a href="">Sub4</a></li>
<li><a href="">Sub5</a></li>
<li><a href="">Sub6</a></li>
</ul>
<div class="clear"></div>
</li>
</ul>
</div>
<br>
<br>
<p><b>Please Note:</b> added css code not related to Bootstrap navigation. It's just for snippet preview purpose </p>
_x000D_
Output
Completely reset?
Delete the .git
directory locally.
Recreate the git repostory:
$ cd (project-directory)
$ git init
$ (add some files)
$ git add .
$ git commit -m 'Initial commit'
Push to remote server, overwriting. Remember you're going to mess everyone else up doing this … you better be the only client.
$ git remote add origin <url>
$ git push --force --set-upstream origin master
Though there are already quite a few answers, I thought my answer might help some who have exactly the same problem as mine. In my case, the problem is caused by the following permissions added per the suggestion of an ad network:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
The consequence of the above permissions is that the following features are added automatically:
android.hardware.LOCATION
android.hardware.location.GPS
android.hardware.location.NETWORK
The reason is that "Google Play attempts to discover an application's implied feature requirements by examining other elements declared in the manifest file, specifically, elements." Two of my testing devices do not have the above features, so the app became incompatible with them. Removing those permissions solved the problem immediately.
name = city.getName()!=null?city.getName():"N/A"
An interface defines what a class that inherits from it must implement. In this way, multiple classes can inherit from an interface, and because of that inherticance, you can
for more info, see this http://msdn.microsoft.com/en-us/library/ms173156.aspx
If you are into performance, then it is worth using ENUM type. It will probably be faster on big tables, due to the better index performance.
The way of using it (source: http://dev.mysql.com/doc/refman/5.5/en/enum.html):
CREATE TABLE shirts (
name VARCHAR(40),
size ENUM('x-small', 'small', 'medium', 'large', 'x-large')
);
But, I always say that explaining the query like this:
EXPLAIN SELECT * FROM shirts WHERE size='medium';
will tell you lots of information about your query and help on building a better table structure. For this end, it is usefull to let phpmyadmin Propose a table table structure - but this is more a long time optimisation possibility, when the table is already filled with lots of data.
mkdir -p newDir/subdir{1..8}
ls newDir/
subdir1 subdir2 subdir3 subdir4 subdir5 subdir6 subdir7 subdir8
Are you sure that floated block-level elements are the best solution to this problem?
Often with CSS difficulties in my experience it turns out that the reason I can't see a way of doing the thing I want is that I have got caught in a tunnel-vision with regard to my markup ( thinking "how can I make these elements do this?" ) rather than going back and looking at what exactly it is I need to achieve and maybe reworking my html slightly to facilitate that.
In my case the solutions above did not work I had to do the following:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(f)));
I've written a library to handle this for me. It's called DataTableProxy and is available as a NuGet package. Code and documentation is on Github
Look at this example for clear understanding of how dynamic import works.
Dynamic Module Imports Example
To have Basic Understanding of importing and exporting Modules.
Reference Resolution is described by RFC 3986 Uniform Resource Identifier (URI): Generic Syntax. And that is exactly how it supposed to work. To preserve base URI path you need to add slash at the end of the base URI and remove slash at the beginning of relative URI.
If base URI contains non-empty path, merge procedure discards it's last part (after last /
). Relevant section:
5.2.3. Merge Paths
The pseudocode above refers to a "merge" routine for merging a relative-path reference with the path of the base URI. This is accomplished as follows:
If the base URI has a defined authority component and an empty path, then return a string consisting of "/" concatenated with the reference's path; otherwise
return a string consisting of the reference's path component appended to all but the last segment of the base URI's path (i.e., excluding any characters after the right-most "/" in the base URI path, or excluding the entire base URI path if it does not contain any "/" characters).
If relative URI starts with a slash, it is called a absolute-path relative URI. In this case merge procedure ignore all base URI path. For more information check 5.2.2. Transform References section.
Just for convenient reference as I see that there are a lot of people searching for this topic and are too laz... sorry, busy, to check themselves (including me). Here a list of the default set of colour schemes for Vim 7.4:
blue.vim
darkblue.vim,
delek.vim
desert.vim
elflord.vim
evening.vim
industry.vim
koehler.vim
morning.vim
murphy.vim
pablo.vim
peachpuff.vim
ron.vim
shine.vim
slate.vim
torte.vim
zellner.vim
Right click on the web page you want to use as the default page and choose "Set as Start Page" whenever you run the web application from Visual Studio, it will open the selected page.
I know this has already been answered, but for anybody looking for a simple, no-frills implementation of a ViewPager indicator, I've implemented one that I've open sourced. For anyone finding Jake Wharton's version a bit complex for their needs, have a look at https://github.com/jarrodrobins/SimpleViewPagerIndicator.
It seems like your problem may be arising at
while(in.read(outputByte,0,4096)!=-1){
where it might go into an infinite loop for not advancing the offset (which is 0 always in the call). Try
while(in.read(outputByte)!=-1){
which will by default try to read upto outputByte.length into the byte[]
. This way you dont have to worry about the offset. See FileInputStrem's read method
You can use .present? which comes included with ActiveSupport.
@city = @user.city.present?
# etc ...
You could even write it like this
def show
%w(city state bio contact twitter mail).each do |attr|
instance_variable_set "@#{attr}", @user[attr].present?
end
end
It's worth noting that if you want to test if something is blank, you can use .blank?
(this is the opposite of .present?
)
Also, don't use foo == nil
. Use foo.nil?
instead.
BULK INSERT dbo.temp
FROM 'c:\temp\file.txt' --- path file in db server
WITH
(
ROWTERMINATOR ='\n'
)
it work for me but save as by editplus to ansi encoding for multilanguage
Putting this information here for future readers' benefit.
401 (Unauthorized) response header -> Request authentication header
Here are several WWW-Authenticate
response headers. (The full list is at IANA: HTTP Authentication Schemes.)
WWW-Authenticate: Basic
-> Authorization: Basic + token - Use for basic authentication WWW-Authenticate: NTLM
-> Authorization: NTLM + token (2 challenges)WWW-Authenticate: Negotiate
-> Authorization: Negotiate + token - used for Kerberos authentication
Negotiate
: This authentication scheme violates both HTTP semantics (being connection-oriented) and syntax (use of syntax incompatible with the WWW-Authenticate and Authorization header field syntax).You can set the Authorization: Basic
header only when you also have the WWW-Authenticate: Basic
header on your 401 challenge.
But since you have WWW-Authenticate: Negotiate
this should be the case for Kerberos based authentication.
Starting from iOS 6 right way to do it by using SKStoreProductViewController class.
Swift 5.x:
func openStoreProductWithiTunesItemIdentifier(_ identifier: String) {
let storeViewController = SKStoreProductViewController()
storeViewController.delegate = self
let parameters = [ SKStoreProductParameterITunesItemIdentifier : identifier]
storeViewController.loadProduct(withParameters: parameters) { [weak self] (loaded, error) -> Void in
if loaded {
// Parent class of self is UIViewContorller
self?.present(storeViewController, animated: true, completion: nil)
}
}
}
private func productViewControllerDidFinish(viewController: SKStoreProductViewController) {
viewController.dismiss(animated: true, completion: nil)
}
// Usage:
openStoreProductWithiTunesItemIdentifier("1234567")
Swift 3.x:
func openStoreProductWithiTunesItemIdentifier(identifier: String) {
let storeViewController = SKStoreProductViewController()
storeViewController.delegate = self
let parameters = [ SKStoreProductParameterITunesItemIdentifier : identifier]
storeViewController.loadProduct(withParameters: parameters) { [weak self] (loaded, error) -> Void in
if loaded {
// Parent class of self is UIViewContorller
self?.present(storeViewController, animated: true, completion: nil)
}
}
}
func productViewControllerDidFinish(_ viewController: SKStoreProductViewController) {
viewController.dismiss(animated: true, completion: nil)
}
// Usage:
openStoreProductWithiTunesItemIdentifier(identifier: "13432")
You can get the app's itunes item identifier like this: (instead of a static one)
Swift 3.2
var appID: String = infoDictionary["CFBundleIdentifier"]
var url = URL(string: "http://itunes.apple.com/lookup?bundleId=\(appID)")
var data = Data(contentsOf: url!)
var lookup = try? JSONSerialization.jsonObject(with: data!, options: []) as? [AnyHashable: Any]
var appITunesItemIdentifier = lookup["results"][0]["trackId"] as? String
openStoreProductViewController(withITunesItemIdentifier: Int(appITunesItemIdentifier!) ?? 0)
Swift 2.x:
func openStoreProductWithiTunesItemIdentifier(identifier: String) {
let storeViewController = SKStoreProductViewController()
storeViewController.delegate = self
let parameters = [ SKStoreProductParameterITunesItemIdentifier : identifier]
storeViewController.loadProductWithParameters(parameters) { [weak self] (loaded, error) -> Void in
if loaded {
// Parent class of self is UIViewContorller
self?.presentViewController(storeViewController, animated: true, completion: nil)
}
}
}
func productViewControllerDidFinish(viewController: SKStoreProductViewController) {
viewController.dismissViewControllerAnimated(true, completion: nil)
}
// Usage
openStoreProductWithiTunesItemIdentifier("2321354")
objective-C:
static NSInteger const kAppITunesItemIdentifier = 324684580;
[self openStoreProductViewControllerWithITunesItemIdentifier:kAppITunesItemIdentifier];
- (void)openStoreProductViewControllerWithITunesItemIdentifier:(NSInteger)iTunesItemIdentifier {
SKStoreProductViewController *storeViewController = [[SKStoreProductViewController alloc] init];
storeViewController.delegate = self;
NSNumber *identifier = [NSNumber numberWithInteger:iTunesItemIdentifier];
NSDictionary *parameters = @{ SKStoreProductParameterITunesItemIdentifier:identifier };
UIViewController *viewController = self.window.rootViewController;
[storeViewController loadProductWithParameters:parameters
completionBlock:^(BOOL result, NSError *error) {
if (result)
[viewController presentViewController:storeViewController
animated:YES
completion:nil];
else NSLog(@"SKStoreProductViewController: %@", error);
}];
[storeViewController release];
}
#pragma mark - SKStoreProductViewControllerDelegate
- (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController {
[viewController dismissViewControllerAnimated:YES completion:nil];
}
You can get
kAppITunesItemIdentifier
(app's itunes item identifier) like this: (instead of a static one)
NSDictionary* infoDictionary = [[NSBundle mainBundle] infoDictionary];
NSString* appID = infoDictionary[@"CFBundleIdentifier"];
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/lookup?bundleId=%@", appID]];
NSData* data = [NSData dataWithContentsOfURL:url];
NSDictionary* lookup = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSString * appITunesItemIdentifier = lookup[@"results"][0][@"trackId"];
[self openStoreProductViewControllerWithITunesItemIdentifier:[appITunesItemIdentifier intValue]];
I had the same problem and figured it out from your comments, but thought I would add the reason I caused the error to occur (for other beginners).
I had opened and edited .bash_profile using the open command in Terminal, which opened it in Text Editor. I typed in an addition to .bash_profile and it used improper quote characters. I opened .bash_profile in Atom and fixed up the error. I also associated the file with Atom for future editing.
wget -nd -r -l 2 -A jpg,jpeg,png,gif http://t.co
-nd
: no directories (save all files to the current directory; -P directory
changes the target directory)-r -l 2
: recursive level 2-A
: accepted extensionswget -nd -H -p -A jpg,jpeg,png,gif -e robots=off example.tumblr.com/page/{1..2}
-H
: span hosts (wget doesn't download files from different domains or subdomains by default)-p
: page requisites (includes resources like images on each page)-e robots=off
: execute command robotos=off
as if it was part of .wgetrc
file. This turns off the robot exclusion which means you ignore robots.txt and the robot meta tags (you should know the implications this comes with, take care).Example: Get all .jpg
files from an exemplary directory listing:
$ wget -nd -r -l 1 -A jpg http://example.com/listing/
The followin example shows how to capture and process video frames in HTML5:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Capturing & Processing Video in HTML5</title>
</head>
<body>
<div>
<h2>Camera Preview</h2>
<video id="cameraPreview" width="240" height="180" autoplay></video>
<p>
<button id="startButton" onclick="startCapture();">Start Capture</button>
<button id="stopButton" onclick="stopCapture();">Stop Capture</button>
</p>
</div>
<div>
<h2>Processing Preview</h2>
<canvas id="processingPreview" width="240" height="180"></canvas>
</div>
<div>
<h2>Recording Preview</h2>
<video id="recordingPreview" width="240" height="180" autoplay controls></video>
<p>
<a id="downloadButton">Download</a>
</p>
</div>
<script>
const ROI_X = 250;
const ROI_Y = 150;
const ROI_WIDTH = 240;
const ROI_HEIGHT = 180;
const FPS = 25;
let cameraStream = null;
let processingStream = null;
let mediaRecorder = null;
let mediaChunks = null;
let processingPreviewIntervalId = null;
function processFrame() {
let cameraPreview = document.getElementById("cameraPreview");
processingPreview
.getContext('2d')
.drawImage(cameraPreview, ROI_X, ROI_Y, ROI_WIDTH, ROI_HEIGHT, 0, 0, ROI_WIDTH, ROI_HEIGHT);
}
function generateRecordingPreview() {
let mediaBlob = new Blob(mediaChunks, { type: "video/webm" });
let mediaBlobUrl = URL.createObjectURL(mediaBlob);
let recordingPreview = document.getElementById("recordingPreview");
recordingPreview.src = mediaBlobUrl;
let downloadButton = document.getElementById("downloadButton");
downloadButton.href = mediaBlobUrl;
downloadButton.download = "RecordedVideo.webm";
}
function startCapture() {
const constraints = { video: true, audio: false };
navigator.mediaDevices.getUserMedia(constraints)
.then((stream) => {
cameraStream = stream;
let processingPreview = document.getElementById("processingPreview");
processingStream = processingPreview.captureStream(FPS);
mediaRecorder = new MediaRecorder(processingStream);
mediaChunks = []
mediaRecorder.ondataavailable = function(event) {
mediaChunks.push(event.data);
if(mediaRecorder.state == "inactive") {
generateRecordingPreview();
}
};
mediaRecorder.start();
let cameraPreview = document.getElementById("cameraPreview");
cameraPreview.srcObject = stream;
processingPreviewIntervalId = setInterval(processFrame, 1000 / FPS);
})
.catch((err) => {
alert("No media device found!");
});
};
function stopCapture() {
if(cameraStream != null) {
cameraStream.getTracks().forEach(function(track) {
track.stop();
});
}
if(processingStream != null) {
processingStream.getTracks().forEach(function(track) {
track.stop();
});
}
if(mediaRecorder != null) {
if(mediaRecorder.state == "recording") {
mediaRecorder.stop();
}
}
if(processingPreviewIntervalId != null) {
clearInterval(processingPreviewIntervalId);
processingPreviewIntervalId = null;
}
};
</script>
</body>
</html>
_x000D_
No, there is no built-in MySQL command for that. There are various tools and scripts that support it, you can kill some connections manually or restart the server (but that will be slower).
Use SHOW PROCESSLIST
to view all connections, and KILL
the process ID's you want to kill.
You could edit the timeout setting to have the MySQL daemon kill the inactive processes itself, or raise the connection count. You can even limit the amount of connections per username, so that if the process keeps misbehaving, the only affected process is the process itself and no other clients on your database get locked out.
If you can't connect yourself anymore to the server, you should know that MySQL always reserves 1 extra connection for a user with the SUPER
privilege. Unless your offending process is for some reason using a username with that privilege...
Then after you can access your database again, you should fix the process (website) that's spawning that many connections.
This depends on what you're actually trying to do.
If you simply wish to apply styles to a :before
pseudo-element when the a
element matches a pseudo-class, you need to write a:hover:before
or a:visited:before
instead. Notice the pseudo-element comes after the pseudo-class (and in fact, at the very end of the entire selector). Notice also that they are two different things; calling them both "pseudo-selectors" is going to confuse you once you run into syntax problems such as this one.
If you're writing CSS3, you can denote a pseudo-element with double colons to make this distinction clearer. Hence, a:hover::before
and a:visited::before
. But if you're developing for legacy browsers such as IE8 and older, then you can get away with using single colons just fine.
This specific order of pseudo-classes and pseudo-elements is stated in the spec:
One pseudo-element may be appended to the last sequence of simple selectors in a selector.
A sequence of simple selectors is a chain of simple selectors that are not separated by a combinator. It always begins with a type selector or a universal selector. No other type selector or universal selector is allowed in the sequence.
A simple selector is either a type selector, universal selector, attribute selector, class selector, ID selector, or pseudo-class.
A pseudo-class is a simple selector. A pseudo-element, however, is not, even though it resembles a simple selector.
However, for user-action pseudo-classes such as :hover
1, if you need this effect to apply only when the user interacts with the pseudo-element itself but not the a
element, then this is not possible other than through some obscure layout-dependent workaround. As implied by the text, standard CSS pseudo-elements cannot currently have pseudo-classes. In that case, you will need to apply :hover
to an actual child element instead of a pseudo-element.
1 Of course, this does not apply to link pseudo-classes such as :visited
as in the question, since pseudo-elements aren't links.
How about giving the port number while invoking the command without need to change anything in your application code or environment files? That way it is possible running and serving same code base from several different ports.
like:
$ export PORT=4000 && npm start
You can put the port number you like in place of the example value 4000
above.
Another possibility to store numpy arrays efficiently is Bloscpack:
#!/usr/bin/python
import numpy as np
import bloscpack as bp
import time
n = 10000000
a = np.arange(n)
b = np.arange(n) * 10
c = np.arange(n) * -0.5
tsizeMB = sum(i.size*i.itemsize for i in (a,b,c)) / 2**20.
blosc_args = bp.DEFAULT_BLOSC_ARGS
blosc_args['clevel'] = 6
t = time.time()
bp.pack_ndarray_file(a, 'a.blp', blosc_args=blosc_args)
bp.pack_ndarray_file(b, 'b.blp', blosc_args=blosc_args)
bp.pack_ndarray_file(c, 'c.blp', blosc_args=blosc_args)
t1 = time.time() - t
print "store time = %.2f (%.2f MB/s)" % (t1, tsizeMB / t1)
t = time.time()
a1 = bp.unpack_ndarray_file('a.blp')
b1 = bp.unpack_ndarray_file('b.blp')
c1 = bp.unpack_ndarray_file('c.blp')
t1 = time.time() - t
print "loading time = %.2f (%.2f MB/s)" % (t1, tsizeMB / t1)
and the output for my laptop (a relatively old MacBook Air with a Core2 processor):
$ python store-blpk.py
store time = 0.19 (1216.45 MB/s)
loading time = 0.25 (898.08 MB/s)
that means that it can store really fast, i.e. the bottleneck is typically the disk. However, as the compression ratios are pretty good here, the effective speed is multiplied by the compression ratios. Here are the sizes for these 76 MB arrays:
$ ll -h *.blp
-rw-r--r-- 1 faltet staff 921K Mar 6 13:50 a.blp
-rw-r--r-- 1 faltet staff 2.2M Mar 6 13:50 b.blp
-rw-r--r-- 1 faltet staff 1.4M Mar 6 13:50 c.blp
Please note that the use of the Blosc compressor is fundamental for achieving this. The same script but using 'clevel' = 0 (i.e. disabling compression):
$ python bench/store-blpk.py
store time = 3.36 (68.04 MB/s)
loading time = 2.61 (87.80 MB/s)
is clearly bottlenecked by the disk performance.
this
is a reference to the object typed as the current class, and super
is a reference to the object typed as its parent class.
In the constructor, this()
calls a constructor defined in the current class. super()
calls a constructor defined in the parent class. The constructor may be defined in any parent class, but it will refer to the one overridden closest to the current class. Calls to other constructors in this way may only be done as the first line in a constructor.
Calling methods works the same way. Calling this.method()
calls a method defined in the current class where super.method()
will call the same method as defined in the parent class.
It's been a few years since this question was asked (and since someone has posted a response). Since then, ProgressDialog was deprecated in API level O, according to Android's official documentation. As such, you might consider using an inline progress bar instead of a ProgressDialog as the documentation authors suggest.
var ticket = FormsAuthentication.Decrypt(
HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value);
if (ticket.Expired)
{
throw new InvalidOperationException("Ticket expired.");
}
IPrincipal user = (System.Security.Principal.IPrincipal) new RolePrincipal(new FormsIdentity(ticket));
Just use .animate()
instead of .css()
(with a duration if you want), like this:
$('#hfont1').hover(function() {
$(this).animate({"color":"#efbe5c","font-size":"52pt"}, 1000);
}, function() {
$(this).animate({"color":"#e8a010","font-size":"48pt"}, 1000);
});
You can test it here. Note though, you need either the jQuery color plugin, or jQuery UI included to animate the color. In the above, the duration is 1000ms, you can change it, or just leave it off for the default 400ms duration.
You can use the codecs module, like this:
import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile:
with codecs.open(targetFileName, "w", "utf-8") as targetFile:
while True:
contents = sourceFile.read(BLOCKSIZE)
if not contents:
break
targetFile.write(contents)
EDIT: added BLOCKSIZE
parameter to control file chunk size.
You should never use the unidirectional @OneToMany
annotation because:
Now, in your first example, both sides are owning the association, and this is bad.
While the @JoinColumn
would let the @OneToMany
side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy
attribute on the @OneToMany
side.
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<APost> aPosts;
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<BPost> bPosts;
}
public class BPost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
public class APost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
You have two options:
1) Using String.valueOf() method:
int sdRate=5;
text_Rate.setText(String.valueOf(sdRate)); //faster!, recommended! :)
2) adding an empty string:
int sdRate=5;
text_Rate.setText("" + sdRate));
Casting is not an option, will throw a ClassCastException
int sdRate=5;
text_Rate.setText(String.valueOf((String)sdRate)); //EXCEPTION!
Use the following method in the table view delegate's didSelectRowAtIndexpath
(Or from anywhere)
[myTable deselectRowAtIndexPath:[myTable indexPathForSelectedRow] animated:YES];
You don't want regular expressions here.
s = "144,1231693144,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,1563,2747941 288,1231823695,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,909,4725008"
print s.split(',')
Gives you:
['144', '1231693144', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898738574164086137773096960', '1.00
', '4295032833', '1563', '2747941 288', '1231823695', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898
738574164086137773096960', '1.00', '4295032833', '909', '4725008']
with php you can use two redirections. It works same as refresh in some issues.
you can use a page redirect.php and post your last url to it by GET method (for example). then in redirect.php you can change header to location you`ve sent to it by GET method.
like this: your page:
<?php
header("location:redirec.php?ref=".$your_url);
?>
redirect.php:
<?php
$ref_url=$_GET["ref"];
header("location:redirec.php?ref=".$ref_url);
?>
that worked for me good.
Try this, if you don't have a primary key or identical column:
select [Stu_Id],[Student_Name] ,[City] ,[Registered],
RowNum = row_number() OVER (ORDER BY (SELECT 0))
from student
ORDER BY RowNum desc
ser.read(64)
should be ser.read(size=64)
; ser.read uses keyword arguments, not positional.
Also, you're reading from the port twice; what you probably want to do is this:
i=0
for modem in PortList:
for port in modem:
try:
ser = serial.Serial(port, 9600, timeout=1)
ser.close()
ser.open()
ser.write("ati")
time.sleep(3)
read_val = ser.read(size=64)
print read_val
if read_val is not '':
print port
except serial.SerialException:
continue
i+=1
You might try boost::lexical_cast
. It throws an bad_lexical_cast
exception if it fails.
In your case:
int number;
try
{
number = boost::lexical_cast<int>(word);
}
catch(boost::bad_lexical_cast& e)
{
std::cout << word << "isn't a number" << std::endl;
}
This might be more desirable, that is use float instead
SELECT fullName, CAST(totalBal as float) totalBal FROM client_info ORDER BY totalBal DESC
The equivalent of .live() in 1.7 looks like this:
$(document).on('click', '#child', function() ...);
Basically, watch the document for click events and filter them for #child.
Go download HTMLAgilityPack, now! ;) Download LInk
This allows you to load and parse HTML. Then you can navigate the DOM and extract the inner values of all attributes. Seriously, it will take you about 10 lines of code at the maximum. It is one of the greatest free .net libraries out there.
Here is a sample:
string htmlContents = new System.IO.StreamReader(resultsStream,Encoding.UTF8,true).ReadToEnd();
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(htmlContents);
if (doc == null) return null;
string output = "";
foreach (var node in doc.DocumentNode.ChildNodes)
{
output += node.InnerText;
}
As has been said in other answers, the correct conversion specifier is "%Lf"
.
You might want to turn on the format warning by using -Wformat
(or -Wall
, which includes -Wformat
) in the gcc invocation
$ gcc source.c $ gcc -Wall source.c source.c: In function `main`: source.c:5: warning: format "%lf" expects type `double`, but argument 2 has type `long double` source.c:5: warning: format "%le" expects type `double`, but argument 3 has type `long double` $
Use microsoft's tool for remote commands executions: PsExec
If there isn't your bat-file on remote host, copy it first. For example:
copy D:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat \\RemoteServerNameOrIP\d$\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\
And then execute:
psexec \\RemoteServerNameOrIP d:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat
Note: filepath for psexec is path to file on remote server, not your local.
Here is the complete code for REST API requests using NSURLSession in swift
For GET Request
let configuration = NSURLSessionConfiguration .defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration)
let urlString = NSString(format: "your URL here")
print("get wallet balance url string is \(urlString)")
//let url = NSURL(string: urlString as String)
let request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: NSString(format: "%@", urlString) as String)
request.HTTPMethod = "GET"
request.timeoutInterval = 30
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let dataTask = session.dataTaskWithRequest(request) {
(let data: NSData?, let response: NSURLResponse?, let error: NSError?) -> Void in
// 1: Check HTTP Response for successful GET request
guard let httpResponse = response as? NSHTTPURLResponse, receivedData = data
else {
print("error: not a valid http response")
return
}
switch (httpResponse.statusCode)
{
case 200:
let response = NSString (data: receivedData, encoding: NSUTF8StringEncoding)
print("response is \(response)")
do {
let getResponse = try NSJSONSerialization.JSONObjectWithData(receivedData, options: .AllowFragments)
EZLoadingActivity .hide()
// }
} catch {
print("error serializing JSON: \(error)")
}
break
case 400:
break
default:
print("wallet GET request got response \(httpResponse.statusCode)")
}
}
dataTask.resume()
For POST request ...
let configuration = NSURLSessionConfiguration .defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration)
let params = ["username":bindings .objectForKey("username"), "provider":"walkingcoin", "securityQuestion":securityQuestionField.text!, "securityAnswer":securityAnswerField.text!] as Dictionary<String, AnyObject>
let urlString = NSString(format: “your URL”);
print("url string is \(urlString)")
let request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: NSString(format: "%@", urlString)as String)
request.HTTPMethod = "POST"
request.timeoutInterval = 30
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])
let dataTask = session.dataTaskWithRequest(request)
{
(let data: NSData?, let response: NSURLResponse?, let error: NSError?) -> Void in
// 1: Check HTTP Response for successful GET request
guard let httpResponse = response as? NSHTTPURLResponse, receivedData = data
else {
print("error: not a valid http response")
return
}
switch (httpResponse.statusCode)
{
case 200:
let response = NSString (data: receivedData, encoding: NSUTF8StringEncoding)
if response == "SUCCESS"
{
}
default:
print("save profile POST request got response \(httpResponse.statusCode)")
}
}
dataTask.resume()
I hope it works.
You can use the following flags --single-branch
&& --depth
to download the specific branch and to limit the amount of history which will be downloaded.
You will clone the repo from a certain point in time and only for the given branch
git clone -b <branch> --single-branch <url> --depth <number of commits>
--[no-]single-branch
Clone only the history leading to the tip of a single branch, either specified by the
--branch
option or the primary branch remote’sHEAD
points at.Further fetches into the resulting repository will only update the
remote-tracking
branch for the branch this option was used for the initial cloning. If the HEAD at the remote did not point at any branch when--single-branch
clone was made, no remote-tracking branch is created.
--depth
Create a shallow clone with a history truncated to the specified number of commits
There are many ways. Here are at least five:
/*
* An example of converting std::string to (const)char* using five
* different methods. Error checking is emitted for simplicity.
*
* Compile and run example (using gcc on Unix-like systems):
*
* $ g++ -Wall -pedantic -o test ./test.cpp
* $ ./test
* Original string (0x7fe3294039f8): hello
* s1 (0x7fe3294039f8): hello
* s2 (0x7fff5dce3a10): hello
* s3 (0x7fe3294000e0): hello
* s4 (0x7fe329403a00): hello
* s5 (0x7fe329403a10): hello
*/
#include <alloca.h>
#include <string>
#include <cstring>
int main()
{
std::string s0;
const char *s1;
char *s2;
char *s3;
char *s4;
char *s5;
// This is the initial C++ string.
s0 = "hello";
// Method #1: Just use "c_str()" method to obtain a pointer to a
// null-terminated C string stored in std::string object.
// Be careful though because when `s0` goes out of scope, s1 points
// to a non-valid memory.
s1 = s0.c_str();
// Method #2: Allocate memory on stack and copy the contents of the
// original string. Keep in mind that once a current function returns,
// the memory is invalidated.
s2 = (char *)alloca(s0.size() + 1);
memcpy(s2, s0.c_str(), s0.size() + 1);
// Method #3: Allocate memory dynamically and copy the content of the
// original string. The memory will be valid until you explicitly
// release it using "free". Forgetting to release it results in memory
// leak.
s3 = (char *)malloc(s0.size() + 1);
memcpy(s3, s0.c_str(), s0.size() + 1);
// Method #4: Same as method #3, but using C++ new/delete operators.
s4 = new char[s0.size() + 1];
memcpy(s4, s0.c_str(), s0.size() + 1);
// Method #5: Same as 3 but a bit less efficient..
s5 = strdup(s0.c_str());
// Print those strings.
printf("Original string (%p): %s\n", s0.c_str(), s0.c_str());
printf("s1 (%p): %s\n", s1, s1);
printf("s2 (%p): %s\n", s2, s2);
printf("s3 (%p): %s\n", s3, s3);
printf("s4 (%p): %s\n", s4, s4);
printf("s5 (%p): %s\n", s5, s5);
// Release memory...
free(s3);
delete [] s4;
free(s5);
}
Similar like the one before, but more compact. (Booleans are just numbers)
breaker = False #our mighty loop exiter!
while True:
while True:
ok = get_input("Is this ok? (y/n)")
breaker+= (ok.lower() == "y")
break
if breaker: # the interesting part!
break # <--- !
Added an example to understand the use of __ in python. Here is the list of All __
https://docs.python.org/3/genindex-all.html#_
Certain classes of identifiers (besides keywords) have special meanings. Any use of * names, in any other context, that does not follow explicitly documented use, is subject to breakage without warning
Access restriction using __
"""
Identifiers:
- Contain only (A-z, 0-9, and _ )
- Start with a lowercase letter or _.
- Single leading _ : private
- Double leading __ : strong private
- Start & End __ : Language defined Special Name of Object/ Method
- Class names start with an uppercase letter.
-
"""
class BankAccount(object):
def __init__(self, name, money, password):
self.name = name # Public
self._money = money # Private : Package Level
self.__password = password # Super Private
def earn_money(self, amount):
self._money += amount
print("Salary Received: ", amount, " Updated Balance is: ", self._money)
def withdraw_money(self, amount):
self._money -= amount
print("Money Withdraw: ", amount, " Updated Balance is: ", self._money)
def show_balance(self):
print(" Current Balance is: ", self._money)
account = BankAccount("Hitesh", 1000, "PWD") # Object Initalization
# Method Call
account.earn_money(100)
# Show Balance
print(account.show_balance())
print("PUBLIC ACCESS:", account.name) # Public Access
# account._money is accessible because it is only hidden by convention
print("PROTECTED ACCESS:", account._money) # Protected Access
# account.__password will throw error but account._BankAccount__password will not
# because __password is super private
print("PRIVATE ACCESS:", account._BankAccount__password)
# Method Call
account.withdraw_money(200)
# Show Balance
print(account.show_balance())
# account._money is accessible because it is only hidden by convention
print(account._money) # Protected Access
If you want to declare a new substance with no parameter (knowing that the object have default parameters) don't write
type substance1();
but
type substance;
Looks like you missed a few closing tags and you nshould have "http://" on the front of an external URL. Also, you should move your styles to external style sheets instead of using inline styles.
.box{
float:right;
}
.box a img{
vertical-align: middle;
border: 0px;
}
<div class="box">
<a href="<?php echo "http://www.someotherwebsite.com"; ?>">
<img src="<?php echo url::file_loc('img'); ?>media/img/twitter.png" alt="Image Decription">
</a>
</div>
As noted in other comments, it may be easier to use straight HTML, depending on your exact setup.
<div class="box">
<a href="http://www.someotherwebsite.com">
<img src="file_location/media/img/twitter.png" alt="Image Decription">
</a>
</div>
Please have a look at the below code sample;
Swift 4:
@IBDesignable class DesignableUITextField: UITextField {
let border = CALayer()
@IBInspectable var borderColor: UIColor? {
didSet {
setup()
}
}
@IBInspectable var borderWidth: CGFloat = 0.5 {
didSet {
setup()
}
}
func setup() {
border.borderColor = self.borderColor?.cgColor
border.borderWidth = borderWidth
self.layer.addSublayer(border)
self.layer.masksToBounds = true
}
override func layoutSubviews() {
super.layoutSubviews()
border.frame = CGRect(x: 0, y: self.frame.size.height - borderWidth, width: self.frame.size.width, height: self.frame.size.height)
}
}
check this link here i change display:inline-block http://cssdesk.com/gUGBH
All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)
Based on this related answer, you are looking at a list that looks like: A-Z
, a-z
, 0-9
, -
, .
, _
, ~
, :
, /
, ?
, #
, [
, ]
, @
, !
, $
, &
, '
, (
, )
, *
, +
, ,
, ;
, %
, and =
. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. %
can only be used in conjunction with url encoding as in %20
), the RFC has all of these specifics.
Pretty sure that this exception is thrown when the Excel file is either password protected or the file itself is corrupted. If you just want to read a .xlsx file, try my code below. It's a lot more shorter and easier to read.
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
//.....
static final String excelLoc = "C:/Documents and Settings/Users/Desktop/testing.xlsx";
public static void ReadExcel() {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(new File(excelLoc));
Workbook wb = WorkbookFactory.create(inputStream);
int numberOfSheet = wb.getNumberOfSheets();
for (int i = 0; i < numberOfSheet; i++) {
Sheet sheet = wb.getSheetAt(i);
//.... Customize your code here
// To get sheet name, try -> sheet.getSheetName()
}
} catch {}
}
For Swift 5, here's a quick short class to get the location:
class MyLocationManager: NSObject, CLLocationManagerDelegate {
let manager: CLLocationManager
override init() {
manager = CLLocationManager()
super.init()
manager.delegate = self
manager.distanceFilter = kCLDistanceFilterNone
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// do something with locations
}
}
What about:
#region Using Statements
using System;
using System.Xml;
#endregion
class Program {
static void Main( string[ ] args ) {
XmlDocument doc = new XmlDocument( );
//(1) the xml declaration is recommended, but not mandatory
XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration( "1.0", "UTF-8", null );
XmlElement root = doc.DocumentElement;
doc.InsertBefore( xmlDeclaration, root );
//(2) string.Empty makes cleaner code
XmlElement element1 = doc.CreateElement( string.Empty, "body", string.Empty );
doc.AppendChild( element1 );
XmlElement element2 = doc.CreateElement( string.Empty, "level1", string.Empty );
element1.AppendChild( element2 );
XmlElement element3 = doc.CreateElement( string.Empty, "level2", string.Empty );
XmlText text1 = doc.CreateTextNode( "text" );
element3.AppendChild( text1 );
element2.AppendChild( element3 );
XmlElement element4 = doc.CreateElement( string.Empty, "level2", string.Empty );
XmlText text2 = doc.CreateTextNode( "other text" );
element4.AppendChild( text2 );
element2.AppendChild( element4 );
doc.Save( "D:\\document.xml" );
}
}
(1) Does a valid XML file require an xml declaration?
(2) What is the difference between String.Empty and “” (empty string)?
The result is:
<?xml version="1.0" encoding="UTF-8"?>
<body>
<level1>
<level2>text</level2>
<level2>other text</level2>
</level1>
</body>
But I recommend you to use LINQ to XML which is simpler and more readable like here:
#region Using Statements
using System;
using System.Xml.Linq;
#endregion
class Program {
static void Main( string[ ] args ) {
XDocument doc = new XDocument( new XElement( "body",
new XElement( "level1",
new XElement( "level2", "text" ),
new XElement( "level2", "other text" ) ) ) );
doc.Save( "D:\\document.xml" );
}
}
NestedScrollView
NestedScrollView is just like ScrollView, but it supports acting as both a nested scrolling parent and child on both new and old versions of Android. Nested scrolling is enabled by default.
https://developer.android.com/reference/android/support/v4/widget/NestedScrollView.html
ScrollView
Layout container for a view hierarchy that can be scrolled by the user, allowing it to be larger than the physical display. A ScrollView is a FrameLayout, meaning you should place one child in it containing the entire contents to scroll; this child may itself be a layout manager with a complex hierarchy of objects
https://developer.android.com/reference/android/widget/ScrollView.html
This has a good general description: https://gephi.wordpress.com/tag/maven/
Let me make a few statement that can put the difference in focus:
We migrated our code base from Ant to Maven
All 3rd party librairies have been uploaded to Nexus. Maven is using Nexus as a source for libraries.
Basic functionalities of a repository manager like Sonatype are:
Since you've already looked into strtok
just continue down the same path and split your string using space (' '
) as a delimiter, then use something as realloc
to increase the size of the array containing the elements to be passed to execvp
.
See the below example, but keep in mind that strtok
will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy
or similar function.
char str[]= "ls -l";
char ** res = NULL;
char * p = strtok (str, " ");
int n_spaces = 0, i;
/* split string and append tokens to 'res' */
while (p) {
res = realloc (res, sizeof (char*) * ++n_spaces);
if (res == NULL)
exit (-1); /* memory allocation failed */
res[n_spaces-1] = p;
p = strtok (NULL, " ");
}
/* realloc one extra element for the last NULL */
res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;
/* print the result */
for (i = 0; i < (n_spaces+1); ++i)
printf ("res[%d] = %s\n", i, res[i]);
/* free the memory allocated */
free (res);
res[0] = ls
res[1] = -l
res[2] = (null)
If using Visual Studio 2012 and later (which uses .NET regular expressions), you can remove trailing whitespace without removing blank lines by using the following regex
Replace (?([^\r\n])\s)+(\r?\n)
With $1
Some explanation
The reason you need the rather complicated expression is that the character class \s
matches spaces, tabs and newline characters, so \s+
will match a group of lines containing only whitespace. It doesn't help adding a $
termination to this regex, because this will still match a group of lines containing only whitespace and newline characters.
You may also want to know (as I did) exactly what the (?([^\r\n])\s)
expression means. This is an Alternation Construct, which effectively means match to the whitespace character class if it is not a carriage return or linefeed.
Alternation constructs normally have a true and false part,
(?( expression ) yes | no )
but in this case the false part is not specified.
Since you want the function to be executed periodically, use setInterval
unsigned char c;
for( int i = 7; i >= 0; i-- ) {
printf( "%d", ( c >> i ) & 1 ? 1 : 0 );
}
printf("\n");
Explanation:
With every iteration, the most significant bit is being read from the byte by shifting it and binary comparing with 1.
For example, let's assume that input value is 128, what binary translates to 1000 0000. Shifting it by 7 will give 0000 0001, so it concludes that the most significant bit was 1. 0000 0001 & 1 = 1. That's the first bit to print in the console. Next iterations will result in 0 ... 0.
I have a project which uses LINQ-to-SQL for the data back-end. I have two main namespaces: Biz and Data. The LINQ data model lives in Data and is marked "internal"; the Biz namespace has public classes which wrap around the LINQ data classes.
So there's Data.Client
, and Biz.Client
; the latter exposes all relevant properties of the data object, e.g.:
private Data.Client _client;
public int Id { get { return _client.Id; } set { _client.Id = value; } }
The Biz objects have a private constructor (to force the use of factory methods), and an internal constructor which looks like this:
internal Client(Data.Client client) {
this._client = client;
}
That can be used by any of the business classes in the library, but the front-end (UI) has no way of directly accessing the data model, ensuring that the business layer always acts as an intermediary.
This is the first time I've really used internal
much, and it's proving quite useful.
I've had success using this in response to a button click, so I guess that you can use it too after updating your contents:
myListView.smoothScrollToPosition(theListAdapter.getCount() -1);
The iPhoneOS does capture onscroll
events, except not the way you may expect.
One-finger panning doesn’t generate any events until the user stops panning—an
onscroll
event is generated when the page stops moving and redraws—as shown in Figure 6-1.
Similarly, scroll with 2 fingers fires onscroll
only after you've stopped scrolling.
The usual way of installing the handler works e.g.
window.addEventListener('scroll', function() { alert("Scrolled"); });
// or
$(window).scroll(function() { alert("Scrolled"); });
// or
window.onscroll = function() { alert("Scrolled"); };
// etc
Try
ps -ef | grep "KEYWORD" | awk '{print $2}'
That command should give you the PID of the processes with KEYWORD in them. In this instance, awk
is returning what is in the 2nd column from the output.
a[0]
isn't an array, it's the first element of a
and therefore has no dimensions.
Try using a[0:1]
instead, which will return the first element of a
inside a single item array.
[request setValue:@"application/zip" forHTTPHeaderField:@"Content-Type"];
Here is some PowerShell that creates a single TypeScript definition file a library that includes multiple *.js
files with modern JavaScript.
First, change all the extensions to .ts
.
Get-ChildItem | foreach { Rename-Item $_ $_.Name.Replace(".js", ".ts") }
Second, use the TypeScript compiler to generate definition files. There will be a bunch of compiler errors, but we can ignore those.
Get-ChildItem | foreach { tsc $_.Name }
Finally, combine all the *.d.ts
files into one index.d.ts
, removing the import
statements and removing the default
from each export statement.
Remove-Item index.d.ts;
Get-ChildItem -Path *.d.ts -Exclude "Index.d.ts" | `
foreach { Get-Content $_ } | `
where { !$_.ToString().StartsWith("import") } | `
foreach { $_.Replace("export default", "export") } | `
foreach { Add-Content index.d.ts $_ }
This ends with a single, usable index.d.ts
file that includes many of the definitions.
sender
refers to the object that invoked the event that fired the event handler. This is useful if you have many objects using the same event handler.
EventArgs
is something of a dummy base class. In and of itself it's more or less useless, but if you derive from it, you can add whatever data you need to pass to your event handlers.
When you implement your own events, use an EventHandler
or EventHandler<T>
as their type. This guarantees that you'll have exactly these two parameters for all your events (which is a good thing).
its better to bind a click handler to the entire table and then use event.target to get the clicked TD. Thats all i can add to this as its 1:20am
You can use the >> operator. This will append data from a command to the end of a text file.
To test this try running:
echo "Hi this is a test" >> textfile.txt
Do this a couple of times and then run:
cat textfile.txt
You'll see your text has been appended several times to the textfile.txt file.
What you're using is called the haversine formula, which calculates the distance between two points on a sphere as the crow flies. The Google Maps link you provided shows the distance as 2.2 km because it's not a straight line.
Wolphram Alpha is a great resource for doing geographic calculations, and also shows a distance of 1.652 km between these two points.
If you're looking for straight-line distance (as the crow files), your function is working correctly. If what you want is driving distance (or biking distance or public transportation distance or walking distance), you'll have to use a mapping API (Google or Bing being the most popular) to get the appropriate route, which will include the distance.
Incidentally, the Google Maps API provides a packaged method for spherical distance, in its google.maps.geometry.spherical
namespace (look for computeDistanceBetween
). It's probably better than rolling your own (for starters, it uses a more precise value for the Earth's radius).
For the picky among us, when I say "straight-line distance", I'm referring to a "straight line on a sphere", which is actually a curved line (i.e. the great-circle distance), of course.
SET NOCOUNT ON even does allows to access to the affected rows like this:
SET NOCOUNT ON
DECLARE @test TABLE (ID int)
INSERT INTO @test
VALUES (1),(2),(3)
DECLARE @affectedRows int = -99
DELETE top (1)
FROM @test
SET @affectedRows = @@rowcount
SELECT @affectedRows as affectedRows
Results
affectedRows
1
Messages
Commands completed successfully.
Completion time: 2020-06-18T16:20:16.9686874+02:00
Simply use
java.util.Collections.sort(list)
without String.CASE_INSENSITIVE_ORDER comparator parameter.
All the answers above are correct, but when I use windows and disable the Prettier ESLint extension rvest.vs-code-prettier-eslint
the issue will be fixed.
Run java
with CLASSPATH
environmental variable pointing to driver's JAR file, e.g.
CLASSPATH='.:drivers/mssql-jdbc-6.2.1.jre8.jar' java ConnectURL
Where drivers/mssql-jdbc-6.2.1.jre8.jar
is the path to driver file (e.g. JDBC for for SQL Server).
The ConnectURL
is the sample app from that driver (samples/connections/ConnectURL.java
), compiled via javac ConnectURL.java
.
Regards,
In Javascript the implementation of stacks and queues is as follows:
Stack: A stack is a container of objects that are inserted and removed according to the last-in-first-out (LIFO) principle.
Queue: A queue is a container of objects (a linear collection) that are inserted and removed according to the first-in-first-out (FIFO) principle.
Unshift: Method adds one or more elements to the beginning of an array.
Shift: The method removes the first element from an array.
let stack = [];_x000D_
stack.push(1);//[1]_x000D_
stack.push(2);//[1,2]_x000D_
stack.push(3);//[1,2,3]_x000D_
_x000D_
console.log('It was inserted 1,2,3 in stack:', ...stack);_x000D_
_x000D_
stack.pop(); //[1,2]_x000D_
console.log('Item 3 was removed:', ...stack);_x000D_
_x000D_
stack.pop(); //[1]_x000D_
console.log('Item 2 was removed:', ...stack);_x000D_
_x000D_
_x000D_
let queue = [];_x000D_
queue.push(1);//[1]_x000D_
queue.push(2);//[1,2]_x000D_
queue.push(3);//[1,2,3]_x000D_
_x000D_
console.log('It was inserted 1,2,3 in queue:', ...queue);_x000D_
_x000D_
queue.shift();// [2,3]_x000D_
console.log('Item 1 was removed:', ...queue);_x000D_
_x000D_
queue.shift();// [3]_x000D_
console.log('Item 2 was removed:', ...queue);
_x000D_
Use the entire file path and use "\\" instead of "\" in the xml file path.
The file path should be as follows:
face_cascade = cv2.CascadeClassifier('C:\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_default.xml')
instead of:
cascade_fn = args.get('--cascade', "..\..\data\haarcascades\haarcascade_frontalface_alt.xml")
Syntax for Describe table
db2 describe table <tablename>
or For all table details
select * from syscat.tables
or For all table details
select * from sysibm.tables
you can use the following function:
function nl2br (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
like so:
var mystr="line\nanother line\nanother line";
mystr=nl2br(mystr);
alert(mystr);
this should alert line<br>another line<br>another line
the source of the function is from here: http://phpjs.org/functions/nl2br:480
this imitates the nl2br
function in php...
First create an array of objects,
var arr = {'name': []};
Next, push the value to the object.
var val = 2;
arr['name'].push(val);
To read from it:
var val = arr.name[0];
The solution can be found here
The eclipse.ini
file should be somewhat like this...
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20120913-144807
-product
adtproduct
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vm
C:\Program Files\Java\jdk1.8.0_25\bin\javaw.exe
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms40m
-Xmx768m
For me it work fine
&:not(:last-child){
text-transform: uppercase;
}
Inside Eclipse I've used the Clay plugin (ex Clay-Azurri). The free version allows to introspect ("reverse engineer") an existing DB schema (via JDBC) and make a diagram of some selected tables.
That is very odd.
I went through ItemNotFoundException
's base classes and tested the following multiple catch
es to see what would catch it:
try {
remove-item C:\nonexistent\file.txt -erroraction stop
}
catch [System.Management.Automation.ItemNotFoundException] {
write-host 'ItemNotFound'
}
catch [System.Management.Automation.SessionStateException] {
write-host 'SessionState'
}
catch [System.Management.Automation.RuntimeException] {
write-host 'RuntimeException'
}
catch [System.SystemException] {
write-host 'SystemException'
}
catch [System.Exception] {
write-host 'Exception'
}
catch {
write-host 'well, darn'
}
As it turns out, the output was 'RuntimeException'
. I also tried it with a different exception CommandNotFoundException
:
try {
do-nonexistent-command
}
catch [System.Management.Automation.CommandNotFoundException] {
write-host 'CommandNotFoundException'
}
catch {
write-host 'well, darn'
}
That output 'CommandNotFoundException'
correctly.
I vaguely remember reading elsewhere (though I couldn't find it again) of problems with this. In such cases where exception filtering didn't work correctly, they would catch the closest Type
they could and then use a switch
. The following just catches Exception
instead of RuntimeException
, but is the switch
equivalent of my first example that checks all base types of ItemNotFoundException
:
try {
Remove-Item C:\nonexistent\file.txt -ErrorAction Stop
}
catch [System.Exception] {
switch($_.Exception.GetType().FullName) {
'System.Management.Automation.ItemNotFoundException' {
write-host 'ItemNotFound'
}
'System.Management.Automation.SessionStateException' {
write-host 'SessionState'
}
'System.Management.Automation.RuntimeException' {
write-host 'RuntimeException'
}
'System.SystemException' {
write-host 'SystemException'
}
'System.Exception' {
write-host 'Exception'
}
default {'well, darn'}
}
}
This writes 'ItemNotFound'
, as it should.
If you are on windows, what i suppose you need to do set the PATH like this:
SET PATH=%M2%
furthermore i assume you need to set your path to something like C:...\apache-maven-3.0.3\ cause this is the default folder for the windows archive. On the other i assume you need to add the path of maven to your and not set it to only maven so you setting should look like this:
SET PATH=%PATH%;%M2%
This worked for me:
curl -v --cookie "USER_TOKEN=Yes" http://127.0.0.1:5000/
I could see the value in backend using
print request.cookies
You can also use COALESCE ( expression [ ,...n ] ) - returns first non-null like:
SELECT COALESCE(MAX(X),0) AS MaxX
FROM tbl
WHERE XID = 1
Just hide them before showing them:
$(document).ready(function(){
$("input[name$='group2']").click(function() {
var test = $(this).val();
$("div.desc").hide();
$("#"+test).show();
});
});
try use this
lblresult.Content = lblresult.Content + "prime are :" + j + "\n";
On newer versions of OS X you should find ALL JREs (and JDKs) under
/Library/Java/JavaVirtualMachines/
/System/Library/Java/JavaVirtualMachines/
the old path
/System/Library/Frameworks/JavaVM.framework/
has been deprecated.
Here is the official deprecation note:
There is actually a very simple solution. Just set them both like this:
view.layer.borderWidth = 5
view.layer.borderColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.5).cgColor
view.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.25).cgColor
if the database is created and you have started the connection to the, then al you need is to add the driver jar. from the project window, right click on the libraries folder, goto c:programsfiles\sun\javadb\lib\derbyclient.jar. load the file and you should be able to run.
all the best
ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;
This is all you need to:
id
columnCredit is given to @resnyanskiy who gave this answer in a comment.
You could easily use the following to list only files:
ls -d -1 $PWD/*.*
the following to list directories:
ls -d -1 $PWD/**
the following to list everything (files/dirs):
ls -d -1 $PWD/**/*
More helpful options:
-d list directories not their content
-R recursive
-1 list one file per line
-l use long listing format
-a list all including entries starting with . and ..
-A list all but don't list implied . and ..
for more info, just type the following
ls --help
To whoever it might concern, here's my version that checks for Office 95-2019 & O365, both MSI based and ClickAndRun are supported, on both 32 and 64 bit systems (falls back to 32 bits when 64 bit version is not installed).
Written in Python 3.5 but of course you can always use that logic in order to write your own code in another language:
from winreg import *
from typing import Tuple, Optional, List
# Let's make sure the dictionnary goes from most recent to oldest
KNOWN_VERSIONS = {
'16.0': '2016/2019/O365',
'15.0': '2013',
'14.0': '2010',
'12.0': '2007',
'11.0': '2003',
'10.0': '2002',
'9.0': '2000',
'8.0': '97',
'7.0': '95',
}
def get_value(hive: int, key: str, value: Optional[str], arch: int = 0) -> str:
"""
Returns a value from a given registry path
:param hive: registry hive (windows.registry.HKEY_LOCAL_MACHINE...)
:param key: which registry key we're searching for
:param value: which value we query, may be None if unnamed value is searched
:param arch: which registry architecture we seek (0 = default, windows.registry.KEY_WOW64_64KEY, windows.registry.KEY_WOW64_32KEY)
Giving multiple arches here will return first result
:return: value
"""
def _get_value(hive: int, key: str, value: Optional[str], arch: int) -> str:
try:
open_reg = ConnectRegistry(None, hive)
open_key = OpenKey(open_reg, key, 0, KEY_READ | arch)
value, type = QueryValueEx(open_key, value)
# Return the first match
return value
except (FileNotFoundError, TypeError, OSError) as exc:
raise FileNotFoundError('Registry key [%s] with value [%s] not found. %s' % (key, value, exc))
# 768 = 0 | KEY_WOW64_64KEY | KEY_WOW64_32KEY (where 0 = default)
if arch == 768:
for _arch in [KEY_WOW64_64KEY, KEY_WOW64_32KEY]:
try:
return _get_value(hive, key, value, _arch)
except FileNotFoundError:
pass
raise FileNotFoundError
else:
return _get_value(hive, key, value, arch)
def get_keys(hive: int, key: str, arch: int = 0, open_reg: HKEYType = None, recursion_level: int = 1,
filter_on_names: List[str] = None, combine: bool = False) -> dict:
"""
:param hive: registry hive (windows.registry.HKEY_LOCAL_MACHINE...)
:param key: which registry key we're searching for
:param arch: which registry architecture we seek (0 = default, windows.registry.KEY_WOW64_64KEY, windows.registry.KEY_WOW64_32KEY)
:param open_reg: (handle) handle to already open reg key (for recursive searches), do not give this in your function call
:param recursion_level: recursivity level
:param filter_on_names: list of strings we search, if none given, all value names are returned
:param combine: shall we combine multiple arch results or return first match
:return: list of strings
"""
def _get_keys(hive: int, key: str, arch: int, open_reg: HKEYType, recursion_level: int, filter_on_names: List[str]):
try:
if not open_reg:
open_reg = ConnectRegistry(None, hive)
open_key = OpenKey(open_reg, key, 0, KEY_READ | arch)
subkey_count, value_count, _ = QueryInfoKey(open_key)
output = {}
values = []
for index in range(value_count):
name, value, type = EnumValue(open_key, index)
if isinstance(filter_on_names, list) and name not in filter_on_names:
pass
else:
values.append({'name': name, 'value': value, 'type': type})
if not values == []:
output[''] = values
if recursion_level > 0:
for subkey_index in range(subkey_count):
try:
subkey_name = EnumKey(open_key, subkey_index)
sub_values = get_keys(hive=0, key=key + '\\' + subkey_name, arch=arch,
open_reg=open_reg, recursion_level=recursion_level - 1,
filter_on_names=filter_on_names)
output[subkey_name] = sub_values
except FileNotFoundError:
pass
return output
except (FileNotFoundError, TypeError, OSError) as exc:
raise FileNotFoundError('Cannot query registry key [%s]. %s' % (key, exc))
# 768 = 0 | KEY_WOW64_64KEY | KEY_WOW64_32KEY (where 0 = default)
if arch == 768:
result = {}
for _arch in [KEY_WOW64_64KEY, KEY_WOW64_32KEY]:
try:
if combine:
result.update(_get_keys(hive, key, _arch, open_reg, recursion_level, filter_on_names))
else:
return _get_keys(hive, key, _arch, open_reg, recursion_level, filter_on_names)
except FileNotFoundError:
pass
return result
else:
return _get_keys(hive, key, arch, open_reg, recursion_level, filter_on_names)
def get_office_click_and_run_ident():
# type: () -> Optional[str]
"""
Try to find the office product via clickandrun productID
"""
try:
click_and_run_ident = get_value(HKEY_LOCAL_MACHINE,
r'Software\Microsoft\Office\ClickToRun\Configuration',
'ProductReleaseIds',
arch=KEY_WOW64_64KEY |KEY_WOW64_32KEY,)
except FileNotFoundError:
click_and_run_ident = None
return click_and_run_ident
def _get_used_word_version():
# type: () -> Optional[int]
"""
Try do determine which version of Word is used (in case multiple versions are installed)
"""
try:
word_ver = get_value(HKEY_CLASSES_ROOT, r'Word.Application\CurVer', None)
except FileNotFoundError:
word_ver = None
try:
version = int(word_ver.split('.')[2])
except (IndexError, ValueError, AttributeError):
version = None
return version
def _get_installed_office_version():
# type: () -> Optional[str, bool]
"""
Try do determine which is the highest current version of Office installed
"""
for possible_version, _ in KNOWN_VERSIONS.items():
try:
office_keys = get_keys(HKEY_LOCAL_MACHINE,
r'SOFTWARE\Microsoft\Office\{}'.format(possible_version),
recursion_level=2,
arch=KEY_WOW64_64KEY |KEY_WOW64_32KEY,
combine=True)
try:
is_click_and_run = True if office_keys['ClickToRunStore'] is not None else False
except:
is_click_and_run = False
try:
is_valid = True if office_keys['Word'] is not None else False
if is_valid:
return possible_version, is_click_and_run
except KeyError:
pass
except FileNotFoundError:
pass
return None, None
def get_office_version():
# type: () -> Tuple[str, Optional[str]]
"""
It's plain horrible to get the office version installed
Let's use some tricks, ie detect current Word used
"""
word_version = _get_used_word_version()
office_version, is_click_and_run = _get_installed_office_version()
# Prefer to get used word version instead of installed one
if word_version is not None:
office_version = word_version
version = float(office_version)
click_and_run_ident = get_office_click_and_run_ident()
def _get_office_version():
# type: () -> str
if version:
if version < 16:
try:
return KNOWN_VERSIONS['{}.0'.format(version)]
except KeyError:
pass
# Special hack to determine which of 2016, 2019 or O365 it is
if version == 16:
if isinstance(click_and_run_ident, str):
if '2016' in click_and_run_ident:
return '2016'
if '2019' in click_and_run_ident:
return '2019'
if 'O365' in click_and_run_ident:
return 'O365'
return '2016/2019/O365'
# Let's return whatever we found out
return 'Unknown: {}'.format(version, click_and_run_ident)
if isinstance(click_and_run_ident, str) or is_click_and_run:
click_and_run_suffix = 'ClickAndRun'
else:
click_and_run_suffix = None
return _get_office_version(), click_and_run_suffix
You can than use the code like the following example:
office_version, click_and_run = get_office_version()
print('Office {} {}'.format(office_version, click_and_run))
Remarks
Use the S_ISDIR
macro:
int isDirectory(const char *path) {
struct stat statbuf;
if (stat(path, &statbuf) != 0)
return 0;
return S_ISDIR(statbuf.st_mode);
}
I believe you need to be in a TTY for docker to be able to allocate a TTY (the -t
option). Jenkins executes its jobs not in a TTY.
Having said that, the script you are running within Jenkins you may also want to run locally. In that case it can be really convenient to have a TTY allocated so you can send signals like ctrl+c when running it locally.
To fix this make your script optionally use the -t
option, like so:
test -t 1 && USE_TTY="-t"
docker run ${USE_TTY} ...
Function errors are a common thing in almost all content management systems and there is a few ways you can approach this.
Wrap your code using:
<script>
jQuery(function($) {
YOUR CODE GOES HERE
});
</script>
You can also use jQuery's API using noConflict();
<script>
$.noConflict();
jQuery( document ).ready(function( $ ) {
// Code that uses jQuery's $ can follow here.
});
// Code that uses other library's $ can follow here.
</script>
Another example of using noConflict without using document ready:
<script>
jQuery.noConflict();
(function( $ ) {
$(function() {
// YOUR CODE HERE
});
});
</script>
You could even choose to create your very alias to avoid conflicts like so:
var jExample = jQuery.noConflict();
// Do something with jQuery
jExample( "div p" ).hide();
Yet another longer solution is to rename all referances of $ to jQuery:
$( "div p" ).hide();
to jQuery( "div p" ).hide();
Combining the answer by "Pushcode" and the one using the seed for the random generator. I needed it to create a serie of pseudo-readable 'words'.
private int RandomNumber(int min, int max, int seed=0)
{
Random random = new Random((int)DateTime.Now.Ticks + seed);
return random.Next(min, max);
}
As simple as it can be
Use $(this)
here too
$(document).on("click",".appDetails", function () {
var clickedBtnID = $(this).attr('id'); // or var clickedBtnID = this.id
alert('you clicked on button #' + clickedBtnID);
});
Each statement has a distinct use case. They are not interchangeable.
SELECT...INTO MyTable...
creates a new MyTable
where one did not exist before.
INSERT INTO MyTable...SELECT...
is used when MyTable
already exists.
Simple solution for HTML5 ready browsers...
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
if (document.createEvent) {
var event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
pom.dispatchEvent(event);
}
else {
pom.click();
}
}
Usage
download('test.txt', 'Hello world!');
Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.
-
is the 'binary operator' your error is referencing, and either CurrentDay
or MA
(or both) are non-numeric.
A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). +
is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).
R only knows how to apply +
(and other binary operators, such as -
) to numeric arguments:
> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator
When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.
EDIT:
Your error lies in the use of [
instead of [[
. Because Day
is a list, subsetting with [
will return a list, not a numeric vector. [[
, however, returns an object of the class of the item contained in the list:
> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator
> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3
Transaction
, as you've defined it, returns a list of two vectors. Above, Day
is a list contain one vector. Day2
, however, is simply a vector.
String rat_values = "Food 1 | Service 3 | Atmosphere 3 | Value for money 1 ";
String[] value_split = rat_values.split("\\|");
for (String string : value_split) {
System.out.println(string);
}
static String findFirstKeyByValue(Dictionary<string, string> Data_Array, String value)
{
if (Data_Array.ContainsValue(value))
{
foreach (String key in Data_Array.Keys)
{
if (Data_Array[key].Equals(value))
return key;
}
}
return null;
}
Use a struct or a class for the return value. Using std::pair
may work for now, but
Returning a structure with self-documenting member variable names will likely be less bug-prone for anyone using your function. Putting my coworker hat on for a moment, your divide_result
structure is easy for me, a potential user of your function, to immediately understand after 2 seconds. Messing around with ouput parameters or mysterious pairs and tuples would take more time to read through and may be used incorrectly. And most likely even after using the function a few times I still won't remember the correct order of the arguments.
I like that one, because you can "define rules" for the arguments, needed or not,...
or if you're a Unix guy, than you might like the GNU Getopt .NET port.
Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?
) as the request body.
This requires Content-Type
and Content-Length
headers, so the receiving server knows how to interpret the incoming data. (*)
var querystring = require('querystring');
var http = require('http');
var data = querystring.stringify({
username: yourUsernameValue,
password: yourPasswordValue
});
var options = {
host: 'my.url',
port: 80,
path: '/login',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data)
}
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
});
});
req.write(data);
req.end();
(*) Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencoded
for the traditional format that a standard HTML form would use.
It's easy to send JSON (application/json
) in exactly the same manner; just JSON.stringify()
the data beforehand.
URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure.
The bottom line is: The server must be able to interpret the content type in question. It could be text/plain
or anything else; there is no need to convert data if the receiving server understands it as it is.
Add a charset parameter (e.g. application/json; charset=Windows-1252
) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.
There are multiple ways you can remove/filter the null values from a column in DataFrame.
Lets create a simple DataFrame with below code:
date = ['2016-03-27','2016-03-28','2016-03-29', None, '2016-03-30','2016-03-31']
df = spark.createDataFrame(date, StringType())
Now you can try one of the below approach to filter out the null values.
# Approach - 1
df.filter("value is not null").show()
# Approach - 2
df.filter(col("value").isNotNull()).show()
# Approach - 3
df.filter(df["value"].isNotNull()).show()
# Approach - 4
df.filter(df.value.isNotNull()).show()
# Approach - 5
df.na.drop(subset=["value"]).show()
# Approach - 6
df.dropna(subset=["value"]).show()
# Note: You can also use where function instead of a filter.
You can also check the section "Working with NULL Values" on my blog for more information.
I hope it helps.
Example:
<songs>
<song dateplayed="2011-07-24 19:40:26">
<title>I left my heart on Europa</title>
<artist>Ship of Nomads</artist>
</song>
<song dateplayed="2011-07-24 19:27:42">
<title>Oh Ganymede</title>
<artist>Beefachanga</artist>
</song>
<song dateplayed="2011-07-24 19:23:50">
<title>Kallichore</title>
<artist>Jewitt K. Sheppard</artist>
</song>
then:
<?php
$mysongs = simplexml_load_file('songs.xml');
echo $mysongs->song[0]->artist;
?>
Output on your browser: Ship of Nomads
credits: http://blog.teamtreehouse.com/how-to-parse-xml-with-php5
Follow the example --
songs = [
{"title": "happy birthday", "playcount": 4},
{"title": "AC/DC", "playcount": 2},
{"title": "Billie Jean", "playcount": 6},
{"title": "Human Touch", "playcount": 3}
]
print("===========================")
print(f'Songs --> {songs} \n')
title = list(map(lambda x : x['title'], songs))
print(f'Print Title --> {title}')
playcount = list(map(lambda x : x['playcount'], songs))
print(f'Print Playcount --> {playcount}')
print (f'Print Sorted playcount --> {sorted(playcount)}')
# Aliter -
print(sorted(list(map(lambda x: x['playcount'],songs))))
The ES6 way to split a string into an array character-wise is by using the spread operator. It is simple and nice.
array = [...myString];
Example:
let myString = "Hello world!"
array = [...myString];
console.log(array);
// another example:
console.log([..."another splitted text"]);
_x000D_
I tried type(of:...)
in Playground with Swift 3. This is my result.
This is the code format version.
print(String(describing: type(of: UIButton.self)))
print(String(describing: type(of: UIButton())))
UIButton.Type
UIButton
You can do that with a grid:
article {
display: grid;
}
.one {
grid-area: 1 / 1 / 2 / 2;
}
.two {
grid-area: 1 / 1 / 2 / 2;
}
a.h:
#ifndef A_H
#define A_H
struct a {
int i;
struct b {
int j;
}
};
#endif
there you go, now you just need to include a.h to the files where you want to use this structure.
As you went through the tutorial you must have come across the section on migration, as this was one of the major changes in Django 1.7
Prior to Django 1.7, the syncdb command never made any change that had a chance to destroy data currently in the database. This meant that if you did syncdb for a model, then added a new row to the model (a new column, effectively), syncdb would not affect that change in the database.
So either you dropped that table by hand and then ran syncdb again (to recreate it from scratch, losing any data), or you manually entered the correct statements at the database to add only that column.
Then a project came along called south
which implemented migrations. This meant that there was a way to migrate forward (and reverse, undo) any changes to the database and preserve the integrity of data.
In Django 1.7, the functionality of south
was integrated directly into Django. When working with migrations, the process is a bit different.
models.py
(as normal).makemigrations
command. This command is smart enough to detect what has changed and will create a script to effect that change to your database.migrate
. This command applies all migrations in order.So your normal syncdb
is now a two-step process, python manage.py makemigrations
followed by python manage.py migrate
.
Now, on to your specific problem:
class Snippet(models.Model):
owner = models.ForeignKey('auth.User', related_name='snippets')
highlighted = models.TextField()
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES,
default='python',
max_length=100)
style = models.CharField(choices=STYLE_CHOICES,
default='friendly',
max_length=100)
In this model, you have two fields highlighted
and code
that is required (they cannot be null).
Had you added these fields from the start, there wouldn't be a problem because the table has no existing rows?
However, if the table has already been created and you add a field that cannot be null, you have to define a default value to provide for any existing rows - otherwise, the database will not accept your changes because they would violate the data integrity constraints.
This is what the command is prompting you about. You can tell Django to apply a default during migration, or you can give it a "blank" default highlighted = models.TextField(default='')
in the model itself.
Simplest way to add borders to inset the borders using InsetDrawable
,following will show top border only :
<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetBottom="-2dp"
android:insetLeft="-2dp"
android:insetRight="-2dp">
<shape android:shape="rectangle">
<solid android:color="@color/light_gray" />
<stroke
android:width=".5dp"
android:color="@color/dark_gray" />
</shape>
</inset>
Use the STR
function:
SELECT STR(field_name) FROM table_name
float_expression
Is an expression of approximate numeric (float) data type with a decimal point.
length
Is the total length. This includes decimal point, sign, digits, and spaces. The default is 10.
decimal
Is the number of places to the right of the decimal point. decimal must be less than or equal to 16. If decimal is more than 16 then the result is truncated to sixteen places to the right of the decimal point.
source: https://msdn.microsoft.com/en-us/library/ms189527.aspx
The following snippet will iterate over nested objects. Objects within the objects. Feel free to change it to meet your requirements. Like if you want to add array support make if-else and make a function that loop through arrays ...
var p = {_x000D_
"p1": "value1",_x000D_
"p2": "value2",_x000D_
"p3": "value3",_x000D_
"p4": {_x000D_
"p4": 'value 4'_x000D_
}_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
/**_x000D_
* Printing a nested javascript object_x000D_
*/_x000D_
function jsonPrinter(obj) {_x000D_
_x000D_
for (let key in obj) {_x000D_
// checking if it's nested_x000D_
if (obj.hasOwnProperty(key) && (typeof obj[key] === "object")) {_x000D_
jsonPrinter(obj[key])_x000D_
} else {_x000D_
// printing the flat attributes_x000D_
console.log(key + " -> " + obj[key]);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
jsonPrinter(p);
_x000D_
1.gcc version >= 5
2.CXXFLAGS += -std=c++14
3. #include <memory>
Any kind of wrapper is good.
With Java 8+, use either an AtomicInteger
:
AtomicInteger ordinal = new AtomicInteger(0);
list.forEach(s -> {
s.setOrdinal(ordinal.getAndIncrement());
});
... or an array:
int[] ordinal = { 0 };
list.forEach(s -> {
s.setOrdinal(ordinal[0]++);
});
With Java 10+:
var wrapper = new Object(){ int ordinal = 0; };
list.forEach(s -> {
s.setOrdinal(wrapper.ordinal++);
});
Note: be very careful if you use a parallel stream. You might not end up with the expected result. Other solutions like Stuart's might be more adapted for those cases.
int
Of course, this is still valid for types other than int
. You only need to change the wrapping type to an AtomicReference
or an array of that type. For instance, if you use a String
, just do the following:
AtomicReference<String> value = new AtomicReference<>();
list.forEach(s -> {
value.set("blah");
});
Use an array:
String[] value = { null };
list.forEach(s-> {
value[0] = "blah";
});
Or with Java 10+:
var wrapper = new Object(){ String value; };
list.forEach(s->{
wrapper.value = "blah";
});
You need to pass the values of the dict into the Bike
constructor before using like that. Or, see the namedtuple
-- seems more in line with what you're trying to do.
In the simplest terms, an ASP.NET HttpHandler is a class that implements the System.Web.IHttpHandler
interface.
ASP.NET HTTPHandlers are responsible for intercepting requests made to your ASP.NET web application server. They run as processes in response to a request made to the ASP.NET Site. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler.
ASP.NET offers a few default HTTP handlers:
You can create your own custom HTTP handlers that render custom output to the browser. Typical scenarios for HTTP Handlers in ASP.NET are for example
You implement the IHttpHandler
interface to create a synchronous handler and the IHttpAsyncHandler
interface to create an asynchronous handler. The interfaces require you to implement the ProcessRequest
method and the IsReusable
property.
The ProcessRequest
method handles the actual processing for requests made, while the Boolean IsReusable
property specifies whether your handler can be pooled for reuse (to increase performance) or whether a new handler is required for each request.
Error Code: 1005 -- there is a wrong primary key reference in your code
Usually it's due to a referenced foreign key field that does not exist. It might be you have a typo mistake, or check case it should be same, or there's a field-type mismatch. Foreign key-linked fields must match definitions exactly.
Some known causes may be:
INT(10)
the key field needs to be INT(10)
as well and not INT(11)
or TINYINT
. You may want to confirm the field size using SHOW
CREATE
TABLE
because Query Browser will sometimes visually show just INTEGER
for both INT(10)
and INT(11)
. You should also check that one is not SIGNED
and the other is UNSIGNED
. They both need to be exactly the same.MyISAM
table. In order to use foreign keys, the tables must both be InnoDB
. (Actually, if both tables are MyISAM
then you won’t get an error message - it just won’t create the key.) In Query Browser, you can specify the table type.ON
DELETE
SET
NULL
, but the relevant key field is set to NOT
NULL
. You can fix this by either changing your cascade or setting the field to allow NULL
values.ALTER
statement or you have mistyped one of the field names in the relationshipFor more details, refer to: MySQL Error Number 1005 Can’t create table
After hours struggling with this... I did the following:
web.config
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
</dependentAssembly>
<!-- other assemblies... -->
</assemblyBinding>
</runtime>
The key to enter the correct newVersion and oldVersion number is open the project's References
find the package go to its properties or click alt + enter
You'll find a section Version
which in my case was 12.0.0.0
while its actually 12.0.3
when exploring with Manage NuGet.
So you need to pick the package's version from the reference properties (in my case
12.0.0.0
)
Finally, clean
and rebuild
the project (you might want to delete the bin
and obj
folders before).
You might face other packages dependencies issues, i did that for all and they worked.
The removeAttr()
function only removes HTML attributes. The display
is not a HTML attribute, it's a CSS property. You'd like to use css()
function instead to manage CSS properties.
But jQuery offers a show()
function which does exactly what you want in a concise call:
$("span").show();
<script>
var someSession = '<%= Session["SessionName"].ToString() %>';
alert(someSession)
</script>
This code you can write in Aspx. If you want this in some js.file, you have two ways:
no need to overwhelm with ton of above examples, just keep in mind two points of view:
typeof var;
is an unary operator will return the original type or root type of var. so that it will return primitive types(string
, number
, bigint
, boolean
, undefined
, and symbol
) or object
type.
in case of higher-level object, like built-in objects (String, Number, Boolean, Array..) or complex or custom objects, all of them is object
root type, but instance type built base on them is vary(like OOP class inheritance concept), here a instanceof A
- a binary operator - will help you, it will go through the prototype chain to check whether constructor of the right operand(A) appears or not.
so whenever you want to check "root type" or work with primitive variable - use "typeof", otherwise using "instanceof".
null
is a special case,which is seemingly primitive, but indeed is a special case for object. Using a === null
to check null instead.
on the other hand, function
is also a special case, which is built-in object but typeof
return function
as you can see instanceof
must go through the prototype chain meanwhile typeof
just check the root type one time so it's easy to understand why typeof
is faster than instanceof
If you want to add your custom headers to ALL requests, you can change the defaults on $httpProvider to always add this header…
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.common = {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
};
}]);
You can use a Null-Object like so:
public class Convert {
@SuppressWarnings({"UnnecessaryBoxing"})
public static final Integer NULL = new Integer(0);
public static Integer convert(String integer) {
try {
return Integer.valueOf(integer);
} catch (NumberFormatException e) {
return NULL;
}
}
public static void main(String[] args) {
Integer a = convert("123");
System.out.println("a.equals(123) = " + a.equals(123));
System.out.println("a == NULL " + (a == NULL));
Integer b = convert("onetwothree");
System.out.println("b.equals(123) = " + b.equals(123));
System.out.println("b == NULL " + (b == NULL));
Integer c = convert("0");
System.out.println("equals(0) = " + c.equals(0));
System.out.println("c == NULL " + (c == NULL));
}
}
The result of main in this example is:
a.equals(123) = true
a == NULL false
b.equals(123) = false
b == NULL true
c.equals(0) = true
c == NULL false
This way you can always test for failed conversion but still work with the results as Integer instances. You might also want to tweak the number NULL represents (? 0).
I had this problem too. I had used stateSave
option and that made this problem.
Remove this option and problem is solved.
In addition to the ioctl() method Filip demonstrated you can use getifaddrs(). There is an example program at the bottom of the man page.
I'm working with .NET 4.5 and couldn't get this working... I was using WPF Custom Control Library. This worked for me in the end...
<ResourceDictionary Source="/MyAssembly;component/mytheme.xaml" />
source: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/11a42336-8d87-4656-91a3-275413d3cc19
Use Encoding.Convert to adjust the byte array before attempting to decode it into your destination encoding.
Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(Message);
byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
string msg = iso.GetString(isoBytes);
ModelState.Values.SelectMany(v => v.Errors).ToList().ForEach(x => _logger.Error($"{x.ErrorMessage}\n"));
You have to use @BotFather, send it command: /setjoingroups There will be dialog like this:
YOU: /setjoingroups
BotFather: Choose a bot to change group membership settings.
YOU: @YourBot
BotFather: 'Enable' - bot can be added to groups. 'Disable' - block group invitations, the bot can't be added to groups. Current status is: DISABLED
YOU: Enable
BotFather: Success! The new status is: ENABLED.
After this you will see button "Add to Group" in your bot's profile.
If it is Long
object then You can use longValue == null
or you can use Objects.isNull(longValue)
method in Java 8 .
Please check Objects for more info.
I cannot find where I read it at, but I believe gmail utilizes an open TCP connection to do the e-mail push.
We can resolve this problem without using JQuery and other libs.
I wrote following code for this purpose:
You have similar structure ->
<div class="parent">
<div class="child-one">
</div>
<div class="child-two">
</div>
</div>
JS:
scrollToElement() {
var parentElement = document.querySelector('.parent');
var childElement = document.querySelector('.child-two');
parentElement.scrollTop = childElement.offsetTop - parentElement.offsetTop;
}
We can easily rewrite this method for passing parent and child as an arguments
You should put your processing into the class constructor or an OnInit
hook method.
You're doing nothing wrong! You've changed the directory, but only within the subshell that runs the script.
You can run the script in your current process with the "dot" command:
. proj
But I'd prefer Greg's suggestion to use an alias in this simple case.
Maxlength
The maximum number of characters that will be accepted as input. The maxlength attribute specifies the maximum number of characters allowed in the element.
<form action="/action_page.php">
Username: <input type="text" name="usrname" maxlength="5"><br>
<input type="submit" value="Submit">
</form>
maybe whole database + tables + fields should have the same charset??!
i.e.
CREATE TABLE `politicas` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Nombre` varchar(250) CHARACTER SET utf8 NOT NULL,
-------------------------------------^here!!!!!!!!!!!
PRIMARY KEY (`ID`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-------------------------------------------------^here!!!!!!!!!
A web service endpoint is the URL that another program would use to communicate with your program. To see the WSDL you add ?wsdl
to the web service endpoint URL.
Web services are for program-to-program interaction, while web pages are for program-to-human interaction.
So:
Endpoint is: http://www.blah.com/myproject/webservice/webmethod
Therefore,
WSDL is: http://www.blah.com/myproject/webservice/webmethod?wsdl
To expand further on the elements of a WSDL, I always find it helpful to compare them to code:
A WSDL has 2 portions (physical & abstract).
Physical Portion:
Definitions - variables - ex: myVar, x, y, etc.
Types - data types - ex: int, double, String, myObjectType
Operations - methods/functions - ex: myMethod(), myFunction(), etc.
Messages - method/function input parameters & return types
Porttypes - classes (i.e. they are a container for operations) - ex: MyClass{}, etc.
Abstract Portion:
Binding - these connect to the porttypes and define the chosen protocol for communicating with this web service. - a protocol is a form of communication (so text/SMS, vs. phone vs. email, etc.).
Service - this lists the address where another program can find your web service (i.e. your endpoint).
You can use this regex to get the yyyy-MM-dd format:
((?:19|20)\\d\\d)-(0?[1-9]|1[012])-([12][0-9]|3[01]|0?[1-9])
You can find example for date validation: How to validate date with regular expression.
FORMAT()
is slower than CONVERT()
. This answer is slightly better than @jpx's answer because it only does a replace on the time part of the date.
112 = yyyymmdd - no format change needed
108 = hh:mm:ss - remove :
SELECT CONVERT(VARCHAR, GETDATE(), 112) +
REPLACE(CONVERT(VARCHAR, GETDATE(), 108), ':', '')
It seems the solutions for HTML/JS/CSS desktop apps are in no short supply.
One solution I have just come across is TideSDK: http://www.tidesdk.org/, which seems very promising, looking at the documentation.
You can develop with Python, PHP or Ruby, and package it for Mac, Windows or Linux.
document.getElementById("demo").innerHTML = voteable
finds the element with the id demo and then places the voteable
value into it; either too young or old enough.
So effectively <p id="demo"></p>
becomes for example <p id="demo">Old Enough</p>
Main thing to worry about is how would you notify the elevator that it needs to move up or down. and also if you are going to have a centralized class to control this behavior and how could you distribute the control.
It seems like it can be very simple or very complicated. If we don't take concurrency or the time for an elevator to get to one place, then it seems like it will be simple since we just need to check the states of elevator, like is it moving up or down, or standing still. But if we make Elevator implement Runnable, and constantly check and synchronize a queue (linkedList). A Controller class will assign which floor to go in the queue. When the queue is empty, the run() method will wait (queue.wait() ), when a floor is assigned to this elevator, it will call queue.notify() to wake up the run() method, and run() method will call goToFloor(queue.pop()). This will make the problem too complicated. I tried to write it on paper, but dont think it works. It seems like we don't really need to take concurrency or timing issue into account here, but we do need to somehow use a queue to distribute the control.
Any suggestion?
If you are doing this manually, download LibreOffice and use LibreOffice Calc to import your CSV. It does a much better job of stuff like this than any version of Excel I've tried, and it can save to XLS or XLSX as required if you need to transfer to Excel afterwards.
But if you're stuck with Excel and need a better fix, there seems to be a way. It seems to be locale dependent (which seems idiotic, in my humble opinion). I don't have Excel 2007, but I have Excel 2010, and the example given:
ID,Name,Description
"12345","Smith, Joe","Hey.
My name is Joe."
doesn't work. I wrote it in Notepad and chose Save as..., and next to the Save button you can choose the encoding. I chose UTF-8 as suggested, but with no luck. Changing the commas to semicolons worked for me, though. I didn't change anything else, and it just worked. So I changed the example to look like this, and chose the UTF-8 encoding when saving in Notepad:
ID;Name;Description
"12345";"Smith, Joe";"Hey.
My name is Joe."
But there's a catch! The only way it works is if you double-click the CSV file to open it in Excel. If I try to import data from text and chose this CSV, then it still fails on quoted newlines.
But there's another catch! The working field separator (comma in the original example, semicolon in my case) seems to depend on the system's Regional Settings (set under Control Panel -> Region and Language). In Norway, comma is the decimal separator. Excel seems to avoid this character and prefer a semicolon instead. I have access to another computer set to UK English locale, and on that computer, the first example with a comma separator works fine (only on doubleclick), and the one with semicolon actually fails! So much for interoperability. If you want to publish this CSV online and users may have Excel, I guess you have to publish both versions and suggest that people check which file gives the correct number of rows.
So all the details that I've been able to gather to get this to work are:
Hope this helps someone.
.cut_text {_x000D_
white-space: nowrap; _x000D_
width: 200px; _x000D_
border: 1px solid #000000;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
}
_x000D_
<div class="cut_text">_x000D_
_x000D_
very long text_x000D_
</div>
_x000D_
I accomplished this today by loading my SQL from a text file into one string. I then used the string Split function to separate the string into individual commands which were then sent to the server individually. Simples :)
Just realised that you need to split on \nGO just in case the letters GO appear in any of your table names etc. Guess I was lucky there!
Adding my localhost on Valid OAuth redirect URIs at https://developers.facebook.com/apps/YOUR_APP_ID/fb-login/ solved the problem!
And pay attention for one detail here:
In this case http://localhost:3000 is not the same of http://0.0.0.0:3000 or http://127.0.0.1:3000
Make sure you are using exactly the running url of you sandbox server. I spend some time to discover that...
// Environment.GetFolderPath
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // Current User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); // All User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles); // Program Files
Environment.GetFolderPath(Environment.SpecialFolder.Cookies); // Internet Cookie
Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Logical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); // Physical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.Favorites); // Favorites
Environment.GetFolderPath(Environment.SpecialFolder.History); // Internet History
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache); // Internet Cache
Environment.GetFolderPath(Environment.SpecialFolder.MyComputer); // "My Computer" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // "My Documents" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic); // "My Music" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); // "My Pictures" Folder
Environment.GetFolderPath(Environment.SpecialFolder.Personal); // "My Document" Folder
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); // Program files Folder
Environment.GetFolderPath(Environment.SpecialFolder.Programs); // Programs Folder
Environment.GetFolderPath(Environment.SpecialFolder.Recent); // Recent Folder
Environment.GetFolderPath(Environment.SpecialFolder.SendTo); // "Sent to" Folder
Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); // Start Menu
Environment.GetFolderPath(Environment.SpecialFolder.Startup); // Startup
Environment.GetFolderPath(Environment.SpecialFolder.System); // System Folder
Environment.GetFolderPath(Environment.SpecialFolder.Templates); // Document Templates
The easiest thing to do would be to insert the elements with the disabled
attribute.
<input type="hidden" name="not_gonna_submit" disabled="disabled" value="invisible" />
This way you can still access them as children of the form.
Disabled fields have the downside that the user can't interact with them at all- so if you have a disabled
text field, the user can't select the text. If you have a disabled
checkbox, the user can't change its state.
You could also write some javascript to fire on form submission to remove the fields you don't want to submit.
You don't need to run Xcode 10.2 for iOS 12.2 support. You just need access to the appropriate folder in DeviceSupport.
A possible solution is
/Applications
. It's possible to have multiple Xcode versions in the same directory.Create a symbolic link in Terminal.app to have access to the 12.2 device support folder in Xcode 10.2
ln -s /Applications/Xcode102.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/12.2\ \(16E226\) /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport
You can move Xcode 10.2 to somewhere else but then you have to adjust the path.
Now Xcode 10.1 supports devices running iOS 12.2
This is my experience
.navbar { min-height:38px; }
.navbar .navbar-brand{ padding: 0 12px;font-size: 16px;line-height: 38px;height: 38px; }
.navbar .navbar-nav > li > a { padding-top: 0px; padding-bottom: 0px; line-height: 38px; }
.navbar .navbar-toggle { margin-top: 3px; margin-bottom: 0px; padding: 8px 9px; }
.navbar .navbar-form { margin-top: 2px; margin-bottom: 0px }
.navbar .navbar-collapse {border-color: #A40303;}