Use:
MessageBoxResult m = MessageBox.Show("The file will be saved here.", "File Save", MessageBoxButton.OKCancel);
if(m == m.Yes)
{
// Do something
}
else if (m == m.No)
{
// Do something else
}
MessageBoxResult is used on Windows Phone instead of DialogResult...
If you are using Django admin, here is the simplest solution.
class ReadonlyFieldsMixin(object):
def get_readonly_fields(self, request, obj=None):
if obj:
return super(ReadonlyFieldsMixin, self).get_readonly_fields(request, obj)
else:
return tuple()
class MyAdmin(ReadonlyFieldsMixin, ModelAdmin):
readonly_fields = ('sku',)
The answer above with spark-csv is correct but there is an issue - the library creates several files based on the data frame partitioning. And this is not what we usually need. So, you can combine all partitions to one:
df.coalesce(1).
write.
format("com.databricks.spark.csv").
option("header", "true").
save("myfile.csv")
and rename the output of the lib (name "part-00000") to a desire filename.
This blog post provides more details: https://fullstackml.com/2015/12/21/how-to-export-data-frame-from-apache-spark/
Option 1: Have an index on a non-null column present that can be used for the scan. Or create a function-based index as:
create index idx on t(0);
this can then be scanned to give the count.
Option 2: If you have monitoring turned on then check the monitoring view USER_TAB_MODIFICATIONS and add/subtract the relevant values to the table statistics.
Option 3: For a quick estimate on large tables invoke the SAMPLE clause ... for example ...
SELECT 1000*COUNT(*) FROM sometable SAMPLE(0.1);
Option 4: Use a materialized view to maintain the count(*). Powerful medicine though.
um ...
Based on @md-nazrul-islam reply, This is what I did with SCSS:
ul.ui-autocomplete {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
float: left;
display: none;
min-width: 160px;
margin: 0 0 10px 25px;
list-style: none;
background-color: #ffffff;
border: 1px solid #ccc;
border-color: rgba(0, 0, 0, 0.2);
//@include border-radius(5px);
@include box-shadow( rgba(0, 0, 0, 0.1) 0 5px 10px );
@include background-clip(padding-box);
*border-right-width: 2px;
*border-bottom-width: 2px;
li.ui-menu-item{
padding:0 .5em;
line-height:2em;
font-size:.8em;
&.ui-state-focus{
background: #F7F7F7;
}
}
}
As of June 2019, if your user's are on iOS 13 the cellular download limit has been lifted. User's just get a warning now. Read here
In case the article is removed here are screen shots of it below
You are copying singleton's customVar
into a singletonVar
variable and changing that variable does not affect the original value in singleton.
// This does not update singleton variable
// It just assigns value of your local variable
Log.d("Test",singletonVar);
singletonVar="World";
Log.d("Test",singletonVar);
// This actually assigns value of variable in singleton
Singleton.customVar = singletonVar;
It's used for raising errors.
if something:
raise Exception('My error!')
Some examples here
You can use the encoded flag on the @Path
annotation:
public interface APIService {
@GET("{fullUrl}")
Call<Users> getUsers(@Path(value = "fullUrl", encoded = true) String fullUrl);
}
/
with %2F
.?
being replaced by %3F
, however, so you still can't pass in dynamic query strings. let controlStates: Array<UIControl.State> = [.normal, .highlighted, .disabled, .selected, .focused, .application, .reserved]
for controlState in controlStates {
button.setTitle(NSLocalizedString("Title", comment: ""), for: controlState)
}
* * * * * wget --quiet https://example.com/file --output-document=/dev/null
I find --quiet
clearer than -q
, and --output-document=/dev/null
clearer than -O - > /dev/null
I don't know if I understand your question, but maybe:
foreach ($_POST as $id=>$value)
if (strncmp($id,'id[',3) $info[rtrim(ltrim($id,'id['),']')]=$_POST[$id];
would help
That is if you really want to have a different name (id[key]) on each checkbox of the html form (not very efficient). If not you can just name them all the same, i.e. 'id' and iterate on the (selected) values of the array, like: foreach ($_POST['id'] as $key=>$value)...
The $@
and $<
are special macros.
Where:
$@
is the file name of the target.
$<
is the name of the first dependency.
import time
time.sleep(5) # Delays for 5 seconds. You can also use a float value.
Here is another example where something is run approximately once a minute:
import time
while True:
print("This prints once a minute.")
time.sleep(60) # Delay for 1 minute (60 seconds).
By default [Route("api/[controller]") will generated by .Net Core/Asp.Net Web API.You need to modify little bit,just add [Action] like [Route("api/[controller]/[action]")]. I have mentioned a dummy solution:
// Default generated controller
//
[Route("api/[controller]")
public class myApiController : Controller
{
[HttpGet]
public string GetInfo()
{
return "Information";
}
}
//
//A little change would do the magic
//
[Route("api/[controller]/[action]")]
public class ServicesController : Controller
{
[HttpGet]
[ActionName("Get01")]
public string Get01()
{
return "GET 1";
}
[HttpGet]
[ActionName("Get02")]
public string Get02()
{
return "Get 2";
}
[HttpPost]
[ActionName("Post01")]
public HttpResponseMessage Post01(MyCustomModel01 model)
{
if (!ModelState.IsValid)
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
//.. DO Something ..
return Request.CreateResonse(HttpStatusCode.OK, "Optional Message");
}
[HttpPost]
[ActionName("Post02")]
public HttpResponseMessage Post02(MyCustomModel02 model)
{
if (!ModelState.IsValid)
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
//.. DO Something ..
return Request.CreateResonse(HttpStatusCode.OK, "Optional Message");
}
}
Lets say you saved your software onto your desktop.
if you want to remove an entire folder like an uninstaller program you could use this.
cd C:\Users\User\Detsktop\
rd /s /q SOFTWARE
this will delete the entire folder called software and all of its files and subfolders
Make Sure You Delete The Correct Folder Cause This Does Not Have A Yes / No Option
For the most part, the method is the same as setting the whole body
.divi{
background-image: url('path');
}
</style>
<div class="divi"></div>
Check out umount2
:
Linux 2.1.116 added the umount2() system call, which, like umount(), unmounts a target, but allows additional flags controlling the behaviour of the operation:
MNT_FORCE (since Linux 2.1.116) Force unmount even if busy. (Only for NFS mounts.) MNT_DETACH (since Linux 2.4.11) Perform a lazy unmount: make the mount point unavailable for new accesses, and actually perform the unmount when the mount point ceases to be busy. MNT_EXPIRE (since Linux 2.6.8) Mark the mount point as expired. If a mount point is not currently in use, then an initial call to umount2() with this flag fails with the error EAGAIN, but marks the mount point as expired. The mount point remains expired as long as it isn't accessed by any process. A second umount2() call specifying MNT_EXPIRE unmounts an expired mount point. This flag cannot be specified with either MNT_FORCE or MNT_DETACH. Return Value
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
why don't u try using an absolute xPath
//soap:Envelope[1]/soap:Body[1]/PaymentNotification[1]/payment
or since u know that it is a payment and payment doesn't have any attributes just select directly from payment
//soap:Envelope[1]/soap:Body[1]/PaymentNotification[1]/payment/*
Please use SqlBulkCopyColumnMapping.
Example:
private void SaveFileToDatabase(string filePath)
{
string strConnection = System.Configuration.ConfigurationManager.ConnectionStrings["MHMRA_TexMedEvsConnectionString"].ConnectionString.ToString();
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
//Create Connection to Excel work book
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
//Create OleDbCommand to fetch data from Excel
using (OleDbCommand cmd = new OleDbCommand("Select * from [Crosswalk$]", excelConnection))
{
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
//Give your Destination table name
sqlBulk.DestinationTableName = "PaySrcCrosswalk";
// this is a simpler alternative to explicit column mappings, if the column names are the same on both sides and data types match
foreach(DataColumn column in dt.Columns) {
s.ColumnMappings.Add(new SqlBulkCopyColumnMapping(column.ColumnName, column.ColumnName));
}
sqlBulk.WriteToServer(dReader);
}
}
}
}
}
is to pass $args...
to the @mixin
.
That way, no matter how many $args
you will pass.
In the @input
call, you can pass all args needed.
Like so:
@mixin box-shadow($args...) {
-webkit-box-shadow: $args;
-moz-box-shadow: $args;
box-shadow: $args;
}
And now you can reuse your box-shadow in every class you want by passing all needed args:
.my-box-shadow {
@include box-shadow(2px 2px 5px #555, inset 0 0 0);
}
ls | xargs -I % mv % %_`date +%d%b%Y`
One line is enough. ls all files/dirs under current dir and append date to each file.
To programmatically maximize the windowstate you can use:
this.WindowState = FormWindowState.Maximized;
this.MaximizeBox = false;
This is not so easy because basically popups are not supported in windows forms. Although windows forms is based on win32 and in win32 popup are supported. If you accept a few tricks, following code will set you going with a popup. You decide if you want to put it to good use :
class PopupWindow : Control
{
private const int WM_ACTIVATE = 0x0006;
private const int WM_MOUSEACTIVATE = 0x0021;
private Control ownerControl;
public PopupWindow(Control ownerControl)
:base()
{
this.ownerControl = ownerControl;
base.SetTopLevel(true);
}
public Control OwnerControl
{
get
{
return (this.ownerControl as Control);
}
set
{
this.ownerControl = value;
}
}
protected override CreateParams CreateParams
{
get
{
CreateParams createParams = base.CreateParams;
createParams.Style = WindowStyles.WS_POPUP |
WindowStyles.WS_VISIBLE |
WindowStyles.WS_CLIPSIBLINGS |
WindowStyles.WS_CLIPCHILDREN |
WindowStyles.WS_MAXIMIZEBOX |
WindowStyles.WS_BORDER;
createParams.ExStyle = WindowsExtendedStyles.WS_EX_LEFT |
WindowsExtendedStyles.WS_EX_LTRREADING |
WindowsExtendedStyles.WS_EX_RIGHTSCROLLBAR |
WindowsExtendedStyles.WS_EX_TOPMOST;
createParams.Parent = (this.ownerControl != null) ? this.ownerControl.Handle : IntPtr.Zero;
return createParams;
}
}
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr SetActiveWindow(HandleRef hWnd);
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_ACTIVATE:
{
if ((int)m.WParam == 1)
{
//window is being activated
if (ownerControl != null)
{
SetActiveWindow(new HandleRef(this, ownerControl.FindForm().Handle));
}
}
break;
}
case WM_MOUSEACTIVATE:
{
m.Result = new IntPtr(MouseActivate.MA_NOACTIVATE);
return;
//break;
}
}
base.WndProc(ref m);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.FillRectangle(SystemBrushes.Info, 0, 0, Width, Height);
e.Graphics.DrawString((ownerControl as VerticalDateScrollBar).FirstVisibleDate.ToLongDateString(), this.Font, SystemBrushes.InfoText, 2, 2);
}
}
Experiment with it a bit, you have to play around with its position and its size. Use it wrong and nothing shows.
In later versions (tested with TensorFlow 1.14) there's a more numpy-like way to get the shape of a tensor. You can use tensor.shape
to get the shape of the tensor.
tensor_shape = tensor.shape
print(tensor_shape)
Implementation with Guzzle library:
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
$httpClient = new Client();
$response = $httpClient->post(
'https://postman-echo.com/post',
[
RequestOptions::BODY => 'POST raw request content',
RequestOptions::HEADERS => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
]
);
echo(
$response->getBody()->getContents()
);
PHP CURL extension:
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://postman-echo.com/post',
CURLOPT_RETURNTRANSFER => true,
/**
* Specify POST method
*/
CURLOPT_POST => true,
/**
* Specify request content
*/
CURLOPT_POSTFIELDS => 'POST raw request content',
]);
$response = curl_exec($curlHandler);
curl_close($curlHandler);
echo($response);
Describe Formatted/Extended will show the data definition of the table in hive
hive> describe Formatted dbname.tablename;
use the relative path
main page might be: /index.html
secondary page: /otherFolder/otherpage.html
link would be like so:
<a href="/otherFolder/otherpage.html">otherpage</a>
How about this, using an overlay?
.image:hover > .overlay {
width:100%;
height:100%;
position:absolute;
background-color:#000;
opacity:0.5;
border-radius:30px;
}
Just use two Listboxes, one for header and other for data
for headers - set RowSource property to top row e.g. Incidents!Q4:S4
for data - set Row Source Property to Incidents!Q5:S10
The DNS server seems out of order. You can use another DNS server such as 8.8.8.8. Put nameserver 8.8.8.8
to the first line of /etc/resolv.conf
.
I think what you're looking for is not hashing but encryption. With hashing, you will not be able to retrieve the original filename from the "hash" variable. With encryption you can, and it is secure.
See AES in ASP.NET with VB.NET for more information about encryption in .NET.
put your javascript at the bottom of the page (ie after the element getting defined..)
Heredoc may be an option, see example 2 here: http://php.net/manual/en/language.types.string.php
StatTransfer is a program that moves data easily between Stata, Excel (or csv), SAS, etc. It is very user friendly (requires no programming skills). See www.stattransfer.com
If you use the program just note that you will have to choose "ASCII/Text - Delimited" to work with .csv files rather than .xls
As of IE 9. You can now load a text file and set a style.innerHTML property. So essentially you can now load a css file through ajax (and get the callback) and then just set the text inside of a style tag like this.
This works in other browsers, not sure how far back. But as long as you don't need to support IE8 then it would work.
// RESULT: doesn't work in IE8 and below. Works in IE9 and other browsers.
$(document).ready(function() {
// we want to load the css as a text file and append it with a style.
$.ajax({
url:'myCss.css',
success: function(result) {
var s = document.createElement('style');
s.setAttribute('type', 'text/css');
s.innerHTML = result;
document.getElementsByTagName("head")[0].appendChild(s);
},
fail: function() {
alert('fail');
}
})
});
and then you can have it pull an external file like the myCss.css
.myClass { background:#F00; }
The zsh shell has an option to make all background processes run with nohup.
In ~/.zshrc
add the lines:
setopt nocheckjobs #don't warn about bg processes on exit
setopt nohup #don't kill bg processes on exit
Then you just need to run a process like so: python bgservice.py &
, and you no longer need to use the nohup command.
I know not many people use zsh, but it's a really cool shell which I would recommend.
Although all the approaches regarding the use of async: false
are not good because of its deprecation and stuck the page untill the request comes back. Thus here are 2 ways to do it:
1st: Return whole ajax response in a function and then make use of done
function to capture the response when the request is completed.(RECOMMENDED, THE BEST WAY)
function getAjax(url, data){
return $.ajax({
type: 'POST',
url : url,
data: data,
dataType: 'JSON',
//async: true, //NOT NEEDED
success: function(response) {
//Data = response;
}
});
}
CALL THE ABOVE LIKE SO:
getAjax(youUrl, yourData).done(function(response){
console.log(response);
});
FOR MULTIPLE AJAX CALLS MAKE USE OF $.when
:
$.when( getAjax(youUrl, yourData), getAjax2(yourUrl2, yourData2) ).done(function(response){
console.log(response);
});
2nd: Store the response in a cookie and then outside of the ajax call get that cookie value.(NOT RECOMMENDED)
$.ajax({
type: 'POST',
url : url,
data: data,
//async: false, // No need to use this
success: function(response) {
Cookies.set(name, response);
}
});
// Outside of the ajax call
var response = Cookies.get(name);
NOTE: In the exmple above jquery cookies
library is used.It is quite lightweight and works as snappy. Here is the link https://github.com/js-cookie/js-cookie
Yes, you can!
$ ln -sfn source_file_or_directory_name softlink_name
There are two named emulator
binary file. which located under $SDK/tools/emulator
another under $SDK/emulator/
$SDK/emulator
to your env PATHI have write a script to help me to invoke the avd list
#!/bin/bash -e
echo "--- $# $(PWD)"
HOME_CURRENT=$(PWD)
HOME_EMULATOR=/Users/pcao/Library/Android/sdk/emulator
if [ "$#" -eq 0 ]
then
echo "ERROR pls try avd 23 or avd 28 "
fi
if [ "$1" = "23" ]
then
echo "enter 23"
cd $HOME_EMULATOR
./emulator -avd Nexus_5_API_23_Android6_ &
cd $HOME_CURRENT
fi
if [ "$1" = "28" ]
then
echo "enter 28"
cd $HOME_EMULATOR
./emulator -avd Nexus_5_API_28_GooglePlay_ &
cd $HOME_CURRENT
fi
As everyone said, references can't be null. That is because, a reference refers to an object. In your code:
// this compiles, but doesn't work, and does this even mean anything?
if (&str == NULL)
you are taking the address of the object str
. By definition, str
exists, so it has an address. So, it cannot be NULL
. So, syntactically, the above is correct, but logically, the if
condition is always going to be false.
About your questions: it depends upon what you want to do. Do you want the function to be able to modify the argument? If yes, pass a reference. If not, don't (or pass reference to const
). See this C++ FAQ for some good details.
In general, in C++, passing by reference is preferred by most people over passing a pointer. One of the reasons is exactly what you discovered: a reference can't be NULL
, thus avoiding you the headache of checking for it in the function.
You might also need to provide your user with an alert showing that those functions are disabled for the text input fields. This will work
function showError(){_x000D_
alert('you are not allowed to cut,copy or paste here');_x000D_
}_x000D_
_x000D_
$('.form-control').bind("cut copy paste",function(e) {_x000D_
e.preventDefault();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<textarea class="form-control" oncopy="showError()" onpaste="showError()"></textarea>
_x000D_
The solution is to use
android:fillViewport="true"
on Scroll view and moreover try to use
"wrap_content"
instead of "fill_parent"
as "fill_parent"
is deprecated now.
Use OnCommand event of imagebutton. Within it do
<asp:Button id="Button1" Text="Click" CommandName="Something" CommandArgument="your command arg" OnCommand="CommandBtn_Click" runat="server"/>
Code-behind:
void CommandBtn_Click(Object sender, CommandEventArgs e)
{
switch(e.CommandName)
{
case "Something":
// Do your code
break;
default:
break;
}
}
In plain C you can use a pointer/size combination in your API.
void doSomething(MyStruct* mystruct, size_t numElements)
{
for (size_t i = 0; i < numElements; ++i)
{
MyStruct current = mystruct[i];
handleElement(current);
}
}
Using pointers is the closest to call-by-reference available in C.
Now you should be able to do it directly in the IB.
Not sure though, if this was available when the question was posted originally.
Go to inspect element and check if .justify-content-center is listed as a class name under 'Styles' tab. If not, probably you are using bootstrap v3 in which justify-content-center is not defined.
If so, please update bootstrap, worked for me.
As of today, you can read some values from HTML5 data
attributes in CSS3 declarations. In CaioToOn's fiddle the CSS code can use the data
properties for setting the content
.
Unfortunately it is not working for the width
and height
(tested in Google Chrome 35, Mozilla Firefox 30 & Internet Explorer 11).
But there is a CSS3 attr() Polyfill from Fabrice Weinberg which provides support for data-width
and data-height
. You can find the GitHub repo to it here: cssattr.js.
I had to remove the following files too since brew complained in install later after manually removing all files.
/usr/local/share/doc/node/gdbinit
/usr/local/share/systemtap/tapset/node.stp
and then do the following
brew install node
brew link node
1.) Storage of database passwords Use some kind of hash with a salt and then alter the hash, obfuscate it, for example add a distinct value for each byte. That way your passwords a super secured against dictionary attacks and rainbow tables.
2.) To check if the password matches, create your hash for the password the user put in. Then perform a query against the database for the username and just check if the two password hashes are identical. If they are, give the user an authentication token.
The query should then look like this:
select hashedPassword from users where username=?
Then compare the password to the input.
Further questions?
if you are using extracted tomcat then,
startup.sh
and shutdown.sh
are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that
if tomcat is installed then
/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart
What worked for me on CentOS was:
sudo yum -y install gcc
sudo yum install python-devel
I suggest using JavaScript's Array method filter()
to identify an element by value. It filters data by using a "function to test each element of the array. Return true to keep the element, false otherwise.."
The following function filters the data, returning data for which the callback returns true
, i.e. where data.code
equals the requested country code.
function getCountryByCode(code) {
return data.filter(
function(data){ return data.code == code }
);
}
var found = getCountryByCode('DZ');
See the demonstration below:
var data = [{_x000D_
"name": "Afghanistan",_x000D_
"code": "AF"_x000D_
}, {_x000D_
"name": "Åland Islands",_x000D_
"code": "AX"_x000D_
}, {_x000D_
"name": "Albania",_x000D_
"code": "AL"_x000D_
}, {_x000D_
"name": "Algeria",_x000D_
"code": "DZ"_x000D_
}];_x000D_
_x000D_
_x000D_
function getCountryByCode(code) {_x000D_
return data.filter(_x000D_
function(data) {_x000D_
return data.code == code_x000D_
}_x000D_
);_x000D_
}_x000D_
_x000D_
var found = getCountryByCode('DZ');_x000D_
_x000D_
document.getElementById('output').innerHTML = found[0].name;
_x000D_
<div id="output"></div>
_x000D_
A File object in Java is a representation of a path to a directory or file, not the file itself. You don't need to have write access to the filesystem to create a File
object, you only need it if you intend to actually write to the file (using a FileOutputStream for example)
Using NewRequest
just to create an URL is an overkill. Use the net/url
package:
package main
import (
"fmt"
"net/url"
)
func main() {
base, err := url.Parse("http://www.example.com")
if err != nil {
return
}
// Path params
base.Path += "this will get automatically encoded"
// Query params
params := url.Values{}
params.Add("q", "this will get encoded as well")
base.RawQuery = params.Encode()
fmt.Printf("Encoded URL is %q\n", base.String())
}
Playground: https://play.golang.org/p/YCTvdluws-r
Try this:
par(adj = 0)
plot(1, 1, main = "Title")
or equivalent:
plot(1, 1, main = "Title", adj = 0)
adj = 0
produces left-justified text, 0.5 (the default) centered text and 1 right-justified text. Any value in [0, 1]
is allowed.
However, the issue is that this will also change the position of the label of the x-axis and y-axis.
Sometimes if you change the starting activity you have to click edit in the run dropdown play button and in app change the Launch Options Activity to the one you have set the LAUNCHER intent filter in the manifest.
The view (blade template): Inside the loop you can retrieve whatever column you looking for
@foreach ($products as $product)
{{$product->sku}}
@endforeach
.
matches any character. Used in conjunction with the curly braces already mentioned:
$: cat > test
========
============================
oo
ooooooooooooooooooooooo
$: grep -E '(.)\1{10}' test
============================
ooooooooooooooooooooooo
Use std::reference_wrapper
like this:
#include <functional>
#include <string>
#include <vector>
#include <iostream>
int main()
{
std::string hello = "Hello, ";
std::string world = "everyone!";
typedef std::vector<std::reference_wrapper<std::string>> vec_t;
vec_t vec = {hello, world};
vec[1].get() = "world!";
std::cout << hello << world << std::endl;
return 0;
}
As standard suggests, for a standard container X
containing objects of type T
, T
must be Erasable
from X
.
Erasable
means that the following expression is well formed:
allocator_traits<A>::destroy(m, p)
A
is container's allocator type, m
is allocator instance and p
is a pointer of type *T
. See here for Erasable
definition.
By default, std::allocator<T>
is used as vector's allocator. With the default allocator, the requirement is equivalent to the validity of p->~T()
(Note the T
is a reference type and p
is pointer to a reference). However, pointer to a reference is illegal, hence the expression is not well formed.
You have two ways:
First go to the particular path of Android SDK:
1) Open your command prompt and traverse to the platform-tools directory through it such as
$ cd Frameworks\Android-Sdk\platform-tools
2) Run your adb commands now such as to know that your adb is working properly :
$ adb devices OR adb logcat OR simply adb
Second way is :
1) Right click on your My Computer.
2) Open Environment variables.
3) Add new variable to your System PATH variable(Add if not exist otherwise no need to add new variable if already exist).
4) Add path of platform-tools directory to as value of this variable such as C:\Program Files\android-sdk\platform-tools.
5) Restart your computer once.
6) Now run the above adb commands such adb devices or other adb commands from anywhere in command prompt.
Also on you can fire a command on terminal setx PATH "%PATH%;C:\Program Files\android-sdk\platform-tools"
Starting Python 3.8
, the standard library provides the NormalDist
object as part of the statistics
module.
It can be used to get the inverse cumulative distribution function (inv_cdf
- inverse of the cdf
), also known as the quantile function or the percent-point function for a given mean (mu
) and standard deviation (sigma
):
from statistics import NormalDist
NormalDist(mu=10, sigma=2).inv_cdf(0.95)
# 13.289707253902943
Which can be simplified for the standard normal distribution (mu = 0
and sigma = 1
):
NormalDist().inv_cdf(0.95)
# 1.6448536269514715
Depends on the information you need. For debugging the stack trace & inner exception are useful:
string message =
"Exception type " + ex.GetType() + Environment.NewLine +
"Exception message: " + ex.Message + Environment.NewLine +
"Stack trace: " + ex.StackTrace + Environment.NewLine;
if (ex.InnerException != null)
{
message += "---BEGIN InnerException--- " + Environment.NewLine +
"Exception type " + ex.InnerException.GetType() + Environment.NewLine +
"Exception message: " + ex.InnerException.Message + Environment.NewLine +
"Stack trace: " + ex.InnerException.StackTrace + Environment.NewLine +
"---END Inner Exception";
}
If you choose to use a generic collection, such as List<MyObject>
instead of ArrayList
, you'll find that the List<MyObject>
will provide both generic and non-generic enumerators that you can use.
using System.Collections;
class MyObjects : IEnumerable<MyObject>
{
List<MyObject> mylist = new List<MyObject>();
public MyObject this[int index]
{
get { return mylist[index]; }
set { mylist.Insert(index, value); }
}
public IEnumerator<MyObject> GetEnumerator()
{
return mylist.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
descending alphabet:
List<String> list;
...
Collections.sort(list);
Collections.reverse(list);
session_start();
echo session_id();
What worked for me
import databricks.koalas as ks
df1k = df1.to_koalas()
df2k = df2.to_koalas()
df3k = df1k.merge(df2k, on=['col1', 'col2'])
df3 = df3k.to_spark()
All of the columns except for col1 and col2 had "_x" appended to their names if they had come from df1 and "_y" appended if they had come from df2, which is exactly what I needed.
make sure columns are identical(of same type) and if reference column is not primary_key
, make sure it is INDEXED
.
time.second helps a lot put that at the top of your python.
temperature = input("What's the current temperature in your city? (please use the format ??C or ???F) >>> ")
### warning... the result from input will <str> on Python 3.x only
### in the case of Python 2.x, the result from input is the variable type <int>
### for the <str> type as the result for Python 2.x it's neccessary to use the another: raw_input()
temp_int = int(temperature[:-1]) # 25 <int> (as example)
temp_str = temperature[-1:] # "C" <str> (as example)
if temp_str.lower() == 'c':
print("Your temperature in Fahrenheit is: {}".format( (9/5 * temp_int) + 32 ) )
elif temp_str.lower() == 'f':
print("Your temperature in Celsius is: {}".format( ((5/9) * (temp_int - 32)) ) )
To receive a pure JSON string, without it being wrapped into an XML, you have to write the JSON string directly to the HttpResponse
and change the WebMethod
return type to void
.
[System.Web.Script.Services.ScriptService]
public class WebServiceClass : System.Web.Services.WebService {
[WebMethod]
public void WebMethodName()
{
HttpContext.Current.Response.Write("{property: value}");
}
}
In my case, it is a maven project, I Reimported maven (right click on pom.xml file and click Reimport) that's it worked immediately.
This answer is a much cleaner way to do it using new syntax.
Based on Glenn Howes' excellent answer, I created an extension to calculate the width of a string. If you're doing something like setting the width of a UISegmentedControl
, this can set the width based on the segment's title string.
extension String {
func widthOfString(usingFont font: UIFont) -> CGFloat {
let fontAttributes = [NSAttributedString.Key.font: font]
let size = self.size(withAttributes: fontAttributes)
return size.width
}
func heightOfString(usingFont font: UIFont) -> CGFloat {
let fontAttributes = [NSAttributedString.Key.font: font]
let size = self.size(withAttributes: fontAttributes)
return size.height
}
func sizeOfString(usingFont font: UIFont) -> CGSize {
let fontAttributes = [NSAttributedString.Key.font: font]
return self.size(withAttributes: fontAttributes)
}
}
usage:
// Set width of segmentedControl
let starString = "??"
let starWidth = starString.widthOfString(usingFont: UIFont.systemFont(ofSize: 14)) + 16
segmentedController.setWidth(starWidth, forSegmentAt: 3)
I was looking for a pure CSS solution using img
tags (not the background image way).
I found this brilliant way to achieve the goal on crop thumbnails with css:
.thumbnail {
position: relative;
width: 200px;
height: 200px;
overflow: hidden;
}
.thumbnail img {
position: absolute;
left: 50%;
top: 50%;
height: 100%;
width: auto;
-webkit-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
.thumbnail img.portrait {
width: 100%;
height: auto;
}
It is similar to @Nathan Redblur's answer but it allows for portrait images, too.
Works like a charm for me. The only thing you need to know about the image is whether it is portrait or landscape in order to set the .portrait
class so I had to use a bit of Javascript for this part.
<gradient android:startColor="#ffdd00"
android:endColor="@color/colorPrimary"
android:centerColor="#ffff" />
<corners android:radius="33dp"/>
<padding
android:bottom="7dp"
android:left="7dp"
android:right="7dp"
android:top="7dp"
/>
You need to leverage the @ViewChild
decorator to reference the child component from the parent one by injection:
import { Component, ViewChild } from 'angular2/core';
(...)
@Component({
selector: 'my-app',
template: `
<h1>My First Angular 2 App</h1>
<child></child>
<button (click)="submit()">Submit</button>
`,
directives:[App]
})
export class AppComponent {
@ViewChild(Child) child:Child;
(...)
someOtherMethod() {
this.searchBar.someMethod();
}
}
Here is the updated plunkr: http://plnkr.co/edit/mrVK2j3hJQ04n8vlXLXt?p=preview.
You can notice that the @Query
parameter decorator could also be used:
export class AppComponent {
constructor(@Query(Child) children:QueryList<Child>) {
this.childcmp = children.first();
}
(...)
}
I just tried this, and this could be a jQuery version-specific error, but
$("meta[property=twitter:image]").attr("content");
resulted in the following syntax error for me:
Error: Syntax error, unrecognized expression: meta[property=twitter:image]
Apparently it doesn't like the colon. I was able to fix it by using double and single quotes like this:
$("meta[property='twitter:image']").attr("content");
(jQuery version 1.8.3 -- sorry, I would have made this a comment to @Danilo, but it won't let me comment yet)
You could read the html file manually and then use loadData
or loadDataWithBaseUrl
methods of WebView to show it.
Unfortunately, this does not work on macOS. Despite the fact that I have export CONDA_DEFAULT_ENV='$HOME/anaconda3/envs/dev'
in my .zshrc and "python.pythonPath": "${env.CONDA_DEFAULT_ENV}/bin/python",
in my VSCode prefs, the built-in terminal does not use that environment's Python, even if I have started VSCode from the command line where that variable is set.
Unfortunately, no. In 2013, there is no way to do it with pure CSS.
Update: thanks to showdev for linking to the obsolete spec of CSS3 Hyperlinks, and yes, no browser has implemented it. So the answer still stands valid.
Maybe you installed python from source. In this case, you can recompile python with tcl/tk supported.
/home/xxx/local/tcl-tk/
.# install tcl
wget -c https://prdownloads.sourceforge.net/tcl/tcl8.6.9-src.tar.gz
tar -xvzf tcl8.6.9-src.tar.gz
cd tcl8.6.9
./configure --prefix=/home/xxx/local/tcl-tk/
make
make install
# install tk
wget -c https://prdownloads.sourceforge.net/tcl/tk8.6.9.1-src.tar.gz
tar -xvzf tk8.6.9.1-src.tar.gz
cd tk8.6.9.1
./configure --prefix=/home/xxx/local/tcl-tk/
make
make install
# download the source code of python and decompress it first.
cd <your-python-src-dir>
./configure --prefix=/home/xxx/local/python \
--with-tcltk-includes=/home/xxx/local/tcl-tk/include \
--with-tcltk-libs=/home/xxx/local/tcl-tk/lib
make
make install
I think the commands you are looking for are:
cd repo2
git checkout master
git remote add r1remote **url-of-repo1**
git fetch r1remote
git merge r1remote/master --allow-unrelated-histories
git remote rm r1remote
After that repo2/master
will contain everything from repo2/master
and repo1/master
, and will also have the history of both of them.
This limit is indeed not specified, however their TOS mentions that: "FOR EXAMPLE, WE DON’T MAKE ANY COMMITMENTS ABOUT THE CONTENT WITHIN THE SERVICES, THE SPECIFIC FUNCTIONS OF THE SERVICES, OR THEIR RELIABILITY, AVAILABILITY, OR ABILITY TO MEET YOUR NEEDS. WE PROVIDE THE SERVICES “AS IS”. "
This means to me that the download limit is calculated based on a set of factors that describe the user and is subject to change from one to another.
Maybe using the TOR network may help you do your job.
As everyone pointed out even though having multiple template directives in a single element works in angular 1.x it is not allowed in Angular 2. you can find more info from here : https://github.com/angular/angular/issues/7315
solution is to use the <template>
as a placeholder, so the code goes like this
<template *ngFor="let nav_link of defaultLinks" >
<li *ngIf="nav_link.visible">
.....
</li>
</template>
but for some reason above does not work in 2.0.0-rc.4
in that case you can use this
<template ngFor let-nav_link [ngForOf]="defaultLinks" >
<li *ngIf="nav_link.visible">
.....
</li>
</template>
With updates, right now in 2018 angular v6 recommend to use <ng-container>
instead of <template>
so here is the updated answer.
<ng-container *ngFor="let nav_link of defaultLinks" >
<li *ngIf="nav_link.visible">
.....
</li>
</ng-container>
You could do this: <a href="">This page</a>
but I don't think it preserves GET and POST data.
As you know the display
property cannot be animated BUT just by having it in your CSS it overrides the visibility
and opacity
transitions.
The solution...just removed the display
properties.
nav.main ul ul {_x000D_
position: absolute;_x000D_
list-style: none;_x000D_
opacity: 0;_x000D_
visibility: hidden;_x000D_
padding: 10px;_x000D_
background-color: rgba(92, 91, 87, 0.9);_x000D_
-webkit-transition: opacity 600ms, visibility 600ms;_x000D_
transition: opacity 600ms, visibility 600ms;_x000D_
}_x000D_
nav.main ul li:hover ul {_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
}
_x000D_
<nav class="main">_x000D_
<ul>_x000D_
<li>_x000D_
<a href="">Lorem</a>_x000D_
<ul>_x000D_
<li><a href="">Ipsum</a>_x000D_
</li>_x000D_
<li><a href="">Dolor</a>_x000D_
</li>_x000D_
<li><a href="">Sit</a>_x000D_
</li>_x000D_
<li><a href="">Amet</a>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</nav>
_x000D_
Above solution works best if multiple matching sub documents are required. $elemMatch also comes in very use if single matching sub document is required as output
db.test.find({list: {$elemMatch: {a: 1}}}, {'list.$': 1})
Result:
{
"_id": ObjectId("..."),
"list": [{a: 1}]
}
Another alternative to @TouchBoarder's answer above is that you may also have two layout files with the same name but for different api versions. You should delete the older my_file.xml file
my_file.xml
my_file.xml(v21)
You should use ContextWrapper like this:
ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("media", Context.MODE_PRIVATE);
As always, refer to documentation, ContextWrapper has a lot to offer.
Bear in mind that a standards-compliant XML processor will have replaced any entity references other than XML's five standard ones (&
, >
, <
, '
, "
) with the corresponding character in the target encoding by the time XPath expressions are evaluated. Given that behavior, PhiLho's and jsulak's suggestions are the way to go if you want to work with XML tools. When you enter  
in the XPath expression, it should be converted to the corresponding byte sequence before the XPath expression is applied.
var result = string.Join("", input.Select(c => ((int)c).ToString("X2")));
OR
var result =string.Join("",
input.Select(c=> String.Format("{0:X2}", Convert.ToInt32(c))));
If there is a good chance that the list will contain as much elements as it contains when clearing it, and if you're not in need for free memory, clearing the list is a better option. But my guess is that it probably doesn't matter. Don't try to optimize until you have detected a performance problem, and identified where it comes from.
I don't know what things were like in the alpha, but I'm using beta 12 right now and this works fine. If you have an array of objects, create a select like this:
<select [(ngModel)]="simpleValue"> // value is a string or number
<option *ngFor="let obj of objArray" [value]="obj.value">{{obj.name}}</option>
</select>
If you want to match on the actual object, I'd do it like this:
<select [(ngModel)]="objValue"> // value is an object
<option *ngFor="let obj of objArray" [ngValue]="obj">{{obj.name}}</option>
</select>
Here I present an alternative way to detect a browser, based on feature availability.
To detect only IE, you can use this:
if(/*@cc_on!@*/false || typeof ScriptEngineMajorVersion === "function")
{
//You are using IE>=4 (unreliable for IE11)
}
else
{
//You are using other browser
}
To detect the most popular browsers:
if(/*@cc_on!@*/false || typeof ScriptEngineMajorVersion === "function")
{
//You are using IE >= 4 (unreliable for IE11!!!)
}
else if(window.chrome)
{
//You are using Chrome or Chromium
}
else if(window.opera)
{
//You are using Opera >= 9.2
}
else if('MozBoxSizing' in document.body.style)
{
//You are using Firefox or Firefox based >= 3.2
}
else if({}.toString.call(window.HTMLElement).indexOf('Constructor')+1)
{
//You are using Safari >= 3.1
}
else
{
//Unknown
}
This answer was updated because IE11 no longer supports conditional compilation (the /*@cc_on!@*/false
trick).
You can check Did IE11 remove javascript conditional compilation? for more informations regarding this topic.
I've used the suggestion they presented there.
Alternatively, you can use typeof document.body.style.msTransform == "string"
or document.body.style.msTransform !== window.undefined
or even 'msTransform' in document.body.style
.
Both would return true on Unix systems - in Unix everything is a file, including directories. But to test if that name is taken, you should check both. There might be a regular file named 'foo', which would prevent you from creating a directory name 'foo'.
For intellij console the 0x08
character worked for me!
System.out.print((char) 8);
The flush()
method causes Hibernate to flush the session. You can configure Hibernate to use flushing mode for the session by using setFlushMode()
method. To get the flush mode for the current session, you can use getFlushMode()
method. To check, whether session is dirty, you can use isDirty()
method. By default, Hibernate manages flushing of the sessions.
As stated in the documentation:
https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/chapters/flushing/Flushing.html
Flushing
Flushing is the process of synchronizing the state of the persistence context with the underlying database. The
EntityManager
and the HibernateSession
expose a set of methods, through which the application developer can change the persistent state of an entity.The persistence context acts as a transactional write-behind cache, queuing any entity state change. Like any write-behind cache, changes are first applied in-memory and synchronized with the database during flush time. The flush operation takes every entity state change and translates it to an
INSERT
,UPDATE
orDELETE
statement.The flushing strategy is given by the flushMode of the current running Hibernate Session. Although JPA defines only two flushing strategies (
AUTO
andCOMMIT
), Hibernate has a much broader spectrum of flush types:
ALWAYS
: Flushes the Session before every query;AUTO
: This is the default mode and it flushes the Session only if necessary;COMMIT
: The Session tries to delay the flush until the current Transaction is committed, although it might flush prematurely too;MANUAL
: The Session flushing is delegated to the application, which must callSession.flush()
explicitly in order to apply the persistence context changes.By default, Hibernate uses the
AUTO
flush mode which triggers a flush in the following circumstances:
- prior to committing a Transaction;
- prior to executing a JPQL/HQL query that overlaps with the queued entity actions;
- before executing any native SQL query that has no registered synchronization.
You can use reflection to iterate over the object's field, and set them. You'd obviously need some sort of mapping between types or even field names and required default values but this can be done quite easily in a loop. For example:
for (Field f : obj.getClass().getFields()) {
f.setAccessible(true);
if (f.get(obj) == null) {
f.set(obj, getDefaultValueForType(f.getType()));
}
}
[Update]
With modern Java, you can use annotations to set the default values for fields on a per class basis. A complete implementation might look like this:
// DefaultString.java:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface DefaultString {
String value();
}
// DefaultInteger.java:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface DefaultInteger {
int value();
}
// DefaultPojo.java:
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
public class DefaultPojo {
public void setDefaults() {
for (Field f : getClass().getFields()) {
f.setAccessible(true);
try {
if (f.get(this) == null) {
f.set(this, getDefaultValueFromAnnotation(f.getAnnotations()));
}
} catch (IllegalAccessException e) { // shouldn't happen because I used setAccessible
}
}
}
private Object getDefaultValueFromAnnotation(Annotation[] annotations) {
for (Annotation a : annotations) {
if (a instanceof DefaultString)
return ((DefaultString)a).value();
if (a instanceof DefaultInteger)
return ((DefaultInteger)a).value();
}
return null;
}
}
// Test Pojo
public class TestPojo extends DefaultPojo {
@DefaultString("Hello world!")
public String stringValue;
@DefaultInteger(42);
public int integerValue;
}
Then default values for a TestPojo
can be set just by running test.setDetaults()
As none of the answers above are straight forward:
Backslash escape \ is what you need:
myscript \"test\"
Create a function to move it:
function move_file($file, $to){
$path_parts = pathinfo($file);
$newplace = "$to/{$path_parts['basename']}";
if(rename($file, $newplace))
return $newplace;
return null;
}
Tested in Android Studio 0.8.14:
I was able to get a standard project running with minimal steps in this way:
You can then add your code, and choose Build > Run 'YourClassName'. Presto, your code is running with no Android device!
as a single line:
long value_ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now()).time_since_epoch()).count();
Try this.
public enum Event {
FORGOT_PASSWORD("forgot password");
private final String value;
private Event(final String description) {
this.value = description;
}
private Event() {
this.value = this.name();
}
@JsonValue
final String value() {
return this.value;
}
}
Go to config/sessions.php
find the row
'secure' => env('SESSION_SECURE_COOKIE', true),
change it to false
'secure' => env('SESSION_SECURE_COOKIE', false),
If this parameter is set to TRUE browser will require you to use HTTPS protocol, otherwise it wont store the session. As it is not valid
Update - I verified the below works. Maybe the creation of your JArray isn't quite right.
[TestMethod]
public void TestJson()
{
var jsonString = @"{""trends"": [
{
""name"": ""Croke Park II"",
""url"": ""http://twitter.com/search?q=%22Croke+Park+II%22"",
""promoted_content"": null,
""query"": ""%22Croke+Park+II%22"",
""events"": null
},
{
""name"": ""Siptu"",
""url"": ""http://twitter.com/search?q=Siptu"",
""promoted_content"": null,
""query"": ""Siptu"",
""events"": null
},
{
""name"": ""#HNCJ"",
""url"": ""http://twitter.com/search?q=%23HNCJ"",
""promoted_content"": null,
""query"": ""%23HNCJ"",
""events"": null
},
{
""name"": ""Boston"",
""url"": ""http://twitter.com/search?q=Boston"",
""promoted_content"": null,
""query"": ""Boston"",
""events"": null
},
{
""name"": ""#prayforboston"",
""url"": ""http://twitter.com/search?q=%23prayforboston"",
""promoted_content"": null,
""query"": ""%23prayforboston"",
""events"": null
},
{
""name"": ""#TheMrsCarterShow"",
""url"": ""http://twitter.com/search?q=%23TheMrsCarterShow"",
""promoted_content"": null,
""query"": ""%23TheMrsCarterShow"",
""events"": null
},
{
""name"": ""#Raw"",
""url"": ""http://twitter.com/search?q=%23Raw"",
""promoted_content"": null,
""query"": ""%23Raw"",
""events"": null
},
{
""name"": ""Iran"",
""url"": ""http://twitter.com/search?q=Iran"",
""promoted_content"": null,
""query"": ""Iran"",
""events"": null
},
{
""name"": ""#gaa"",
""url"": ""http://twitter.com/search?q=%23gaa"",
""promoted_content"": null,
""query"": ""gaa"",
""events"": null
},
{
""name"": ""Facebook"",
""url"": ""http://twitter.com/search?q=Facebook"",
""promoted_content"": null,
""query"": ""Facebook"",
""events"": null
}]}";
var twitterObject = JToken.Parse(jsonString);
var trendsArray = twitterObject.Children<JProperty>().FirstOrDefault(x => x.Name == "trends").Value;
foreach (var item in trendsArray.Children())
{
var itemProperties = item.Children<JProperty>();
//you could do a foreach or a linq here depending on what you need to do exactly with the value
var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
var myElementValue = myElement.Value; ////This is a JValue type
}
}
So call Children on your JArray to get each JObject in JArray. Call Children on each JObject to access the objects properties.
foreach(var item in yourJArray.Children())
{
var itemProperties = item.Children<JProperty>();
//you could do a foreach or a linq here depending on what you need to do exactly with the value
var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
var myElementValue = myElement.Value; ////This is a JValue type
}
For Data access you can use OData. Here is a demo where Scott Hanselman creates an OData front end to StackOverflow database in 30 minutes, with XML and JSON access: Creating an OData API for StackOverflow including XML and JSON in 30 minutes.
For administrative access, like phpMyAdmin package, there is no well established one. You may give a try to IIS Database Manager.
Use
<a href="/fruits/index.html">Back to Fruits List</a>
or
<a href="../index.html">Back to Fruits List</a>
Declare this code in Android Manifest :
<meta-data android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_stat_name" />
I hope this useful to you.
For OGG on Windows: Theoraconverter
Use the Git GUI in the Git plugin.
Clone your online repository with the URL which you have.
After cloning, make changes to the files. When you make changes, you can see the number changes. Commit those changes.
Fetch from the remote (to check if anything is updated while you are working).
If the fetch operation gives you an update about the changes in the remote repository, make a pull operation which will update your copy in Visual Studio Code. Otherwise, do not make a pull operation if there aren't any changes in the remote repository.
Push your changes to the upstream remote repository by making a push operation.
Answering on a more general level for anyone who landed here as they are fixing problems in spacing caused by the <br>
tag. I have to do a lot of resets in order to get close to pixel perfect.
br {
content: " ";
display: block;
}
For the specific issue I was addressing I had to have a specific space between the lines. I added a margin to the top and bottom.
br {
content: " ";
display: block;
margin: 0.25em 0;
}
Try this workaround for the theming problem:
@Override
public void onBackPressed() {
NavUtils.navigateUpTo(this, new Intent(this,
MyNeedToBeRefreshed.class));
}
solution is easy:
replace
mask = (50 < df['heart rate'] < 101 &
140 < df['systolic blood pressure'] < 160 &
90 < df['dyastolic blood pressure'] < 100 &
35 < df['temperature'] < 39 &
11 < df['respiratory rate'] < 19 &
95 < df['pulse oximetry'] < 100
, "excellent", "critical")
by
mask = ((50 < df['heart rate'] < 101) &
(140 < df['systolic blood pressure'] < 160) &
(90 < df['dyastolic blood pressure'] < 100) &
(35 < df['temperature'] < 39) &
(11 < df['respiratory rate'] < 19) &
(95 < df['pulse oximetry'] < 100)
, "excellent", "critical")
The one-liner version in Python:
$ python -c "import sys; print(sum(int(l) for l in sys.stdin))"
Try this:
if (items.elementAt(1) instanceof Double) {
sum.add( i, items.elementAt(1));
}
You would generally test these sorts of things in an integration test, which actually connects to a service. To do a unit test, you should test the objects used by your servlet's doGet/doPost methods.
In general you don't want to have much code in your servlet methods, you would want to create a bean class to handle operations and pass your own objects to it and not servlet API objects.
SELECT account_id, open_emp_id
^^^^ ^^^^
1 2
FROM account
GROUP BY 1;
In above query GROUP BY 1
refers to the first column in select statement
which is
account_id
.
You also can specify in ORDER BY
.
Note : The number in ORDER BY and GROUP BY always start with 1 not with 0.
split with the + sign like this way
String a = tv.getText().toString();
String aa[];
if(a.contains("+"))
aa = a.split("+");
now convert the array
Integer.parseInt(aa[0]); // and so on
If you are like me, and manually installed your webserver without using Xampp or some other installer,
Your data is probably stored at C:\ProgramData\MySQL\MySQL Server 5.6\data
Try linux command chsh
.
The detailed command is chsh -s /bin/bash
.
It will prompt you to enter your password.
Your default login shell is /bin/bash
now. You must log out and log back in to see this change.
The following is quoted from man page:
The chsh command changes the user login shell. This determines the name of the users initial login command. A normal user may only change the login shell for her own account, the superuser may change the login shell for any account
This command will change the default login shell permanently.
Note: If your user account is remote such as on Kerberos authentication (e.g. Enterprise RHEL) then you will not be able to use chsh
.
<head>
<title>Test</title>
</head>
<body>
<h1>Hi there<span id="username"></span>!</h1>
<script>
let userName = prompt("What is your name?");
document.getElementById('username').innerHTML = userName;
</script>
</body>
If you came here from Google
Alternative answer to an older question refers to John Skeet's Library that has tools for letting you write primitive data types directly into a byte[] with an Index offset. Far better than BitConverter
if you need performance.
Older thread discussing this issue here
John Skeet's Libraries are here
Just download the source and look at the MiscUtil.Conversion
namespace. EndianBitConverter.cs
handles everything for you.
If you're really have time and money:
One way of doing it is by 1) Writing an image detection algorithm to find whether an object is human or not. This can be done by bitmasking an image to retrieve it's "contours" and see if the contours fits a human contour.
2) Data mine a lot of porn images and use data mining techniques such as the C4 algorithms or Particle Swarm Optimization to learn to detect pattern that matches porn images.
This will require that you identify how a naked man/woman contours of a human body must look like in digitized format (this can be achieved in the same way OCR image recognition algorithms works).
Hope you have fun! :-)
webRequest.ContentType = "application/x-www-form-urlencoded";
Where does application/x-www-form-urlencoded's name come from?
If you send HTTP GET request, you can use query parameters as follows:
http://example.com/path/to/page
?name=ferret&color=purple
The content of the fields is encoded as a query string. The application/x-www-form-
urlencoded
's name come from the previous url query parameter but the query parameters is
in where the body of request instead of url.
The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character
e.g. field1=value1&field2=value2
It can be simple request called simple - don't trigger a preflight check
Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests
3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.
request.ContentType = "application/json; charset=utf-8";
axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.
{ "id": 1, "name": "Foo", "price": 123, "tags": [ "Bar", "Eek" ], "stock": { "warehouse": 300, "retail": 20 } }
Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.
I know this is an older post, but I found what worked for me to fix this error was using the IP address of my server instead of using the domain name within my fetch request. So for example:
#(original) var request = new Request('https://davidwalsh.name/demo/arsenal.json');
#use IP instead
var request = new Request('https://0.0.0.0/demo/arsenal.json');
fetch(request).then(function(response) {
// Convert to JSON
return response.json();
}).then(function(j) {
// Yay, `j` is a JavaScript object
console.log(JSON.stringify(j));
}).catch(function(error) {
console.log('Request failed', error)
});
You need to place ScrollView as the first child of Layout file and now put your linearlayout inside it. Now, android will decide on the basis of content and device size available whether to show a scrollable or not.
Make sure linearlayout has no sibling because ScrollView can not have more than one child.
x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty).Where(l => l.Internal NAme != String.Empty)
or
x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty && l.Internal NAme != String.Empty)
If you take a look at the MSIL as it's being executed you'll see that it doesn't compile down to the exact same code. When you use IsNothing() it actually makes a call to that method as opposed to just evaluating the expression.
The reason I would tend to lean towards using "Is Nothing" is when I'm negating it becomes "IsNot Nothing' rather than "Not IsNothing(object)" which I personally feel looks more readable.
The correct answer to this question has been changed by the publication of RFC 8314. As a result, port 465 and 587 are both valid ports for a mail submission agent (MSA). Port 465 requires negotiation of TLS/SSL at connection setup and port 587 uses STARTTLS if one chooses to negotiate TLS. The IANA registry was updated to allow legitimate use of port 465 for this purpose. For mail relay, only port 25 is used so STARTTLS is the only way to do TLS with mail relay. It's helpful to think of mail relay and mail submission as two very different services (with many behavior differences like requiring auth, different timeouts, different message modification rules, etc.) that happen to use a similar wire protocol.
For those of us who this above valid solution didnt work, there's another workaround here
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean isFocused) {
if(!isFocused)
{
Toast.makeText(MainActivity.this,"not focused",Toast.LENGTH_SHORT).show();
}
}
});
If you want to remove spaces at the beginning/end of a line too(common when shortening html) you can try:
string.Join("",input.Split('\n','\r').Select(s=>s.Trim()))
Else use the simple Replace
Marc suggested.
The basic difference between all these annotations is as follows -
All these annotations along with the usage is defined on Codingeek - Junit5 Test Lifecycle
My 2 cents (more generic):
import csv, sqlite3
import logging
def _get_col_datatypes(fin):
dr = csv.DictReader(fin) # comma is default delimiter
fieldTypes = {}
for entry in dr:
feildslLeft = [f for f in dr.fieldnames if f not in fieldTypes.keys()]
if not feildslLeft: break # We're done
for field in feildslLeft:
data = entry[field]
# Need data to decide
if len(data) == 0:
continue
if data.isdigit():
fieldTypes[field] = "INTEGER"
else:
fieldTypes[field] = "TEXT"
# TODO: Currently there's no support for DATE in sqllite
if len(feildslLeft) > 0:
raise Exception("Failed to find all the columns data types - Maybe some are empty?")
return fieldTypes
def escapingGenerator(f):
for line in f:
yield line.encode("ascii", "xmlcharrefreplace").decode("ascii")
def csvToDb(csvFile, outputToFile = False):
# TODO: implement output to file
with open(csvFile,mode='r', encoding="ISO-8859-1") as fin:
dt = _get_col_datatypes(fin)
fin.seek(0)
reader = csv.DictReader(fin)
# Keep the order of the columns name just as in the CSV
fields = reader.fieldnames
cols = []
# Set field and type
for f in fields:
cols.append("%s %s" % (f, dt[f]))
# Generate create table statement:
stmt = "CREATE TABLE ads (%s)" % ",".join(cols)
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute(stmt)
fin.seek(0)
reader = csv.reader(escapingGenerator(fin))
# Generate insert statement:
stmt = "INSERT INTO ads VALUES(%s);" % ','.join('?' * len(cols))
cur.executemany(stmt, reader)
con.commit()
return con
As @alex said, you could float it right, but if you wanted to keep the markup the same, float it to the left!
#ul_top_hypers li {
float: left;
}
For windows users:
To download into a file open your cmd and folow this:
cd <*the file-path where you want to save it*>
pip download <*package name*>
the package and the dependencies will be downloaded in the current working directory.
To install from the current working directory:
set your folder where you downloaded as the cwd then follow these:
pip install <*the package name which is downloded as .whl*> --no-index --find-links <*the file locaation where the files are downloaded*>
this will search for dependencies in that location.
In C, character constant expressions such as '\n'
or 'a'
have type int
(thus sizeof '\n' == sizeof (int)
), whereas in C++ they have type char
.
The statement printf("%d", '\0');
should simply print 0; the type of the expression '\0'
is int
, and its value is 0.
The statement printf("%d", ch);
should print the integer encoding for the value in ch
(for ASCII, 'a'
== 97).
This allows you to type on every line simultaneously.
I found the solution above here.
I think this is much easier than using regex.
You want to use the stringizing operator:
#define STRING(s) #s
int main()
{
const char * cstr = STRING(abc); //cstr == "abc"
}
You can try:
df[0] = df[0].str.strip()
or more specifically for all string columns
non_numeric_columns = list(set(df.columns)-set(df._get_numeric_data().columns))
df[non_numeric_columns] = df[non_numeric_columns].apply(lambda x : str(x).strip())
The problem with your code is :
String show[]= {rs4.getString(1)};
String actuate[]={rs4.getString(2)};
This will create a new array every time your loop (an not append as you might be assuming) and hence in the end you will have only one element per array.
Here is one more way to solve this :
StringBuilder sids = new StringBuilder ();
StringBuilder lids = new StringBuilder ();
while (rs4.next()) {
sids.append(rs4.getString(1)).append(" ");
lids.append(rs4.getString(2)).append(" ");
}
String show[] = sids.toString().split(" ");
String actuate[] = lids.toString().split(" ");
These arrays will have all the required element.
Also check to see if you are missing the www in the url which was on my case
i was testing on http://www.mywebsite.com and in the facebook app i had set http://mywebsite.com
I would expect that on most compilers and target platforms, there will be cases where "if" is faster and cases where ?: is faster. There will also be cases where one form is more or less compact than the other. Which cases favor one form or the other will vary between compilers and platforms. If you're writing performance-critical code on an embedded micro, look at what the compiler is generating in each case and see which is better. On a "mainstream" PC, because of caching issues, the only way to see which is better is to benchmark both forms in something resembling the real application.
Just repair Visual Studio itself from the control panel and that should do the trick!
The former is more Pythonic (better ideomatic code), but will not execute the block if A is False (not None).
user@host> g++ hw.cpp
user@host> ./a.out
In legacy projects, I need to create native Java code. I create this code similar to Paulitex code. See that:
public class FileHelper {
public static boolean delete(File fileOrFolder) {
boolean result = true;
if(fileOrFolder.isDirectory()) {
for (File file : fileOrFolder.listFiles()) {
result = result && delete(file);
}
}
result = result && fileOrFolder.delete();
return result;
}
}
And the unit test:
public class FileHelperTest {
@Before
public void setup() throws IOException {
new File("FOLDER_TO_DELETE/SUBFOLDER").mkdirs();
new File("FOLDER_TO_DELETE/SUBFOLDER_TWO").mkdirs();
new File("FOLDER_TO_DELETE/SUBFOLDER_TWO/TEST_FILE.txt").createNewFile();
}
@Test
public void deleteFolderWithFiles() {
File folderToDelete = new File("FOLDER_TO_DELETE");
Assert.assertTrue(FileHelper.delete(folderToDelete));
Assert.assertFalse(new File("FOLDER_TO_DELETE").exists());
}
}
The following will return you the "a" letter:
$a = array_shift(explode('.', 'a.b'));
You can hack the useMemo hook to imitate a componentWillMount lifecycle event. Just do:
const Component = () => {
useMemo(() => {
// componentWillMount events
},[]);
useEffect(() => {
// componentDidMount events
return () => {
// componentWillUnmount events
}
}, []);
};
You would need to keep the useMemo hook before anything that interacts with your state. This is not how it is intended but it worked for me for all componentWillMount issues.
This works because useMemo doesnt require to actually return a value and you dont have to actually use it as anything, but since it memorizes a value based on dependencies which will only run once ("[]") and its on top of our component it runs once when the component mounts before anything else.
First set the opacity explicitly in your HTML thus:
<div id="box" style="height:150px; width:150px; background-color:orange; margin:25px; opacity:1"></div>
otherwise it is 0 or null
this is then in my .js file
document.getElementById("fadeButton90").addEventListener("click", function(){
document.getElementById("box").style.opacity = document.getElementById("box").style.opacity*0.90; });
Use the basename
command:
basename /home/user/new/*.txt
Updated Answer:
DynamoDB allows for specification of secondary indexes to aid in this sort of query. Secondary indexes can either be global, meaning that the index spans the whole table across hash keys, or local meaning that the index would exist within each hash key partition, thus requiring the hash key to also be specified when making the query.
For the use case in this question, you would want to use a global secondary index on the "CreatedAt" field.
For more on DynamoDB secondary indexes see the secondary index documentation
Original Answer:
DynamoDB does not allow indexed lookups on the range key only. The hash key is required such that the service knows which partition to look in to find the data.
You can of course perform a scan operation to filter by the date value, however this would require a full table scan, so it is not ideal.
If you need to perform an indexed lookup of records by time across multiple primary keys, DynamoDB might not be the ideal service for you to use, or you might need to utilize a separate table (either in DynamoDB or a relational store) to store item metadata that you can perform an indexed lookup against.
I would like to show you the way I access IISExpress Web APIs from my Android Emulator. I'm using Visual Studio 2015. And I call the Android Emulator from Android Studio.
All of what I need to do is adding the following line to the binding configuration in my applicationhost.config file
<binding protocol="http" bindingInformation="*:<your-port>:" />
Then I check and use the IP4 Address to access my API from Android emulator
Requirement: you must run Visual Studio as Administrator. This post gives a perfect way to do this.
For more details, please visit my post on github
Hope this helps.
Where supported, you can use the ::input-placeholder
pseudoselector combined with ::before
.
See an example at:
http://codepen.io/JonFabritius/pen/nHeJg
I was just working on this and came across this article, from which I modified this stuff:
imageView.setLayoutParams
(new ViewGroup.MarginLayoutParams
(width, ViewGroup.LayoutParams.MATCH_PARENT));
The Type of layout params depends on the parent view group. If you put the wrong one it will cause exception.
Heres the method I used in my logging library: https://github.com/goktugyil/QorumLogs
This method fills html forms inside Google Forms.
var url = NSURL(string: urlstring)
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding)
var connection = NSURLConnection(request: request, delegate: nil, startImmediately: true)
Use ..
to indicate the parent directory:
background-image: url('../images/bg.png');
You can use the desc
command.
desc MY_TABLE
This will give you the column names, whether null is valid, and the datatype (and length if applicable)
Later versions of dataTables
have the following language
settings (taken from here):
"infoEmpty"
- displayed when there are no records in the table"zeroRecords"
- displayed when there no records matching the filteringe.g.
$('#example').DataTable( {
"language": {
"infoEmpty": "No records available - Got it?",
}
});
Note: As the property names do not contain any special characters you can remove the quotes:
$('#example').DataTable( {
language: {
infoEmpty: "No records available - Got it?",
}
});
We've solved this, although we didn't think having the addListener outside of the for would make any difference, it seems to. Here's the answer:
Create a new function with your information for the infoWindow in it:
function addInfoWindow(marker, message) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
Then call the function with the array ID and the marker you want to create:
addInfoWindow(marker, hotels[i][3]);
Perhaps using SIMILAR TO
would work ?
SELECT * from table WHERE column SIMILAR TO '(AAA|BBB|CCC)%';
UPD. The answer and demo are updated to align with latest Angular.
You can subscribe to entire form changes due to the fact that FormGroup representing a form provides valueChanges
property which is an Observerable instance:
this.form.valueChanges.subscribe(data => console.log('Form changes', data));
In this case you would need to construct form manually using FormBuilder. Something like this:
export class App {
constructor(private formBuilder: FormBuilder) {
this.form = formBuilder.group({
firstName: 'Thomas',
lastName: 'Mann'
})
this.form.valueChanges.subscribe(data => {
console.log('Form changes', data)
this.output = data
})
}
}
Check out valueChanges
in action in this demo: http://plnkr.co/edit/xOz5xaQyMlRzSrgtt7Wn?p=preview
The blocksize is usually selected to maximize the "occupancy". Search on CUDA Occupancy for more information. In particular, see the CUDA Occupancy Calculator spreadsheet.
If the return value is string and you need to search by Id you can use:
string name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name")).ToString();
or using generic variable:
var name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name"));
http://jsfiddle.net/isherwood/gfgux
html, body {
height: 100%;
}
#table-row, #table-col, #table-wrapper {
height: 80%;
}
<div id="content" class="container">
<div id="table-row" class="row">
<div id="table-col" class="col-md-7 col-xs-10 pull-left">
<p>Hello</p>
<div id="table-wrapper" class="table-responsive">
<table class="table table-bordered ">
What is the style item to make it disappear?
In order to remove the shadow add this to your app theme:
<style name="MyAppTheme" parent="android:Theme.Holo.Light">
<item name="android:windowContentOverlay">@null</item>
</style>
UPDATE:
As @Quinny898 stated, on Android 5.0 this has changed, you have to call setElevation(0)
on your action bar. Note that if you're using the support library you must call it to that like so:
getSupportActionBar().setElevation(0);
Another alternative to use the exact json within javascript. As it is Javascript Object Notation you can just create your object directly with the json notation. If you store this in a .js file you can use the object in your application. This was a useful option for me when I had some static json data that I wanted to cache in a file separately from the rest of my app.
//Just hard code json directly within JS
//here I create an object CLC that represents the json!
$scope.CLC = {
"ContentLayouts": [
{
"ContentLayoutID": 1,
"ContentLayoutTitle": "Right",
"ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/right.png",
"ContentLayoutIndex": 0,
"IsDefault": true
},
{
"ContentLayoutID": 2,
"ContentLayoutTitle": "Bottom",
"ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/bottom.png",
"ContentLayoutIndex": 1,
"IsDefault": false
},
{
"ContentLayoutID": 3,
"ContentLayoutTitle": "Top",
"ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/top.png",
"ContentLayoutIndex": 2,
"IsDefault": false
}
]
};
Well in order to understand how static and dynamic binding actually works? or how they are identified by compiler and JVM?
Let's take below example where Mammal
is a parent class which has a method speak()
and Human
class extends Mammal
, overrides the speak()
method and then again overloads it with speak(String language)
.
public class OverridingInternalExample {
private static class Mammal {
public void speak() { System.out.println("ohlllalalalalalaoaoaoa"); }
}
private static class Human extends Mammal {
@Override
public void speak() { System.out.println("Hello"); }
// Valid overload of speak
public void speak(String language) {
if (language.equals("Hindi")) System.out.println("Namaste");
else System.out.println("Hello");
}
@Override
public String toString() { return "Human Class"; }
}
// Code below contains the output and bytecode of the method calls
public static void main(String[] args) {
Mammal anyMammal = new Mammal();
anyMammal.speak(); // Output - ohlllalalalalalaoaoaoa
// 10: invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V
Mammal humanMammal = new Human();
humanMammal.speak(); // Output - Hello
// 23: invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V
Human human = new Human();
human.speak(); // Output - Hello
// 36: invokevirtual #7 // Method org/programming/mitra/exercises/OverridingInternalExample$Human.speak:()V
human.speak("Hindi"); // Output - Namaste
// 42: invokevirtual #9 // Method org/programming/mitra/exercises/OverridingInternalExample$Human.speak:(Ljava/lang/String;)V
}
}
When we compile the above code and try to look at the bytecode using javap -verbose OverridingInternalExample
, we can see that compiler generates a constant table where it assigns integer codes to every method call and byte code for the program which I have extracted and included in the program itself (see the comments below every method call)
By looking at above code we can see that the bytecodes of humanMammal.speak()
, human.speak()
and human.speak("Hindi")
are totally different (invokevirtual #4
, invokevirtual #7
, invokevirtual #9
) because the compiler is able to differentiate between them based on the argument list and class reference. Because all of this get resolved at compile time statically that is why Method Overloading is known as Static Polymorphism or Static Binding.
But bytecode for anyMammal.speak()
and humanMammal.speak()
is same (invokevirtual #4
) because according to compiler both methods are called on Mammal
reference.
So now the question comes if both method calls have same bytecode then how does JVM know which method to call?
Well, the answer is hidden in the bytecode itself and it is invokevirtual
instruction set. JVM uses the invokevirtual
instruction to invoke Java equivalent of the C++ virtual methods. In C++ if we want to override one method in another class we need to declare it as virtual, But in Java, all methods are virtual by default because we can override every method in the child class (except private, final and static methods).
In Java, every reference variable holds two hidden pointers
So all object references indirectly hold a reference to a table which holds all the method references of that object. Java has borrowed this concept from C++ and this table is known as virtual table (vtable).
A vtable is an array like structure which holds virtual method names and their references on array indices. JVM creates only one vtable per class when it loads the class into memory.
So whenever JVM encounter with a invokevirtual
instruction set, it checks the vtable of that class for the method reference and invokes the specific method which in our case is the method from a object not the reference.
Because all of this get resolved at runtime only and at runtime JVM gets to know which method to invoke, that is why Method Overriding is known as Dynamic Polymorphism or simply Polymorphism or Dynamic Binding.
You can read it more details on my article How Does JVM Handle Method Overloading and Overriding Internally.
parseInt is faster then Math.floor
function floorFigure(figure, decimals){
if (!decimals) decimals = 2;
var d = Math.pow(10,decimals);
return (parseInt(figure*d)/d).toFixed(decimals);
};
floorFigure(123.5999) => "123.59"
floorFigure(123.5999, 3) => "123.599"
GAC (Global Assembly Cache) is where all shared .NET assembly reside.
export function isObjectEmpty(obj) {
return (
Object.keys(obj).length === 0 &&
Object.getOwnPropertySymbols(obj).length === 0 &&
obj.constructor === Object
);
}
This include checking for objects containing symbol properties.
Object.keys does not retrieve symbol properties.
pxpgraphics's answer for Swift 3.0.
import Foundation
import UIKit
extension UINavigationBar {
func hideBottomHairline() {
let navigationBarImageView = hairlineImageViewInNavigationBar(view: self)
navigationBarImageView!.isHidden = true
}
func showBottomHairline() {
let navigationBarImageView = hairlineImageViewInNavigationBar(view: self)
navigationBarImageView!.isHidden = false
}
private func hairlineImageViewInNavigationBar(view: UIView) -> UIImageView? {
if view is UIImageView && view.bounds.height <= 1.0 {
return (view as! UIImageView)
}
let subviews = (view.subviews as [UIView])
for subview: UIView in subviews {
if let imageView: UIImageView = hairlineImageViewInNavigationBar(view: subview) {
return imageView
}
}
return nil
}
}
extension UIToolbar {
func hideHairline() {
let navigationBarImageView = hairlineImageViewInToolbar(view: self)
navigationBarImageView!.isHidden = true
}
func showHairline() {
let navigationBarImageView = hairlineImageViewInToolbar(view: self)
navigationBarImageView!.isHidden = false
}
private func hairlineImageViewInToolbar(view: UIView) -> UIImageView? {
if view is UIImageView && view.bounds.height <= 1.0 {
return (view as! UIImageView)
}
let subviews = (view.subviews as [UIView])
for subview: UIView in subviews {
if let imageView: UIImageView = hairlineImageViewInToolbar(view: subview) {
return imageView
}
}
return nil
}
}
If you want to clean the whole database, you can use: python manage.py flush If you want to clean database table of a Django app, you can use: python manage.py migrate appname zero
Just to add to the existing answers, when you are creating views you must separate these commands into batches using go
, otherwise you will get the error 'CREATE VIEW' must be the only statement in the batch
. So, for example, you won't be able to execute the following sql script without go
create view MyView1 as
select Id,Name from table1
go
create view MyView2 as
select Id,Name from table1
go
select * from MyView1
select * from MyView2
You could use the substr
function please check following example,
$string1 = "tarunmodi";
$first4 = substr($string1, 4);
echo $first4;
Output: nmodi
$HOME/.gitconfig
is your global config for git.
There are three levels of config files.
cat $(git rev-parse --show-toplevel)/.git/config
(mentioned by bereal) is your local config, local to the repo you have cloned.
you can also type from within your repo:
git remote -v
And see if there is any remote named 'origin' listed in it.
If not, if that remote (which is created by default when cloning a repo) is missing, you can add it again:
git remote add origin url/to/your/fork
The OP mentions:
Doing
git remote -v
gives:
upstream git://git.moodle.org/moodle.git (fetch)
upstream git://git.moodle.org/moodle.git (push)
So 'origin
' is missing: the reference to your fork.
See "What is the difference between origin
and upstream
in github"
Without changing any of the configuration files..
secure_file_priv
using the command posted by @vhu: SHOW VARIABLES LIKE "secure_file_priv"
.select * from table into outfile 'secure_file_priv_PATH/OUTPUT-FILE' ... rest of your query
this worked for my in mysql-shell on ubuntu 18.04 LTS mysql 5.7.29
You can use the Entry<U,V>
class that HashMap
uses but you'll be stuck with its semantics of getKey
and getValue
:
List<Entry<Float,Short>> pairList = //...
My preference would be to create your own simple Pair
class:
public class Pair<L,R> {
private L l;
private R r;
public Pair(L l, R r){
this.l = l;
this.r = r;
}
public L getL(){ return l; }
public R getR(){ return r; }
public void setL(L l){ this.l = l; }
public void setR(R r){ this.r = r; }
}
Then of course make a List
using this new class, e.g.:
List<Pair<Float,Short>> pairList = new ArrayList<Pair<Float,Short>>();
You can also always make a List
s of List
s, but it becomes difficult to enforce sizing (that you have only pairs) and you would be required, as with arrays, to have consistent typing.
If you want to find dependencies recursively (including dependencies of dependencies, dependencies of dependencies of dependencies and so on)…
You may use ldd
command.
ldd - print shared library dependencies
why is my java logging not working
provides a jar file that will help you work out why your logging in not working as expected. It gives you a complete dump of what loggers and handlers have been installed and what levels are set and at which level in the logging hierarchy.
You were close. The key is to have the hidden layout inflate to match_parent
in both height and weight. Simply start it off as View.GONE
. This way, using the percentage in the animators works properly.
Layout (activity_main.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_screen"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="@string/hello_world" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/hello_world" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:onClick="slideUpDown"
android:text="Slide up / down" />
<RelativeLayout
android:id="@+id/hidden_panel"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:visibility="gone" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:layout_centerInParent="true"
android:onClick="slideUpDown" />
</RelativeLayout>
</RelativeLayout>
Activity (MainActivity.java):
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
public class OffscreenActivity extends Activity {
private View hiddenPanel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
hiddenPanel = findViewById(R.id.hidden_panel);
}
public void slideUpDown(final View view) {
if (!isPanelShown()) {
// Show the panel
Animation bottomUp = AnimationUtils.loadAnimation(this,
R.anim.bottom_up);
hiddenPanel.startAnimation(bottomUp);
hiddenPanel.setVisibility(View.VISIBLE);
}
else {
// Hide the Panel
Animation bottomDown = AnimationUtils.loadAnimation(this,
R.anim.bottom_down);
hiddenPanel.startAnimation(bottomDown);
hiddenPanel.setVisibility(View.GONE);
}
}
private boolean isPanelShown() {
return hiddenPanel.getVisibility() == View.VISIBLE;
}
}
Only other thing I changed was in bottom_up.xml
. Instead of
android:fromYDelta="75%p"
I used:
android:fromYDelta="100%p"
But that's a matter of preference, I suppose.
Simple! The folder named ..
is the parent folder, so you can make the path to the file you need as such
var foobar = require('../config/dev/foobar.json');
If you needed to go up two levels, you would write ../../
etc
Some more details about this in this SO answer and it's comments
For a list of full path names I prefer this version to the other solutions here:
def listdirs(dir):
return [os.path.join(os.path.join(dir, x)) for x in os.listdir(dir)
if os.path.isdir(os.path.join(dir, x))]
I have a function next()
which will maybe inspire you.
function queue(target) {
var array = Array.prototype;
var queueing = [];
target.queue = queue;
target.queued = queued;
return target;
function queued(action) {
return function () {
var self = this;
var args = arguments;
queue(function (next) {
action.apply(self, array.concat.apply(next, args));
});
};
}
function queue(action) {
if (!action) {
return;
}
queueing.push(action);
if (queueing.length === 1) {
next();
}
}
function next() {
queueing[0](function (err) {
if (err) {
throw err;
}
queueing = queueing.slice(1);
if (queueing.length) {
next();
}
});
}
}
If you think all those prototype definitions, array creations, and join operations are overkill, just use a single line code where you need it. String S repeating N times:
for (var i = 0, result = ''; i < N; i++) result += S;
For php 7.1
sudo apt-get install php7.1-mbstring
Cheers!
I was recently shown this website for liquid layouts using CSS. http://matthewjamestaylor.com/blog/perfect-multi-column-liquid-layouts (Take a look at the demo pages in the links below).
The author now provides an example for fixed width layouts. Check out; http://matthewjamestaylor.com/blog/how-to-convert-a-liquid-layout-to-fixed-width.
This provides the following example(s), http://matthewjamestaylor.com/blog/ultimate-2-column-left-menu-pixels.htm (for two column layout like you are after I think)
http://matthewjamestaylor.com/blog/fixed-width-or-liquid-layout.htm (for three column layout).
Sorry for so many links to this guys site, but I think it is an AWESOME resource.
Gantt chart is wrong... First process P3 has arrived so it will execute first. Since the burst time of P3 is 3sec after the completion of P3, processes P2,P4, and P5 has been arrived. Among P2,P4, and P5 the shortest burst time is 1sec for P2, so P2 will execute next. Then P4 and P5. At last P1 will be executed.
Gantt chart for this ques will be:
| P3 | P2 | P4 | P5 | P1 |
1 4 5 7 11 14
Average waiting time=(0+2+2+3+3)/5=2
Average Turnaround time=(3+3+4+7+6)/5=4.6
Assume s = socket.socket() The server can be bound by following methods: Method 1:
host = socket.gethostname()
s.bind((host, port))
Method 2:
host = socket.gethostbyname("localhost") #Note the extra letters "by"
s.bind((host, port))
Method 3:
host = socket.gethostbyname("192.168.1.48")
s.bind((host, port))
If you do not exactly use same method on the client side, you will get the error: socket.error errno 111 connection refused.
So, you have to use on the client side exactly same method to get the host, as you do on the server. For example, in case of client, you will correspondingly use following methods:
Method 1:
host = socket.gethostname()
s.connect((host, port))
Method 2:
host = socket.gethostbyname("localhost") # Get local machine name
s.connect((host, port))
Method 3:
host = socket.gethostbyname("192.168.1.48") # Get local machine name
s.connect((host, port))
Hope that resolves the problem.
Something like:
>>> bytes.fromhex('4a4b4c').decode('utf-8')
'JKL'
Just put the actual encoding you are using.
Make sure your /etc/apt/sources.list has http://old-releases.ubuntu.com instead of in.archive
This might not exactly you want but I've used jquery smartmenu(https://github.com/vadikom/smartmenus) to build a ng2 dropdown menu.
$('#main-menu').smartmenus();
http://plnkr.co/edit/wLqLUoBQYgcDwOgSoRfF?p=preview https://github.com/Longfld/DynamicaLoadMultiLevelDropDownMenu
To delete a single element, you could do:
std::vector<int> vec;
vec.push_back(6);
vec.push_back(-17);
vec.push_back(12);
// Deletes the second element (vec[1])
vec.erase(vec.begin() + 1);
Or, to delete more than one element at once:
// Deletes the second through third elements (vec[1], vec[2])
vec.erase(vec.begin() + 1, vec.begin() + 3);
Neither is "more correct". My personal preference is for the more concise form but either is fine. To me, life is too short to even think about arguing the toss over stuff like this.
The second line is transformed to the following code:
s = (new StringBuilder()).append((String)null).append("hello").toString();
The append methods can handle null
arguments.
The equality test, for example, in a case statement when clause, can be changed from
XYZ = NULL
to
XYZ IS NULL
If I want to treat blanks and empty string as equal to NULL I often also use an equality test like:
(NULLIF(ltrim( XYZ ),'') IS NULL)
From a little reading, it appears that under the hood the String.Contains method simply calls String.IndexOf. The difference is String.Contains returns a boolean while String.IndexOf returns an integer with (-1) representing that the substring was not found.
I would suggest writing a little test with 100,000 or so iterations and see for yourself. If I were to guess, I'd say that IndexOf may be slightly faster but like I said it just a guess.
Jeff Atwood has a good article on strings at his blog. It's more about concatenation but may be helpful nonetheless.