Easiest way to clear/reset the text field on click is to clear/reset the scope
<input type="text" class="form-control" ng-model="searchAll" ng-click="clearfunction(this)"/>
In Controller
$scope.clearfunction=function(event){
event.searchAll=null;
}
I got this one in my project.
div > .b ~ .b:not(:first-child) {_x000D_
background: none;_x000D_
}_x000D_
div > .b {_x000D_
background: red;_x000D_
}
_x000D_
<div>_x000D_
<p class="a">The first paragraph.</p>_x000D_
<p class="a">The second paragraph.</p>_x000D_
<p class="b">The third paragraph.</p>_x000D_
<p class="b">The fourth paragraph.</p>_x000D_
</div>
_x000D_
That's a half-open interval.
[a,b]
includes the end points.(a,b)
excludes them.In your case the end-point at the start of the interval is included, but the end is excluded. So it means the interval "first1 <= x < last1".
Half-open intervals are useful in programming because they correspond to the common idiom for looping:
for (int i = 0; i < n; ++i) { ... }
Here i is in the range [0, n).
Dynamic resources can only be used when property being set is on object which is derived from dependency object or freezable where as static resources can be used anywhere. You can abstract away entire control using static resources.
Static resources are used under following circumstances:
Dynamic resources:
I had a similar problem what worked for me was to set JAVA_HOME. I tired it first in R:
Sys.setenv(JAVA_HOME = "C:/Program Files/Java/jdk1.8.0_101/")
And when it actually worked I set it in
System Properties -> Advanced -> Environment Variables
by adding a new System variable. I then restarted R/RStudio and everything worked.
Which specific index? If you want 'Add New' to be first on the dropdownlist you can add it though the code like this:
<asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server">
<asp:ListItem Text="Add New" Value="0" />
</asp:DropDownList>
If you want to add it at a different index, maybe the last then try:
ListItem lst = new ListItem ( "Add New" , "0" );
DropDownList1.Items.Insert( DropDownList1.Items.Count-1 ,lst);
The idea of a linear index for arrays in matlab is an important one. An array in MATLAB is really just a vector of elements, strung out in memory. MATLAB allows you to use either a row and column index, or a single linear index. For example,
A = magic(3)
A =
8 1 6
3 5 7
4 9 2
A(2,3)
ans =
7
A(8)
ans =
7
We can see the order the elements are stored in memory by unrolling the array into a vector.
A(:)
ans =
8
3
4
1
5
9
6
7
2
As you can see, the 8th element is the number 7. In fact, the function find returns its results as a linear index.
find(A>6)
ans =
1
6
8
The result is, we can access each element in turn of a general n-d array using a single loop. For example, if we wanted to square the elements of A (yes, I know there are better ways to do this), one might do this:
B = zeros(size(A));
for i = 1:numel(A)
B(i) = A(i).^2;
end
B
B =
64 1 36
9 25 49
16 81 4
There are many circumstances where the linear index is more useful. Conversion between the linear index and two (or higher) dimensional subscripts is accomplished with the sub2ind and ind2sub functions.
The linear index applies in general to any array in matlab. So you can use it on structures, cell arrays, etc. The only problem with the linear index is when they get too large. MATLAB uses a 32 bit integer to store these indexes. So if your array has more then a total of 2^32 elements in it, the linear index will fail. It is really only an issue if you use sparse matrices often, when occasionally this will cause a problem. (Though I don't use a 64 bit MATLAB release, I believe that problem has been resolved for those lucky individuals who do.)
The recommended approach in this case is to sort the data in the database, adding an ORDER BY
at the end of the query that fetches the results, something like this:
SELECT temperature FROM temperatures ORDER BY temperature ASC; -- ascending order
SELECT temperature FROM temperatures ORDER BY temperature DESC; -- descending order
If for some reason that is not an option, you can change the sorting order like this in Python:
templist = [25, 50, 100, 150, 200, 250, 300, 33]
sorted(templist, key=int) # ascending order
> [25, 33, 50, 100, 150, 200, 250, 300]
sorted(templist, key=int, reverse=True) # descending order
> [300, 250, 200, 150, 100, 50, 33, 25]
As has been pointed in the comments, the int
key (or float
if values with decimals are being stored) is required for correctly sorting the data if the data received is of type string
, but it'd be very strange to store temperature values as strings, if that is the case, go back and fix the problem at the root, and make sure that the temperatures being stored are numbers.
1) What is the difference between awk and sed ?
Both are tools that transform text. BUT awk can do more things besides just manipulating text. Its a programming language by itself with most of the things you learn in programming, like arrays, loops, if/else flow control etc You can "program" in sed as well, but you won't want to maintain the code written in it.
2) What kind of application are best use cases for sed and awk tools ?
Conclusion: Use sed for very simple text parsing. Anything beyond that, awk is better. In fact, you can ditch sed altogether and just use awk. Since their functions overlap and awk can do more, just use awk. You will reduce your learning curve as well.
Nevermind. I was making this way more complicated than it really needed to be.
This was all that I needed. The rename methods just generate a call to the sp_rename system stored procedure and I guess that took care of everything, including the foreign keys with the new column name.
public override void Up()
{
RenameTable("ReportSections", "ReportPages");
RenameTable("ReportSectionGroups", "ReportSections");
RenameColumn("ReportPages", "Group_Id", "Section_Id");
}
public override void Down()
{
RenameColumn("ReportPages", "Section_Id", "Group_Id");
RenameTable("ReportSections", "ReportSectionGroups");
RenameTable("ReportPages", "ReportSections");
}
Promise.all
is all or nothing. It resolves once all promises in the array resolve, or reject as soon as one of them rejects. In other words, it either resolves with an array of all resolved values, or rejects with a single error.
Some libraries have something called Promise.when
, which I understand would instead wait for all promises in the array to either resolve or reject, but I'm not familiar with it, and it's not in ES6.
Your code
I agree with others here that your fix should work. It should resolve with an array that may contain a mix of successful values and errors objects. It's unusual to pass error objects in the success-path but assuming your code is expecting them, I see no problem with it.
The only reason I can think of why it would "not resolve" is that it's failing in code you're not showing us and the reason you're not seeing any error message about this is because this promise chain is not terminated with a final catch (as far as what you're showing us anyway).
I've taken the liberty of factoring out the "existing chain" from your example and terminating the chain with a catch. This may not be right for you, but for people reading this, it's important to always either return or terminate chains, or potential errors, even coding errors, will get hidden (which is what I suspect happened here):
Promise.all(state.routes.map(function(route) {
return route.handler.promiseHandler().catch(function(err) {
return err;
});
}))
.then(function(arrayOfValuesOrErrors) {
// handling of my array containing values and/or errors.
})
.catch(function(err) {
console.log(err.message); // some coding error in handling happened
});
If is ok for you to index the array you can do this:
<form>
<input type="text" class="form-control" placeholder="Titel" name="levels[0][level]">
<input type="text" class="form-control" placeholder="Titel" name="levels[0][build_time]">
<input type="text" class="form-control" placeholder="Titel" name="levels[1][level]">
<input type="text" class="form-control" placeholder="Titel" name="levels[1][build_time]">
<input type="text" class="form-control" placeholder="Titel" name="levels[2][level]">
<input type="text" class="form-control" placeholder="Titel" name="levels[2][build_time]">
</form>
... to achieve that:
[levels] => Array (
[0] => Array (
[level] => 1
[build_time] => 2
)
[1] => Array (
[level] => 234
[build_time] => 456
)
[2] => Array (
[level] => 111
[build_time] => 222
)
)
But if you remove one pair of inputs (dynamically, I suppose) from the middle of the form then you'll get holes in your array, unless you update the input names...
The cleanest fastest way:
processAlreadyRunning () {
process="$(basename "${0}")"
pidof -x "${process}" -o $$ &>/dev/null
}
n=int(input())
pair = dict()
for i in range(0,n):
word = input().split()
key = word[0]
value = word[1]
pair[key]=value
print(pair)
The method to call has changed in .NET Standard (as of 1.6). Also we can use C# 6's null conditional operator.
using System.Reflection;
public static object GetPropValue(object src, string propName)
{
return src.GetType().GetRuntimeProperty(propName)?.GetValue(src);
}
It's 2020 and stuffs had greatly evolved with php 7.4 and opcache.
Here is the OP^ benchmark, ran as unix CLI, without the echo and html parts.
Test ran locally on a regular computer.
php -v
PHP 7.4.6 (cli) (built: May 14 2020 10:02:44) ( NTS )
Modified benchmark script:
<?php
## preperations; just a simple environment state
$test_iterations = 100;
$test_arr_size = 1000;
// a shared function that makes use of the loop; this should
// ensure no funny business is happening to fool the test
function test($input)
{
//echo '<!-- '.trim($input).' -->';
}
// for each test we create a array this should avoid any of the
// arrays internal representation or optimizations from getting
// in the way.
// normal array
$test_arr1 = array();
$test_arr2 = array();
$test_arr3 = array();
// hash tables
$test_arr4 = array();
$test_arr5 = array();
for ($i = 0; $i < $test_arr_size; ++$i)
{
mt_srand();
$hash = md5(mt_rand());
$key = substr($hash, 0, 5).$i;
$test_arr1[$i] = $test_arr2[$i] = $test_arr3[$i] = $test_arr4[$key] = $test_arr5[$key]
= $hash;
}
## foreach
$start = microtime(true);
for ($j = 0; $j < $test_iterations; ++$j)
{
foreach ($test_arr1 as $k => $v)
{
test($v);
}
}
echo 'foreach '.(microtime(true) - $start)."\n";
## foreach (using reference)
$start = microtime(true);
for ($j = 0; $j < $test_iterations; ++$j)
{
foreach ($test_arr2 as &$value)
{
test($value);
}
}
echo 'foreach (using reference) '.(microtime(true) - $start)."\n";
## for
$start = microtime(true);
for ($j = 0; $j < $test_iterations; ++$j)
{
$size = count($test_arr3);
for ($i = 0; $i < $size; ++$i)
{
test($test_arr3[$i]);
}
}
echo 'for '.(microtime(true) - $start)."\n";
## foreach (hash table)
$start = microtime(true);
for ($j = 0; $j < $test_iterations; ++$j)
{
foreach ($test_arr4 as $k => $v)
{
test($v);
}
}
echo 'foreach (hash table) '.(microtime(true) - $start)."\n";
## for (hash table)
$start = microtime(true);
for ($j = 0; $j < $test_iterations; ++$j)
{
$keys = array_keys($test_arr5);
$size = sizeOf($test_arr5);
for ($i = 0; $i < $size; ++$i)
{
test($test_arr5[$keys[$i]]);
}
}
echo 'for (hash table) '.(microtime(true) - $start)."\n";
Output:
foreach 0.0032877922058105
foreach (using reference) 0.0029420852661133
for 0.0025191307067871
foreach (hash table) 0.0035080909729004
for (hash table) 0.0061779022216797
As you can see the evolution is insane, about 560 time faster than reported in 2012.
On my machines and servers, following my numerous experiments, basics for loops are the fastest. This is even clearer using nested loops ($i $j $k..)
It is also the most flexible in usage, and has a better readability from my view.
write the code that you want to be executed inside this. When your document is ready, this will be executed.
$(document).ready(function() {
});
Use padding
on the cells and border-spacing
on the table. The former will give you cellpadding while the latter will give you cellspacing.
table { border-spacing: 5px; } /* cellspacing */
th, td { padding: 5px; } /* cellpadding */
I did not want to add style to <body>
tag and <html>
tag.
.quodrant{
width: 100%;
height: 100vh;
margin: 0;
padding: 0;
}
.qtop,
.qbottom{
width: 100%;
height: 50vh;
}
.quodrant1,
.quodrant2,
.quodrant3,
.quodrant4{
display: inline;
float: left;
width: 50%;
height: 100%;
}
.quodrant1{
top: 0;
left: 50vh;
background-color: red;
}
.quodrant2{
top: 0;
left: 0;
background-color: yellow;
}
.quodrant3{
top: 50vw;
left: 0;
background-color: blue;
}
.quodrant4{
top: 50vw;
left: 50vh;
background-color: green;
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link type="text/css" rel="stylesheet" href="main.css" />
</head>
<body>
<div class='quodrant'>
<div class='qtop'>
<div class='quodrant1'></div>
<div class='quodrant2'></div>
</div>
<div class='qbottom'>
<div class='quodrant3'></div>
<div class='quodrant4'></div>
</div>
</div>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
_x000D_
Or making it looks nicer.
.quodrant{
width: 100%;
height: 100vh;
margin: 0;
padding: 0;
}
.qtop,
.qbottom{
width: 96%;
height: 46vh;
}
.quodrant1,
.quodrant2,
.quodrant3,
.quodrant4{
display: inline;
float: left;
width: 46%;
height: 96%;
border-radius: 30px;
margin: 2%;
}
.quodrant1{
background-color: #948be5;
}
.quodrant2{
background-color: #22e235;
}
.quodrant3{
background-color: #086e75;
}
.quodrant4{
background-color: #7cf5f9;
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link type="text/css" rel="stylesheet" href="main.css" />
</head>
<body>
<div class='quodrant'>
<div class='qtop'>
<div class='quodrant1'></div>
<div class='quodrant2'></div>
</div>
<div class='qbottom'>
<div class='quodrant3'></div>
<div class='quodrant4'></div>
</div>
</div>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
_x000D_
The core way to send emails from PHP is to use its built in mail()
function, but there are a couple of ready-to-use SDKs which can ease the integration:
P.S. I am employed with Pepipost.
SELECT * FROM news WHERE date < DATEADD(Day, -1, date)
k old post but no one use list expression to answer :P
list =[ ['a','b'], ['a','c'], ['b','d'] ]
Search = 'c'
# return if it find in either item 0 or item 1
print [x for x,y in list if x == Search or y == Search]
# return if it find in item 1
print [x for x,y in list if y == Search]
Pretty late and not sure if this was available when the question was asked, set width: auto;
Seems to do the trick
You may find this thread useful. And here's a google code project exemplifying this (it P/Invokes into setupapi.dll
).
Logits often are the values of Z function of the output layer in Tensorflow.
Switch the alloc type:
GCHandle handle = GCHandle.Alloc(a, GCHandleType.Normal);
Here is a sample code showing how to align text using UILabel:
label = [[UILabel alloc] initWithFrame:CGRectMake(60, 30, 200, 12)];
label.textAlignment = NSTextAlignmentCenter;
You can read more about it here UILabel
Before wasting lots of time in installing and uninstalling, read this.
If you already installed angular before and found this issue, may be it is the reason that you installed angular before with running terminal as Administrator and now trying this command without administrator mode or vice versa. There is a difference in these two.
If you installed angular without administrator mode you can only use angular commands such as ng without administrator mode. Similarly,
If you installed angular with administrator mode you can use angular commands such as ng in administrator mode only.
We use something like this [use in one line]:
<a title="send to Facebook"
href="http://www.facebook.com/sharer.php?s=100&p[title]=YOUR_TITLE&p[summary]=YOUR_SUMMARY&p[url]=YOUR_URL&p[images][0]=YOUR_IMAGE_TO_SHARE_OBJECT"
target="_blank">
<span>
<img width="14" height="14" src="'icons/fb.gif" alt="Facebook" /> Facebook
</span>
</a>
IsNullOrEmpty
is essentially shorthand for the following:
return str == null || str == String.Empty;
So, no there is no function that just checks for nulls because it would be too simple. obj != null
is the correct way. But you can create such a (superfluous) function yourself using the following extension:
public bool IsNull(this object obj)
{
return obj == null;
}
Then you are able to run anyObject.IsNull()
.
For Swift 3
let button = UIButton()
button.frame = CGRect(x: self.view.frame.size.width - 60, y: 60, width: 50, height: 50)
button.backgroundColor = UIColor.red
button.setTitle("your Button Name", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
self.view.addSubview(button)
func buttonAction(sender: UIButton!) {
print("Button tapped")
}
For Swift 4+
let button = UIButton()
button.frame = CGRect(x: self.view.frame.size.width - 60, y: 60, width: 50, height: 50)
button.backgroundColor = UIColor.red
button.setTitle("Name your Button ", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
self.view.addSubview(button)
@objc func buttonAction(sender: UIButton!) {
print("Button tapped")
}
I am just going to touch on overcoming the trade-off of regular adjacency list representation, since other answers have covered other aspects.
It is possible to represent a graph in adjacency list with EdgeExists query in amortized constant time, by taking advantage of Dictionary and HashSet data structures. The idea is to keep vertices in a dictionary, and for each vertex, we keep a hash set referencing to other vertices it has edges with.
One minor trade-off in this implementation is that it will have space complexity O(V + 2E) instead of O(V + E) as in regular adjacency list, since edges are represented twice here (because each vertex have its own hash set of edges). But operations such as AddVertex, AddEdge, RemoveEdge can be done in amortized time O(1) with this implementation, except for RemoveVertex which takes O(V) like adjacency matrix. This would mean that other than implementation simplicity, adjacency matrix don't have any specific advantage. We can save space on sparse graph with almost the same performance in this adjacency list implementation.
Take a look at implementations below in Github C# repository for details. Note that for weighted graph it uses a nested dictionary instead of dictionary-hash set combination so as to accommodate weight value. Similarly for directed graph there is separate hash sets for in & out edges.
Note: I believe using lazy deletion we can further optimize RemoveVertex operation to O(1) amortized, even though I haven't tested that idea. For example, upon deletion just mark the vertex as deleted in dictionary, and then lazily clear orphaned edges during other operations.
You can go from String (hex)
to byte array
to String as UTF-8(?)
. Make sure your hex string does not have leading spaces and stuff.
public static byte[] hexStringToByteArray(String hex) {
int l = hex.length();
byte[] data = new byte[l / 2];
for (int i = 0; i < l; i += 2) {
data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
+ Character.digit(hex.charAt(i + 1), 16));
}
return data;
}
Usage:
String b = "0xfd00000aa8660b5b010006acdc0100000101000100010000";
byte[] bytes = hexStringToByteArray(b);
String st = new String(bytes, StandardCharsets.UTF_8);
System.out.println(st);
For an inner join, WHERE
and ON
can be used interchangeably. In fact, it's possible to use ON
in a correlated subquery. For example:
update mytable
set myscore=100
where exists (
select 1 from table1
inner join table2
on (table2.key = mytable.key)
inner join table3
on (table3.key = table2.key and table3.key = table1.key)
...
)
This is (IMHO) utterly confusing to a human, and it's very easy to forget to link table1
to anything (because the "driver" table doesn't have an "on" clause), but it's legal.
PKCS#1 OAEP is an asymmetric cipher based on RSA and the OAEP padding
from Crypto.PublicKey import RSA
from Crypto import Random
from Crypto.Cipher import PKCS1_OAEP
def rsa_encrypt_decrypt():
key = RSA.generate(2048)
private_key = key.export_key('PEM')
public_key = key.publickey().exportKey('PEM')
message = input('plain text for RSA encryption and decryption:')
message = str.encode(message)
rsa_public_key = RSA.importKey(public_key)
rsa_public_key = PKCS1_OAEP.new(rsa_public_key)
encrypted_text = rsa_public_key.encrypt(message)
#encrypted_text = b64encode(encrypted_text)
print('your encrypted_text is : {}'.format(encrypted_text))
rsa_private_key = RSA.importKey(private_key)
rsa_private_key = PKCS1_OAEP.new(rsa_private_key)
decrypted_text = rsa_private_key.decrypt(encrypted_text)
print('your decrypted_text is : {}'.format(decrypted_text))
If you are using mysql client you can set up the resultFormat per session e.g.
mysql -h localhost -u root --resutl-format=json
or
mysql -h localhost -u root --vertical
Check out the full list of arguments here.
Simple solution for vertical align middle... for me it works like a charm
ul{display:table; text-align:center; margin:0 auto;}
li{display:inline-block; text-align:center;}
li.items_inside_li{display:inline-block; vertical-align:middle;}
The original poster is asking on how to open a link on a new tab. So this is how I have done it in C#.
IWebDriver driver = new ChromeDriver();
driver.Manage().Window.Maximize();
driver.Navigate().GoToUrl("https://microsoft.com");
IWebElement eventlink = driver.FindElement(By.Id("uhfLogo"));
Actions action = new Actions(driver);
action.KeyDown(Keys.Control).MoveToElement(eventlink).Click().Perform();
This actually performs a Control+Click on the selected element in order to open the link in a new tab.
Do you perhaps have one too many here?
describe "when name is too long" do
before { @user.name = "a" * 51 }
it { should_not be_valid }
end
end
For me I got NumberFormatException when trying to deal with the negative numbers. I used the following for the negative and positive numbers.
System.out.println(Integer.parseUnsignedInt("11111111111111111111111111110111", 2));
Output : -9
No, there is no "easy" way. Your best bet would be to do a loop where you first check each previous sibling, then move to the parent node and all of its previous siblings.
You'll need to break the selector into two, 1 to check if the current node could be the top level node in your selector, and 1 to check if it's descendants match.
Edit: This might as well be a plugin. You can use this with any selector in any HTML:
(function($) {
$.fn.closestPrior = function(selector) {
selector = selector.replace(/^\s+|\s+$/g, "");
var combinator = selector.search(/[ +~>]|$/);
var parent = selector.substr(0, combinator);
var children = selector.substr(combinator);
var el = this;
var match = $();
while (el.length && !match.length) {
el = el.prev();
if (!el.length) {
var par = el.parent();
// Don't use the parent - you've already checked all of the previous
// elements in this parent, move to its previous sibling, if any.
while (par.length && !par.prev().length) {
par = par.parent();
}
el = par.prev();
if (!el.length) {
break;
}
}
if (el.is(parent) && el.find(children).length) {
match = el.find(children).last();
}
else if (el.find(selector).length) {
match = el.find(selector).last();
}
}
return match;
}
})(jQuery);
The best way is to run this batch file. open notepad and type:-
@echo off
echo Set oWS = WScript.CreateObject("WScript.Shell") > CreateShortcut.vbs
echo sLinkFile = "GIVETHEPATHOFLINK.lnk" >> CreateShortcut.vbs
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> CreateShortcut.vbs
echo oLink.TargetPath = "GIVETHEPATHOFTARGETFILEYOUWANTTHESHORTCUT" >> CreateShortcut.vbs
echo oLink.Save >> CreateShortcut.vbs
cscript CreateShortcut.vbs
del CreateShortcut.vbs
Save as filename.bat(be careful while saving select all file types) worked well in win XP.
May help to someone:
I'm sending data from react
application to golang
server.
Once I change this, w.Header().Set("Access-Control-Allow-Origin", "*")
. Error has fixed.
React form submit function:
async handleSubmit(e) {
e.preventDefault();
const headers = {
'Content-Type': 'text/plain'
};
await axios.post(
'http://localhost:3001/login',
{
user_name: this.state.user_name,
password: this.state.password,
},
{headers}
).then(response => {
console.log("Success ========>", response);
})
.catch(error => {
console.log("Error ========>", error);
}
)
}
Go server got Router,
func main() {
router := mux.NewRouter()
router.HandleFunc("/login", Login.Login).Methods("POST")
log.Fatal(http.ListenAndServe(":3001", router))
}
Login.go,
func Login(w http.ResponseWriter, r *http.Request) {
var user = Models.User{}
data, err := ioutil.ReadAll(r.Body)
if err == nil {
err := json.Unmarshal(data, &user)
if err == nil {
user = Postgres.GetUser(user.UserName, user.Password)
w.Header().Set("Access-Control-Allow-Origin", "*")
json.NewEncoder(w).Encode(user)
}
}
}
The answer is "no, you probably can't".
While there is stuff in there that might say who created a given object, there are a lot of "ifs" behind them. A quick (and not necessarily complete) review:
sys.objects (and thus sys.tables, sys.procedures, sys.views, etc.) has column principal_id. This value is a foreign key that relates to the list of database users, which in turn can be joined with the list of SQL (instance) logins. (All of this info can be found in further system views.)
But.
A quick check on our setup here and a cursory review of BOL indicates that this value is only set (i.e. not null) if it is "different from the schema owner". In our development system, and we've got dbo + two other schemas, everything comes up as NULL. This is probably because everyone has dbo rights within these databases.
This is using NT authentication. SQL authentication probably works much the same. Also, does everyone have and use a unique login, or are they shared? If you have employee turnover and domain (or SQL) logins get dropped, once again the data may not be there or may be incomplete.
You can look this data over (select * from sys.objects), but if principal_id is null, you are probably out of luck.
I'm not sure if you have seen THIS, but Chris Coyier's excellent CSS-Tricks.com posted a link to this a while back and it's a pure CSS solution that accomplishes exactly what you seek.
<div class="ellipsis">
<div>
<p>
Call me Ishmael. Some years ago – never mind how long precisely – having
little or no money in my purse, and nothing particular to interest me on
shore, I thought I would sail about a little and see the watery part of the
world. It is a way I have of driving off the spleen, and regulating the
circulation. Whenever I find myself growing grim about the mouth; whenever it
is a damp, drizzly November in my soul; whenever I find myself involuntarily
pausing before coffin warehouses, and bringing up the rear of every funeral I
meet; and especially whenever my hypos get such an upper hand of me, that it
requires a strong moral principle to prevent me from deliberately stepping
into the street, and methodically knocking people's hats off – then, I account
it high time to get to sea as soon as I can.
</p>
</div>
</div>
html,body,p {
margin: 0;
padding: 0;
font-family: sans-serif;
}
.ellipsis {
overflow: hidden;
height: 200px;
line-height: 25px;
margin: 20px;
border: 5px solid #AAA;
}
.ellipsis:before {
content: "";
float: left;
width: 5px;
height: 200px;
}
.ellipsis > *:first-child {
float: right;
width: 100%;
margin-left: -5px;
}
.ellipsis:after {
content: "\02026";
box-sizing: content-box;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
float: right;
position: relative;
top: -25px;
left: 100%;
width: 3em;
margin-left: -3em;
padding-right: 5px;
text-align: right;
background-size: 100% 100%;/* 512x1 image,gradient for IE9. Transparent at 0% -> white at 50% -> white at 100%.*/
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgAAAAABCAMAAACfZeZEAAAABGdBTUEAALGPC/xhBQAAAwBQTFRF////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAA////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////wDWRdwAAAP90Uk5TgsRjMZXhS30YrvDUP3Emow1YibnM9+ggOZxrBtpRRo94gxItwLOoX/vsHdA2yGgL8+TdKUK8VFufmHSGgAQWJNc9tk+rb5KMCA8aM0iwpWV6dwP9+fXuFerm3yMs0jDOysY8wr5FTldeoWKabgEJ8RATG+IeIdsn2NUqLjQ3OgBDumC3SbRMsVKsValZplydZpZpbJOQco2KdYeEe36BDAL8/vgHBfr2CvTyDu8R7esU6RcZ5ecc4+Af3iLcJSjZ1ivT0S/PMs3LNck4x8U7wz7Bv0G9RLtHuEq1TbJQr1OtVqqnWqRdoqBhnmSbZ5mXapRtcJGOc4t2eYiFfH9AS7qYlgAAARlJREFUKM9jqK9fEGS7VNrDI2+F/nyB1Z4Fa5UKN4TbbeLY7FW0Tatkp3jp7mj7vXzl+4yrDsYoVx+JYz7mXXNSp/a0RN25JMcLPP8umzRcTZW77tNyk63tdprzXdmO+2ZdD9MFe56Y9z3LUG96mcX02n/CW71JH6Qmf8px/cw77ZvVzB+BCj8D5vxhn/vXZh6D4uzf1rN+Cc347j79q/zUL25TPrJMfG/5LvuNZP8rixeZz/mf+vU+Vut+5NL5gPOeb/sd1dZbTs03hBuvmV5JuaRyMfk849nEM7qnEk6IHI8/qn049hB35QGHiv0yZXuMdkXtYC3ebrglcqvYxoj1muvC1nDlrzJYGbpcdHHIMo2FwYv+j3QAAOBSfkZYITwUAAAAAElFTkSuQmCC);
background: -webkit-gradient(linear,left top,right top,
from(rgba(255,255,255,0)),to(white),color-stop(50%,white));
background: -moz-linear-gradient(to right,rgba(255,255,255,0),white 50%,white);
background: -o-linear-gradient(to right,rgba(255,255,255,0),white 50%,white);
background: -ms-linear-gradient(to right,rgba(255,255,255,0),white 50%,white);
background: linear-gradient(to right,rgba(255,255,255,0),white 50%,white);
}
Of course, being a pure CSS solution means that it's also a pretty complicated one, but it works cleanly and elegantly. I will assume that Javascript is out of the question because this is much easier to achieve (and arguably more degradable) with Javascript.
As an added bonus, there's a downloadable zip file of the complete process (if you want to understand it and all), but also a SASS mixin file so that you can fold it into your process easy-peasy.
Hope this helps!
insert this line driver.execute_script("window.scrollBy(0,925)", "")
I used below format
git push https://username:[email protected]/file.git --all
and if your password or username contain @ replace it with %40
Use std::printf and c_str() example:
std::printf("Follow this command: %s", myString.c_str());
4+ years later after the original reply in 2015, virtualbox.org now offers an official user manual in both html and pdf formats, which effectively deprecates the previous version of this answer:
Because there isn't an official answer yet and I literally just did this for my OS X/WinXP install, here's what I did:
Hope that helps.
OK, so I found the answer from http://binglongx.wordpress.com/2009/01/26/visual-c-does-not-generate-lib-file-for-a-dll-project/ says that this problem was caused by not exporting any symbols and further instructs on how to export symbols to create the lib file. To do so, add the following code to your .h file for your DLL.
#ifdef BARNABY_EXPORTS
#define BARNABY_API __declspec(dllexport)
#else
#define BARNABY_API __declspec(dllimport)
#endif
Where BARNABY_EXPORTS and BARNABY_API are unique definitions for your project. Then, each function you export you simply precede by:
BARNABY_API int add(){
}
This problem could have been prevented either by clicking the Export Symbols box on the new project DLL Wizard or by voting yes for lobotomies for computer programmers.
Summernote converts your uploaded images to a base64 encoded string by default, you can process this string or as other fellows mentioned you can upload images using onImageUpload
callback. You can take a look at this gist which I modified a bit to adapt laravel csrf token
here. But that did not work for me and I had no time to find out why! Instead, I solved it via a server-side solution based on this blog post. It gets the output of the summernote and then it will upload the images and updates the final markdown HTML.
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
Route::get('/your-route-to-editor', function () {
return view('your-view');
});
Route::post('/your-route-to-processor', function (Request $request) {
$this->validate($request, [
'editordata' => 'required',
]);
$data = $request->input('editordata');
//loading the html data from the summernote editor and select the img tags from it
$dom = new \DomDocument();
$dom->loadHtml($data, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$images = $dom->getElementsByTagName('img');
foreach($images as $k => $img){
//for now src attribute contains image encrypted data in a nonsence string
$data = $img->getAttribute('src');
//getting the original file name that is in data-filename attribute of img
$file_name = $img->getAttribute('data-filename');
//extracting the original file name and extension
$arr = explode('.', $file_name);
$upload_base_directory = 'public/';
$original_file_name='time()'.$k;
$original_file_extension='png';
if (sizeof($arr) == 2) {
$original_file_name = $arr[0];
$original_file_extension = $arr[1];
}
else
{
//the file name contains extra . in itself
$original_file_name = implode("_",array_slice($arr,0,sizeof($arr)-1));
$original_file_extension = $arr[sizeof($arr)-1];
}
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$path = $upload_base_directory.$original_file_name.'.'.$original_file_extension;
//uploading the image to an actual file on the server and get the url to it to update the src attribute of images
Storage::put($path, $data);
$img->removeAttribute('src');
//you can remove the data-filename attribute here too if you want.
$img->setAttribute('src', Storage::url($path));
// data base stuff here :
//saving the attachments path in an array
}
//updating the summernote WYSIWYG markdown output.
$data = $dom->saveHTML();
// data base stuff here :
// save the post along with it attachments array
return view('your-preview-page')->with(['data'=>$data]);
});
or use display property with table-cell;
css
.table-layout {
display:table;
width:100%;
}
.table-layout .table-cell {
display:table-cell;
border:solid 1px #ccc;
}
.fixed-width-200 {
width:200px;
}
html
<div class="table-layout">
<div class="table-cell fixed-width-200">
<p>fixed width div</p>
</div>
<div class="table-cell">
<p>fluid width div</p>
</div>
</div>
This example program illustrates initialization of an array of C strings.
#include <stdio.h>
const char * array[] = {
"First entry",
"Second entry",
"Third entry",
};
#define n_array (sizeof (array) / sizeof (const char *))
int main ()
{
int i;
for (i = 0; i < n_array; i++) {
printf ("%d: %s\n", i, array[i]);
}
return 0;
}
It prints out the following:
0: First entry
1: Second entry
2: Third entry
resetForm(){
ObjectName = {};
}
You can't "add" values to an array as the array length is immutable. You can set values at specific array positions.
If you know how to do it with one-dimensional arrays then you know how to do it with n-dimensional arrays: There are no n-dimensional arrays in Java, only arrays of arrays (of arrays...).
But you can chain the index operator for array element access.
String[][] x = new String[2][];
x[0] = new String[1];
x[1] = new String[2];
x[0][0] = "a1";
// No x[0][1] available
x[1][0] = "b1";
x[1][1] = "b2";
Note the dimensions of the child arrays don't need to match.
Fetch API
function load_home (e) {
(e || window.event).preventDefault();
fetch("http://www.yoursite.com/home.html" /*, options */)
.then((response) => response.text())
.then((html) => {
document.getElementById("content").innerHTML = html;
})
.catch((error) => {
console.warn(error);
});
}
XHR API
function load_home (e) {
(e || window.event).preventDefault();
var con = document.getElementById('content')
, xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4 && xhr.status == 200) {
con.innerHTML = xhr.responseText;
}
}
xhr.open("GET", "http://www.yoursite.com/home.html", true);
xhr.setRequestHeader('Content-type', 'text/html');
xhr.send();
}
based on your constraints you should use ajax and make sure that your javascript is loaded before the markup that calls the load_home()
function
Here is one possible solution to solve the problem without a library :
public static boolean delete(File file) {
File[] flist = null;
if(file == null){
return false;
}
if (file.isFile()) {
return file.delete();
}
if (!file.isDirectory()) {
return false;
}
flist = file.listFiles();
if (flist != null && flist.length > 0) {
for (File f : flist) {
if (!delete(f)) {
return false;
}
}
}
return file.delete();
}
Since Laravel 5.2.23, you have the @php Blade directive, which you can use inline or as block statement:
@php($old_section = "whatever")
or
@php
$old_section = "whatever"
@endphp
Both questions are answered in git status
.
To unstage adding a new file use git rm --cached filename.ext
# Changes to be committed:
# (use "git rm --cached <file>..." to unstage)
#
# new file: test
To unstage deleting a file use git reset HEAD filename.ext
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# deleted: test
In the other hand, git checkout --
never unstage, it just discards non-staged changes.
I was able to solve this issue in Chrome by turning off the Calendly Chrome extension which I had recently installed. May not be Calendly specific so I would recommend turning off any newly installed Chrome extensions. Below are the steps I took:
A 2019 answer if you're using .NET Core - use the Nuget ToDataTable library. Advantages:
Disclaimer - I'm the author of ToDataTable
Performance - I span up some Benchmark .Net tests and included them in the ToDataTable repo. The results were as follows:
Creating a 100,000 Row Datatable:
Reflection 818.5 ms
DataTableProxy 1,068.8 ms
ToDataTable 449.0 ms
Use all SQL server: ;with tbl as (SELECT ROW_NUMBER() over(order by(select 1)) as RowIndex,* from table) select top 10 * from tbl where RowIndex>=10
Top answer doesn't work in mysql 5.6+. Use this instead:
[mysqld]
general_log = on
general_log_file=/usr/log/general.log
in your my.cnf / my.ini file
Ubuntu/Debian: /etc/mysql/my.cnf
Windows: c:\ProgramData\MySQL\MySQL Server 5.x
wamp: c:\wamp\bin\mysql\mysqlx.y.z\my.ini
xampp: c:\xampp\mysql\bin\my.ini.
I'm using Firefox, and my working solution is very close to obysky. The only difference is that the method you call in an svg element will return multiple rects and you need to select the first one.
var chart = document.getElementsByClassName("chart")[0];
var width = chart.getClientRects()[0].width;
var height = chart.getClientRects()[0].height;
I wrote something like this the other day:
import time, datetime
def nowString():
# we want something like '2007-10-18 14:00+0100'
mytz="%+4.4d" % (time.timezone / -(60*60) * 100) # time.timezone counts westwards!
dt = datetime.datetime.now()
dts = dt.strftime('%Y-%m-%d %H:%M') # %Z (timezone) would be empty
nowstring="%s%s" % (dts,mytz)
return nowstring
So the interesting part for you is probably the line starting with "mytz=...". time.timezone returns the local timezone, albeit with opposite sign compared to UTC. So it says "-3600" to express UTC+1.
Despite its ignorance towards Daylight Saving Time (DST, see comment), I'm leaving this in for people fiddling around with time.timezone
.
Try this hack :-) Gulp v3.x Hack for Async bug
I tried all of the "official" ways in the Readme, they didn't work for me but this did. You can also upgrade to gulp 4.x but I highly recommend you don't, it breaks so much stuff. You could use a real js promise, but hey, this is quick, dirty, simple :-) Essentially you use:
var wait = 0; // flag to signal thread that task is done
if(wait == 0) setTimeout(... // sleep and let nodejs schedule other threads
Check out the post!
Sonatype Nexus and Apache Maven are two pieces of software that often work together but they do very different parts of the job. Nexus provides a repository while Maven uses a repository to build software.
Here's a quote from "What is Nexus?":
Nexus manages software "artifacts" required for development. If you develop software, your builds can download dependencies from Nexus and can publish artifacts to Nexus creating a new way to share artifacts within an organization. While Central repository has always served as a great convenience for developers you shouldn't be hitting it directly. You should be proxying Central with Nexus and maintaining your own repositories to ensure stability within your organization. With Nexus you can completely control access to, and deployment of, every artifact in your organization from a single location.
And here is a quote from "Maven and Nexus Pro, Made for Each Other" explaining how Maven uses repositories:
Maven leverages the concept of a repository by retrieving the artifacts necessary to build an application and deploying the result of the build process into a repository. Maven uses the concept of structured repositories so components can be retrieved to support the build. These components or dependencies include libraries, frameworks, containers, etc. Maven can identify components in repositories, understand their dependencies, retrieve all that are needed for a successful build, and deploy its output back to repositories when the build is complete.
So, when you want to use both you will have a repository managed by Nexus and Maven will access this repository.
You can do that without the terminal. You just need to create a branch with the new name, and remove the old after.
Create a branch
In your repository’s branch selector, just start typing a new branch name. It’ll give you the option to create a new branch:
It’ll branch off of your current context. For example, if you’re on the bugfix branch, it’ll create a new branch from bugfix instead of master. Looking at a commit or a tag instead? It’ll branch your code from that specific revision.
Delete a branch
You’ll also see a delete button in your repository’s Branches page:
As an added bonus, it’ll also give you a link to the branch’s Pull Request, if it has one.
I just copied this content from: Create and delete branches
To update the local list of remote branches:
git remote update origin --prune
To show all local and remote branches that (local) Git knows about
git branch -a
$($("li").get().reverse()).each(function() { /* ... */ });
You didn't specify a GradientType
:
background: #f0f0f0; /* Old browsers */
background: -moz-linear-gradient(top, #ffffff 0%, #eeeeee 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#eeeeee)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#eeeeee',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* W3C */
If the program was written in C# you can get the source code in almost its original form using .NET Reflector. You won't be able to see comments and local variable names, but it is very readable.
If it was written C++ it's not so easy... even if you could decompile the code into valid C++ it is unlikely that it will resemble the original source because of inlined functions and optimizations which are hard to reverse.
Please note that by reverse engineering and modifying the source code you might breaking the terms of use of the programs unless you wrote them yourself or have permission from the author.
Here is a sample helper class which converts an Object and returns an Expando with all public properties of the given object.
public static class dynamicHelper
{
public static ExpandoObject convertToExpando(object obj)
{
//Get Properties Using Reflections
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = obj.GetType().GetProperties(flags);
//Add Them to a new Expando
ExpandoObject expando = new ExpandoObject();
foreach (PropertyInfo property in properties)
{
AddProperty(expando, property.Name, property.GetValue(obj));
}
return expando;
}
public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
{
//Take use of the IDictionary implementation
var expandoDict = expando as IDictionary;
if (expandoDict.ContainsKey(propertyName))
expandoDict[propertyName] = propertyValue;
else
expandoDict.Add(propertyName, propertyValue);
}
}
Usage:
//Create Dynamic Object
dynamic expandoObj= dynamicHelper.convertToExpando(myObject);
//Add Custom Properties
dynamicHelper.AddProperty(expandoObj, "dynamicKey", "Some Value");
Hope I've understood you correctly, take a look at this: http://jsfiddle.net/EAEKc/
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
<meta charset="UTF-8" />_x000D_
<title>Content with Menu</title>_x000D_
<style>_x000D_
.content .left {_x000D_
float: left;_x000D_
width: 100px;_x000D_
background-color: green;_x000D_
}_x000D_
_x000D_
.content .right {_x000D_
margin-left: 100px;_x000D_
background-color: red;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div class="content">_x000D_
<div class="left">_x000D_
<p>Hi, Flo!</p>_x000D_
</div>_x000D_
<div class="right">_x000D_
<p>is</p>_x000D_
<p>this</p>_x000D_
<p>what</p>_x000D_
<p>you are looking for?</p>_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
If you have Excel 2010 you can copy your data into another column, than select it and choose Data -> Remove Duplicates. You can then write =COUNTIF($A$1:$A$100,B1)
next to it and copy the formula down. This assumes you have your values in range A1:A100
and the de-duplicated values are in column B.
To expound on Stephane's answer.
I got this error when I tried to grant remote connections privileges of a particular database to a root
user on MySQL server by running the command:
USE database_name;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%';
This gave an error:
ERROR 1133 (42000): Can't find any matching row in the user table
Here's how I fixed it:
First, confirm that your MySQL server allows for remote connections. Use your preferred text editor to open the MySQL server configuration file:
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
Scroll down to the bind-address line and ensure that is either commented out or replaced with 0.0.0.0
(to allow all remote connections) or replaced with Ip-Addresses that you want remote connections from.
Once you make the necessary changes, save and exit the configuration file. Apply the changes made to the MySQL config file by restarting the MySQL service:
sudo systemctl restart mysql
Next, log into the MySQL server console on the server it was installed:
mysql -u root -p
Enter your mysql user password
Check the hosts that the user you want has access to already. In my case the user is root
:
SELECT host FROM mysql.user WHERE user = "root";
This gave me this output:
+-----------+
| host |
+-----------+
| localhost |
+-----------+
Next, I ran the command below which is similar to the previous one that was throwing errors, but notice that I added a password to it this time:
USE database_name;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'my-password';
Note: %
grants a user remote access from all hosts on a network. You can specify the Ip-Address of the individual hosts that you want to grant the user access from using the command - GRANT ALL PRIVILEGES ON *.* TO 'root'@'Ip-Address' IDENTIFIED BY 'my-password';
Afterwhich I checked the hosts that the user now has access to. In my case the user is root
:
SELECT host FROM mysql.user WHERE user = "root";
This gave me this output:
+-----------+
| host |
+-----------+
| % |
| localhost |
+-----------+
Finally, you can try connecting to the MySQL server from another server using the command:
mysql -u username -h mysql-server-ip-address -p
Where u represents user, h represents mysql-server-ip-address and p represents password. So in my case it was:
mysql -u root -h 34.69.261.158 -p
Enter your mysql user password
You should get this output depending on your MySQL server version:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.31 MySQL Community Server (GPL)
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
Resources: How to Allow Remote Connections to MySQL
That's all.
I hope this helps
Step 1: Go to the the first column of the first line you want to comment.
Step 2: Press: Ctrl+v and select the lines you want to comment:
Step 3: Shift-I
#space (Enter Insert-at-left mode, type chars to insert. The selection will disappear, but all lines within it will be modified after Step 4.)
Step 4: Esc
Is null an instance of anything?
No. That is why null instanceof X
will return false
for all classes X
. (Don't be fooled by the fact that you can assign null
to a variable whose type is an object type. Strictly speaking, the assignment involves an implicit type conversion; see below.)
What set does 'null' belong to?
It is the one and only member of the null type, where the null type is defined as follows:
"There is also a special null type, the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type. In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type." JLS 4.1
What is null?
See above. In some contexts, null
is used to denote "no object" or "unknown" or "unavailable", but these meanings are application specific.
How is it represented in the memory?
That is implementation specific, and you won't be able to see the representation of null
in a pure Java program. (But null
is represented as a zero machine address / pointer in most if not all Java implementations.)
The move
instruction copies a value from one register to another. The li
instruction loads a specific numeric value into that register.
For the specific case of zero, you can use either the constant zero or the zero register to get that:
move $s0, $zero
li $s0, 0
There's no register that generates a value other than zero, though, so you'd have to use li
if you wanted some other number, like:
li $s0, 12345678
It started happening to me when I changed variables for Android Studio. Go to your studio64.exe.vmoptions
file (located in c:\users\userName\.AndroidStudio{version}\
and comments the arguments.
I have given a simple code to upload files from Javascript browser to AWS S3 and list the all files in S3 bucket.
Steps:
To know how to create Create IdentityPoolId http://docs.aws.amazon.com/cognito/latest/developerguide/identity-pools.html
Goto S3's console page and open cors configuration from bucket properties and write following XML code into that.
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<AllowedMethod>HEAD</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
Create HTML file containing following code change the credentials, open file in browser and enjoy.
<script type="text/javascript">
AWS.config.region = 'ap-north-1'; // Region
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'ap-north-1:*****-*****',
});
var bucket = new AWS.S3({
params: {
Bucket: 'MyBucket'
}
});
var fileChooser = document.getElementById('file-chooser');
var button = document.getElementById('upload-button');
var results = document.getElementById('results');
function upload() {
var file = fileChooser.files[0];
console.log(file.name);
if (file) {
results.innerHTML = '';
var params = {
Key: n + '.pdf',
ContentType: file.type,
Body: file
};
bucket.upload(params, function(err, data) {
results.innerHTML = err ? 'ERROR!' : 'UPLOADED.';
});
} else {
results.innerHTML = 'Nothing to upload.';
} }
</script>
<body>
<input type="file" id="file-chooser" />
<input type="button" onclick="upload()" value="Upload to S3">
<div id="results"></div>
</body>
I have tried most of the solutions suggested here but I had no luck. I found a solution that worked for me, which was manually updating the gemfile to 2.6.7. The guide on how to do is in guides.rubygems.org: installing-using-update-packages
Download rubygems-update-2.6.7.gem to your C:\
Now, using your Command Prompt:
C:\>gem install --local C:\rubygems-update-2.6.7.gem
C:\>update_rubygems --no-ri --no-rdoc
After this, gem --version should report the new update version (2.6.7).
You can now safely uninstall rubygems-update gem:
C:\>gem uninstall rubygems-update -x
Removing update_rubygems
Successfully uninstalled rubygems-update-2.6.7
The reason why this did not work before was because server used certificates SHA-1, now this was updated to SHA-2.
I've taken Anas Nakawa's idea and improved it. First of all, there is no reason to actually run the function being declared. We want to know whether it parses correctly, not whether the code works. Second, a literal object is a better context for our purpose than var XXX
as it's harder to break out of.
function isValidVarName( name ) {
try {
return name.indexOf('}') === -1 && eval('(function() { a = {' + name + ':1}; a.' + name + '; var ' + name + '; }); true');
} catch( e ) {
return false;
}
return true;
}
// so we can see the test code
var _eval = eval;
window.eval = function(s) {
console.log(s);
return _eval(s);
}
console.log(isValidVarName('name'));
console.log(isValidVarName('$name'));
console.log(isValidVarName('not a name'));
console.log(isValidVarName('a:2,b'));
console.log(isValidVarName('"a string"'));
console.log(isValidVarName('xss = alert("I\'m in your vars executin mah scrip\'s");;;;;'));
console.log(isValidVarName('_;;;'));
console.log(isValidVarName('_=location="#!?"'));
console.log(isValidVarName('?'));
console.log(isValidVarName('HELLO'));
console.log(isValidVarName('????'));
console.log(isValidVarName('?????????????'));
console.log(isValidVarName('KingGeorge?'));
console.log(isValidVarName('}; }); alert("I\'m in your vars executin\' mah scripts"); true; // yeah, super valid'));
console.log(isValidVarName('if'));
Use TextureLoader to load a image as texture and then simply apply that texture to scene background.
new THREE.TextureLoader();
loader.load('https://images.pexels.com/photos/1205301/pexels-photo-1205301.jpeg' , function(texture)
{
scene.background = texture;
});
Result:
https://codepen.io/hiteshsahu/pen/jpGLpq?editors=0011
See the Pen Flat Earth Three.JS by Hitesh Sahu (@hiteshsahu) on CodePen.If you want to declare a new substance with no parameter (knowing that the object have default parameters) don't write
type substance1();
but
type substance;
Use:
Console.ReadKey();
For it to close when someone presses any key, or:
Console.ReadLine();
For when the user types something and presses enter.
Mine was a TLS
version incompatible error.
Previously it was TLSv1
I changed it TLSV1.2
this solved my problem.
I have been using the Dina - http://www.donationcoder.com/Software/Jibz/Dina/index.html - font for awhile now for text editing and it seems to be doing the job nicely.
Well, me also I was struggling with this issue: this is how I solved it: apply table-layout: auto;
to the <table>
element.
You can add color in the style rule of your input: color:#ccc;
npm --depth 9999 update
fixed the issue for me--apparently because package-lock.json
was insisting on the outdated versions.
You can use regular multiple expressions with the use of OR (|) operator.
function validateDate(date){
var regex=new RegExp("([0-9]{4}[-](0[1-9]|1[0-2])[-]([0-2]{1}[0-9]{1}|3[0-1]{1})|([0-2]{1}[0-9]{1}|3[0-1]{1})[-](0[1-9]|1[0-2])[-][0-9]{4})");
var dateOk=regex.test(date);
if(dateOk){
alert("Ok");
}else{
alert("not Ok");
}
}
Above function can validate YYYY-MM-DD, DD-MM-YYYY date formats. You can simply extend the regular expression to validate any date format. Assume you want to validate YYYY/MM/DD, just replace "[-]" with "[-|/]". This expression can validate dates to 31, months to 12. But leap years and months ends with 30 days are not validated.
Make sure the outermost div has the following CSS properties:
.outer {
/* ... */
height: auto;
overflow: hidden;
/* ... */
}
Simply using an outer directory for the output, solved the problem for me.
sudo tar czf ./../31OCT18.tar.gz ./
Another bit of "wisdom". I have a database facing both, the internet and an internal app. I have a context for each face. That helps me to keep a disciplined, secured segregation.
Create a folder ${USER_HOME}/.mvn
and put a file called maven.config
in it.
The content should be:
-Dmaven.wagon.http.ssl.insecure=true
-Dmaven.wagon.http.ssl.allowall=true
-Dmaven.wagon.http.ssl.ignore.validity.dates=true
Hope this helps.
I have being struggling with this issue, but my problem was much easier to solve.
I had copied OBJ folder to "OBJ___" name to do some compilation tests.
So, I don't know why, this folder was being also compiled, creating the assembly attributes duplication.
I simply deleted the "OBJ___" folder and could compile successfuly.
As Jesse said, use self join:
SELECT
e.emp_id
, e.emp_name
, e.emp_mgr_id
, m.emp_name AS mgr_name
FROM [dbo].[tblEmployeeDetails] e
LEFT JOIN [dbo].[tblEmployeeDetails] m ON e.emp_mgr_id = m.emp_id
Note: I see that someone (not @unutbu) changed the referenced answer so that it no longer uses vars()['Foo']
— so the primary point of my post no longer applies.
FWIW, here's what I meant about @unutbu's answer only working with locally defined classes — and that using eval()
instead of vars()
would make it work with any accessible class, not only those defined in the current scope.
For those who dislike using eval()
, a way is also shown to avoid it.
First here's a concrete example demonstrating the potential problem with using vars()
:
class Foo(object): pass
class Bar(Foo): pass
class Baz(Foo): pass
class Bing(Bar): pass
# unutbu's approach
def all_subclasses(cls):
return cls.__subclasses__() + [g for s in cls.__subclasses__()
for g in all_subclasses(s)]
print(all_subclasses(vars()['Foo'])) # Fine because Foo is in scope
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]
def func(): # won't work because Foo class is not locally defined
print(all_subclasses(vars()['Foo']))
try:
func() # not OK because Foo is not local to func()
except Exception as e:
print('calling func() raised exception: {!r}'.format(e))
# -> calling func() raised exception: KeyError('Foo',)
print(all_subclasses(eval('Foo'))) # OK
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]
# using eval('xxx') instead of vars()['xxx']
def func2():
print(all_subclasses(eval('Foo')))
func2() # Works
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]
This could be improved by moving the eval('ClassName')
down into the function defined, which makes using it easier without loss of the additional generality gained by using eval()
which unlike vars()
is not context-sensitive:
# easier to use version
def all_subclasses2(classname):
direct_subclasses = eval(classname).__subclasses__()
return direct_subclasses + [g for s in direct_subclasses
for g in all_subclasses2(s.__name__)]
# pass 'xxx' instead of eval('xxx')
def func_ez():
print(all_subclasses2('Foo')) # simpler
func_ez()
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]
Lastly, it's possible, and perhaps even important in some cases, to avoid using eval()
for security reasons, so here's a version without it:
def get_all_subclasses(cls):
""" Generator of all a class's subclasses. """
try:
for subclass in cls.__subclasses__():
yield subclass
for subclass in get_all_subclasses(subclass):
yield subclass
except TypeError:
return
def all_subclasses3(classname):
for cls in get_all_subclasses(object): # object is base of all new-style classes.
if cls.__name__.split('.')[-1] == classname:
break
else:
raise ValueError('class %s not found' % classname)
direct_subclasses = cls.__subclasses__()
return direct_subclasses + [g for s in direct_subclasses
for g in all_subclasses3(s.__name__)]
# no eval('xxx')
def func3():
print(all_subclasses3('Foo'))
func3() # Also works
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]
A Type agnostic solution:
for _, key := range reflect.ValueOf(yourMap).MapKeys() {
value := s.MapIndex(key).Interface()
fmt.Println("Key:", key, "Value:", value)
}
Since you are creating a markup as a string you don't have convert it into json. Just send it as it is combining all the array elements using implode
method. Try this.
PHP change
$response = array();
$response[] = "<a href=''>link</a>";
$response[] = 1;
echo implode("", $response);//<-----Combine array items into single string
JS (Change the dataType from json to html or just don't set it jQuery will figure it out)
$.ajax({
type: "POST",
dataType: "html",
url: "main.php",
data: "action=loadall&id=" + id,
success: function(response){
$('#main').html(response);
}
});
The 2
in Anaconda2
means that the main version of Python will be 2.x rather than the 3.x installed in Anaconda3
. The current release has Python 2.7.13.
The 4.4.0.1
is the version number of Anaconda. The current advertised version is 4.4.0
and I assume the .1
is a minor release or for other similar use. The Windows releases, which I use, just say 4.4.0
in the file name.
Others have now explained the difference between Anaconda and Miniconda, so I'll skip that.
Given a data setup like this:
The formula in cell D2 and copied down is:
=INDEX($B$2:$B$28,MATCH(1,INDEX(($A$2:$A$28=LARGE($A$2:$A$28,ROWS(D$1:D1)))*(COUNTIF(D$1:D1,$B$2:$B$28)=0),),0))
This formula will work even if there are tied OPS scores among players.
Since the string "North" might be the beginning of a street name, e.g. "Northern Boulevard", street directions are always between the street number and the street name, and separated from street number and street name.
Public Function strReplace(varValue As Variant) as Variant
Select Case varValue
Case "Avenue"
strReplace = "Ave"
Case " North "
strReplace = " N "
Case Else
strReplace = varValue
End Select
End Function
Using getcwd()
to extract in the same directory
<?php
$unzip = new ZipArchive;
$out = $unzip->open('wordpress.zip');
if ($out === TRUE) {
$unzip->extractTo(getcwd());
$unzip->close();
echo 'File unzipped';
} else {
echo 'Error';
}
?>
To do links, you can do
.social h2 a:link {
color: pink;
font-size: 14px;
}
You can change the hover, visited, and active link styling too. Just replace "link" with what you want to style. You can learn more at the w3schools page CSS Links.
Had the same issue, but my code must work on both PHP 5 & PHP 7..
Here is my piece of code, which solved this.. Input a date in dmY format with one of delimiters "/ . -"
<?php
function DateToEN($date){
if ($date!=""){
list($d, $m, $y) = function_exists("split") ? split("[/.-]", $date) : preg_split("/[\/\.\-]+/", $date);
return $y."-".$m."-".$d;
}else{
return false;
}
}
?>
1)
select *
from employee em
where CONCAT(em.firstname, ' ', em.lastname) like '%parth pa%';
2)
select *
from employee em
where CONCAT_ws('-', em.firstname, em.lastname) like '%parth-pa%';
First is usefull when we have data like : 'firstname lastname'.
e.g
Second is usefull when we have data like : 'firstname-lastname'. In it you can also use special characters.
e.g
The existing JSON replacements where too much for me, so I wrote my own function. This seems to work, but I might have missed several edge cases (that don't occur in my project). And will probably not work for any pre-existing objects, only for self-made data.
function simpleJSONstringify(obj) {
var prop, str, val,
isArray = obj instanceof Array;
if (typeof obj !== "object") return false;
str = isArray ? "[" : "{";
function quote(str) {
if (typeof str !== "string") str = str.toString();
return str.match(/^\".*\"$/) ? str : '"' + str.replace(/"/g, '\\"') + '"'
}
for (prop in obj) {
if (!isArray) {
// quote property
str += quote(prop) + ": ";
}
// quote value
val = obj[prop];
str += typeof val === "object" ? simpleJSONstringify(val) : quote(val);
str += ", ";
}
// Remove last colon, close bracket
str = str.substr(0, str.length - 2) + ( isArray ? "]" : "}" );
return str;
}
Should remove units while preserving decimals.
var regExp = new RegExp("[a-z][A-Z]","g");
parseFloat($(this).css("property").replace(regExp, ""));
I think list comprehension is one of the cleanest ways that doesn't need any additional imports:
>>> d={"foo": 1, "bar": 2, "baz": 3}
>>> a = [d.get(k) for k in ["foo", "bar", "baz"]]
>>> a
[1, 2, 3]
Of if you want the values as individual variables then use multiple-assignment:
>>> a,b,c = [d.get(k) for k in ["foo", "bar", "baz"]]
>>> a,b,c
(1, 2, 3)
This is a javascript function adapted from @Telanor's code. When passing a image base64 as first argument to the function, it returns the base64 of the resized image. maxWidth and maxHeight are optional.
function thumbnail(base64, maxWidth, maxHeight) {
// Max size for thumbnail
if(typeof(maxWidth) === 'undefined') var maxWidth = 500;
if(typeof(maxHeight) === 'undefined') var maxHeight = 500;
// Create and initialize two canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var canvasCopy = document.createElement("canvas");
var copyContext = canvasCopy.getContext("2d");
// Create original image
var img = new Image();
img.src = base64;
// Determine new ratio based on max size
var ratio = 1;
if(img.width > maxWidth)
ratio = maxWidth / img.width;
else if(img.height > maxHeight)
ratio = maxHeight / img.height;
// Draw original image in second canvas
canvasCopy.width = img.width;
canvasCopy.height = img.height;
copyContext.drawImage(img, 0, 0);
// Copy and resize second canvas to first canvas
canvas.width = img.width * ratio;
canvas.height = img.height * ratio;
ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);
return canvas.toDataURL();
}
Chrome developer tools now have the ability to list WebSocket frames and also inspect the data if the frames are not binary.
Process:
If your WebSocket connection uses binary frames then you will probably still want to use Wireshark to debug the connection. Wireshark 1.8.0 added dissector and filtering support for WebSockets. An alternative may be found in this other answer.
add:
margin: 0 0 3px 0;
to your #access li
and move
background: #0f84e8; /* Show a solid color for older browsers */
to the #access a
and take out the border-bottom
. Then it will work
Google fonts in React.js?
Open your stylesheet i.e, app.css, style.css (what name you have), it doesn't matter, just open stylesheet and paste this code
@import url('https://fonts.googleapis.com/css?family=Josefin+Sans');
and don't forget to change URL of your font that you want, else working fine
and use this as :
body {
font-family: 'Josefin Sans', cursive;
}
The reason your main form isn't showing is because once you close the login form, your application's message pump is shut down, which causes the entire application to exit. The Windows message loop is tied to the login form because that's the one you have set as the startup form in your project properties. Look in your "Program.cs" file, and you'll see the responsible bit of code: Application.Run(new LoginForm())
. Check out the documentation for that method here on MSDN, which explains this in greater detail.
The best solution is to move the code out of your login form into the "Program.cs" file. When your program first starts, you'll create and show the login form as a modal dialog (which runs on a separate message loop and blocks execution of the rest of your code until it closes). When the login dialog closes, you'll check its DialogResult
property to see if the login was successful. If it was, you can start the main form using Application.Run
(thus creating the main message loop); otherwise, you can exit the application without showing any form at all. Something like this:
static void Main()
{
LoginForm fLogin = new LoginForm();
if (fLogin.ShowDialog() == DialogResult.OK)
{
Application.Run(new MainForm());
}
else
{
Application.Exit();
}
}
I have to say here (I realise that I'm probably going to open myself up to a slating!), but surely the only time when NVARCHAR
is actually more useful (notice the more there!) than VARCHAR
is when all of the collations on all of the dependant systems and within the database itself are the same...? If not then collation conversion has to happen anyway and so makes VARCHAR
just as viable as NVARCHAR
.
To add to this, some database systems, such as SQL Server (before 2012) have a page size of approx. 8K. So, if you're looking at storing searchable data not held in something like a TEXT
or NTEXT
field then VARCHAR
provides the full 8k's worth of space whereas NVARCHAR
only provides 4k (double the bytes, double the space).
I suppose, to summarise, the use of either is dependent on:
In here:
if (ValidationUtils.isNullOrEmpty(lastName)) {
registrationErrors.add(ValidationErrors.LAST_NAME);
}
if (!ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do
if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.
use code=>generate=>getter() and setter() dialog ,select all the variables ,generate all the getter(),setter() methods at one time.
Your code won't work because you haven't assigned anything to n
before you first use it. Try this:
def oracle():
n = None
while n != 'Correct':
# etc...
A more readable approach is to move the test until later and use a break
:
def oracle():
guess = 50
while True:
print 'Current number = {0}'.format(guess)
n = raw_input("lower, higher or stop?: ")
if n == 'stop':
break
# etc...
Also input
in Python 2.x reads a line of input and then evaluates it. You want to use raw_input
.
Note: In Python 3.x, raw_input
has been renamed to input
and the old input
method no longer exists.
A way to do this is to have your method protected
and write a test fixture which inherits your class to be tested. This way, you are nor turning your method public
, but you enable the testing.
No, but you can use the s///
substitution operator and the \s
whitespace assertion to get the same result.
I had the same problem, current update, but rendering failed because I need to update.
Try changing the update version you are on. The default is Stable, but there are 3 more options, Canary being the newest and potentially least stable. I chose to check for updates from the Dev Channel, which is a little more stable than Canary build. It fixed the problem and seems to work fine.
To change the version, Check for Updates, then click the Updates link on the popup that says you already have the latest version.
table {
width: 100%;
th, td {
width: 1%;
}
}
SCSS syntax
new_header = df.iloc[0] #grab the first row for the header
df = df[1:] #take the data less the header row
df.columns = new_header #set the header row as the df header
As the other poster mention, py2exe
, will generate an executable + some libraries to load. You can also have some data to add to your program.
Next step is to use an installer, to package all this into one easy-to-use installable/unistallable program.
I have used InnoSetup with delight for several years and for commercial programs, so I heartily recommend it.
Here's an example:
#Create a data frame
> d<- data.frame(a=1:3, b=2:4)
> d
a b
1 1 2
2 2 3
3 3 4
#currently, there are no levels in the `a` column, since it's numeric as you point out.
> levels(d$a)
NULL
#Convert that column to a factor
> d$a <- factor(d$a)
> d
a b
1 1 2
2 2 3
3 3 4
#Now it has levels.
> levels(d$a)
[1] "1" "2" "3"
You can also handle this when reading in your data. See the colClasses
and stringsAsFactors
parameters in e.g. readCSV()
.
Note that, computationally, factoring such columns won't help you much, and may actually slow down your program (albeit negligibly). Using a factor will require that all values are mapped to IDs behind the scenes, so any print of your data.frame requires a lookup on those levels -- an extra step which takes time.
Factors are great when storing strings which you don't want to store repeatedly, but would rather reference by their ID. Consider storing a more friendly name in such columns to fully benefit from factors.
If the Toggle Visual Space
icon shall be added to a Visual Studio toolbar of your choice, because it shall be turned on and off via mouse click, then follow this instruction:
Customize the desired toolbar
Click on Customize...
Click on Add Command...
Go to Edit
and chose Toggle Visual Space
Click on OK
Tested with Visual Studio 2019.
In SQL without SELECT
you cannot result anything. Instead of IF-ELSE
block I prefer to use CASE
statement for this
SELECT CASE
WHEN EXISTS (SELECT 1
FROM tblGLUserAccess
WHERE GLUserName = 'xxxxxxxx') THEN 1
ELSE 2
END
As an alternative to explicitly catching and handling the exception you could tell Oracle to catch and automatically ignore the exception by including a /*+ hint */
in the insert statement. This is a little faster than explicitly catching the exception and then articulating how it should be handled. It is also easier to setup. The downside is that you do not get any feedback from Oracle that an exception was caught.
Here is an example where we would be selecting from another table, or perhaps an inner query, and inserting the results into a table called TABLE_NAME
which has a unique constraint on a column called IDX_COL_NAME
.
INSERT /*+ ignore_row_on_dupkey_index(TABLE_NAME(IDX_COL_NAME)) */
INTO TABLE_NAME(
INDEX_COL_NAME
, col_1
, col_2
, col_3
, ...
, col_n)
SELECT
INDEX_COL_NAME
, col_1
, col_2
, col_3
, ...
, col_n);
This is not a great solution if your goal it to catch and handle (i.e. print out or update the row that is violating the constraint). But if you just wanted to catch it and ignore the violating row then then this should do the job.
If you just need the name of the device here is a little hack which i wrote in bash. To run it in python you need the following snippet. Just replace $1 and $2 with Bus number and Device number eg 001 or 002.
import os
os.system("lsusb | grep \"Bus $1 Device $2\" | sed 's/\// /' | awk '{for(i=7;i<=NF;++i)print $i}'")
Alternately you can save it as a bash script and run it from there too. Just save it as a bash script like foo.sh make it executable.
#!/bin/bash
myvar=$(lsusb | grep "Bus $1 Device $2" | sed 's/\// /' | awk '{for(i=7;i<=NF;++i)print $i}')
echo $myvar
Then call it in python script as
import os
os.system('foo.sh')
For some - possibly valid - reason the url was encoded twice. %25
is the urlencoded %
sign. So the original url looked like:
http://server.com/my path/
Then it got urlencoded once:
http://server.com/my%20path/
and twice:
http://server.com/my%2520path/
So you should do no urlencoding - in your case - as other components seems to to that already for you. Use simply a space
If your project doesn't have an upstream branch, that is if this is the very first time the remote repository is going to know about the branch created in your local repository the following command should work.
git push --set-upstream origin <branch-name>
To increase uploading file's size limit we have two ways
1. IIS6 or lower
By default, in ASP.Net the maximum size of a file to be uploaded to the server is around 4MB. This value can be increased by modifying the maxRequestLength attribute in web.config.
Remember : maxRequestLenght is in KB
Example: if you want to restrict uploads to 15MB, set maxRequestLength to “15360” (15 x 1024).
<system.web>
<!-- maxRequestLength for asp.net, in KB -->
<httpRuntime maxRequestLength="15360" ></httpRuntime>
</system.web>
2. IIS7 or higher
A slight different way used here to upload files.IIS7 has introduced request filtering module.Which executed before ASP.Net.Means the way pipeline works is that the IIS value(maxAllowedContentLength) checked first then ASP.NET value(maxRequestLength) is checked.The maxAllowedContentLength attribute defaults to 28.61 MB.This value can be increased by modifying both attribute in same web.config.
Remember : maxAllowedContentLength is in bytes
Example : if you want to restrict uploads to 15MB, set maxRequestLength to “15360” and maxAllowedContentLength to "15728640" (15 x 1024 x 1024).
<system.web>
<!-- maxRequestLength for asp.net, in KB -->
<httpRuntime maxRequestLength="15360" ></httpRuntime>
</system.web>
<system.webServer>
<security>
<requestFiltering>
<!-- maxAllowedContentLength, for IIS, in bytes -->
<requestLimits maxAllowedContentLength="15728640" ></requestLimits>
</requestFiltering>
</security>
</system.webServer>
MSDN Reference link : https://msdn.microsoft.com/en-us/library/e1f13641(VS.80).aspx
As I just ran into the same problem, I would like to share a few lines of code with you. In fact there are several rather similar posts about autocorrelation in stackoverflow by now. If you define the autocorrelation as a(x, L) = sum(k=0,N-L-1)((xk-xbar)*(x(k+L)-xbar))/sum(k=0,N-1)((xk-xbar)**2)
[this is the definition given in IDL's a_correlate function and it agrees with what I see in answer 2 of question #12269834], then the following seems to give the correct results:
import numpy as np
import matplotlib.pyplot as plt
# generate some data
x = np.arange(0.,6.12,0.01)
y = np.sin(x)
# y = np.random.uniform(size=300)
yunbiased = y-np.mean(y)
ynorm = np.sum(yunbiased**2)
acor = np.correlate(yunbiased, yunbiased, "same")/ynorm
# use only second half
acor = acor[len(acor)/2:]
plt.plot(acor)
plt.show()
As you see I have tested this with a sin curve and a uniform random distribution, and both results look like I would expect them. Note that I used mode="same"
instead of mode="full"
as the others did.
This can a time consuming problem. For those who want to get on with their work because they do not want to waste much time, I would like to suggest that you download the zip file and unpack the zip file and use it. The zip file is available for all major OS.
https://www.eclipse.org/downloads/packages/
Here instead of hitting the Download button, which will download the Eclipse installer, scroll to the middle area where a list of the various Eclipse IDEs with their respective features are shown. Select the Eclipse IDE of your like and click on the link on the right-hand-side to download the zip or corresponding file for your OS version.
If you still want to use your other Eclipse installations because, for example, you have plugins installed, then download the Eclipse installer and on the right-hand top corner press the icon with 3 minus. After that press Update, then after restart, install the version of Eclipse IDE, which you want (the one that you want to reactivate) in a different folder. The installation will take some time. After the installation is finished you should be able to start your old Eclipse IDE.
For footer change from position: relative;
to position:fixed;
footer {
background-color: #333;
width: 100%;
bottom: 0;
position: fixed;
}
Example: http://jsfiddle.net/a6RBm/
Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.
Let me explain using step-by-step guidance.
First, download the source code from https://github.com/rmtheis/tess-two.
Import all three projects. After importing you will get an error.
To solve the error you have to create a res
folder in the tess-two project
First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"
After doing this in all three project the error should be gone.
Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.
Now you just need to import it into your workspace, but first you have to download android-ndk from this site:
http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file
Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable
Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture
done it
Now open cmd and go to on D:\Android Workspace\tess-two like below
If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:
Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest
Import test-two in this and run OCRTest and run it; you will get the best example of OCR.
NOTE: Colin's solution didn't work for me. Facebook may have changed their markup. Using *
should be more future-proof.
Wrap the Like box with a div:
<div id="likebox-wrapper">
<iframe src="..."></iframe> <!-- likebox code -->
</div>
and add this to your css file:
#likebox-wrapper * {
width: 100% !important;
}
Use this to obtain only the filename.
Path.GetFileName(files[0]);
Here is another solution that is very easy to implement with 5 lines of code:
Example:
//This is an IE fix because pointer-events does not work in IE
$(document).on('mousedown', '.TopElement', function (e) {
$(this).hide();
var BottomElement = document.elementFromPoint(e.clientX, e.clientY);
$(this).show();
$(BottomElement).mousedown(); //Manually fire the event for desired underlying element
return false;
});
With Python>3.5, using glob, .
pointing to your current folder and looking for .txt
files:
python -c "import glob;[print(x) for x in glob.glob('./**/*txt', recursive=True)]"
For older versions of Python, you can install glob2
In recent browser, you can use filter
var size = arr.filter(function(value) { return value !== undefined }).length;
console.log(size);
Another method, if the browser supports indexOf for arrays:
var size = arr.slice(0).sort().indexOf(undefined);
If for absurd you have one-digit-only elements in the array, you could use that dirty trick:
console.log(arr.join("").length);
There are several methods you can use, but at the end we have to see if it's really worthy doing these instead of a loop.
I tried the accepted answer, it did not work.
However the simple way to do it is below:-
<option value="1" <c:if test="${item.quantity == 1}"> <c:out value= "selected=selected"/</c:if>>1</option>
<option value="2" <c:if test="${item.quantity == 2}"> <c:out value= "selected=selected"/</c:if>>2</option>
<option value="3" <c:if test="${item.quantity == 3}"> <c:out value= "selected=selected"/</c:if>>3</option>
Enjoy!!
Fastest way I found is via inner1d. Here's how it compares to other numpy methods:
import numpy as np
from numpy.core.umath_tests import inner1d
V = np.random.random_sample((10**6,3,)) # 1 million vectors
A = np.sqrt(np.einsum('...i,...i', V, V))
B = np.linalg.norm(V,axis=1)
C = np.sqrt((V ** 2).sum(-1))
D = np.sqrt((V*V).sum(axis=1))
E = np.sqrt(inner1d(V,V))
print [np.allclose(E,x) for x in [A,B,C,D]] # [True, True, True, True]
import cProfile
cProfile.run("np.sqrt(np.einsum('...i,...i', V, V))") # 3 function calls in 0.013 seconds
cProfile.run('np.linalg.norm(V,axis=1)') # 9 function calls in 0.029 seconds
cProfile.run('np.sqrt((V ** 2).sum(-1))') # 5 function calls in 0.028 seconds
cProfile.run('np.sqrt((V*V).sum(axis=1))') # 5 function calls in 0.027 seconds
cProfile.run('np.sqrt(inner1d(V,V))') # 2 function calls in 0.009 seconds
inner1d is ~3x faster than linalg.norm and a hair faster than einsum
simplifying the general answer
SQL Case Sensitive String Compare
These examples may be helpful:
Declare @S1 varchar(20) = 'SQL'
Declare @S2 varchar(20) = 'sql'
if @S1 = @S2 print 'equal!' else print 'NOT equal!' -- equal (default non-case sensitivity for SQL
if cast(@S1 as binary) = cast(Upper(@S2) as binary) print 'equal!' else print 'NOT equal!' -- equal
if cast(@S1 as binary) = cast(@S2 as binary) print 'equal!' else print 'NOT equal!' -- not equal
if @S1 COLLATE Latin1_General_CS_AS = Upper(@S2) COLLATE Latin1_General_CS_AS print 'equal!' else print 'NOT equal!' -- equal
if @S1 COLLATE Latin1_General_CS_AS = @S2 COLLATE Latin1_General_CS_AS print 'equal!' else print 'NOT equal!' -- not equal
The convert is probably more efficient than something like runtime calculation of hashbytes, and I'd expect the collate may be even faster.
OnClientClick seems to be very picky when used with OnClick.
I tried unsuccessfully with the following use cases:
OnClientClick="return ValidateSearch();"
OnClientClick="if(ValidateSearch()) return true;"
OnClientClick="ValidateSearch();"
But they did not work. The following worked:
<asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1"
OnClick="keywordSearch_Click"
OnClientClick="if (!ValidateSearch()) { return false;};" />
Another solution:
z = 10
for x in range (z):
y = z-x
print y
Result:
10
9
8
7
6
5
4
3
2
1
Tip: If you are using this method to count back indices in a list, you will want to -1 from the 'y' value, as your list indices will begin at 0.
If only the columns are required then DataTable.Clone()
can be used. With Clone
function only the schema will be copied. But DataTable.Copy()
copies both the structure and data
E.g.
DataTable dt = new DataTable();
dt.Columns.Add("Column Name");
dt.Rows.Add("Column Data");
DataTable dt1 = dt.Clone();
DataTable dt2 = dt.Copy();
dt1
will have only the one column but dt2
will have one column with one row.
My Parent Activity extends AppCompatActivity so I had to cast my context to AppCompatActivity instead of just Activity.
eg.
FragmentAddProduct fragmentAddProduct = FragmentAddProduct.newInstance();
FragmentTransaction fragmentTransaction = ((AppCompatActivity)mcontext).getSupportFragmentManager().beginTransaction();
If you want to use Graph API to get current user ID then just send a request to:
https://graph.facebook.com/me?access_token=...
The simplest way:
td:nth-child(2) {
padding-right: 20px;
}?
But that won't work if you need to work with background color or images in your table. In that case, here is a slightly more advanced solution (CSS3):
td:nth-child(2) {
border-right: 10px solid transparent;
-webkit-background-clip: padding;
-moz-background-clip: padding;
background-clip: padding-box;
}
It places a transparent border to the right of the cell and pulls the background color/image away from the border, creating the illusion of spacing between the cells.
Note: For this to work, the parent table must have border-collapse: separate
. If you have to work with border-collapse: collapse
then you have to apply the same border style to the next table cell, but on the left side, to accomplish the same results.
Extract jar file for ex. with winrar and use CAVAJ:
Cavaj Java Decompiler is a graphical freeware utility that reconstructs Java source code from CLASS files.
here is video tutorial if you need: https://www.youtube.com/watch?v=ByLUeem7680
You should be aware that you should avoid file I/O from within Linux kernel when possible. The main idea is to go "one level deeper" and call VFS level functions instead of the syscall handler directly:
Includes:
#include <linux/fs.h>
#include <asm/segment.h>
#include <asm/uaccess.h>
#include <linux/buffer_head.h>
Opening a file (similar to open):
struct file *file_open(const char *path, int flags, int rights)
{
struct file *filp = NULL;
mm_segment_t oldfs;
int err = 0;
oldfs = get_fs();
set_fs(get_ds());
filp = filp_open(path, flags, rights);
set_fs(oldfs);
if (IS_ERR(filp)) {
err = PTR_ERR(filp);
return NULL;
}
return filp;
}
Close a file (similar to close):
void file_close(struct file *file)
{
filp_close(file, NULL);
}
Reading data from a file (similar to pread):
int file_read(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size)
{
mm_segment_t oldfs;
int ret;
oldfs = get_fs();
set_fs(get_ds());
ret = vfs_read(file, data, size, &offset);
set_fs(oldfs);
return ret;
}
Writing data to a file (similar to pwrite):
int file_write(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size)
{
mm_segment_t oldfs;
int ret;
oldfs = get_fs();
set_fs(get_ds());
ret = vfs_write(file, data, size, &offset);
set_fs(oldfs);
return ret;
}
Syncing changes a file (similar to fsync):
int file_sync(struct file *file)
{
vfs_fsync(file, 0);
return 0;
}
[Edit] Originally, I proposed using file_fsync, which is gone in newer kernel versions. Thanks to the poor guy suggesting the change, but whose change was rejected. The edit was rejected before I could review it.
There's another solution for the case that you are working with big data and need to concatenate multiple datasets. concat
can get performance-intensive, so if you don't want to create a new df each time, you can instead use a list comprehension:
frames = [ process_file(f) for f in dataset_files ]
result = pd.append(frames)
(as pointed out here in the docs at the bottom of the section):
Note: It is worth noting however, that
concat
(and thereforeappend
) makes a full copy of the data, and that constantly reusing this function can create a significant performance hit. If you need to use the operation over several datasets, use a list comprehension.
Why not just try opening the file ? fs.open('YourFile', 'a', function (err, fd) { ... })
anyway after a minute search try this :
var path = require('path');
path.exists('foo.txt', function(exists) {
if (exists) {
// do something
}
});
// or
if (path.existsSync('foo.txt')) {
// do something
}
For Node.js v0.12.x and higher
Both path.exists
and fs.exists
have been deprecated
*Edit:
Changed: else if(err.code == 'ENOENT')
to: else if(err.code === 'ENOENT')
Linter complains about the double equals not being the triple equals.
Using fs.stat:
fs.stat('foo.txt', function(err, stat) {
if(err == null) {
console.log('File exists');
} else if(err.code === 'ENOENT') {
// file does not exist
fs.writeFile('log.txt', 'Some log\n');
} else {
console.log('Some other error: ', err.code);
}
});
If you want to input a description you can use this. This works on IE 9 and all other browsers.
<input type="text" onclick="if(this.value=='CVC2: '){this.value='';}" onblur="if(this.value==''){this.value='CVC2: ';}" value="CVC2: "/>
Berkelium is a C++ tool for making chrome embeddable.
AwesomiumDotNet is a wrapper around both Berkelium and Awesomium
BTW, the link here to Awesomium appears to be more current.
Change
for(j = 0; j<=90; j+3)
to
for(j = 0; j<=90; j=j+3)
Try something like this - it works for the cases you have mentioned.
select * from tbl
where answer like '%[0-9]%'
and answer not like '%[:]%'
and answer not like '%[A-Z]%'
Yes: TIME_CREATED contains a date and a time. Use TRUNC
to strip the time:
SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TRUNC(TIME_CREATED) = TO_DATE('26/JAN/2011','dd/mon/yyyy')
UPDATE:
As Dave Costa points out in the comment below, this will prevent Oracle from using the index of the column TIME_CREATED
if it exists. An alternative approach without this problem is this:
SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TIME_CREATED >= TO_DATE('26/JAN/2011','dd/mon/yyyy')
AND TIME_CREATED < TO_DATE('26/JAN/2011','dd/mon/yyyy') + 1
For people (like me) looking to read INI files from shell scripts (read shell, not bash) - I've knocked up the a little helper library which tries to do exactly that:
https://github.com/wallyhall/shini (MIT license, do with it as you please. I've linked above including it inline as the code is quite lengthy.)
It's somewhat more "complicated" than the simple sed
lines suggested above - but works on a very similar basis.
Function reads in a file line-by-line - looking for section markers ([section]
) and key/value declarations (key=value
).
Ultimately you get a callback to your own function - section, key and value.
You can override bean definitions with mocks with spring-reinject https://github.com/sgri/spring-reinject/
Import numpy as np
FOR INDEX
S=[11,2,44,55,66,0,10,3,33]
r=np.argsort(S)
[output]=array([5, 1, 7, 6, 0, 8, 2, 3, 4])
argsort Returns the indices of S in sorted order
FOR VALUE
np.sort(S)
[output]=array([ 0, 2, 3, 10, 11, 33, 44, 55, 66])
For a dynamic approach, if your labels are always in front of your text areas:
$(object).prev("label").text(charsleft);
You can cast an integer to a string in this way
intval::text
and so in your case
SELECT * FROM table WHERE <some integer>::text = 'string of numbers'
I just add numbers to the beginning of file name:
0_normalize.scss
1_tikitaka.scss
main.scss
It works in gulp without any problems.
Random URL and filename string safe (1 liner)
Crypto.randomBytes(48).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
Hey now you can give to body background image
and set the background-position:center center;
as like this
body{
background:url('../img/some.jpg') no-repeat center center;
min-height:100%;
}
One of the most elegant solutions was here Get characters after last / in url
by DisgruntledGoat
$id = substr($url, strrpos($url, '/') + 1);
strrpos gets the position of the last occurrence of the slash; substr returns everything after that position.
Dan Abramov's answer is right about redux-thunk
but I will talk a bit more about redux-saga that is quite similar but more powerful.
redux-thunk
is imperative / redux-saga
is declarativeWhen you have a thunk in your hands, like an IO monad or a promise, you can't easily know what it will do once you execute. The only way to test a thunk is to execute it, and mock the dispatcher (or the whole outside world if it interacts with more stuff...).
If you are using mocks, then you are not doing functional programming.
Seen through the lens of side-effects, mocks are a flag that your code is impure, and in the functional programmer's eye, proof that something is wrong. Instead of downloading a library to help us check the iceberg is intact, we should be sailing around it. A hardcore TDD/Java guy once asked me how you do mocking in Clojure. The answer is, we usually don't. We usually see it as a sign we need to refactor our code.
The sagas (as they got implemented in redux-saga
) are declarative and like the Free monad or React components, they are much easier to test without any mock.
See also this article:
in modern FP, we shouldn’t write programs — we should write descriptions of programs, which we can then introspect, transform, and interpret at will.
(Actually, Redux-saga is like a hybrid: the flow is imperative but the effects are declarative)
There is a lot of confusion in the frontend world on how some backend concepts like CQRS / EventSourcing and Flux / Redux may be related, mostly because in Flux we use the term "action" which can sometimes represent both imperative code (LOAD_USER
) and events (USER_LOADED
). I believe that like event-sourcing, you should only dispatch events.
Imagine an app with a link to a user profile. The idiomatic way to handle this with each middleware would be:
redux-thunk
<div onClick={e => dispatch(actions.loadUserProfile(123)}>Robert</div>
function loadUserProfile(userId) {
return dispatch => fetch(`http://data.com/${userId}`)
.then(res => res.json())
.then(
data => dispatch({ type: 'USER_PROFILE_LOADED', data }),
err => dispatch({ type: 'USER_PROFILE_LOAD_FAILED', err })
);
}
redux-saga
<div onClick={e => dispatch({ type: 'USER_NAME_CLICKED', payload: 123 })}>Robert</div>
function* loadUserProfileOnNameClick() {
yield* takeLatest("USER_NAME_CLICKED", fetchUser);
}
function* fetchUser(action) {
try {
const userProfile = yield fetch(`http://data.com/${action.payload.userId }`)
yield put({ type: 'USER_PROFILE_LOADED', userProfile })
}
catch(err) {
yield put({ type: 'USER_PROFILE_LOAD_FAILED', err })
}
}
This saga translates to:
every time a username gets clicked, fetch the user profile and then dispatch an event with the loaded profile.
As you can see, there are some advantages of redux-saga
.
The usage of takeLatest
permits to express that you are only interested to get the data of the last username clicked (handle concurrency problems in case the user click very fast on a lot of usernames). This kind of stuff is hard with thunks. You could have used takeEvery
if you don't want this behavior.
You keep action creators pure. Note it's still useful to keep actionCreators (in sagas put
and components dispatch
), as it might help you to add action validation (assertions/flow/typescript) in the future.
Your code becomes much more testable as the effects are declarative
You don't need anymore to trigger rpc-like calls like actions.loadUser()
. Your UI just needs to dispatch what HAS HAPPENED. We only fire events (always in the past tense!) and not actions anymore. This means that you can create decoupled "ducks" or Bounded Contexts and that the saga can act as the coupling point between these modular components.
This means that your views are more easy to manage because they don't need anymore to contain that translation layer between what has happened and what should happen as an effect
For example imagine an infinite scroll view. CONTAINER_SCROLLED
can lead to NEXT_PAGE_LOADED
, but is it really the responsibility of the scrollable container to decide whether or not we should load another page? Then he has to be aware of more complicated stuff like whether or not the last page was loaded successfully or if there is already a page that tries to load, or if there is no more items left to load? I don't think so: for maximum reusability the scrollable container should just describe that it has been scrolled. The loading of a page is a "business effect" of that scroll
Some might argue that generators can inherently hide state outside of redux store with local variables, but if you start to orchestrate complex things inside thunks by starting timers etc you would have the same problem anyway. And there's a select
effect that now permits to get some state from your Redux store.
Sagas can be time-traveled and also enables complex flow logging and dev-tools that are currently being worked on. Here is some simple async flow logging that is already implemented:
Sagas are not only replacing redux thunks. They come from backend / distributed systems / event-sourcing.
It is a very common misconception that sagas are just here to replace your redux thunks with better testability. Actually this is just an implementation detail of redux-saga. Using declarative effects is better than thunks for testability, but the saga pattern can be implemented on top of imperative or declarative code.
In the first place, the saga is a piece of software that permits to coordinate long running transactions (eventual consistency), and transactions across different bounded contexts (domain driven design jargon).
To simplify this for frontend world, imagine there is widget1 and widget2. When some button on widget1 is clicked, then it should have an effect on widget2. Instead of coupling the 2 widgets together (ie widget1 dispatch an action that targets widget2), widget1 only dispatch that its button was clicked. Then the saga listen for this button click and then update widget2 by dispaching a new event that widget2 is aware of.
This adds a level of indirection that is unnecessary for simple apps, but make it more easy to scale complex applications. You can now publish widget1 and widget2 to different npm repositories so that they never have to know about each others, without having them to share a global registry of actions. The 2 widgets are now bounded contexts that can live separately. They do not need each others to be consistent and can be reused in other apps as well. The saga is the coupling point between the two widgets that coordinate them in a meaningful way for your business.
Some nice articles on how to structure your Redux app, on which you can use Redux-saga for decoupling reasons:
I want my components to be able to trigger the display of in-app notifications. But I don't want my components to be highly coupled to the notification system that has its own business rules (max 3 notifications displayed at the same time, notification queueing, 4 seconds display-time etc...).
I don't want my JSX components to decide when a notification will show/hide. I just give it the ability to request a notification, and leave the complex rules inside the saga. This kind of stuff is quite hard to implement with thunks or promises.
I've described here how this can be done with saga
The term saga comes from the backend world. I initially introduced Yassine (the author of Redux-saga) to that term in a long discussion.
Initially, that term was introduced with a paper, the saga pattern was supposed to be used to handle eventual consistency in distributed transactions, but its usage has been extended to a broader definition by backend developers so that it now also covers the "process manager" pattern (somehow the original saga pattern is a specialized form of process manager).
Today, the term "saga" is confusing as it can describe 2 different things. As it is used in redux-saga, it does not describe a way to handle distributed transactions but rather a way to coordinate actions in your app. redux-saga
could also have been called redux-process-manager
.
See also:
If you don't like the idea of using generators but you are interested by the saga pattern and its decoupling properties, you can also achieve the same with redux-observable which uses the name epic
to describe the exact same pattern, but with RxJS. If you're already familiar with Rx, you'll feel right at home.
const loadUserProfileOnNameClickEpic = action$ =>
action$.ofType('USER_NAME_CLICKED')
.switchMap(action =>
Observable.ajax(`http://data.com/${action.payload.userId}`)
.map(userProfile => ({
type: 'USER_PROFILE_LOADED',
userProfile
}))
.catch(err => Observable.of({
type: 'USER_PROFILE_LOAD_FAILED',
err
}))
);
yield put(someActionThunk)
if it makes sense.If you are frightened of using Redux-saga (or Redux-observable) but just need the decoupling pattern, check redux-dispatch-subscribe: it permits to listen to dispatches and trigger new dispatches in listener.
const unsubscribe = store.addDispatchListener(action => {
if (action.type === 'ping') {
store.dispatch({ type: 'pong' });
}
});
Install Django pylint:
pip install pylint-django
ctrl+shift+p > Preferences: Configure Language Specific Settings > Python
The settings.json available for python language should look like the below:
{
"python.linting.pylintArgs": [
"--load-plugins=pylint_django"
],
"[python]": {
}
}
This command will get you the Git parent commit-hash:
git log -n 2 <commit-hash>
After that git diff-tool <commit-hash> <parent-commit-hash>
Example:
bonnie@bonnie ~/ $ git log -n 2 7f65b9a9d3820525766fcba285b3c678e889fe3
commit 7f65b9a9d3820525766fcba285b3c678e889fe3b
Author: souparno <[email protected]>
Date: Mon Jul 25 13:17:07 2016 +0530
CSS changed to maintain the aspect ratio of the channel logos and to fit them properly.
commit c3a61f17e14e2b80cf64b172a45f1b4826ee291f
Author: souparno <[email protected]>
Date: Mon Jul 25 11:28:09 2016 +0530
The ratio of the height to width of the channel images are maintained.
After this
git difftool 7f65b9a9d3820525766fcba285b3c678e889fe3b c3a61f17e14e2b80cf64b172a45f1b4826ee291f
A SELECT INTO
statement creates the table for you. There is no need for the CREATE TABLE
statement before hand.
What is happening is that you create #ivmy_cash_temp1
in your CREATE
statement, then the DB tries to create it for you when you do a SELECT INTO
. This causes an error as it is trying to create a table that you have already created.
Either eliminate the CREATE TABLE
statement or alter your query that fills it to use INSERT INTO SELECT
format.
If you need a unique ID added to your new row then it's best to use SELECT INTO
... since IDENTITY()
only works with this syntax.
pure JS solution that will add preloader, set the background-image and then set it up for garbage collection along with it's event listener:
Short version:
const imageUrl = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";_x000D_
let bgElement = document.querySelector("body");_x000D_
let preloaderImg = document.createElement("img");_x000D_
preloaderImg.src = imageUrl;_x000D_
_x000D_
preloaderImg.addEventListener('load', (event) => {_x000D_
bgElement.style.backgroundImage = `url(${imageUrl})`;_x000D_
preloaderImg = null;_x000D_
});
_x000D_
A bit longer with nice opacity transition:
const imageUrl = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";_x000D_
let bgElement = document.querySelector(".bg-lazy");_x000D_
bgElement.classList.add("bg-loading");_x000D_
let preloaderImg = document.createElement("img");_x000D_
preloaderImg.src = imageUrl;_x000D_
_x000D_
preloaderImg.addEventListener('load', (event) => {_x000D_
bgElement.classList.remove("bg-loading");_x000D_
bgElement.style.backgroundImage = `url(${imageUrl})`;_x000D_
preloaderImg = null;_x000D_
});
_x000D_
.bg-lazy {_x000D_
height: 100vh;_x000D_
width: 100vw;_x000D_
transition: opacity 1s ease-out;_x000D_
}_x000D_
_x000D_
.bg-loading {_x000D_
opacity: 0;_x000D_
}
_x000D_
<div class="bg-lazy"></div>
_x000D_
try this one
String fileSuffix = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
If you want to change MSSQL server language, you can use the following QUERY:
EXEC sp_configure 'default language', 'British English';
public static bool TestOpenPort(int Port)
{
var tcpListener = default(TcpListener);
try
{
var ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
tcpListener = new TcpListener(ipAddress, Port);
tcpListener.Start();
return true;
}
catch (SocketException)
{
}
finally
{
if (tcpListener != null)
tcpListener.Stop();
}
return false;
}
Here's a demo of the above:https://jsfiddle.net/sajadweb/mjnyLm0q/11
new Vue({_x000D_
el: '#app',_x000D_
data: {_x000D_
users: [{ name: 'sajadweb',email:'[email protected]' }] _x000D_
},_x000D_
methods: {_x000D_
addUser: function () {_x000D_
this.users.push({ name: '',email:'' });_x000D_
},_x000D_
deleteUser: function (index) {_x000D_
console.log(index);_x000D_
console.log(this.finds);_x000D_
this.users.splice(index, 1);_x000D_
if(index===0)_x000D_
this.addUser()_x000D_
}_x000D_
}_x000D_
});
_x000D_
<script src="https://unpkg.com/vue/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
<h1>Add user</h1>_x000D_
<div v-for="(user, index) in users">_x000D_
<input v-model="user.name">_x000D_
<input v-model="user.email">_x000D_
<button @click="deleteUser(index)">_x000D_
delete_x000D_
</button>_x000D_
</div>_x000D_
_x000D_
<button @click="addUser">_x000D_
New User_x000D_
</button>_x000D_
_x000D_
<pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
In my opinion, jQuery's animate
is a bit overused, compared to the CSS3 transition
, which performs such animation on any 2D or 3D property. Also I'm afraid, that leaving it to the browser and by forgetting the layer called JavaScript could lead to spare CPU juice - specially, when you wish to blast with the animations. Thus, I like to have animations where the style definitions are, since you define functionality with JavaScript. The more presentation you inject into JavaScript, the more problems you'll face later on.
All you have to do is to use addClass
to the element you wish to animate, where you set a class that has CSS transition
properties. You just "activate" the animation, which stays implemented on the pure presentation layer.
.js
// with jQuery
$("#element").addClass("Animate");
// without jQuery library
document.getElementById("element").className += "Animate";
One could easly remove a class with jQuery, or remove a class without library.
.css
#element{
color : white;
}
#element.Animate{
transition : .4s linear;
color : red;
/**
* Not that ugly as the JavaScript approach.
* Easy to maintain, the most portable solution.
*/
-webkit-transform : rotate(90deg);
}
.html
<span id="element">
Text
</span>
This is a fast and convenient solution for most use cases.
I also use this when I want to implement a different styling (alternative CSS properties), and wish to change the style on-the-fly with a global .5s animation. I add a new class to the BODY
, while having alternative CSS in a form like this:
.js
$("BODY").addClass("Alternative");
.css
BODY.Alternative #element{
color : blue;
transition : .5s linear;
}
This way you can apply different styling with animations, without loading different CSS files. You only involve JavaScript to set a class
.
Look at your actual html code and check that the weird symbols are not originating there. This issue came up when I started coding in Notepad++ halfway after coding in Notepad. It seems to me that the older version of Notepad I was using may have used different encoding to Notepad's++ UTF-8 encoding. After I transferred my code from Notepad to Notepad++, the apostrophes got replaced with weird symbols, so I simply had to remove the symbols from my Notepad++ code.
If you want easy to use libraries, you can use the NUGET packages:
Note these are 3rd-Party packages - you can use them for basic functionality for free, but if you want more features there might be a "pro" version.
They are using a two-dimensional object array (i.e. object[][] cells
) to read / write data.
Another way to set the status bar color is through the style.xml.
To do that, create a style.xml file under res/values-v21 folder with this content:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="android:Theme.Material">
<!-- darker variant for the status bar and contextual app bars -->
<item name="android:colorPrimaryDark">@color/blue_dark</item>
</style>
</resources>
Edit: as pointed out in comments, when using AppCompat the code is different. In file res/values/style.xml use instead:
<style name="Theme.MyTheme" parent="Theme.AppCompat.Light">
<!-- Set AppCompat’s color theming attrs -->
<item name="colorPrimary">@color/my_awesome_red</item>
<item name="colorPrimaryDark">@color/my_awesome_darker_red</item>
<!-- Other attributes -->
</style>
Here is worked for me:
Subject: SomeSubject
From:Company B (me)
Reply-to:Company A
To:Company A's customers
A few of my view controllers were missing the storyboardIdentifier attribute.
Before:
<viewController
id="pka-il-u5E"
customClass="YourViewControllerName"
customModule="ModuleName"
customModuleProvider="target"
sceneMemberID="viewController">
After:
<viewController
storyboardIdentifier="YourViewControllerName" <----
id="pka-il-u5E"
customClass="YourViewControllerName"
customModule="ModuleName"
customModuleProvider="target"
sceneMemberID="viewController">
Java's parser in java.net.URI
is going to fail if the URI isn't fully encoded to its standards. For example, try to parse: http://www.google.com/search?q=cat|dog
. An exception will be thrown for the vertical bar.
urllib makes it easy to convert a string to a java.net.URI
. It will pre-process and escape the URL.
assertEquals("http://www.google.com/search?q=cat%7Cdog",
Urls.createURI("http://www.google.com/search?q=cat|dog").toString());
It's an indication that connection pooling is being used (which is a good thing).
Or, if you know the width of the two "side" images and don't want to deal with floats:
<div class="container">
<div class="left-panel"><img src="myleftimage" /></div>
<div class="center-panel">Content goes here...</div>
<div class="right-panel"><img src="myrightimage" /></div>
</div>
CSS:
.container {
position:relative;
padding-left:50px;
padding-right:50px;
}
.container .left-panel {
width: 50px;
position:absolute;
left:0px;
top:0px;
}
.container .right-panel {
width: 50px;
position:absolute;
right:0px;
top:0px;
}
.container .center-panel {
background: url('mymiddleimage');
}
Notes:
Position:relative on the parent div is used to make absolutely positioned children position themselves relative to that node.
Even at the time of this question, over 3 years ago, Sage (which is completely free) existed and was pretty good at graph theory. But, in 2012 it is about the best graph theory tool there is. Thus, Sage already has a huge amount of graph theory material built in, including other free and open source stuff that is out there. So, simply messing around with various things to learn more is easy as no programming is required.
And, if you are interested in the programming part as well, first Sage is open source so you can see any code that already exists. And, second, you can re-program any function you want if you really want to practice, or you can be the first to program something that does not already exist. In the latter case, you can even submit that new functionality and make Sage better for all other users.
At this time, this answer may not be that useful to the OP (since it has been 3 years), but hopefully it is useful to any one else who sees this question in the future.
I have found a good work-around for continue (love the break sample above). Here I do not want to list "agency". In PHP I'd "continue" but in twig, I came up with alternative:
{% for basename, perms in permsByBasenames %}
{% if basename == 'agency' %}
{# do nothing #}
{% else %}
<a class="scrollLink" onclick='scrollToSpot("#{{ basename }}")'>{{ basename }}</a>
{% endif %}
{% endfor %}
OR I simply skip it if it doesn't meet my criteria:
{% for tr in time_reports %}
{% if not tr.isApproved %}
.....
{% endif %}
{% endfor %}
The correct way to do this is to use show
and hide
:
$('#id').hide();
$('#id').show();
An alternate way is to use the jQuery css method:
$("#id").css("display", "none");
$("#id").css("display", "block");
you may use yourArray.length
to findout number of elements in an array.
Make sure yourArray is not null before doing yourArray.length
, otherwise you will end up with NullPointerException
.
If you want to increase or add time limit to all sites then you can add below lines to the
nginx.conf
file.
Add below lines to the http
section of /usr/local/etc/nginx/nginx.conf
or /etc/nginx/nginx.conf
file.
fastcgi_read_timeout 600;
proxy_read_timeout 600;
If the above lines doesn't exist in conf
file then add them, otherwise increase fastcgi_read_timeout
and proxy_read_timeout
to make sure that nginx and php-fpm did not timeout.
To increase time limit for only one site then you can edit in vim
/etc/nginx/sites-available/example.com
location ~ \.php$ {
include /etc/nginx/fastcgi_params;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_read_timeout 300;
}
and after adding these lines in nginx.conf
, then don't forget to restart nginx.
service php7-fpm reload
service nginx reload
or, if you're using valet then simply type valet restart
.
Just for the sake of completeness, here is a link to the golang documentation which describes all types. In your case it is numeric types:
uint8 the set of all unsigned 8-bit integers (0 to 255)
uint16 the set of all unsigned 16-bit integers (0 to 65535)
uint32 the set of all unsigned 32-bit integers (0 to 4294967295)
uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615)
int8 the set of all signed 8-bit integers (-128 to 127)
int16 the set of all signed 16-bit integers (-32768 to 32767)
int32 the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)
float32 the set of all IEEE-754 32-bit floating-point numbers
float64 the set of all IEEE-754 64-bit floating-point numbers
complex64 the set of all complex numbers with float32 real and imaginary parts
complex128 the set of all complex numbers with float64 real and imaginary parts
byte alias for uint8
rune alias for int32
Which means that you need to use float64(integer_value)
.
I'm 9 years late but a more dynamic way would be
function myFunction {
for i in "$*"; do echo "$i"; done;
}
The following will solve your problem:
td.last {
width: 1px;
white-space: nowrap;
}
And a more flexible solution is creating a .fitwidth
class and applying that to any columns you want to ensure their contents are fit on one line:
td.fitwidth {
width: 1px;
white-space: nowrap;
}
And then in your HTML:
<tr>
<td class="fitwidth">ID</td>
<td>Description</td>
<td class="fitwidth">Status</td>
<td>Notes</td>
</tr>
Since it's a long time and people keep suggesting to use Scanner#nextLine()
, there's another chance that Scanner
can take spaces included in input.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You can use Scanner#useDelimiter()
to change the delimiter of Scanner
to another pattern such as a line feed
or something else.
Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;
System.out.println("Please input question:");
question = in.next();
// TODO do something with your input such as removing spaces...
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
Something like this might work:
$("body").attr("class", "about");
It uses jQuery's attr()
to add the class 'about' to the body.