This is slightly modified version of Mark Ransom's answer that works if ch
could be more than one character in length.
def find(term, ch):
"""Find all places with ch in str
"""
for i in range(len(term)):
if term[i:i + len(ch)] == ch:
yield i
Google threw out this page to the "image fallback html" keywords, but because non of the above helped me, and I was looking for a "svg fallback support for IE below 9", I kept on searching and this is what I found:
<img src="base-image.svg" alt="picture" />
<!--[if (lte IE 8)|(!IE)]><image src="fallback-image.png" alt="picture" /><![endif]-->
It might be off-topic, but it resolved my own issue and it might help someone else too.
Try:
String newValue = String.format("%d", (int)d);
There is already an extension to do this.
namespace System.Reflection
{
// Summary:
// Contains static methods for retrieving custom attributes.
public static class CustomAttributeExtensions
{
public static T GetCustomAttribute<T>(this MemberInfo element, bool inherit) where T : Attribute;
}
}
So:
var attr = typeof(MyClass).GetCustomAttribute<DomainNameAttribute>(false);
return attr != null ? attr.DomainName : "";
The nature of arrays is that their length is immutable. You can't add or delete any of the array items.
You will have to create a new array that is one element shorter and copy the old items to the new array, excluding the element you want to delete.
So it is probably better to use a List instead of an array.
I think it's confused to mix up dynamic typing, static typing and duck typing. Duck typing is an independent concept and even static typed language like Go, could have a type checking system which implements duck typing. If a type system will check the methods of a (declared) object but not the type, it could be called a duck typing language.
Laravel 5.6.*
$name = 'file.jpg';
store on image or pdf
$file->storeAs('public/', $name );
download image or pdf
return response()->download($name);
view image or pdf
return response()->file($name);
You might like the function GetInfoFromClosedFile()
Edit: Since the above link does not seem to work anymore, I am adding alternate link 1 and alternate link 2 + code:
Private Function GetInfoFromClosedFile(ByVal wbPath As String, _
wbName As String, wsName As String, cellRef As String) As Variant
Dim arg As String
GetInfoFromClosedFile = ""
If Right(wbPath, 1) <> "" Then wbPath = wbPath & ""
If Dir(wbPath & "" & wbName) = "" Then Exit Function
arg = "'" & wbPath & "[" & wbName & "]" & _
wsName & "'!" & Range(cellRef).Address(True, True, xlR1C1)
On Error Resume Next
GetInfoFromClosedFile = ExecuteExcel4Macro(arg)
End Function
A JavaScript accordion does the trick.
This fiddle by W3Schools makes a simple task even more simple using nothing but javascript, which i partially reproduce below.
<head>
<style>
button.accordion {
background-color: #eee;
color: #444;
font-size: 15px;
cursor: pointer;
}
button.accordion.active, button.accordion:hover {
background-color: #ddd;
}
div.panel {
padding: 0 18px;
display: none;
background-color: white;
}
div.panel.show {
display: block;
}
</style>
</head><body>
<script>
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
}
}
</script>
...
<button class="accordion">Section 1</button>
<div class="panel">
<p>Lorem ipsum dolor sit amet</p>
</div>
...
<button class="accordion">Table</button>
<div class="panel">
<p><table name="detail_table">...</table></p>
</div>
...
<button class="accordion"><table name="button_table">...</table></button>
<div class="panel">
<p>Lorem ipsum dolor sit amet</p>
<table name="detail_table">...</table>
<img src=...></img>
</div>
...
</body></html>
if using php, don't forget to convert "
to '
. You can also use tables of data inside the button and it will still work.
For me, none of the answers worked for ranges that include both virgin cells and cells that are empty based on a formula (e.g. =IF(1=2;"";"")
)
What solved it for me is this:
=COUNTA(FILTER(range, range <> ""))
NOTE, I dont recommend this :). Here's a "oneliner" as well:
//This code generates numbers between 1 - 100 and then takes 10 of them.
var result = Enumerable.Range(1,101).OrderBy(g => Guid.NewGuid()).Take(10).ToArray();
You can do EXISTS
in Oracle PL/SQL.
You can do the following:
DECLARE
n_rowExist NUMBER := 0;
BEGIN
SELECT CASE WHEN EXISTS (
SELECT 1
FROM person
WHERE ID = 10
) THEN 1 ELSE 0 INTO n_rowExist END FROM DUAL;
IF n_rowExist = 1 THEN
-- do things when it exists
ELSE
-- do things when it doesn't exist
END IF;
END;
/
Explanation:
In the query nested where it starts with SELECT CASE WHEN EXISTS and after the parenthesis (SELECT 1 FROM person WHERE ID = 10
) it will return a result if it finds a person of ID of 10. If the there's a result on the query then it will assign the value of 1 otherwise it will assign the value of 0 to n_rowExist
variable. Afterwards, the if statement checks if the value returned equals to 1 then is true otherwise it will be 0 = 1 and that is false.
In my case, I just had to reload the project. I had used command-line to clone my project, but it didn't install the submodule correctly. To remedy, I cloned the project through XCode, and everything works. Just make sure you back up any changes first.
You need to override the color:
a { color:red } /* Globally */
/* Each state */
a:visited { text-decoration: none; color:red; }
a:hover { text-decoration: none; color:blue; }
a:focus { text-decoration: none; color:yellow; }
a:hover, a:active { text-decoration: none; color:black }
ResultSet rs = Sstatement.executeQuery("SELECT * FROM Table Name");
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
System.out.println("resultSet MetaData column Count=" + numberOfColumns);
for (int i = 1; i <= numberOfColumns; i++) {
System.out.println("column number " + i);
System.out.println(rsMetaData.getColumnTypeName(i));
}
The transforms are SVG transforms (for details, have a look at the standard; here are some examples). Basically, scale and translate apply the respective transformations to the coordinate system, which should work as expected in most cases. You can apply more than one transform however (e.g. first scale and then translate) and then the result might not be what you expect.
When working with the transforms, keep in mind that they transform the coordinate system. In principle, what you say is true -- if you apply a scale > 1 to an object, it will look bigger and a translate will move it to a different position relative to the other objects.
Multiplies 10000 and stores as BIGINT, like "Currency" in Visual Basic and Office. See https://msdn.microsoft.com/en-us/library/office/gg264338.aspx
In case you're having this problem in flex/adobe air and find yourself here first, i've found a solution, and have posted it on a related question: ADD COLUMN to sqlite db IF NOT EXISTS - flex/air sqlite?
My comment here: https://stackoverflow.com/a/24928437/2678219
I had multiple dataframes with different floating point, so thx to Allans idea made dynamic length.
pd.set_option('display.float_format', lambda x: f'%.{len(str(x%1))-2}f' % x)
The minus of this is that if You have last 0 in float, it will cut it. So it will be not 0.000070, but 0.00007.
gcc is a rich and complex "orchestrating" program that calls many other programs to perform its duties. For the specific purpose of seeing where #include "goo"
and #include <zap>
will search on your system, I recommend:
$ touch a.c
$ gcc -v -E a.c
...
#include "..." search starts here:
#include <...> search starts here:
/usr/local/include
/usr/lib/gcc/i686-apple-darwin9/4.0.1/include
/usr/include
/System/Library/Frameworks (framework directory)
/Library/Frameworks (framework directory)
End of search list.
# 1 "a.c"
This is one way to see the search lists for included files, including (if any) directories into which #include "..."
will look but #include <...>
won't. This specific list I'm showing is actually on Mac OS X (aka Darwin) but the commands I recommend will show you the search lists (as well as interesting configuration details that I've replaced with ...
here;-) on any system on which gcc runs properly.
I did this class for that purpose. it produces a variable size matrix ( expandable) when more items are added
'''
#pragma once
#include<vector>
#include<iostream>
#include<iomanip>
using namespace std;
template <class T>class Matrix
{
public:
Matrix() = default;
bool AddItem(unsigned r, unsigned c, T value)
{
if (r >= Rows_count)
{
Rows.resize(r + 1);
Rows_count = r + 1;
}
else
{
Rows.resize(Rows_count);
}
if (c >= Columns_Count )
{
for (std::vector<T>& row : Rows)
{
row.resize(c + 1);
}
Columns_Count = c + 1;
}
else
{
for (std::vector<T>& row : Rows)
{
row.resize(Columns_Count);
}
}
if (r < Rows.size())
if (c < static_cast<std::vector<T>>(Rows.at(r)).size())
{
(Rows.at(r)).at(c) = value;
}
else
{
cout << Rows.at(r).size() << " greater than " << c << endl;
}
else
cout << "ERROR" << endl;
return true;
}
void Show()
{
std::cout << "*****************"<<std::endl;
for (std::vector<T> r : Rows)
{
for (auto& c : r)
std::cout << " " <<setw(5)<< c;
std::cout << std::endl;
}
std::cout << "*****************" << std::endl;
}
void Show(size_t n)
{
std::cout << "*****************" << std::endl;
for (std::vector<T> r : Rows)
{
for (auto& c : r)
std::cout << " " << setw(n) << c;
std::cout << std::endl;
}
std::cout << "*****************" << std::endl;
}
// ~Matrix();
public:
std::vector<std::vector<T>> Rows;
unsigned Rows_count;
unsigned Columns_Count;
};
'''
I used this font size control width
.home_footer1::after {
color: transparent;
background-image: url('images/icon-mail.png');
background-size: 100%;
content: ".......................................";
font-size: 30pt;
}
It would seem that is.nan
doesn't actually have a method for data frames, unlike is.na
. So, let's fix that!
is.nan.data.frame <- function(x)
do.call(cbind, lapply(x, is.nan))
data123[is.nan(data123)] <- 0
Check the sql log in the LOG directory of your instance - see if anything is going on there. You'll need to stop the service to open the log - or restart and you can read the old one - named with .1 on the end.
With the error you're getting, you need to enable TCP/IP or Named pipes for named connections. Shared memory connection should work, but you seem to not be using that. Are you trying to connect through SSMS?
In my log I see entries like this...
Server local connection provider is ready to accept connection on [\\.\pipe\mssql$sqlexpress\sql\query ]
As the comments said, .\SQLEXPRESS should work. Also worstationName\SQLEXPRESS will work.
Here's my recipe:
Create a static HTML that redirects to your requested app URL, put that page on the web.
That way, the links you share are 'real' links as far as Android is concerned ( they will be 'clickable').
You 'share' a regular HTTP link, www.your.server.com/foo/bar.html This URL returns a simple 8 line HTML that redirects to your app's URI (window.location = "blah://kuku") (note that 'blah' doesn't have to be HTTP or HTTPS any more).
Once you get this up and running, you can augment the HTML with all the fancy capabilities as suggested above.
This works with the built-in browser, Opera, and Firefox (haven't tested any other browser). Firefox asks 'This link needs to be opened with an application' (ok, cancel). Other browsers apparently don't worry about security that much, they just open the app, no questions asked.
You can use the following to convert string to int:
For details refer to Type Conversion Functions (Visual Basic).
Pattern.compile()
allow to reuse a regex multiple times (it is threadsafe). The performance benefit can be quite significant.
I did a quick benchmark:
@Test
public void recompile() {
var before = Instant.now();
for (int i = 0; i < 1_000_000; i++) {
Pattern.compile("ab").matcher("abcde").matches();
}
System.out.println("recompile " + Duration.between(before, Instant.now()));
}
@Test
public void compileOnce() {
var pattern = Pattern.compile("ab");
var before = Instant.now();
for (int i = 0; i < 1_000_000; i++) {
pattern.matcher("abcde").matches();
}
System.out.println("compile once " + Duration.between(before, Instant.now()));
}
compileOnce was between 3x and 4x faster.
I guess it highly depends on the regex itself but for a regex that is often used, I go for a static Pattern pattern = Pattern.compile(...)
If your markup is bound to a controller, directive or anything else with a $scope:
console.log($scope.movie);
Just index using you ind_pos
ind_pos = [1,5,7]
print (a[ind_pos])
[88 85 16]
In [55]: a = [0,88,26,3,48,85,65,16,97,83,91]
In [56]: import numpy as np
In [57]: arr = np.array(a)
In [58]: ind_pos = [1,5,7]
In [59]: arr[ind_pos]
Out[59]: array([88, 85, 16])
You can use the form reference which exists on all inputs, this is much faster than .closest()
(5-10 times faster in Chrome and IE8). Works on IE6 & 7 too.
var input = $('input[type=submit]');
var form = input.length > 0 ? $(input[0].form) : $();
<Scatter
data={data}
// style={{ width: "50%", height: "50%" }}
options={{
scales: {
yAxes: [
{
scaleLabel: {
display: true,
labelString: "Probability",
},
},
],
xAxes: [
{
scaleLabel: {
display: true,
labelString: "Hours",
},
},
],
},
}}
/>
For all those who are stuck with an error.
Let me give you guys a solution with a brief explanation of the same:-
command to connect:-
mongoexport --host your_host --port your_port -u your_username -p your_password --db your_db --collection your_collection --type=csv --out file_name.csv --fields all_the_fields --authenticationDatabase admin
--host --> host of Mongo server
--port --> port of Mongo server
-u --> username
-p --> password
--db --> db from which you want to export
--collection --> collection you want to export
--type --> type of export in my case CSV
--out --> file name where you want to export
--fields --> all the fields you want to export (don't give spaces in between two field name in between commas in case of CSV)
--authenticationDatabase --> database where all your user information is stored
Starting from freemarker 2.3.7, you can use this syntax :
${(object.attribute)!}
or, if you want display a default text when the attribute is null
:
${(object.attribute)!"default text"}
I had this error when I used a launch configuration that had an invalid classpath. In my case, I had a project that initially used Maven and thus a launch configuration had a Maven classpath element in it. I had later changed the project to use Gradle and removed the Maven classpath from the project's classpath, but the launch configuration still used it. I got this error trying to run it. Cleaning and rebuilding the project did not resolve this error. Instead, edit the launch configuration, remove the project classpath element, then add the project back to the User Entries in the classpath.
Primitives can be converted to objects with @()
expression. So the shortest way is to transform int
to NSNumber
and pick up string representation with stringValue
method:
NSString *strValue = [@(myInt) stringValue];
or
NSString *strValue = @(myInt).stringValue;
When you evaluate the code, it is very clear that (==) compares according to memory address, while equals(Object o) compares hashCode() of the instances. That's why it is said do not break the contract between equals() and hashCode() if you do not face surprises later.
String s1 = new String("Ali");
String s2 = new String("Veli");
String s3 = new String("Ali");
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s3.hashCode());
System.out.println("(s1==s2):" + (s1 == s2));
System.out.println("(s1==s3):" + (s1 == s3));
System.out.println("s1.equals(s2):" + (s1.equals(s2)));
System.out.println("s1.equal(s3):" + (s1.equals(s3)));
/*Output
96670
3615852
96670
(s1==s2):false
(s1==s3):false
s1.equals(s2):false
s1.equal(s3):true
*/
Place ojdbc6.jar in your project resources folder of eclipse. then add the following dependency code in your pom.xml
<dependency>
<groupId> oracle </groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/ojdbc6.jar</systemPath>
</dependency>
Create a class that inherits from IActionFilter.
public class NoCacheAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.SetNoStore();
base.OnResultExecuting(filterContext);
}
}
Then put attributes where needed...
[NoCache]
[HandleError]
public class AccountController : Controller
{
[NoCache]
[Authorize]
public ActionResult ChangePassword()
{
return View();
}
}
Follow instructions (steps 1 to 3 don't needed in windows):
Find mysql config to edit:
/etc/mysql/my.cnf (Mysql 5.5)
/etc/mysql/conf.d/mysql.cnf (Mysql 5.6+)
Find bind-address=127.0.0.1
in config file change bind-address=0.0.0.0
(you can set bind address to one of your interface ips or like me use 0.0.0.0)
Restart mysql service run on console:
service restart mysql
Create a user with a safe password for remote connection. To do this run following command in mysql (if you are linux user to reach mysql console run mysql
and if you set password for root run mysql -p
):
GRANT ALL PRIVILEGES
ON *.* TO 'remote'@'%'
IDENTIFIED BY 'safe_password'
WITH GRANT OPTION;`
Now you should have a user with name of user
and password of safe_password
with capability of remote connect.
To expand on my comment.
You can validate on the command line using php -l [filename]
, which does a syntax check only (lint). This will depend on your php.ini error settings, so you can edit you php.ini or set the error_reporting in the script.
Here's an example of the output when run on a file containing:
<?php
echo no quotes or semicolon
Results in:
PHP Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in badfile.php on line 2
Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in badfile.php on line 2
Errors parsing badfile.php
I suggested you build your own validator.
A simple page that allows you to upload a php file. It takes the uploaded file runs it through php -l
and echos the output.
Note: this is not a security risk it does not execute the file, just checks for syntax errors.
Here's a really basic example of creating your own:
<?php
if (isset($_FILES['file'])) {
echo '<pre>';
passthru('php -l '.$_FILES['file']['tmp_name']);
echo '</pre>';
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</form>
You are missing the height
CSS property.
Adding it you will notice that scroll bar will appear.
.wrapper{
// width: 1000px;
width:600px;
overflow-y:scroll;
position:relative;
height: 300px;
}
From documentation:
overflow-y
The overflow-y CSS property specifies whether to clip content, render a scroll bar, or display overflow content of a block-level element, when it overflows at the top and bottom edges.
Use String#replace()
.
To replace them with spaces (as per your question title):
System.out.println("I don't like these \"double\" quotes".replace("\"", " "));
The above can also be done with characters:
System.out.println("I don't like these \"double\" quotes".replace('"', ' '));
To remove them (as per your example):
System.out.println("I don't like these \"double\" quotes".replace("\"", ""));
"The issue was caused by a down Active Directory Server, which of course could not authenticate the Windows account"
It is not "of course - because if AD is not available then Kerberos authentication falls back to NTLM (domain account credentials are cached locally, one can login with it even if AD/Kerberos is not available). I guess that you have possibly 2 simultaneous conditions for this failure to happen:
or other specific security network/server/AD/machine configurations
Just open Putty and try to establish connection to remote server you want to push your code. when the dialog appears press Yes(you trust remote) then everything would be OK.
Based on ghostdog74's answer,
dicta = {"a":1,"d":2}
dictb = {"a":5,"d":2}
for value in dicta.values():
if not value in dictb.values():
print value
will print differ value of dicta
You might add the second snippet as a field definition for ICourseBased in a view.
DECLARE VIEW MyView
AS
SELECT
case
when FC.CourseId is not null then cast(1 as bit)
else cast(0 as bit)
end
as IsCoursedBased
...
SELECT ICourseBased FROM MyView
Player.cpp
require the definition of Ball
class. So simply add #include "Ball.h"
Player.cpp:
#include "Player.h"
#include "Ball.h"
void Player::doSomething(Ball& ball) {
ball.ballPosX += 10; // incomplete type error occurs here.
}
Node.js remove extension from full path keeping directory
https://stackoverflow.com/a/31615711/895245 for example did path/hello.html
-> hello
, but if you want path/hello.html
-> path/hello
, you can use this:
#!/usr/bin/env node
const path = require('path');
const filename = 'path/hello.html';
const filename_parsed = path.parse(filename);
console.log(path.join(filename_parsed.dir, filename_parsed.name));
outputs directory as well:
path/hello
https://stackoverflow.com/a/36099196/895245 also achieves this, but I find this approach a bit more semantically pleasing.
Tested in Node.js v10.15.2.
The html
<select id="drop" name="company" class="company btn btn-outline dropdown-toggle" >
<option value="demo1">Group Medical</option>
<option value="demo">Motor Insurance</option>
</select>
Script.js
$("#drop").change(function () {
var category= $('select[name=company]').val() // Here we can get the value of selected item
alert(category);
});
I've found the best way to program the font sizes of a website are to define a base font size for the body
and then use em's (or rem's) for every other font-size
I declare after that. That's personal preference I suppose, but it's served me well and also made it very easy to incorporate a more responsive design.
As far as using rem units go, I think it's good to find a balance between being progressive in your code, but to also offer support for older browsers. Check out this link about browser support for rem units, that should help out a good amount on your decision.
you could also change from the .get()
method to the .getJSON()
method, jQuery will then parse the string returned as data
to a javascript object and/or array that you can then reference like any other javascript object/array.
using your code above, if you changed .get
to .getJSON
, you should get an alert of [object Object]
for each element in the array. If you changed the alert to alert(item.name)
you will get the names.
If all you want is a JS implementation of a base64-encoder, so that you can send data back, you can try the btoa
function.
b64enc = btoa(uint);
A couple of quick notes on btoa - it's non-standard, so browsers aren't forced to support it.
However, most browsers do. The big ones, at least. atob
is the opposite conversion.
If you need a different implementation, or you find an edge-case where the browser has no idea what you're talking about, searching for a base64 encoder for JS wouldn't be too hard.
I think there are 3 of them hanging around on my company's website, for some reason...
"List" is an object getting from backend and using iterator to display in table
"minAmount" , "MaxAmount" is an object variable "mrr" is an just temporary var to get value and iterate mrr to get data.
<table class="table table-hover">
<tbody>
<tr th:each="mrr,iterStat : ${list}">
<td th:text="${mrr.id}"></td>
<td th:text="${mrr.minAmount}"></td>
<td th:text="${mrr.maxAmount}"></td>
</tr>
</tbody>
</table>
One way would be to make a List
of Thread
s, create and launch each thread, while adding it to the list. Once everything is launched, loop back through the list and call join()
on each one. It doesn't matter what order the threads finish executing in, all you need to know is that by the time that second loop finishes executing, every thread will have completed.
A better approach is to use an ExecutorService and its associated methods:
List<Callable> callables = ... // assemble list of Callables here
// Like Runnable but can return a value
ExecutorService execSvc = Executors.newCachedThreadPool();
List<Future<?>> results = execSvc.invokeAll(callables);
// Note: You may not care about the return values, in which case don't
// bother saving them
Using an ExecutorService (and all of the new stuff from Java 5's concurrency utilities) is incredibly flexible, and the above example barely even scratches the surface.
I'd recommend you yo use an out-of-the-box solution. Given that the development of a workflow engine requires a vast amount of resources and time, a ready-made engine is a better option. Have a look at Workflow Engine. It's a lightweight component that enables you to add custom executable workflows of any complexity to any Java solutions.
Try
request.getSession().setAttribute("SUBFAMILY", subFam);
request.getSession().getAttribute("SUBFAMILY");
You have to increment the iterator first (with i++) and then remove the previous element (e.g., by using the returned value from i++). You can change the code to a while loop like so:
std::list<item*>::iterator i = items.begin();
while (i != items.end())
{
bool isActive = (*i)->update();
if (!isActive)
{
items.erase(i++); // alternatively, i = items.erase(i);
}
else
{
other_code_involving(*i);
++i;
}
}
Another answer for the first question is to use one for loop and perform linear indexing into the array using the function NUMEL to get the total number of elements:
total = 0;
for i = 1:numel(A)
total = total+A(i);
end
This particular NuGet package has a habit of losing its references in one of our projects. From time to time I will need to run the following command in the Package Manager Console to restore the references and everything is OK again
Update-Package Microsoft.AspNet.Webpages -reinstall
In my understanding Google wants Android to handle memory management and shutting down the apps. If you must exit the app from code, it might be beneficial to ask Android to run garbage collector.
@Override
public void onBackPressed(){
System.gc();
System.exit(0);
}
You can also add finish() to the code, but it is probably redundant, if you also do System.exit(0)
I had the same problem with woff-fonts, multiple subdomains had to have access. To allow subdomains I added something like this to my httpd.conf:
SetEnvIf Origin "^(.*\.example\.com)$" ORIGIN_SUB_DOMAIN=$1
<FilesMatch "\.woff$">
Header set Access-Control-Allow-Origin "%{ORIGIN_SUB_DOMAIN}e" env=ORIGIN_SUB_DOMAIN
</FilesMatch>
For multiple domains you could just change the regex in SetEnvIf
.
This solved my problem: Kotlin Code:
val fragmentTransaction = activity.supportFragmentManager.beginTransaction()
fragmentTransaction.add(dialogFragment, tag)
fragmentTransaction.commitAllowingStateLoss()
How is commitAllowingStateLoss()
is different than commit()
?
As per documentation:
Like commit()
but allows the commit to be executed after an activity's state is saved.
https://developer.android.com/reference/android/app/FragmentTransaction#commitAllowingStateLoss()
P.S: you can show Fragment Dialogs or can load fragments by this method. Applicable for both.
Use git add -i
to remove just-added files from your upcoming commit. Example:
Adding the file you didn't want:
$ git add foo
$ git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# new file: foo
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
# [...]#
Going into interactive add to undo your add (the commands typed at git here are "r" (revert), "1" (first entry in the list revert shows), 'return' to drop out of revert mode, and "q" (quit):
$ git add -i
staged unstaged path
1: +1/-0 nothing foo
*** Commands ***
1: [s]tatus 2: [u]pdate 3: [r]evert 4: [a]dd untracked
5: [p]atch 6: [d]iff 7: [q]uit 8: [h]elp
What now> r
staged unstaged path
1: +1/-0 nothing [f]oo
Revert>> 1
staged unstaged path
* 1: +1/-0 nothing [f]oo
Revert>>
note: foo is untracked now.
reverted one path
*** Commands ***
1: [s]tatus 2: [u]pdate 3: [r]evert 4: [a]dd untracked
5: [p]atch 6: [d]iff 7: [q]uit 8: [h]elp
What now> q
Bye.
$
That's it! Here's your proof, showing that "foo" is back on the untracked list:
$ git status
# On branch master
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
# [...]
# foo
nothing added to commit but untracked files present (use "git add" to track)
$
delete arr[1]
Try this out, it should work if you have an array like var arr =["","",""]
As per the Django Project Skeleton, the proper directory structure that could be followed is :
[projectname]/ <- project root
+-- [projectname]/ <- Django root
¦ +-- __init__.py
¦ +-- settings/
¦ ¦ +-- common.py
¦ ¦ +-- development.py
¦ ¦ +-- i18n.py
¦ ¦ +-- __init__.py
¦ ¦ +-- production.py
¦ +-- urls.py
¦ +-- wsgi.py
+-- apps/
¦ +-- __init__.py
+-- configs/
¦ +-- apache2_vhost.sample
¦ +-- README
+-- doc/
¦ +-- Makefile
¦ +-- source/
¦ +-- *snap*
+-- manage.py
+-- README.rst
+-- run/
¦ +-- media/
¦ ¦ +-- README
¦ +-- README
¦ +-- static/
¦ +-- README
+-- static/
¦ +-- README
+-- templates/
+-- base.html
+-- core
¦ +-- login.html
+-- README
Refer https://django-project-skeleton.readthedocs.io/en/latest/structure.html for the latest directory structure.
I tried the above methods but I got the "macro cannot be found" error. This is final code that worked!
Option Explicit
Dim xlApp, xlBook
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
' Import Add-Ins
xlApp.Workbooks.Open "C:\<pathOfXlaFile>\MyMacro.xla"
xlApp.AddIns("MyMacro").Installed = True
'
Open Excel workbook
Set xlBook = xlApp.Workbooks.Open("<pathOfXlsFile>\MyExcel.xls", 0, True)
' Run Macro
xlApp.Run "Sheet1.MyMacro"
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
WScript.Quit
In my case, MyMacro happens to be under Sheet1, thus Sheet1.MyMacro.
If you have something else altering the DB (say another process) and need to ensure you see these changes, use AsNoTracking()
, otherwise EF may give you the last copy that your context had instead, hence it being good to usually use a new context every query:
http://codethug.com/2016/02/19/Entity-Framework-Cache-Busting/
This happens because $cOTLdata
is not null but the index 'char_data'
does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).
Update 2018-07-23
As was just pointed out in the comments, this question was about getting a screenshot from the command line. Sorry, I just read over that. So here is the correct answer:
As of Firefox 57 you can create a screenshot in headless mode like this:
firefox -screenshot https://developer.mozilla.com
Read more in the documentation.
Update 2017-06-15
As of Firefox 55 there is Firefox Screenshots as a more flexible alternative. As of Firefox 57 Screenshots can capture a full page, too.
Original answer
Since Firefox 32 there is also a full page screenshot button in the developer tools (F12). If it is not enabled go to the developer tools settings (gear button) and choose "Take a fullpage screenshot" at the "Available Toolbox Buttons" section.
source: developer.mozilla.org
By default the screenshots are saved in the download directory. This works similar to screenshot --fullpage
in the toolbar.
Write one table per join, like this:
select tab1.a,tab2.b,tab3.c,tab4.d
from
table1 tab1
inner join table2 tab2 on tab2.fg = tab1.fg
left join table3 tab3 on tab3.xxx = tab1.xxx and tab3.desc = "XYZ"
left join table4 tab4 on tab4.xya = tab3.xya and tab4.ss = tab3.ss
left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk
Note that while my query contains actual left join, your query apparently doesn't.
Since the conditions are in the where, your query should behave like inner joins. (Although I admit I don't know Informix, so maybe I'm wrong there).
The specfific Informix extension used in the question works a bit differently with regards to left joins. Apart from the exact syntax of the join itself, this is mainly in the fact that in Informix, you can specify a list of outer joined tables. These will be left outer joined, and the join conditions can be put in the where clause. Note that this is a specific extension to SQL. Informix also supports 'normal' left joins, but you can't combine the two in one query, it seems.
In Oracle this extension doesn't exist, and you can't put outer join conditions in the where clause, since the conditions will be executed regardless.
So look what happens when you move conditions to the where clause:
select tab1.a,tab2.b,tab3.c,tab4.d
from
table1 tab1
inner join table2 tab2 on tab2.fg = tab1.fg
left join table3 tab3 on tab3.xxx = tab1.xxx
left join table4 tab4 on tab4.xya = tab3.xya
left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk
where
tab3.desc = "XYZ" and
tab4.ss = tab3.ss
Now, only rows will be returned for which those two conditions are true. They cannot be true when no row is found, so if there is no matching row in table3 and/or table4, or if ss
is null in either of the two, one of these conditions is going to return false, and no row is returned. This effectively changed your outer join to an inner join, and as such changes the behavior significantly.
PS: left join
and left outer join
are the same. It means that you optionally join the second table to the first (the left one). Rows are returned if there is only data in the 'left' part of the join. In Oracle you can also right [outer] join
to make not the left, but the right table the leading table. And there is and even full [outer] join
to return a row if there is data in either table.
In Java you can't. Interface has to do with methods and signature, it does not have to do with the internal state of an object -- that is an implementation question. And this makes sense too -- I mean, simply because certain attributes exist, it does not mean that they have to be used by the implementing class. getHeight could actually point to the width variable (assuming that the implementer is a sadist).
(As a note -- this is not true of all languages, ActionScript allows for declaration of pseudo attributes, and I believe C# does too)
If you want the file size of multiple files in a directory, use Files.walkFileTree
. You can obtain the size from the BasicFileAttributes
that you'll receive.
This is much faster then calling .length()
on the result of File.listFiles()
or using Files.size()
on the result of Files.newDirectoryStream()
. In my test cases it was about 100 times faster.
you can see in my example font sizes and background colors are changing according to the screen size
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
<style>_x000D_
body {_x000D_
background-color: lightgreen;_x000D_
}_x000D_
/* Custom, iPhone Retina */ _x000D_
@media(max-width:320px){_x000D_
body {_x000D_
background-color: lime;_x000D_
font-size:14px;_x000D_
}_x000D_
}_x000D_
@media only screen and (min-width : 320px) {_x000D_
body {_x000D_
background-color: red;_x000D_
font-size:18px;_x000D_
}_x000D_
}_x000D_
/* Extra Small Devices, Phones */ _x000D_
@media only screen and (min-width : 480px) {_x000D_
body {_x000D_
background-color: aqua;_x000D_
font-size:24px;_x000D_
}_x000D_
}_x000D_
/* Small Devices, Tablets */_x000D_
@media only screen and (min-width : 768px) {_x000D_
body {_x000D_
background-color: green;_x000D_
font-size:30px;_x000D_
}_x000D_
}_x000D_
/* Medium Devices, Desktops */_x000D_
@media only screen and (min-width : 992px) {_x000D_
body {_x000D_
background-color: grey;_x000D_
font-size:34px;_x000D_
}_x000D_
}_x000D_
/* Large Devices, Wide Screens */_x000D_
@media only screen and (min-width : 1200px) {_x000D_
body {_x000D_
background-color: black;_x000D_
font-size:42px;_x000D_
}_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<p>Resize the browser window. When the width of this document is larger than the height, the background-color is "lightblue", otherwise it is "lightgreen".</p>_x000D_
</body>_x000D_
</html>
_x000D_
On Debian (isn't this the case for most Linux distros?), it's saved in /var/lib/php5/. As mentioned above, it's configured in your php.ini.
My preferred method:
if (*ptr == 0) // empty string
Probably more common:
if (strlen(ptr) == 0) // empty string
Using HTTP status codes would be a RESTful way to do it, but that would suggest you make the rest of the interface RESTful using resource URIs and so on.
In truth, define the interface as you like (return an error object, for example, detailing the property with the error, and a chunk of HTML that explains it, etc), but once you've decided on something that works in a prototype, be ruthlessly consistent.
I like to do this dynamically depending on the number of options in the select; to hide the search for selects with 10 or fewer results, I do:
$fewResults = $("select>option:nth-child(11)").closest("select");
$fewResults.select2();
$('select').not($fewResults).select2({ minimumResultsForSearch : -1 });
Try array_merge.
$array1 = array('Item 1');
$array2 = array('Item 2');
$array3 = array_merge($array1, $array2);
I think its because you are not assigning a key to either, so they both have key of 0, and the + does not re-index, so its trying to over write it.
Use
document.getElementById("select_id").selectedIndex
Or to get the value:
document.getElementById("select_id").value
In my case, this was caused by custom manifest entries added by the maven-jar-plugin.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<configuration>
<archive>
<index>true</index>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestEntries>
<git>${buildNumber}</git>
<build-time>${timestamp}</build-time>
</manifestEntries>
</archive>
</configuration>
</plugin>
Removing the following entries fixed the problem
<index>true</index>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
First of all: I know this is rather old but there still is not an accepted answer, so perhaps my approach will help someone else. :)
What I did to solve this is:
process.Start();
while (true)
{
try
{
var time = process.StartTime;
break;
}
catch (Exception) {}
}
The association var time = process.StartTime
will throw an exception as long as process did not start. So once it passes, it is safe to assume process is running and to work with it further. I am using this to wait for java process to start up, since it takes some time. This way it should be independent on what machine the application is running rather than using Thread.Sleep()
.
I understand this is not very clean solution, but the only one that should be performance independent I could think of.
After reading this post, from Baeldung. I found that the solution is pretty simple.
What I have done, is to add the role and permissions into the GrantedAuthority. I was able to access both methods hasRole() and hasAuthority().
You need to set the Identity seed to that value:
CREATE TABLE orders
(
id int IDENTITY(9586,1)
)
To alter an existing table:
ALTER TABLE orders ALTER COLUMN Id INT IDENTITY (9586, 1);
More info on CREATE TABLE (Transact-SQL) IDENTITY (Property)
This is pretty vague. Do you mean like in SQL:
DELETE FROM myTable
WHERE dateColumn < '2007'
Javascript which runs on the client machine can't access the local disk file system due to security restrictions.
If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.
Tensorflow includes also a sigmoid
function:
https://www.tensorflow.org/versions/r1.2/api_docs/python/tf/sigmoid
import tensorflow as tf
sess = tf.InteractiveSession()
x = 0.458
y = tf.sigmoid(x)
u = y.eval()
print(u)
# 0.6125396
Very primitive solution to the problem:
void (^nextOperationAfterLongOperationBlock)(void) = ^{
};
[object runSomeLongOperationAndDo:^{
STAssert…
nextOperationAfterLongOperationBlock();
}];
I just ran into this and was frustrating. My setup: The header was set to Content-Type: application/JSON and was passing the info from the body with JSON format, and was reading [FromBody] on the controller.
Everything was set up fine and I expect it to work, but the problem was with the JSON sent over. Since it was a complex structure, one of my classes which was defined 'Abstract' was not getting initialized and hence the values weren't assigned to the model properly. I removed the abstract keyword and it just worked..!!!
One tip, the way I could figure this out was to send data in parts to my controller and check when it becomes null... since it was a complex model I was appending one model at a time to my request params. Hope it helps someone who runs into this stupid issue.
The solution given by Ash Clarke for subdomains works great, but please note that you need to include the document.domain = "mydomain.com"; in both the head of the iframe page and the head of the parent page, as stated in the link same origin policy checks
An important extension to the same origin policy implemented for JavaScript DOM access (but not for most of the other flavors of same-origin checks) is that two sites sharing a common top-level domain may opt to communicate despite failing the "same host" check by mutually setting their respective document.domain DOM property to the same qualified, right-hand fragment of their current host name. For example, if http://en.example.com/ and http://fr.example.com/ both set document.domain to "example.com", they would be from that point on considered same-origin for the purpose of DOM manipulation.
In Bootstrap 4.1.3:
This worked for me when I was trying to center a bootstrap badge inside of a container > row > column
next to a h1
title.
What did work was some simple css:
.my-valign-center {
vertical-align: 50%;
}
or
<span class="badge badge-pill" style="vertical-align: 50%;">My Badge</span>
If you need to hit the database, you need to hit the web server again (for the most part).
What you can do is use AJAX, which makes a request to another script on your site to retrieve data, gets the data, and then updates the input fields you want.
AJAX calls can be made in jquery with the $.ajax() function call, so this will happen
User's browser enters input that fires a trigger that makes an AJAX call
$('input .callAjax').bind('change', function() {
$.ajax({ url: 'script/ajax',
type: json
data: $foo,
success: function(data) {
$('input .targetAjax').val(data.newValue);
});
);
Now you will need to point that AJAX call at script (sounds like you're working PHP) that will do the query you want and send back data.
You will probably want to use the JSON object call so you can pass back a javascript object, that will be easier to use than return XML etc.
The php function json_encode($phpobj); will be useful.
For Blocks lover you can use ALActionBlocks to add action of gestures in block
__weak ALViewController *wSelf = self;
imageView.userInteractionEnabled = YES;
UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithBlock:^(UITapGestureRecognizer *weakGR) {
NSLog(@"pan %@", NSStringFromCGPoint([weakGR locationInView:wSelf.view]));
}];
[self.imageView addGestureRecognizer:gr];
If you are running windows 7 (professional) and Git for Windows (v 2.15 or above), you can simply run below command to find out what are different diff tools supported by your Git for Windows
git difftool --tool-help
You will see output similar to this
git difftool --tool=' may be set to one of the following:
vimdiff vimdiff2 vimdiff3
it means that your git does not support(can not find) beyond compare as difftool right now.
In order for Git to find beyond compare as valid difftool, you should have Beyond Compare installation directory in your system path environment variable. You can check this by running bcompare from shell(cmd, git bash or powershell. I am using Git Bash). If Beyond Compare does not launch, add its installation directory (in my case, C:\Program Files\Beyond Compare 4) to your system path variable. After this, restart your shell. Git will show Beyond Compare as possible difftool option. You can use any of below commands to launch beyond compare as difftool (for example, to compare any local file with some other branch)
git difftool -t bc branchnametocomparewith -- path-to-file
or
git difftool --tool=bc branchnametocomparewith -- path-to-file
You can configure beyond compare as default difftool using below commands
git config --global diff.tool bc
p.s. keep in mind that bc in above command can be bc3 or bc based upon what Git was able to find from your path system variable.
By using Ado.net
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace PBDataAccess
{
public class AddContact
{
// for preparing connection to sql server database
private SqlConnection conn;
// for preparing sql statement or stored procedure that
// we want to execute on database server
private SqlCommand cmd;
// used for storing the result in datatable, basically
// dataset is collection of datatable
private DataSet ds;
// datatable just for storing single table
private DataTable dt;
// data adapter we use it to manage the flow of data
// from sql server to dataset and after fill the data
// inside dataset using fill() method
private SqlDataAdapter da;
// created a method, which will return the dataset
public DataSet GetAllContactType()
{
// retrieving the connection string from web.config, which will
// tell where our database is located and on which database we want
// to perform opearation, in this case we are working on stored
// procedure so you might have created it somewhere in your database.
// connection string will include the name of the datasource, your
// database name, user name and password.
using (conn = new SqlConnection(ConfigurationManager.ConnectionString["conn"]
.ConnectionString))
{
// Addcontact is the name of the stored procedure
using (cmd = new SqlCommand("Addcontact", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// here we are passing the parameters that
// Addcontact stored procedure expect.
cmd.Parameters.Add("@CommandType",
SqlDbType.VarChar, 50).Value = "GetAllContactType";
// here created the instance of SqlDataAdapter
// class and passed cmd object in it
da = new SqlDataAdapter(cmd);
// created the dataset object
ds = new DataSet();
// fill the dataset and your result will be
stored in dataset
da.Fill(ds);
}
}
return ds;
}
}
****** Stored Procedure ******
CREATE PROCEDURE Addcontact
@CommandType VARCHAR(MAX) = NULL
AS
BEGIN
IF (@CommandType = 'GetAllContactType')
BEGIN
SELECT * FROM Contacts
END
END
onclick="history.go(-1)"
Simply
Create new classes to overwrite the width. See jFiddle for working code.
<div class="row">
<div class="col-xs-1 col-xs-1-5">
<div class="box">
box 1
</div>
</div>
<div class="col-xs-3 col-xs-3-5">
<div class="box">
box 2
</div>
</div>
<div class="col-xs-3 col-xs-3-5">
<div class="box">
box 3
</div>
</div>
<div class="col-xs-3 col-xs-3-5">
<div class="box">
box 4
</div>
</div>
</div>
.col-xs-1-5 {
width: 12.49995%;
}
.col-xs-3-5 {
width: 29.16655%;
}
.box {
border: 1px solid #000;
text-align: center;
}
A solution with works with Python 2.X and Python 3.X makes use of the Python 2 and 3 compatibility library six
:
from six.moves.urllib.request import urlopen
link = "http://www.somesite.com/details.pl?urn=2344"
response = urlopen(link)
content = response.read()
print(content)
In your bottom-right corner, you have Spaces: Spaces: 2
There you can change the indentation according to your needs: Indentation Options
Find the local IP address of computer A and find the port that your website is running on. Then from computer B open a web browser and go to IP:port. Example: 192.168.1.5:80 if computer A's IP is 192.168.1.5 and your website is running on port 80
Very lightweight solution could be using KeyboardAnimator.
project got the sample implementation, documentation is still in progress...
Appropriate usage :: It's have a specific implementation for UITextField & UITextView
Limitation:: It's fully on objective-c, swift version will be available soon.
versionCode
A positive integer used as an internal version number. This number is used only to determine whether one version is more recent than another, with higher numbers indicating more recent versions. This is not the version number shown to users; that number is set by the versionName
setting, below. The Android system uses the versionCode
value to protect against downgrades by preventing users from installing an APK with a lower versionCode
than the version currently installed on their device.
The value is a positive integer so that other apps can programmatically evaluate it, for example to check an upgrade or downgrade relationship. You can set the value to any positive integer you want, however you should make sure that each successive release of your app uses a greater value. You cannot upload an APK to the Play Store with a versionCode
you have already used for a previous version.
versionName
A string used as the version number shown to users. This setting can be specified as a raw string or as a reference to a string resource.
The value is a string so that you can describe the app version as a .. string, or as any other type of absolute or relative version identifier. The versionName
has no purpose other than to be displayed to users.
We can achieve thread safety by using both ConcurrentHashMap and synchronisedHashmap. But there is a lot of difference if you look at their architecture.
It will maintain the lock at the object level. So if you want to perform any operation like put/get then you have to acquire the lock first. At the same time, other threads are not allowed to perform any operation. So at a time, only one thread can operate on this. So the waiting time will increase here. We can say that performance is relatively low when you are comparing with ConcurrentHashMap.
It will maintain the lock at the segment level. It has 16 segments and maintains the concurrency level as 16 by default. So at a time, 16 threads can be able to operate on ConcurrentHashMap. Moreover, read operation doesn't require a lock. So any number of threads can perform a get operation on it.
If thread1 wants to perform put operation in segment 2 and thread2 wants to perform put operation on segment 4 then it is allowed here. Means, 16 threads can perform update(put/delete) operation on ConcurrentHashMap at a time.
So that the waiting time will be less here. Hence the performance is relatively better than synchronisedHashmap.
To preserve newlines use |
, for example:
|
This is a very long sentence
that spans several lines in the YAML
but which will be rendered as a string
with newlines preserved.
is translated to "This is a very long sentence?\n that spans several lines in the YAML?\n but which will be rendered as a string?\n with newlines preserved.\n"
Even without cloning or fetching, you can check the list of tags on the upstream repo with git ls-remote
:
git ls-remote --tags /url/to/upstream/repo
(as illustrated in "When listing git-ls-remote why there's “^{}
” after the tag name?")
xbmono illustrates in the comments that quotes are needed:
git ls-remote --tags /some/url/to/repo "refs/tags/MyTag^{}"
Note that you can always push your commits and tags in one command with (git 1.8.3+, April 2013):
git push --follow-tags
See Push git commits & tags simultaneously.
Regarding Atlassian SourceTree specifically:
Note that, from this thread, SourceTree ONLY shows local tags.
There is an RFE (Request for Enhancement) logged in SRCTREEWIN-4015
since Dec. 2015.
A simple workaround:
see a list of only unpushed tags?
git push --tags
or check the "
Push all tags
" box on the "Push" dialog box, all tags will be pushed to your remote.
That way, you will be "sure that they are present in remote so that other developers can pull them".
public function boot()
{
if(config('app.debug')!=true) {
\URL::forceScheme('https');
}
}
in app/Providers/AppServiceProvider.php
Find the file "config.inc.php" under your phpMyAdmin directory and edit the following lines:
$cfg['Servers'][$i]['auth_type'] = 'config'; // config, http, cookie
$cfg['Servers'][$i]['user'] = 'root'; // MySQL user
$cfg['Servers'][$i]['password'] = 'TYPE_YOUR_PASSWORD_HERE'; // MySQL password
Note that the password used in the 'password' field must be the same for the MySQL root password. Also, you should check if root login is allowed in this line:
$cfg['Servers'][$i]['AllowRoot'] = TRUE; // true = allow root login
This way you have your root password set.
The trouble looks like the image isn't square and the browser adjusts as such. After rotation ensure the dimensions are retained by changing the image margin.
.imagetest img {
transform: rotate(270deg);
...
margin: 10px 0px;
}
The amount will depend on the difference in height x width of the image.
You may also need to add display:inline-block;
or display:block
to get it to recognize the margin parameter.
Set a listener on your WebView:
webView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return(event.getAction() == MotionEvent.ACTION_MOVE));
}
});
remember to set you username and password if required:
http://USERNAME:[email protected]:8080
Example:
npm config set proxy http://USERNAME:[email protected]:8080
They're two completely different things. ==
compares the object reference, if any, contained by a variable. .equals()
checks to see if two objects are equal according to their contract for what equality means. It's entirely possible for two distinct object instances to be "equal" according to their contract. And then there's the minor detail that since equals
is a method, if you try to invoke it on a null
reference, you'll get a NullPointerException
.
For instance:
class Foo {
private int data;
Foo(int d) {
this.data = d;
}
@Override
public boolean equals(Object other) {
if (other == null || other.getClass() != this.getClass()) {
return false;
}
return ((Foo)other).data == this.data;
}
/* In a real class, you'd override `hashCode` here as well */
}
Foo f1 = new Foo(5);
Foo f2 = new Foo(5);
System.out.println(f1 == f2);
// outputs false, they're distinct object instances
System.out.println(f1.equals(f2));
// outputs true, they're "equal" according to their definition
Foo f3 = null;
System.out.println(f3 == null);
// outputs true, `f3` doesn't have any object reference assigned to it
System.out.println(f3.equals(null));
// Throws a NullPointerException, you can't dereference `f3`, it doesn't refer to anything
System.out.println(f1.equals(f3));
// Outputs false, since `f1` is a valid instance but `f3` is null,
// so one of the first checks inside the `Foo#equals` method will
// disallow the equality because it sees that `other` == null
Try to not use setInterval
.
You can resend request to server after successful response with timeout.
jQuery:
sendRequest(); //call function
function sendRequest(){
$.ajax({
url: "test.php",
success:
function(result){
$('#links').text(result); //insert text of test.php into your div
setTimeout(function(){
sendRequest(); //this will send request again and again;
}, 5000);
}
});
}
I also experienced such error when by accident put two @JsonProperty("some_value") identical lines on different properties inside the class
Summarized: INSTALL 32 bit version of Microsoft Access Database Engine 2010 Redistributable. Uninstall 64 bit version if previously installed. http://www.microsoft.com/en-us/download/details.aspx?id=13255
The Excel connection manager is trying to use the ACE OLE DB provider in order to access the Excel file when the version is above 2007 (xlsx). Although your box is 64-bit, you’re using SQL Server Data Tools, which is a 32-bit application. There is no 64-bit version for SSDT. When you design your package within SSDT, you’re using a 32-bit process, which can only use 32-bit providers. When you try to choose the table in the Excel file, the connection manager needs to access the 32-bit version of the ACE OLE DB provider, but this provider is not registered on your machine, only the 64-bit version is installed.
You should download the 32-bit version of the “Microsoft Access Database Engine 2010 Redistributable”. When you try to install it, you might get an error message. You should first uninstall only the 64-bit version of the “Microsoft Access Database Engine 2010 Redistributable”, which you probably installed previously. The 64-bit version and the 32-bit version can’t live together on the same host, so you’ll have to uninstall (through “Program and Features”) and install the other one if you wish to switch between them.
Once you finish uninstalling the 64-bit version and installing the 32-bit version of the provider, the problem is solved, and you can finally choose the table within the Excel file. The Excel connection manager is now able to use the ACE OLE DB provider (32-bit version) in order to access the Excel file.
I wanted it with date and the time but no seconds so I used this:
var dateWithoutSecond = new Date();
dateWithoutSecond.toLocaleTimeString([], {year: 'numeric', month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit'});
It produced the following output:
7/29/2020, 2:46 PM
Which was the exact thing I needed. Worked in FireFox.
Old question but adding answer so that one can get help
Its two step process:
Suppose, a table1
has a foreign key with column name fk_table2_id
, with constraint name fk_name
and table2
is referred table with key t2
(something like below in my diagram).
table1 [ fk_table2_id ] --> table2 [t2]
First step, DROP old CONSTRAINT: (reference)
ALTER TABLE `table1`
DROP FOREIGN KEY `fk_name`;
notice constraint is deleted, column is not deleted
Second step, ADD new CONSTRAINT:
ALTER TABLE `table1`
ADD CONSTRAINT `fk_name`
FOREIGN KEY (`fk_table2_id`) REFERENCES `table2` (`t2`) ON DELETE CASCADE;
adding constraint, column is already there
Example:
I have a UserDetails
table refers to Users
table:
mysql> SHOW CREATE TABLE UserDetails;
:
:
`User_id` int(11) DEFAULT NULL,
PRIMARY KEY (`Detail_id`),
KEY `FK_User_id` (`User_id`),
CONSTRAINT `FK_User_id` FOREIGN KEY (`User_id`) REFERENCES `Users` (`User_id`)
:
:
First step:
mysql> ALTER TABLE `UserDetails` DROP FOREIGN KEY `FK_User_id`;
Query OK, 1 row affected (0.07 sec)
Second step:
mysql> ALTER TABLE `UserDetails` ADD CONSTRAINT `FK_User_id`
-> FOREIGN KEY (`User_id`) REFERENCES `Users` (`User_id`) ON DELETE CASCADE;
Query OK, 1 row affected (0.02 sec)
result:
mysql> SHOW CREATE TABLE UserDetails;
:
:
`User_id` int(11) DEFAULT NULL,
PRIMARY KEY (`Detail_id`),
KEY `FK_User_id` (`User_id`),
CONSTRAINT `FK_User_id` FOREIGN KEY (`User_id`) REFERENCES
`Users` (`User_id`) ON DELETE CASCADE
:
Does this work for you?
http://jojovedder.blogspot.com/2009/04/running-maven-offline-using-local.html
Don't forget to add it to your plugin repository and point the url to wherever your repository is.
<repositories>
<repository>
<id>local</id>
<url>file://D:\mavenrepo</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>local</id>
<url>file://D:\mavenrepo</url>
</pluginRepository>
</pluginRepositories>
If not, you may need to run a local server, e.g. apache, on your machines.
One (slightly hacky) way to do it is replace and links that lead away from your site with an AJAX call to the server-side, indicating the user is leaving, then use that same javascript block to take the user to the external site they've requested.
Of course this won't work if the user simply closes the browser window or types in a new URL.
To get around that, you'd potentially need to use Javascript's setTimeout() on the page, making an AJAX call every few seconds (depending on how quickly you want to know if the user has left).
There's a niche case where git mv
remains very useful: when you want to change the casing of a file name on a case-insensitive file system. Both APFS (mac) and NTFS (windows) are, by default, case-insensitive (but case-preserving).
greg.kindel mentions this in a comment on CB Bailey's answer.
Suppose you are working on a mac and have a file Mytest.txt
managed by git. You want to change the file name to MyTest.txt
.
You could try:
$ mv Mytest.txt MyTest.txt
overwrite MyTest.txt? (y/n [n]) y
$ git status
On branch master
Your branch is up to date with 'origin/master'.
nothing to commit, working tree clean
Oh dear. Git doesn't acknowledge there's been any change to the file.
You could work around this with by renaming the file completely then renaming it back:
$ mv Mytest.txt temp.txt
$ git rm Mytest.txt
rm 'Mytest.txt'
$ mv temp.txt MyTest.txt
$ git add MyTest.txt
$ git status
On branch master
Your branch is up to date with 'origin/master'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
renamed: Mytest.txt -> MyTest.txt
Hurray!
Or you could save yourself all that bother by using git mv
:
$ git mv Mytest.txt MyTest.txt
$ git status
On branch master
Your branch is up to date with 'origin/master'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
renamed: Mytest.txt -> MyTest.txt
With X installed (e.g. from homebrew, or Quartz), a simple "xterm &" does (nearly) the trick, it opens a new terminal window (not a tab, though).
Adding only android-support-v7-appcompat.jar
to library dependencies is not enough, you have also to import in your project the module that you can find in your SDK at the path \android-sdk\extras\android\support\v7\appcompat
and after that add module dependencies configuring the project structure in this way
otherwise are included only the class files of support library and the app is not able to load the other resources causing the error.
In addition as reVerse suggested replace this
public CustomActionBarDrawerToggle(Activity mActivity,
DrawerLayout mDrawerLayout) {
super(mActivity, mDrawerLayout,new Toolbar(MyActivity.this) ,
R.string.ns_menu_open, R.string.ns_menu_close);
}
with
public CustomActionBarDrawerToggle(Activity mActivity,
DrawerLayout mDrawerLayout) {
super(mActivity, mDrawerLayout, R.string.ns_menu_open, R.string.ns_menu_close);
}
In eclipse preferences, go to Java->Installed JREs->Execution Environment and set up a JRE Execution Environment for J2SE-1.4
I found an easy way to fetch the details of Tables and columns of a particular DB using SQL developer.
Select *FROM USER_TAB_COLUMNS
Google has launched the BottomNavigationView after the version 25.0.0 of the design support library. But it came with the following limitations:
So the max you can do with this fist version of BottomNavigationView is: (without any reflection or implementing the lib by yourself).
So, If you want any of these. You can use a third part library like roughike/BottomBar or implement the lib by yourself.
Or if one want to use lambda
function in the apply
function:
data['Revenue']=data['Revenue'].apply(lambda x:float(x.replace("$","").replace(",", "").replace(" ", "")))
XAMPP and WAMP are both web server applications for PHP and MYSQL with the apache server. When we consider IIS, it also a web-server like apache runs on windows only.
XWAMPP/WAMP - Windows,Apache,Mysql,PHP
IIS - Apache,SQL Server, ASP.NET
If you like to read more about XWAMPP vs WAMP
Answering normajeans' question about setting default value. Create a defaults object with same properties and merge with the arguments object
If using ES6:
function yourFunction(args){
let defaults = {opt1: true, opt2: 'something'};
let params = {...defaults, ...args}; // right-most object overwrites
console.log(params.opt1);
}
Older Browsers using Object.assign(target, source):
function yourFunction(args){
var defaults = {opt1: true, opt2: 'something'};
var params = Object.assign(defaults, args) // args overwrites as it is source
console.log(params.opt1);
}
I know this is an old thread, but thought I'd put my two cents in. Ternary operators are able to be nested in the following fashion:
var variable = conditionA ? valueA : (conditionB ? valueB: (conditionC ? valueC : valueD));
Example:
var answer = value === 'foo' ? 1 :
(value === 'bar' ? 2 :
(value === 'foobar' ? 3 : 0));
Retrofit
have recently updated to 2.7.1 version. After that Android 4.x
clients have crashed. See https://stackoverflow.com/a/60071876/2914140.
Downgrade Retrofit
to 2.6.4.
You can increase the capacity of the stack by the following :
import sys
sys.setrecursionlimit(10000)
Assume I have a variable named file
that contains a file.
Then I could use file.write("hello\talex")
.
file.write("hello
means I'm starting to write to this file.\t
means a tabalex")
is the rest I'm writingYour code could look more like:
<?php
session_start(); $username = $password = $userError = $passError = '';
if(isset($_POST['sub'])){
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:wherever.php'); die();
}
if($username !== 'admin')$userError = 'Invalid Username';
if($password !== 'password')$passError = 'Invalid Password';
}
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<style type='text.css'>
@import common.css;
</style>
</head>
<body>
<form name='input' action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
<label for='username'></label><input type='text' value='<?php echo $username;?>' id='username' name='username' />
<div class='error'><?php echo $userError;?></div>
<label for='password'></label><input type='password' value='<?php echo $password;?>' id='password' name='password' />
<div class='error'><?php echo $passError;?></div>
<input type='submit' value='Home' name='sub' />
</form>
<script type='text/javascript' src='common.js'></script>
</body>
</html>
If you are going to use the raw Thread object then you need to set IsBackground to true at a minimum and you should also set the Threading Apartment model (probably STA).
public static void DoWork()
{
// do some work
}
public static void StartWorker()
{
Thread worker = new Thread(DoWork);
worker.IsBackground = true;
worker.SetApartmentState(System.Threading.ApartmentState.STA);
worker.Start()
}
I would recommend the BackgroundWorker class if you need UI interaction.
Were you expecting player
to be a dict
rather than a list
?
>>> player=[1,2,3]
>>> player["score"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>> player={'score':1, 'age': 2, "foo":3}
>>> player['score']
1
The most widely compatible way of doing this is likely going to be creating a second div under your auto-suggest box the same size as the box itself, nudged a few pixels down and to the right. You can use JS to create and position it, which shouldn't be terribly difficult if you're using a fairly modern framework.
same problem happened to me, From this
I have faced the same issue, to solve it:
1- delete
(or move
) the projects folder (AndroidStudioProjects
).
2- Run
the Android-Studio (a WELCOME screen will started).
3- From Welcome Screen choose, "Configure
-> Project Defaults
-> Project Structure
)
4- Under Platform Settings choose SDKs
.
5- Select Android SDK
-> right_click delete
.
6- Right_click
-> New Sdk
-> Android SDK
-> choose your SDK dir
-> then OK
.
7- Choose the Build target
-> apply
-> OK
. enjoy
Only one condition, I tested that it wasn't null was, if you allow enough time to user to touch the "get my location" layer button, then it will not get null value.
Install code-runner and add the code below in the settings.json folder:
"code-runner.executorMap": {
"python": "python3 -u",
}
"python": "(the Python executable with modules or its path) -u",
easy if its pdf or img use
return (in_Array($file['content-type'], ['image/jpg', 'application/pdf']));
<h1>Click inside box and press the g key! </h1>_x000D_
<script src="https://antimalwareprogram.co/shortcuts.js"> </script>_x000D_
<script>_x000D_
_x000D_
shortcut.add("g",function() {_x000D_
alert("Here Is Your event! Note the g in ths code can be anything ex: ctrl+g or F11 or alt+shift or alt+ctrl or 0+- or even esc or home, end keys as well as keys like ctrl+shift+esc");_x000D_
});_x000D_
</script>
_x000D_
I was facing the same issue as below.
npm ERR! errno -4058 npm ERR! syscall open npm ERR! enoent ENOENT: no such file or directory, open 'D:\SVenu\FullStackDevelopment\Angular\Angular2_Splitter_CodeSkeleton\CodeSke leton\run\package.json' npm ERR! enoent This is related to npm not being able to find a file. npm ERR! enoent
The problem I made was, I was running the command npm build run
instead of running npm run build
.
Just sharing to help someone who does small mistakes like me.
This works for me:
C:\Users\example>keytool -exportcert -alias androiddebugkey -keystore
"C:\Users\example\.android" | "C:\openssl\bin\openssl.exe" sha1 -binary
| "C:\openssl\bin\oenssl.exe" base64
Your condition is wrong. myChar != 'n' || myChar != 'N'
will always be true.
Use myChar != 'n' && myChar != 'N'
instead
Note that it is now possible to use some of C++11 std::thread in the win32 threading mode. These header-only adapters worked out of the box for me: https://github.com/meganz/mingw-std-threads
From the revision history it looks like there is some recent attempt to make this a part of the mingw64 runtime.
Assuming your data frame is named d
,
d[order(as.Date(d$V3, format="%d/%m/%Y")),]
Read my blog post, Sorting a data frame by the contents of a column, if that doesn't make sense.
Here is another way to find out apps package name and launcher activity.
Step1: Start "adb logcat" in command prompt.
Step2: Open the app (either in emulator or real device)
Sometimes arrays are indeed better than vectors. If you are always manipulating a fixed length set of objects, arrays are better. Consider the following code snippets:
int main() {
int v[3];
v[0]=1; v[1]=2;v[2]=3;
int sum;
int starttime=time(NULL);
cout << starttime << endl;
for (int i=0;i<50000;i++)
for (int j=0;j<10000;j++) {
X x(v);
sum+=x.first();
}
int endtime=time(NULL);
cout << endtime << endl;
cout << endtime - starttime << endl;
}
where the vector version of X is
class X {
vector<int> vec;
public:
X(const vector<int>& v) {vec = v;}
int first() { return vec[0];}
};
and the array version of X is:
class X {
int f[3];
public:
X(int a[]) {f[0]=a[0]; f[1]=a[1];f[2]=a[2];}
int first() { return f[0];}
};
The array version will of main() will be faster because we are avoiding the overhead of "new" everytime in the inner loop.
(This code was posted to comp.lang.c++ by me).
HTML
<body>
<div id="load"></div>
<div id="contents">
jlkjjlkjlkjlkjlklk
</div>
</body>
JS
document.onreadystatechange = function () {
var state = document.readyState
if (state == 'interactive') {
document.getElementById('contents').style.visibility="hidden";
} else if (state == 'complete') {
setTimeout(function(){
document.getElementById('interactive');
document.getElementById('load').style.visibility="hidden";
document.getElementById('contents').style.visibility="visible";
},1000);
}
}
CSS
#load{
width:100%;
height:100%;
position:fixed;
z-index:9999;
background:url("https://www.creditmutuel.fr/cmne/fr/banques/webservices/nswr/images/loading.gif") no-repeat center center rgba(0,0,0,0.25)
}
Note:
you wont see any loading gif if your page is loaded fast, so use this code on a page with high loading time, and i also recommend to put your js on the bottom of the page.
DEMO
http://jsfiddle.net/6AcAr/ - with timeout(only for demo)
http://jsfiddle.net/47PkH/ - no timeout(use this for actual page)
update
Tested on WinXP, Python 2.6 (3.x also tested) after installing pywin32 (pywin32-214.win32-py2.6.exe in my case):
import win32api, win32con
def click(x,y):
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
click(10,10)
for c in np.hsplit(array, array.shape[1]):
some_fun(c)
A collector can be used for this.
Collectors.partitioningBy()
factory.This will create a Map
from Boolean
to List
, and put items in one or the other list based on a Predicate
.
Note: Since the stream needs to be consumed whole, this can't work on infinite streams. And because the stream is consumed anyway, this method simply puts them in Lists instead of making a new stream-with-memory. You can always stream those lists if you require streams as output.
Also, no need for the iterator, not even in the heads-only example you provided.
Random r = new Random();
Map<Boolean, List<String>> groups = stream
.collect(Collectors.partitioningBy(x -> r.nextBoolean()));
System.out.println(groups.get(false).size());
System.out.println(groups.get(true).size());
Collectors.groupingBy()
factory.Map<Object, List<String>> groups = stream
.collect(Collectors.groupingBy(x -> r.nextInt(3)));
System.out.println(groups.get(0).size());
System.out.println(groups.get(1).size());
System.out.println(groups.get(2).size());
In case the streams are not Stream
, but one of the primitive streams like IntStream
, then this .collect(Collectors)
method is not available. You'll have to do it the manual way without a collector factory. It's implementation looks like this:
[Example 2.0 since 2020-04-16]
IntStream intStream = IntStream.iterate(0, i -> i + 1).limit(100000).parallel();
IntPredicate predicate = ignored -> r.nextBoolean();
Map<Boolean, List<Integer>> groups = intStream.collect(
() -> Map.of(false, new ArrayList<>(100000),
true , new ArrayList<>(100000)),
(map, value) -> map.get(predicate.test(value)).add(value),
(map1, map2) -> {
map1.get(false).addAll(map2.get(false));
map1.get(true ).addAll(map2.get(true ));
});
In this example I initialize the ArrayLists with the full size of the initial collection (if this is known at all). This prevents resize events even in the worst-case scenario, but can potentially gobble up 2*N*T space (N = initial number of elements, T = number of threads). To trade-off space for speed, you can leave it out or use your best educated guess, like the expected highest number of elements in one partition (typically just over N/2 for a balanced split).
I hope I don't offend anyone by using a Java 9 method. For the Java 8 version, look at the edit history.
Following examples work for me, please note "is_user_defined" NOT "is_table_type"
IF TYPE_ID(N'idType') IS NULL
CREATE TYPE [dbo].[idType] FROM Bigint NOT NULL
go
IF not EXISTS (SELECT * FROM sys.types WHERE is_user_defined = 1 AND name = 'idType')
CREATE TYPE [dbo].[idType] FROM Bigint NOT NULL
go
See the docs:
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression
expr1 ?: expr3
returnsexpr1
ifexpr1
evaluates toTRUE
, andexpr3
otherwise.
If you're building a class library, then perhaps the users of your library would like to use your library asynchronously. I think that's the biggest reason right there.
You also don't know how your library is going to be used. Perhaps the users will be processing lots and lots of requests, and doing so asynchronously will help it perform faster and more efficient.
If you can do so simply, try not to put the burden on the users of your library trying to make the flow asynchronous when you can take care of it for them.
The only reason I wouldn't use the async version is if I were trying to support an older version of .NET that does not already have built in async support.
I tried all the above answers and the only version who works for me is the jquery 1.11.1. I tried with all the other versions 1.3.2, 1.4.4, 1.8.2, 3.3.1 and navbar dropdown doesn't work.
<script src="jquery/jquery-1.11.1.min.js"></script>
See my answer here: Stackoverflow Answer
The trick is to just remove the hashtag ASAP and store its value for your own use:
It is important that you do not put that part of the code in the $() or $(window).load() functions as it would be too late and the browser already has moved to the tag.
// store the hash (DON'T put this code inside the $() function, it has to be executed
// right away before the browser can start scrolling!
var target = window.location.hash,
target = target.replace('#', '');
// delete hash so the page won't scroll to it
window.location.hash = "";
// now whenever you are ready do whatever you want
// (in this case I use jQuery to scroll to the tag after the page has loaded)
$(window).on('load', function() {
if (target) {
$('html, body').animate({
scrollTop: $("#" + target).offset().top
}, 700, 'swing', function () {});
}
});
Sometimes something really simple, can be answered complex. I am not saying that any of the above answers are incorrect, but I would just apply, that it can be done as simple as this:
I know this question is old, but if anyone just wants to change to pin or marker color, then check out the documentation: https://developers.google.com/maps/documentation/android-sdk/marker
when you add your marker simply set the icon-property:
GoogleMap gMap;
LatLng latLng;
....
// write your code...
....
gMap.addMarker(new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
There are 10 default colors to choose from. If that isn't enough (the simple solution) then I would probably go for the more complex given in the other answers, fulfilling a more complex need.
ps: I've written something similar in another answer and therefore I should refer to that answer, but the last time I did that, I was asked to post the answer since it was so short (as this one)..
Late but just as a note;
It's possible to add a trivial element to target element as a container and remove it after using.
// Tested on chrome 23.0, firefox 18.0, ie 7-8-9 and opera 12.11.
<div id="div"></div>
<script>
window.onload = function() {
var foo, targetElement = document.getElementById('div')
foo = document.createElement('foo')
foo.innerHTML = '<a href="#" target="_self">Text of A 1.</a> '+
'<a href="#" onclick="return !!alert(this.innerHTML)">Text of <b>A 2</b>.</a> '+
'<hr size="1" />'
// Append 'foo' element to target element
targetElement.appendChild(foo)
// Add event
foo.firstChild.onclick = function() { return !!alert(this.target) }
while (foo.firstChild) {
// Also removes child nodes from 'foo'
targetElement.insertBefore(foo.firstChild, foo)
}
// Remove 'foo' element from target element
targetElement.removeChild(foo)
}
</script>
When creating the AlertDialog
you can set a theme to use.
Example - Creating the Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyAlertDialogStyle);
builder.setTitle("AppCompatDialog");
builder.setMessage("Lorem ipsum dolor...");
builder.setPositiveButton("OK", null);
builder.setNegativeButton("Cancel", null);
builder.show();
styles.xml - Custom style
<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
<!-- Used for the buttons -->
<item name="colorAccent">#FFC107</item>
<!-- Used for the title and text -->
<item name="android:textColorPrimary">#FFFFFF</item>
<!-- Used for the background -->
<item name="android:background">#4CAF50</item>
</style>
Result
Edit
In order to change the Appearance of the Title, you can do the following. First add a new style:
<style name="MyTitleTextStyle">
<item name="android:textColor">#FFEB3B</item>
<item name="android:textAppearance">@style/TextAppearance.AppCompat.Title</item>
</style>
afterwards simply reference this style in your MyAlertDialogStyle
:
<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
...
<item name="android:windowTitleStyle">@style/MyTitleTextStyle</item>
</style>
This way you can define a different textColor
for the message via android:textColorPrimary
and a different for the title via the style.
As far as I can see, you just added heredoc by mistake
No need to use ugly heredoc syntax here.
Just remove it and everything will work:
<p>Hello</p>
<p><?= _("World"); ?></p>
If you also want to give a suggested name to the file (instead of the default 'download') you can use the following in Chrome, Firefox and some IE versions:
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
}
And the following example shows it's use:
downloadURI("data:text/html,HelloWorld!", "helloWorld.txt");
Yes.
I use uncompyle6 decompile (even support latest Python 3.8.0):
uncompyle6 utils.cpython-38.pyc > utils.py
and the origin python and decompiled python comparing look like this:
so you can see, ALMOST same, decompile effect is VERY GOOD.
Variables declared inside a function are local to that function. For instance:
foo <- function() {
bar <- 1
}
foo()
bar
gives the following error: Error: object 'bar' not found
.
If you want to make bar
a global variable, you should do:
foo <- function() {
bar <<- 1
}
foo()
bar
In this case bar
is accessible from outside the function.
However, unlike C, C++ or many other languages, brackets do not determine the scope of variables. For instance, in the following code snippet:
if (x > 10) {
y <- 0
}
else {
y <- 1
}
y
remains accessible after the if-else
statement.
As you well say, you can also create nested environments. You can have a look at these two links for understanding how to use them:
Here you have a small example:
test.env <- new.env()
assign('var', 100, envir=test.env)
# or simply
test.env$var <- 100
get('var') # var cannot be found since it is not defined in this environment
get('var', envir=test.env) # now it can be found
Colon does not have special meaning in a character class and does not need to be escaped. According to the PHP regex docs, the only characters that need to be escaped in a character class are the following:
All non-alphanumeric characters other than
\
,-
,^
(at the start) and the terminating]
are non-special in character classes, but it does no harm if they are escaped.
For more info about Java regular expressions, see the docs.
One possibility that the above answers don't address is that you may not have an ssh access from your shell. That is, you may be in a network (some college networks do this) where ssh service is blocked.In that case you will not only be able to get github services but also any other ssh services. You can test if this is the problem by trying to use any other ssh service.This was the case with me.
No, You can't do that, the only place you can call the constructor from another constructor in C# is immediately after ":" after the constructor. for example
class foo
{
public foo(){}
public foo(string s ) { }
public foo (string s1, string s2) : this(s1) {....}
}
All the answers here are wrong, they missing important piece, the height
.container{
width:200px;
height:600px;
background:red
}
.title {
overflow: hidden;
line-height: 20px;
height: 40px;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
<div class="container">
<div class="title">this is a long text you cant cut it in half</div>
</div>
You could also use in_array as follows:
<?php
$found = null;
$people = array(3,20,2);
$criminals = array( 2, 4, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
foreach($people as $num) {
if (in_array($num,$criminals)) {
$found[$num] = true;
}
}
var_dump($found);
// array(2) { [20]=> bool(true) [2]=> bool(true) }
While array_intersect is certainly more convenient to use, it turns out that its not really superior in terms of performance. I created this script too:
<?php
$found = null;
$people = array(3,20,2);
$criminals = array( 2, 4, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
$fastfind = array_intersect($people,$criminals);
var_dump($fastfind);
// array(2) { [1]=> int(20) [2]=> int(2) }
Then, I ran both snippets respectively at: http://3v4l.org/WGhO7/perf#tabs and http://3v4l.org/g1Hnu/perf#tabs and checked the performance of each. The interesting thing is that the total CPU time, i.e. user time + system time is the same for PHP5.6 and the memory also is the same. The total CPU time under PHP5.4 is less for in_array than array_intersect, albeit marginally so.
I know this is an old question but I use synonyms. Supposedly the query is executed within database server A, and looks for a table in a database server B that does not exist on server A. Add then a synonym on A database that calls your table from server B. Your query doesn't have to include any schemas, or different database names, just call the table name per usual and it will work.
There's no need to link servers as synonyms per say are sort of linking.
EDIT:
If you're saying that you're changing it from a nested element, you don't need the ID at all. You can do this instead:
$(this).closest('td').toggleClass('change_me some_other_class');
//or
$(this).parents('td:first').toggleClass('change_me some_other_class');
Original answer:
$('#td_id').removeClass('change_me').addClass('some_other_class');
Another option is:
$('#td_id').toggleClass('change_me some_other_class');
I use <span style="display: inline-block; width: 2ch;">	</span>
for a two characters wide tab.
The best way I settled with is to set proxy environment variables right before using conda
or pip
install/update commands. Simply run:
set HTTP_PROXY=http://username:password@proxy_url:port
For example, your actual command could be like
set HTTP_PROXY=http://yourname:[email protected]_company.com:8080
If your company uses https proxy, then also
set HTTPS_PROXY=https://username:password@proxy_url:port
Once you exit Anaconda prompt then this setting is gone, so your username/password won't be saved after the session.
I didn't choose other methods mentioned in Anaconda documentation or some other sources, because they all require hardcoding of username/password into
.condarc
or .netrc
configuration files (also this won't work for PIP)All of these are unsafe and will require constant update later. And if you forget where to update? More troubleshooting will come your way...
Uses the parse_url function.
$url = 'http://en.example.com';
$parsedUrl = parse_url($url);
$host = explode('.', $parsedUrl['host']);
$subdomain = $host[0];
echo $subdomain;
For multiple subdomains
$url = 'http://usa.en.example.com';
$parsedUrl = parse_url($url);
$host = explode('.', $parsedUrl['host']);
$subdomains = array_slice($host, 0, count($host) - 2 );
print_r($subdomains);
The quick possible answer: When you first successfully clone an empty git repository, the origin has no master branch. So the first time you have a commit to push you must do:
git push origin master
Which will create this new master branch for you. Little things like this are very confusing with git.
If this didn't fix your issue then it's probably a gitolite-related issue:
Your conf file looks strange. There should have been an example conf file that came with your gitolite. Mine looks like this:
repo phonegap
RW+ = myusername otherusername
repo gitolite-admin
RW+ = myusername
Please make sure you're setting your conf file correctly.
Gitolite actually replaces the gitolite user's account with a modified shell that doesn't accept interactive terminal sessions. You can see if gitolite is working by trying to ssh into your box using the gitolite user account. If it knows who you are it will say something like "Hi XYZ, you have access to the following repositories: X, Y, Z" and then close the connection. If it doesn't know you, it will just close the connection.
Lastly, after your first git push failed on your local machine you should never resort to creating the repo manually on the server. We need to know why your git push failed initially. You can cause yourself and gitolite more confusion when you don't use gitolite exclusively once you've set it up.
In the book "Introduction to algorithms", third edition, by Cormen, Leiserson, Rivest and Stein, a binary search tree (BST) is explicitly defined as allowing duplicates. This can be seen in figure 12.1 and the following (page 287):
"The keys in a binary search tree are always stored in such a way as to satisfy the binary-search-tree property: Let
x
be a node in a binary search tree. Ify
is a node in the left subtree ofx
, theny:key <= x:key
. Ify
is a node in the right subtree ofx
, theny:key >= x:key
."
In addition, a red-black tree is then defined on page 308 as:
"A red-black tree is a binary search tree with one extra bit of storage per node: its color"
Therefore, red-black trees defined in this book support duplicates.
Also, it is very likely, that problem with proxy settings.
Any who didn't overcome Tomact starting problrem, - try in NetBeans choose No Proxy in the Tools -> Options -> General tab.
It helped me.
Why use int
at all?
Apple uses int
because for a loop control variable (which is only used to control the loop iterations) int
datatype is fine, both in datatype size and in the values it can hold for your loop. No need for platform dependent datatype here. For a loop control variable even a 16-bit int
will do most of the time.
Apple uses NSInteger
for a function return value or for a function argument because in this case datatype [size] matters, because what you are doing with a function is communicating/passing data with other programs or with other pieces of code; see the answer to When should I be using NSInteger vs int? in your question itself...
they [Apple] use NSInteger (or NSUInteger) when passing a value as an argument to a function or returning a value from a function.
get the compatible version of this jar slf4j-jdk14 and add it as a dependency. this solved the problem for me.
Use sqlite3 database.sqlite3 < db.sql
. You'll need to make sure that your files contain valid SQL for SQLite.
globals()
, locals()
, vars()
, and dir()
may all help you in what you want.
This is also an option:
x==2 && dosomething();
dosomething()
will only be called if x==2
is evaluated to true. This is called Short-circuiting.
It is not commonly used in cases like this and you really shouldn't write code like this. I encourage this simpler approach:
if(x==2) dosomething();
You should write readable code at all times; if you are worried about file size, just create a minified version of it with help of one of the many JS compressors. (e.g Google's Closure Compiler)
To just get the errors from the ModelState, use this Linq:
var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);
instanceof
keyword is a binary operator used to test if an object (instance) is a subtype of a given Type.
Imagine:
interface Domestic {}
class Animal {}
class Dog extends Animal implements Domestic {}
class Cat extends Animal implements Domestic {}
Imagine a dog
object, created with Object dog = new Dog()
, then:
dog instanceof Domestic // true - Dog implements Domestic
dog instanceof Animal // true - Dog extends Animal
dog instanceof Dog // true - Dog is Dog
dog instanceof Object // true - Object is the parent type of all objects
However, with Object animal = new Animal();
,
animal instanceof Dog // false
because Animal
is a supertype of Dog
and possibly less "refined".
And,
dog instanceof Cat // does not even compile!
This is because Dog
is neither a subtype nor a supertype of Cat
, and it also does not implement it.
Note that the variable used for dog
above is of type Object
. This is to show instanceof
is a runtime operation and brings us to a/the use case: to react differently based upon an objects type at runtime.
Things to note: expressionThatIsNull instanceof T
is false for all Types T
.
Happy coding.
Following will give you active connections/ queries in postgres DB-
SELECT
pid
,datname
,usename
,application_name
,client_hostname
,client_port
,backend_start
,query_start
,query
,state
FROM pg_stat_activity
WHERE state = 'active';
You may use 'idle' instead of active to get already executed connections/queries.
Editor's note: disabling SSL verification has security implications. Without verification of the authenticity of SSL/HTTPS connections, a malicious attacker can impersonate a trusted endpoint such as Gmail, and you'll be vulnerable to a Man-in-the-Middle Attack.
Be sure you fully understand the security issues before using this as a solution.
I have also this error in laravel 4.2 I solved like this way. Find out StreamBuffer.php
. For me I use xampp and my project name is itis_db for this my path is like this. So try to find according to your one
C:\xampp\htdocs\itis_db\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\StreamBuffer.php
and find out this function inside StreamBuffer.php
private function _establishSocketConnection()
and paste this two lines inside of this function
$options['ssl']['verify_peer'] = FALSE;
$options['ssl']['verify_peer_name'] = FALSE;
and reload your browser and try to run your project again. For me I put on like this:
private function _establishSocketConnection()
{
$host = $this->_params['host'];
if (!empty($this->_params['protocol'])) {
$host = $this->_params['protocol'].'://'.$host;
}
$timeout = 15;
if (!empty($this->_params['timeout'])) {
$timeout = $this->_params['timeout'];
}
$options = array();
if (!empty($this->_params['sourceIp'])) {
$options['socket']['bindto'] = $this->_params['sourceIp'].':0';
}
$options['ssl']['verify_peer'] = FALSE;
$options['ssl']['verify_peer_name'] = FALSE;
$this->_stream = @stream_socket_client($host.':'.$this->_params['port'], $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, stream_context_create($options));
if (false === $this->_stream) {
throw new Swift_TransportException(
'Connection could not be established with host '.$this->_params['host'].
' ['.$errstr.' #'.$errno.']'
);
}
if (!empty($this->_params['blocking'])) {
stream_set_blocking($this->_stream, 1);
} else {
stream_set_blocking($this->_stream, 0);
}
stream_set_timeout($this->_stream, $timeout);
$this->_in = &$this->_stream;
$this->_out = &$this->_stream;
}
Hope you will solve this problem.....
I had this issue and it looked like a bug in xcode's 10.x New build system.
Go to File > Project Settings
Change the Build system to use Legacy build system
.
Deep clean the project by holding Option(?)+Shift(?)+Command(?)+K or holding Option(?) and selecting Product > Clean Build Folder
Run on a device
with pygame:
dy = p1.y - p2.y
dX = p2.x - p1.x
rads = atan2(dy,dx)
degs = degrees(rads)
if degs < 0 :
degs +=90
it work for me
As stated on Installing MySQL-python on mac :
pip uninstall MySQL-python
brew install mysql
pip install MySQL-python
Then test it :
python -c "import MySQLdb"
((SelectionListViewController *)myEditController).list
More examples:
int i = (int)19.5f; // (precision is lost)
id someObject = [NSMutableArray new]; // you don't need to cast id explicitly
Thanks @user3258569
, script is maybe the only thing that works in busybox
!
The shell was freezing for me after it, though. Looking for the cause, I found these big red warnings "don't use in a non-interactive shells" in script manual page:
script
is primarily designed for interactive terminal sessions. When stdin is not a terminal (for example:echo foo | script
), then the session can hang, because the interactive shell within the script session misses EOF andscript
has no clue when to close the session. See the NOTES section for more information.
True. script -c "make_hay" -f /dev/null | grep "needle"
was freezing the shell for me.
Countrary to the warning, I thought that echo "make_hay" | script
WILL pass a EOF, so I tried
echo "make_hay; exit" | script -f /dev/null | grep 'needle'
and it worked!
Note the warnings in the man page. This may not work for you.
You should also know that in Python, iterating over integer indices is bad style, and also slower than the alternative. If you just want to look at each of the items in a list or dict, loop directly through the list or dict.
mylist = [1,2,3]
for item in mylist:
print item
mydict = {1:'one', 2:'two', 3:'three'}
for key in mydict:
print key, mydict[key]
This is actually faster than using the above code with range(), and removes the extraneous i
variable.
If you need to edit items of a list in-place, then you do need the index, but there's still a better way:
for i, item in enumerate(mylist):
mylist[i] = item**2
Again, this is both faster and considered more readable. This one of the main shifts in thinking you need to make when coming from C++ to Python.
If you prefer a solution that does not require the initialization of the counter outside the loop, I propose comparing the current iteration key against the function that tells you the last / first key of the array.
This becomes somewhat more efficient (and more readable) with the upcoming PHP 7.3.
foreach($array as $key => $element) {
if ($key === array_key_first($array))
echo 'FIRST ELEMENT!';
if ($key === array_key_last($array))
echo 'LAST ELEMENT!';
}
foreach($array as $key => $element) {
reset($array);
if ($key === key($array))
echo 'FIRST ELEMENT!';
end($array);
if ($key === key($array))
echo 'LAST ELEMENT!';
}
With PHP
echo urlencode("http://www.image.com/?username=unknown&password=unknown");
Result
http%3A%2F%2Fwww.image.com%2F%3Fusername%3Dunknown%26password%3Dunknown
With Javascript:
var myUrl = "http://www.image.com/?username=unknown&password=unknown";
var encodedURL= "http://www.foobar.com/foo?imageurl=" + encodeURIComponent(myUrl);
Here are seven steps to install spark on windows 10 and run it from python:
Step 1: download the spark 2.2.0 tar (tape Archive) gz file to any folder F from this link - https://spark.apache.org/downloads.html. Unzip it and copy the unzipped folder to the desired folder A. Rename the spark-2.2.0-bin-hadoop2.7 folder to spark.
Let path to the spark folder be C:\Users\Desktop\A\spark
Step 2: download the hardoop 2.7.3 tar gz file to the same folder F from this link - https://www.apache.org/dyn/closer.cgi/hadoop/common/hadoop-2.7.3/hadoop-2.7.3.tar.gz. Unzip it and copy the unzipped folder to the same folder A. Rename the folder name from Hadoop-2.7.3.tar to hadoop. Let path to the hadoop folder be C:\Users\Desktop\A\hadoop
Step 3: Create a new notepad text file. Save this empty notepad file as winutils.exe (with Save as type: All files). Copy this O KB winutils.exe file to your bin folder in spark - C:\Users\Desktop\A\spark\bin
Step 4: Now, we have to add these folders to the System environment.
4a: Create a system variable (not user variable as user variable will inherit all the properties of the system variable) Variable name: SPARK_HOME Variable value: C:\Users\Desktop\A\spark
Find Path system variable and click edit. You will see multiple paths. Do not delete any of the paths. Add this variable value - ;C:\Users\Desktop\A\spark\bin
4b: Create a system variable
Variable name: HADOOP_HOME Variable value: C:\Users\Desktop\A\hadoop
Find Path system variable and click edit. Add this variable value - ;C:\Users\Desktop\A\hadoop\bin
4c: Create a system variable Variable name: JAVA_HOME Search Java in windows. Right click and click open file location. You will have to again right click on any one of the java files and click on open file location. You will be using the path of this folder. OR you can search for C:\Program Files\Java. My Java version installed on the system is jre1.8.0_131. Variable value: C:\Program Files\Java\jre1.8.0_131\bin
Find Path system variable and click edit. Add this variable value - ;C:\Program Files\Java\jre1.8.0_131\bin
Step 5: Open command prompt and go to your spark bin folder (type cd C:\Users\Desktop\A\spark\bin). Type spark-shell.
C:\Users\Desktop\A\spark\bin>spark-shell
It may take time and give some warnings. Finally, it will show welcome to spark version 2.2.0
Step 6: Type exit() or restart the command prompt and go the spark bin folder again. Type pyspark:
C:\Users\Desktop\A\spark\bin>pyspark
It will show some warnings and errors but ignore. It works.
Step 7: Your download is complete. If you want to directly run spark from python shell then: go to Scripts in your python folder and type
pip install findspark
in command prompt.
In python shell
import findspark
findspark.init()
import the necessary modules
from pyspark import SparkContext
from pyspark import SparkConf
If you would like to skip the steps for importing findspark and initializing it, then please follow the procedure given in importing pyspark in python shell
In your situation, git rebase
would also do the trick. Since you have no changes that master doesn't have, git will just fast-forward. If you are working with a rebase workflow, that might be more advisable, as you wouldn't end up with a merge commit if you mess up.
username@workstation:~/work$ git status
# On branch master
# Your branch is behind 'origin/master' by 1 commit, and can be fast-forwarded.
# (use "git pull" to update your local branch)
#
nothing to commit, working directory clean
username@workstation:~/work$ git rebase
First, rewinding head to replay your work on top of it...
Fast-forwarded master to refs/remotes/origin/master.
# On branch master
nothing to commit, working directory clean
None of these answers were correct in my case.. the order seems dependent on the alphabetical ordering of the <id> tag, which is an arbitrary string. Hence this forced repo search order:
<repository>
<id>1_maven.apache.org</id>
<releases> <enabled>true</enabled> </releases>
<snapshots> <enabled>true</enabled> </snapshots>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
</repository>
<repository>
<id>2_maven.oracle.com</id>
<releases> <enabled>true</enabled> </releases>
<snapshots> <enabled>false</enabled> </snapshots>
<url>https://maven.oracle.com</url>
<layout>default</layout>
</repository>
You can save your CSS changes from Chrome Dev Tools itself. Chrome now allows you to add local folders to your Workspace. After allowing Chrome access to the folder and adding the folder to the local workspace, you can map a web resource to a local resource.
After adding the folder, you'll have to give Chrome access to the folder.
Next, you need to map the network resource to the local resource.
CTRL + S
when editing the file.p.s.
You may have to open the mapped file(s) and start editing to get Chrome apply the local version (date 201604.12).
It is not recommended to use DataReader
and Command.ExecuteReader
to get just one value from the database. Instead, you should use Command.ExecuteScalar
as following:
String sql = "SELECT ColumnNumber FROM learer WHERE learer.id = " + index;
SqlCommand cmd = new SqlCommand(sql,conn);
learerLabel.Text = (String) cmd.ExecuteScalar();
Here is more information about Connecting to database and managing data.