Delete all app files from Phone
To automate the deletion of an app on your phone you can use the steps below. It can be very useful to delete your app and app data on a quick and clean way.
Make a textfile with this code and save it as Uninstall.sh. Go to the folder (where you've put it) of this script in the terminal and do: sh Uninstall.sh YOURNAMESPACE
Now your namespacefolder (including saved appfiles and database) will be deleted.
echo "Going to platform tools $HOME/Library/Android/sdk/platform-tools"
cd $HOME/Library/Android/sdk/platform-tools
echo "uninstalling app with packagae name $1"
./adb uninstall $1
Delete all app files from pc
Make a textfile with this code and save it as DeleteBinObj.sh.
find . -iname "bin" -o -iname "obj" | xargs rm -rf
Go to the folder of your project where you place this script and do in the terminal: sh DeleteBinObj.sh
My problem was that I had other libraries that my project referenced and those libraries had another version of appcompat referenced. This is what I did to resolve the issue:
(You should back up your project before doing this)
1) I deleted all the appcompat layout folders (ex: /res/layout-v11).
2) Solved the problems that arose from that, usually an error in menu.xml
3) Back to main project and add appcompat library, clean, and everything works!
This solution worked for me using the android sdk v19:
//get the image button by id
ImageButton myImg = (ImageButton) findViewById(R.id.some_id);
//get drawable from image button
GradientDrawable drawable = (GradientDrawable) myImg.getDrawable();
//set color as integer
//can use Color.parseColor(color) if color is a string
drawable.setColor(color)
The solution is much simpler:
$('#date').datepicker({
startDate: "now()"
});
Try Online Demo and fill input Start date: now()
I had some trouble determining the Java package that was installed when I ran into this problem, since the previous answers didn't exactly work for me. To sort it out, I typed:
Sys.setenv(JAVA_HOME="C:/Program Files/Java/
and then hit tab and the two suggested directories were "jre1.8.0_31/" and "jre7/"
Jre7 didn't solve my problem, but jre1.8.0_31/ did. Final answer was running (before library(rJava)):
Sys.setenv(JAVA_HOME="C:/Program Files/Java/jre1.8.0_31/")
I'm using 64-bit Windows 8.1 Hope this helps someone else.
Update:
Check your version to determine what X should be (mine has changed several times since this post):
Sys.setenv(JAVA_HOME="C:/Program Files/Java/jre1.8.0_x/")
Here's how i conditionally applied gray text style on a disabled button
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
styleUrls: [ './app.component.css' ],
template: `
<button
(click)='buttonClick1()'
[disabled] = "btnDisabled"
[ngStyle]="{'color': (btnDisabled)? 'gray': 'black'}">
{{btnText}}
</button>`
})
export class AppComponent {
name = 'Angular';
btnText = 'Click me';
btnDisabled = false;
buttonClick1() {
this.btnDisabled = true;
this.btnText = 'you clicked me';
setTimeout(() => {
this.btnText = 'click me again';
this.btnDisabled = false
}, 5000);
}
}
Here's a working example:
https://stackblitz.com/edit/example-conditional-disable-button?file=src%2Fapp%2Fapp.component.html
From my understanding, the currently accepted answer only changes the order of the factor levels, not the actual labels (i.e., how the levels of the factor are called). To illustrate the difference between levels and labels, consider the following example:
Turn cyl
into factor (specifying levels would not be necessary as they are coded in alphanumeric order):
mtcars2 <- mtcars %>% mutate(cyl = factor(cyl, levels = c(4, 6, 8)))
mtcars2$cyl[1:5]
#[1] 6 6 4 6 8
#Levels: 4 6 8
Change the order of levels (but not the labels itself: cyl is still the same column)
mtcars3 <- mtcars2 %>% mutate(cyl = factor(cyl, levels = c(8, 6, 4)))
mtcars3$cyl[1:5]
#[1] 6 6 4 6 8
#Levels: 8 6 4
all(mtcars3$cyl==mtcars2$cyl)
#[1] TRUE
Assign new labels to cyl
The order of the labels was: c(8, 6, 4), hence we specify new labels as follows:
mtcars4 <- mtcars3 %>% mutate(cyl = factor(cyl, labels = c("new_value_for_8",
"new_value_for_6",
"new_value_for_4" )))
mtcars4$cyl[1:5]
#[1] new_value_for_6 new_value_for_6 new_value_for_4 new_value_for_6 new_value_for_8
#Levels: new_value_for_8 new_value_for_6 new_value_for_4
Note how this column differs from our first columns:
all(as.character(mtcars4$cyl)!=mtcars3$cyl)
#[1] TRUE
#Note: TRUE here indicates that all values are unequal because I used != instead of ==
#as.character() was required as the levels were numeric and thus not comparable to a character vector
More details:
If we were to change the levels of cyl
using mtcars2
instead of mtcars3
, we would need to specify the labels differently to get the same result. The order of labels for mtcars2
was: c(4, 6, 8), hence we specify new labels as follows
#change labels of mtcars2 (order used to be: c(4, 6, 8)
mtcars5 <- mtcars2 %>% mutate(cyl = factor(cyl, labels = c("new_value_for_4",
"new_value_for_6",
"new_value_for_8" )))
Unlike mtcars3$cyl
and mtcars4$cyl
, the labels of mtcars4$cyl
and mtcars5$cyl
are thus identical, even though their levels have a different order.
mtcars4$cyl[1:5]
#[1] new_value_for_6 new_value_for_6 new_value_for_4 new_value_for_6 new_value_for_8
#Levels: new_value_for_8 new_value_for_6 new_value_for_4
mtcars5$cyl[1:5]
#[1] new_value_for_6 new_value_for_6 new_value_for_4 new_value_for_6 new_value_for_8
#Levels: new_value_for_4 new_value_for_6 new_value_for_8
all(mtcars4$cyl==mtcars5$cyl)
#[1] TRUE
levels(mtcars4$cyl) == levels(mtcars5$cyl)
#1] FALSE TRUE FALSE
Your first problem is that you are passing -3 to the 2nd parameter of Columns.Add. It needs to be -2 for it to auto-size the column. Source: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columns.aspx (look at the comments on the code example at the bottom)
private void initListView()
{
// Add columns
lvRegAnimals.Columns.Add("Id", -2,HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);
}
You can also use the other overload, Add(string). E.g:
lvRegAnimals.Columns.Add("Id");
lvRegAnimals.Columns.Add("Name");
lvRegAnimals.Columns.Add("Age");
Reference for more overloads: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columnheadercollection.aspx
Second, to add items to the ListView, you need to create instances of ListViewItem and add them to the listView's Items collection. You will need to use the string[] constructor.
var item1 = new ListViewItem(new[] {"id123", "Tom", "24"});
var item2 = new ListViewItem(new[] {person.Id, person.Name, person.Age});
lvRegAnimals.Items.Add(item1);
lvRegAnimals.Items.Add(item2);
You can also store objects in the item's Tag property.
item2.Tag = person;
And then you can extract it
var person = item2.Tag as Person;
Let me know if you have any questions and I hope this helps!
You are writing to memory you do not own:
int board[2][50]; //make an array with 3 columns (wrong)
//(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
board[2][i] = 'O';
^
Change this line:
int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
^
To:
int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
^
When creating an array, the value used to initialize: [3]
indicates array size.
However, when accessing existing array elements, index values are zero based.
For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]
EDIT To address bad output comment and initialization comment
add an additional "\n" for formatting output:
Change:
...
for (k=0; k<50;k++) {
printf("%d",board[j][k]);
}
}
...
To:
...
for (k=0; k<50;k++) {
printf("%d",board[j][k]);
}
printf("\n");//at the end of every row, print a new line
}
...
Initialize board variable:
int board[3][50] = {0};//initialize all elements to zero
Or you can simply use javascript code :
onClick="javascript:history.go(-1);"
Like:
<a class="back" ng-class="icons">
<img src="../media/icons/right_circular.png" onClick="javascript:history.go(-1);" />
</a>
Well, you can always try WHERE textcolumn LIKE "%SUBSTRING%"
- but this is guaranteed to be pretty slow, as your query can't do an index match because you are looking for characters on the left side.
It depends on the field type - a textarea usually won't be saved as VARCHAR, but rather as (a kind of) TEXT field, so you can use the MATCH AGAINST operator.
To get the columns that don't match, simply put a NOT in front of the like: WHERE textcolumn NOT LIKE "%SUBSTRING%"
.
Whether the search is case-sensitive or not depends on how you stock the data, especially what COLLATION you use. By default, the search will be case-insensitive.
I say that doing a WHERE field LIKE "%value%"
is slower than WHERE field LIKE "value%"
if the column field has an index, but this is still considerably faster than getting all values and having your application filter. Both scenario's:
1/ If you do SELECT field FROM table WHERE field LIKE "%value%"
, MySQL will scan the entire table, and only send the fields containing "value".
2/ If you do SELECT field FROM table
and then have your application (in your case PHP) filter only the rows with "value" in it, MySQL will also scan the entire table, but send all the fields to PHP, which then has to do additional work. This is much slower than case #1.
Solution: Please do use the WHERE
clause, and use EXPLAIN
to see the performance.
This is the right way:
double randd() {
return (double)rand() / ((double)RAND_MAX + 1);
}
or
double randd() {
return (double)rand() / (RAND_MAX + 1.0);
}
You can now (C++14) return a locally-defined (i.e. defined inside the function) as follows:
auto f()
{
struct S
{
int a;
double b;
} s;
s.a = 42;
s.b = 42.0;
return s;
}
auto x = f();
a = x.a;
b = x.b;
Yes, wrap it and use the Collections framework.
List l = new ArrayList();
l.add(new xClass());
// do stuff
l.add(new xClass());
Then use List.toArray() when necessary, or just iterate over said List.
maybe not the most efficient, but reads data in one line:
#include<iostream>
#include<vector>
#include<iterator>
main(int argc,char *argv[]){
// read standard input into vector:
std::vector<char>v(std::istream_iterator<char>(std::cin),
std::istream_iterator<char>());
std::cout << "read " << v.size() << "chars\n";
}
You need the key in dict
idiom for that.
if key in my_dict and not (my_dict[key] is None):
# do something
else:
# do something else
However, you should probably consider using defaultdict
(as dF suggested).
see how exceptions work by default if one vs more attributes are used (tracebacks omitted):
>>> raise Exception('bad thing happened')
Exception: bad thing happened
>>> raise Exception('bad thing happened', 'code is broken')
Exception: ('bad thing happened', 'code is broken')
so you might want to have a sort of "exception template", working as an exception itself, in a compatible way:
>>> nastyerr = NastyError('bad thing happened')
>>> raise nastyerr
NastyError: bad thing happened
>>> raise nastyerr()
NastyError: bad thing happened
>>> raise nastyerr('code is broken')
NastyError: ('bad thing happened', 'code is broken')
this can be done easily with this subclass
class ExceptionTemplate(Exception):
def __call__(self, *args):
return self.__class__(*(self.args + args))
# ...
class NastyError(ExceptionTemplate): pass
and if you don't like that default tuple-like representation, just add __str__
method to the ExceptionTemplate
class, like:
# ...
def __str__(self):
return ': '.join(self.args)
and you'll have
>>> raise nastyerr('code is broken')
NastyError: bad thing happened: code is broken
I did not have much success with the above setTimeout
methods in Firefox.
Instead of a setTimeout, I've used an onload function:
window.onload = function () {
if (location.hash) {
window.scrollTo(0, 0);
}
};
It's still very glitchy, unfortunately.
overflow:hidden
(as mentioned by @Mikael S) doesn't work in every situation, but it should work in most situations.
Another option is to use the :after
trick:
<div class="wrapper">
<div class="col"></div>
<div class="col"></div>
</div>
.wrapper {
min-height: 1px; /* Required for IE7 */
}
.wrapper:after {
clear: both;
display: block;
height: 0;
overflow: hidden;
visibility: hidden;
content: ".";
font-size: 0;
}
.col {
display: inline;
float: left;
}
And for IE6:
.wrapper { height: 1px; }
If you want to convert to integers only, another fast (and short) way is the double-bitwise not (i.e. using two tilde characters):
e.g.
~~x;
Reference: http://james.padolsey.com/cool-stuff/double-bitwise-not/
The 5 common ways I know so far to convert a string to a number all have their differences (there are more bitwise operators that work, but they all give the same result as ~~
). This JSFiddle shows the different results you can expect in the debug console: http://jsfiddle.net/TrueBlueAussie/j7x0q0e3/22/
var values = ["123",
undefined,
"not a number",
"123.45",
"1234 error",
"2147483648",
"4999999999"
];
for (var i = 0; i < values.length; i++){
var x = values[i];
console.log(x);
console.log(" Number(x) = " + Number(x));
console.log(" parseInt(x, 10) = " + parseInt(x, 10));
console.log(" parseFloat(x) = " + parseFloat(x));
console.log(" +x = " + +x);
console.log(" ~~x = " + ~~x);
}
123
Number(x) = 123
parseInt(x, 10) = 123
parseFloat(x) = 123
+x = 123
~~x = 123
undefined
Number(x) = NaN
parseInt(x, 10) = NaN
parseFloat(x) = NaN
+x = NaN
~~x = 0
null
Number(x) = 0
parseInt(x, 10) = NaN
parseFloat(x) = NaN
+x = 0
~~x = 0
"not a number"
Number(x) = NaN
parseInt(x, 10) = NaN
parseFloat(x) = NaN
+x = NaN
~~x = 0
123.45
Number(x) = 123.45
parseInt(x, 10) = 123
parseFloat(x) = 123.45
+x = 123.45
~~x = 123
1234 error
Number(x) = NaN
parseInt(x, 10) = 1234
parseFloat(x) = 1234
+x = NaN
~~x = 0
2147483648
Number(x) = 2147483648
parseInt(x, 10) = 2147483648
parseFloat(x) = 2147483648
+x = 2147483648
~~x = -2147483648
4999999999
Number(x) = 4999999999
parseInt(x, 10) = 4999999999
parseFloat(x) = 4999999999
+x = 4999999999
~~x = 705032703
The ~~x
version results in a number in "more" cases, where others often result in undefined
, but it fails for invalid input (e.g. it will return 0
if the string contains non-number characters after a valid number).
Please note: Integer overflow and/or bit truncation can occur with ~~
, but not the other conversions. While it is unusual to be entering such large values, you need to be aware of this. Example updated to include much larger values.
Some Perf tests indicate that the standard parseInt
and parseFloat
functions are actually the fastest options, presumably highly optimised by browsers, but it all depends on your requirement as all options are fast enough: http://jsperf.com/best-of-string-to-number-conversion/37
This all depends on how the perf tests are configured as some show parseInt/parseFloat to be much slower.
The folder containing your Anaconda installation contains a subfolder called conda-meta
with json files for all installed packages, including one for Anaconda itself. Look for anaconda-<version>-<build>.json
.
My file is called anaconda-5.0.1-py27hdb50712_1.json
, and at the bottom is more info about the version:
"installed_by": "Anaconda2-5.0.1-Windows-x86_64.exe",
"link": { "source": "C:\\ProgramData\\Anaconda2\\pkgs\\anaconda-5.0.1-py27hdb50712_1" },
"name": "anaconda",
"platform": "win",
"subdir": "win-64",
"url": "https://repo.continuum.io/pkgs/main/win-64/anaconda-5.0.1-py27hdb50712_1.tar.bz2",
"version": "5.0.1"
(Slightly edited for brevity.)
The output from conda -V
is the conda version.
Do you mean, a message box?
MessageBox.Show("Error Message", "Error Title", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
More information here: http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox(v=VS.100).aspx
Here's an approach on how you might implement a _class
method that works as self.class
for this situation. Note: Do not use this in production code, this is for interest-sake :)
From: Can you eval code in the context of a caller in Ruby? and also http://rubychallenger.blogspot.com.au/2011/07/caller-binding.html
# Rabid monkey-patch for Object
require 'continuation' if RUBY_VERSION >= '1.9.0'
class Object
def __; eval 'self.class', caller_binding; end
alias :_class :__
def caller_binding
cc = nil; count = 0
set_trace_func lambda { |event, file, lineno, id, binding, klass|
if count == 2
set_trace_func nil
cc.call binding
elsif event == "return"
count += 1
end
}
return callcc { |cont| cc = cont }
end
end
# Now we have awesome
def Tiger
def roar
# self.class.roar
__.roar
# or, even
_class.roar
end
def self.roar
# TODO: tigerness
end
end
Maybe the right answer is to submit a patch for Ruby :)
In the very most simple case of no collisions
See also:
man git-pull
More precisely, git pull runs git fetch with the given parameters and calls git merge to merge the retrieved branch heads into the current branch. With --rebase, it runs git rebase instead of git merge.
See also:
When should I use git pull --rebase?
http://git-scm.com/book/en/Git-Branching-Rebasing
To invoke a dry run:
make -n
This will show what make
is attempting to do.
The field nbytes will give you the size in bytes of all the elements of the array in a numpy.array
:
size_in_bytes = my_numpy_array.nbytes
Notice that this does not measures "non-element attributes of the array object" so the actual size in bytes can be a few bytes larger than this.
I have faced the same issue where my objective is to persist Enum String value into database instead of Ordinal value.
To over come this issue, I have used @Enumerated(EnumType.STRING)
and my objective got resolved.
For Example, you have an Enum
Class:
public enum FurthitMethod {
Apple,
Orange,
Lemon
}
In the entity class, define @Enumerated(EnumType.STRING)
:
@Enumerated(EnumType.STRING)
@Column(name = "Fruits")
public FurthitMethod getFuritMethod() {
return fruitMethod;
}
public void setFruitMethod(FurthitMethod authenticationMethod) {
this.fruitMethod= fruitMethod;
}
While you try to set your value to Database, String value will be persisted into Database as "APPLE
", "ORANGE
" or "LEMON
".
This is old, but someone else may stumble on it as I did. When you connect to the DataCast, you are talking to a daemon that can access the database. It was intended that a customer would write some code to access the database and store the results somewhere. It just happens that telnet works to access data manually. netcat should also work. ssh obviously will not.
"I actually tried to had a normal objective discusssion over pros and cons of 1., using framework over pure javascript and 2., jquery vs. others, since jQuery seems to be easiest to work with with quickest learning curve."
Using any framework because you don't want to actually learn the underlying language is absolutely wrong not only for JavaScript, but for any other programming language.
"Is there any reason (besides browser sniffing and personal "hate" against John Resig) why jQuery is wrong?"
Most of the hate agains it comes from the exaggerated fanboyism which pollutes forums with "use jQuery" as an answer for every single JavaScript question and the overuse which produces code in which simple statements such as declaring a variable are done through library calls.
Nevertheless, there are also some legit technical issues such as the shared guilt in producing illegible code and overhead. Of course those two are aggravated by the lack of developer proficiency rather than the library itself.
Take a loot at the Wikipedia article on random numbers as it talks about using sampling techniques. You can find the equation for your normal distribution by plugging into this one
(equation via Wikipedia)
As for the second issue, go into Options under the circle Office icon, go to formulas, and change calculations to "Manual". That will maintain your sheet and not recalculate the formulas each time.
As previous answers have solved for, but should be stated very explicitly: the php code needs to live in the php-fpm container, while the static files need to live in the nginx container. For simplicity, most people have just attached all the code to both, as I have also done below. If the future, I will likely separate out these different parts of the code in my own projects as to minimize which containers have access to which parts.
Updated my example files below with this latest revelation (thank you @alkaline )
This seems to be the minimum setup for docker 2.0 forward (because things got a lot easier in docker 2.0)
docker-compose.yml:
version: '2'
services:
php:
container_name: test-php
image: php:fpm
volumes:
- ./code:/var/www/html/site
nginx:
container_name: test-nginx
image: nginx:latest
volumes:
- ./code:/var/www/html/site
- ./site.conf:/etc/nginx/conf.d/site.conf:ro
ports:
- 80:80
(UPDATED the docker-compose.yml above: For sites that have css, javascript, static files, etc, you will need those files accessible to the nginx container. While still having all the php code accessible to the fpm container. Again, because my base code is a messy mix of css, js, and php, this example just attaches all the code to both containers)
In the same folder:
site.conf:
server
{
listen 80;
server_name site.local.[YOUR URL].com;
root /var/www/html/site;
index index.php;
location /
{
try_files $uri =404;
}
location ~ \.php$ {
fastcgi_pass test-php:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
In folder code:
./code/index.php:
<?php
phpinfo();
and don't forget to update your hosts file:
127.0.0.1 site.local.[YOUR URL].com
and run your docker-compose up
$docker-compose up -d
and try the URL from your favorite browser
site.local.[YOUR URL].com/index.php
I had a similar problem when I needed to make multiple sql queries. The problem was that some queries did not return the result and I wanted to print that result. And there was a mistake. As already written, there are several solutions.
if cursor.description is None:
# No recordset for INSERT, UPDATE, CREATE, etc
pass
else:
# Recordset for SELECT
As well as:
exist = cursor.fetchone()
if exist is None:
... # does not exist
else:
... # exists
One of the solutions is:
The try
and except
block lets you handle the error
/exceptions
. The finally
block lets you execute code, regardless of the result of the try
and except
blocks.
So the presented problem can be solved by using it.
s = """ set current query acceleration = enable;
set current GET_ACCEL_ARCHIVE = yes;
SELECT * FROM TABLE_NAME;"""
query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
print(f"Executing SQL statements ====> {sql} <=====")
cursor.execute(sql)
print(f"SQL ====> {sql} <===== was executed successfully")
try:
print("\n****************** RESULT ***********************")
for result in cursor.fetchall():
print(result)
print("****************** END RESULT ***********************\n")
except Exception as e:
print(f"SQL: ====> {sql} <==== doesn't have output!\n")
# print(str(e))
output:
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!
Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!
Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====
****************** RESULT ***********************
---------- DATA ----------
****************** END RESULT ***********************
The example above only presents a simple use as an idea that could help with your solution. Of course, you should also pay attention to other errors, such as the correctness of the query, etc.
watch is good but will clean the screen.
watch -n 1 'ps aux | grep php'
HTTP Servers tend to reject old browsers and systems.
The page Tech Blog (wh): Most Common User Agents reflects the user-agent property of your current browser in section "Your user agent is:", which can be applied to set the request property "User-Agent" of a java.net.URLConnection
or the system property "http.agent".
You mean this?
git checkout destination_branch
git merge tag_name
Note that this is the procedural approach, which I use for quick debugging
DB::enableQueryLog();
// Run your queries
// ...
// Then to retrieve everything since you enabled the logging:
$queries = DB::getQueryLog();
foreach($queries as $i=>$query)
{
Log::debug("Query $i: " . json_encode($query));
}
in your header, use:
use DB;
use Illuminate\Support\Facades\Log;
The output will look something like this (default log file is laravel.log):
[2015-09-25 12:33:29] testing.DEBUG: Query 0: {"query":"select * from 'users' where ('user_id' = ?)","bindings":["9"],"time":0.23}
***I know this question specified Laravel 3/4 but this page comes up when searching for a general answer. Newbies to Laravel may not know there is a difference between versions. Since I never see DD::enableQueryLog()
mentioned in any of the answers I normally find, it may be specific to Laravel 5 - perhaps someone can comment on that.
I have just cooked up another solution for this, where it's not longer necessary to use a -much to high- max-height value. It needs a few lines of javascript code to calculate the inner height of the collapsed DIV but after that, it's all CSS.
1) Fetching and setting height
Fetch the inner height of the collapsed element (using scrollHeight
). My element has a class .section__accordeon__content
and I actually run this in a forEach()
loop to set the height for all panels, but you get the idea.
document.querySelectorAll( '.section__accordeon__content' ).style.cssText = "--accordeon-height: " + accordeonPanel.scrollHeight + "px";
2) Use the CSS variable to expand the active item
Next, use the CSS variable to set the max-height
value when the item has an .active
class.
.section__accordeon__content.active {
max-height: var(--accordeon-height);
}
Final example
So the full example goes like this: first loop through all accordeon panels and store their scrollHeight
values as CSS variables. Next use the CSS variable as the max-height
value on the active/expanded/open state of the element.
Javascript:
document.querySelectorAll( '.section__accordeon__content' ).forEach(
function( accordeonPanel ) {
accordeonPanel.style.cssText = "--accordeon-height: " + accordeonPanel.scrollHeight + "px";
}
);
CSS:
.section__accordeon__content {
max-height: 0px;
overflow: hidden;
transition: all 425ms cubic-bezier(0.465, 0.183, 0.153, 0.946);
}
.section__accordeon__content.active {
max-height: var(--accordeon-height);
}
And there you have it. A adaptive max-height animation using only CSS and a few lines of JavaScript code (no jQuery required).
Hope this helps someone in the future (or my future self for reference).
Try this way. make a loop inside java script function to wait until the ajax call finished.
function getLabelById(id)
{
var label = '';
var done = false;
$.ajax({
cache: false,
url: "YourMvcActionUrl",
type: "GET",
dataType: "json",
async: false,
error: function (result) {
label='undefined';
done = true;
},
success: function (result) {
label = result.Message;
done = true;
}
});
//A loop to check done if ajax call is done.
while (!done)
{
setTimeout(function(){ },500); // take a sleep.
}
return label;
}
I know you asked for GET and POST but I will provide CRUD since others may need this just in case: (this was tested in Python 3.7)
#!/usr/bin/env python3
import http.client
import json
print("\n GET example")
conn = http.client.HTTPSConnection("httpbin.org")
conn.request("GET", "/get")
response = conn.getresponse()
data = response.read().decode('utf-8')
print(response.status, response.reason)
print(data)
print("\n POST example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body = {'text': 'testing post'}
json_data = json.dumps(post_body)
conn.request('POST', '/post', json_data, headers)
response = conn.getresponse()
print(response.read().decode())
print(response.status, response.reason)
print("\n PUT example ")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing put'}
json_data = json.dumps(post_body)
conn.request('PUT', '/put', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)
print("\n delete example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing delete'}
json_data = json.dumps(post_body)
conn.request('DELETE', '/delete', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)
Just order the table by a random number and obtain the first 5,000 rows using TOP
.
SELECT TOP 5000 * FROM [Table] ORDER BY newid();
UPDATE
Just tried it and a newid()
call is sufficent - no need for all the casts and all the math.
from datetime import date
def calculate_age(born):
today = date.today()
try:
birthday = born.replace(year=today.year)
except ValueError: # raised when birth date is February 29 and the current year is not a leap year
birthday = born.replace(year=today.year, month=born.month+1, day=1)
if birthday > today:
return today.year - born.year - 1
else:
return today.year - born.year
Update: Use Danny's solution, it's better
You can use transitions to delay the :hover
effect you want, if the effect is CSS-based.
For example
div{
transition: 0s background-color;
}
div:hover{
background-color:red;
transition-delay:1s;
}
this will delay applying the the hover effects (background-color
in this case) for one second.
Demo of delay on both hover on and off:
div{_x000D_
display:inline-block;_x000D_
padding:5px;_x000D_
margin:10px;_x000D_
border:1px solid #ccc;_x000D_
transition: 0s background-color;_x000D_
transition-delay:1s;_x000D_
}_x000D_
div:hover{_x000D_
background-color:red;_x000D_
}
_x000D_
<div>delayed hover</div>
_x000D_
Demo of delay only on hover on:
div{_x000D_
display:inline-block;_x000D_
padding:5px;_x000D_
margin:10px;_x000D_
border:1px solid #ccc;_x000D_
transition: 0s background-color;_x000D_
}_x000D_
div:hover{_x000D_
background-color:red; _x000D_
transition-delay:1s;_x000D_
}
_x000D_
<div>delayed hover</div>
_x000D_
Vendor Specific Extentions for Transitions and W3C CSS3 transitions
How about sys.exit()
from the module sys
.
If sys.exit()
is executed from within a thread it will close that thread only.
This answer here talks about that: Why does sys.exit() not exit when called inside a thread in Python?
conda install python-graphviz
For Windows, install the Python Graphviz which will include the executables in the path.
Save this xml and add as a background for the linear layout....
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="4dp" android:color="#FF00FF00" />
<solid android:color="#ffffff" />
<padding android:left="7dp" android:top="7dp"
android:right="7dp" android:bottom="0dp" />
<corners android:radius="4dp" />
</shape>
Hope this helps! :)
You should stop the submit procedure by returning false on the onsubmit callback.
<script>
function checkRegistration(){
if(!form_valid){
alert('Given data is not correct');
return false;
}
return true;
}
</script>
<form onsubmit="return checkRegistration()"...
Here you have a fully working example. The form will submit only when you write google into input, otherwise it will return an error:
<script>
function checkRegistration(){
var form_valid = (document.getElementById('some_input').value == 'google');
if(!form_valid){
alert('Given data is incorrect');
return false;
}
return true;
}
</script>
<form onsubmit="return checkRegistration()" method="get" action="http://google.com">
Write google to go to google...<br/>
<input type="text" id="some_input" value=""/>
<input type="submit" value="google it"/>
</form>
In Xcode 4.2
Strangely, the answer is to keep adding back the property. I was half expecting a setter
method. :S
System.out.println("Before: " + obj.get("DebugLogId")); // original "02352"
obj.addProperty("DebugLogId", "YYY");
System.out.println("After: " + obj.get("DebugLogId")); // now "YYY"
Just changing the style with c-set-style was enough for me.
for me this is because previously I'm running script which set proxy (to fiddler), reopening console or reboot fix the problem.
You may like to try something like this which covers all the bases, including not relying on whitespace after the number:
>>> import re
>>> numeric_const_pattern = r"""
... [-+]? # optional sign
... (?:
... (?: \d* \. \d+ ) # .1 .12 .123 etc 9.1 etc 98.1 etc
... |
... (?: \d+ \.? ) # 1. 12. 123. etc 1 12 123 etc
... )
... # followed by optional exponent part if desired
... (?: [Ee] [+-]? \d+ ) ?
... """
>>> rx = re.compile(numeric_const_pattern, re.VERBOSE)
>>> rx.findall(".1 .12 9.1 98.1 1. 12. 1 12")
['.1', '.12', '9.1', '98.1', '1.', '12.', '1', '12']
>>> rx.findall("-1 +1 2e9 +2E+09 -2e-9")
['-1', '+1', '2e9', '+2E+09', '-2e-9']
>>> rx.findall("current level: -2.03e+99db")
['-2.03e+99']
>>>
For easy copy-pasting:
numeric_const_pattern = '[-+]? (?: (?: \d* \. \d+ ) | (?: \d+ \.? ) )(?: [Ee] [+-]? \d+ ) ?'
rx = re.compile(numeric_const_pattern, re.VERBOSE)
rx.findall("Some example: Jr. it. was .23 between 2.3 and 42.31 seconds")
All of these methods are great. I have found another simple resource that is a great example of creating a dynamic form using "onchange" with AJAX.
http://www.w3schools.com/php/php_ajax_database.asp
I simply modified the text table output to anther select dropdown populated based on the selection of the first drop down. For my application a user will select a state then the second dropdown will be populated with the cities for the selected state. Much like the JSON example above but with php and mysql.
I come here with the same doubt but for Xamarin for Android, I have used the Sigrist answer to do this method after save my file:
private void UpdateGallery()
{
Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
Java.IO.File file = new Java.IO.File(_path);
Android.Net.Uri contentUri = Android.Net.Uri.FromFile(file);
mediaScanIntent.SetData(contentUri);
Application.Context.SendBroadcast(mediaScanIntent);
}
and it solved my problem, Thx Sigrist. I put it here becouse i did not found an answare about this for Xamarin and i hope it can help other people.
Please try out this one.
d =[{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3} , {'value':
'cars', 'blah': 4}]
b=d[0]['value']
c=d[1]['value']
d=d[2]['value']
new_list=[b,c,d]
print(new_list)
Output:
['apple', 'banana', 'cars']
In computer science, declarative programming is a programming paradigm that expresses the logic of a computation without describing its control flow.
From http://en.wikipedia.org/wiki/Declarative_programming
in a nutshell the declarative language is simpler because it lacks the complexity of control flow ( loops, if statements, etc. )
A good comparison is the ASP.Net 'code-behind' model. You have declarative '.ASPX' files and then the imperative 'ASPX.CS' code files. I often find that if I can do all I need in the declarative half of the script a lot more people can follow what's being done.
In SQL Server 2008 you can use a multi-table update as follows:
UPDATE tblindiantime
SET tblindiantime.CountryName = contacts.BusinessCountry
FROM tblindiantime
JOIN contacts
ON -- join condition here
You need a join condition to specify which row should be updated.
If the target table is currently empty then you should use an INSERT instead:
INSERT INTO tblindiantime (CountryName)
SELECT BusinessCountry FROM contacts
If the .project
and .classpath
are already committed, then they need to be removed from the index (but not the disk)
git rm --cached .project
git rm --cached .classpath
Then the .gitignore
would work (and that file can be added and shared through clones).
For instance, this gitignore.io/api/eclipse
file will then work, which does include:
# Eclipse Core
.project
# JDT-specific (Eclipse Java Development Tools)
.classpath
Note that you could use a "Template Directory" when cloning (make sure your users have an environment variable $GIT_TEMPLATE_DIR
set to a shared folder accessible by all).
That template folder can contain an info/exclude
file, with ignore rules that you want enforced for all repos, including the new ones (git init
) that any user would use.
When you change the index, you need to commit the change and push it.
Then the file is removed from the repository. So the newbies cannot checkout the files.classpath
and.project
from the repo.
use the grid-system of boostrap , more information here
for example
<div class="row">
<div class="col-md-4">here img</div>
<div class="col-md-4">here text</div>
</div>
in this way when the page will shrink the second div(the text) will be found under the first(the image)
The problem was you were trying to perform a Javascript operation on a non existing element. The element was yet to be loaded and setTimeout()
gives more time for an element to load in the following ways:
setTimeout()
causes the event to be ansynchronous therefore being executed after all the synchronous code, giving your element more time to load. Asynchronous callbacks like the callback in setTimeout()
are placed in the event queue and put on the stack by the event loop after the stack of synchronous code is empty. setTimeout()
is often slightly higher (4-10ms depending on browser). This slightly higher time needed for executing the setTimeout()
callbacks is caused by the amount of 'ticks' (where a tick is pushing a callback on the stack if stack is empty) of the event loop. Because of performance and battery life reasons the amount of ticks in the event loop are restricted to a certain amount less than 1000 times per second.Sets pattern validation error key if the ngModel $viewValue does not match a RegExp found by evaluating the Angular expression given in the attribute value. If the expression evaluates to a RegExp object, then this is used directly. If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it in ^ and $ characters.
It seems that a most voted answer in this question should be updated, because when i try it, it does not apply test
function and validation not working.
Example from Angular docs works good for me:
Modifying built-in validators
html
<form name="form" class="css-form" novalidate>
<div>
Overwritten Email:
<input type="email" ng-model="myEmail" overwrite-email name="overwrittenEmail" />
<span ng-show="form.overwrittenEmail.$error.email">This email format is invalid!</span><br>
Model: {{myEmail}}
</div>
</form>
js
var app = angular.module('form-example-modify-validators', []);
app.directive('overwriteEmail', function() {
var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@example\.com$/i;
return {
require: 'ngModel',
restrict: '',
link: function(scope, elm, attrs, ctrl) {
// only apply the validator if ngModel is present and Angular has added the email validator
if (ctrl && ctrl.$validators.email) {
// this will overwrite the default Angular email validator
ctrl.$validators.email = function(modelValue) {
return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue);
};
}
}
};
});
private static Long DateTimeNowTicks(){
long TICKS_AT_EPOCH = 621355968000000000L;
TimeZone timeZone = Calendar.getInstance().getTimeZone();
int offs = timeZone.getRawOffset();
if (timeZone.inDaylightTime(new Date()))
offs += 60 * 60 * 1000;
return (System.currentTimeMillis() + offs) * 10000 + TICKS_AT_EPOCH;
}
You can not add links from CSS, you will have to do so from the HTML code explicitly. For example, something like this:
<a href="whatever.html"><li id="header"></li></a>
C# to convert a string
to a byte
array:
public static byte[] StrToByteArray(string str)
{
System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding();
return encoding.GetBytes(str);
}
Not sure that it will be applicable solution for you. But the only way for monitoring tomcat memory settings as well as number of connections etc. that actually works for us is Lambda Probe.
It shows most of informations that we need for Tomcat tunning. We tested it with Tomcat 5.5 and 6.0 and it works fine despite beta status and date of last update in end of 2006.
Try this, but I don't think it will work because you're not supposed to be able to change this
Put this line in an htaccess file in the directory you want the setting to be enabled:
php_value allow_url_fopen On
Note that this setting will only apply to PHP file's in the same directory as the htaccess file.
As an alternative to using url_fopen, try using curl.
Hooking in programming is a technique employing so-called hooks to make a chain of procedures as an event handler.
Replacing all AppSettings
This is the overkill case where you just want to replace an entire section of the web.config. In this case I will replace all AppSettings in the web.config will new settings in web.release.config. This is my baseline web.config appSettings:
<appSettings>
<add key="KeyA" value="ValA"/>
<add key="KeyB" value="ValB"/>
</appSettings>
Now in my web.release.config file, I am going to create a appSettings section except I will include the attribute xdt:Transform=”Replace” since I want to just replace the entire element. I did not have to use xdt:Locator because there is nothing to locate – I just want to wipe the slate clean and replace everything.
<appSettings xdt:Transform="Replace">
<add key="ProdKeyA" value="ProdValA"/>
<add key="ProdKeyB" value="ProdValB"/>
<add key="ProdKeyC" value="ProdValC"/>
</appSettings>
Note that in the web.release.config file my appSettings section has three keys instead of two, and the keys aren’t even the same. Now let’s look at the generated web.config file what happens when we publish:
<appSettings>
<add key="ProdKeyA" value="ProdValA"/>
<add key="ProdKeyB" value="ProdValB"/>
<add key="ProdKeyC" value="ProdValC"/>
</appSettings>
Just as we expected – the web.config appSettings were completely replaced by the values in web.release config. That was easy!
You could try this:
if(typeof(results) == "undefined") {
return 0;
} else {
return results[1] || 0;
}
This will change your current working directory to so that opening relative paths will work:
import os
os.chdir("/home/udi/foo")
However, you asked how to change into whatever directory your Python script is located, even if you don't know what directory that will be when you're writing your script. To do this, you can use the os.path
functions:
import os
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
This takes the filename of your script, converts it to an absolute path, then extracts the directory of that path, then changes into that directory.
You forgot to specify the variable name. It should be CERas.CERAS newCeras = new CERas.CERAS();
Just paste the below formula in any of the cells, it will render the path of the file:
=LEFT(CELL("filename"),FIND("]",CELL("filename"),1))
The above formula works in any version of Excel.
Some of the answers no longer work as explained.
Currently here is something that works for me in ansible 2.6.x
when: register_var.stdout is search('some_string')
execl("/home/vlc",
"/home/vlc", "/home/my movies/the movie i want to see.mkv",
(char*) NULL);
You need to specify all arguments, included argv[0]
which isn't taken from the executable.
Also make sure the final NULL
gets cast to char*
.
Details are here: http://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html
Please check your web.xml again. You might be making some silly mistake. As my application is working fine with the same init-param configuration...
Please copy paste the web.xml, if the problem still persists.
see to it that the argument of Class. forName method is exactly "com. mysql. jdbc. Driver". If yes then see to it that mysql connector is present in lib folder of the project. if yes then see to it that the same mysql connector . jar file is in the ClassPath variable (system variable)..
Also in IOS if you want to get rid of gray semi-transparent overlays appearing ontouch, add css:
-webkit-tap-highlight-color: rgba(0,0,0,0);
-webkit-touch-callout: none;
When you use spring then you can use
boolean isNullOrEmpty = org.springframework.util.ObjectUtils.isEmpty(obj);
where obj is any [map,collection,array,aything...]
otherwise: the code is:
public static boolean isEmpty(Object[] array) {
return (array == null || array.length == 0);
}
public static boolean isEmpty(Object obj) {
if (obj == null) {
return true;
}
if (obj.getClass().isArray()) {
return Array.getLength(obj) == 0;
}
if (obj instanceof CharSequence) {
return ((CharSequence) obj).length() == 0;
}
if (obj instanceof Collection) {
return ((Collection) obj).isEmpty();
}
if (obj instanceof Map) {
return ((Map) obj).isEmpty();
}
// else
return false;
}
for String best is:
boolean isNullOrEmpty = (str==null || str.trim().isEmpty());
I have just had this problem when building a second version of my website. It didn't happen when I built it the first time.
I have just deleted the bin and obj folders, run a Clean Solution and built it again, this time without any problem.
DECLARE @i AS FLOAT = 2 SELECT @i / 3 SELECT cast(@i / cast(3 AS DECIMAL(18,2))as decimal (18,2))
Both factor and result requires casting to be considered as decimals.
There's no NotifyIcon for WPF.
A colleague of mine used this freely available library to good effect:
Try something like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
Write-Host $_.Exception.ToString()
}
The exception is in the $_
variable. You might explore $_
like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
$_ | fl * -Force
}
I think it will give you all the info you need.
My rule: if there is some data that is not displayed, try to use -force
.
No.
You need to write a wrapper in PHP, and then export the returned data (probably as Json). NEVER, get from your "_GET" the SQL code, as this is called an SQL injection (people who learn this will have full control over your database).
This is an example I wrote:
function getJsonData()
{
global $db;
if (!$db->isConnected()) {
return "Not connected";
}
$db->query("SELECT * FROM entries");
$values = array();
while( $v = $db->fetchAssoc()){
$values[] = $v;
}
return json_encode($values);
}
switch (@$_GET["cmd"]){
case 'data':
print getJsonData();
exit;
default:
print getMainScreen();
exit;
}
Do learn about SQL injections please.
If you want to make sure that the order of execution is retained you can use flatMap as the following example
const first = Rx.Observable.of(1).delay(1000).do(i => console.log(i));
const second = Rx.Observable.of(11).delay(500).do(i => console.log(i));
const third = Rx.Observable.of(111).do(i => console.log(i));
first
.flatMap(() => second)
.flatMap(() => third)
.subscribe(()=> console.log('finished'));
The outcome would be:
"1"
"11"
"111"
"finished"
The answer is Not possible yet. You have to remove it manually.
As KhAn SaAb has stated, you need to set your path.
But in order for your JDK to take advantage of tools such as Maven in the future, I would assign a JAVA_HOME
path to point to your JDK folder and then just add the %JAVA_HOME%\bin
directory to your PATH
.
JAVA_HOME = "C:\Program Files\Java\jdk1.8.0"
PATH = %PATH%\%JAVA_HOME%\bin
In Windows:
blah;blah;blah;
C:\Program Files\Java\jdk1.8.0\bin;blah,blah;blah
to:
blah;blah;blah;
%JAVA_HOME%\bin;blah,blah;blah
Current Version 1.38.1
I had a problem with intending. The default Command+] is set to 4 and I wanted it to be 2. Installed "Indent 4-to-2" but it changed the entire file and not the selected text.
I changed the tab spacing in settings and it was simple.
Go to Settings
-> Text Editor
-> Tab Size
use enumerate:
>>> l = ['a', 'b', 'c', 'd']
>>> for index, val in enumerate(l):
... print "%d: %s" % (index, val)
...
0: a
1: b
2: c
3: d
@nCdy: index_of_cell should be replaced by an integer, corresponding to the index number of the cell that you wish to hide in the .Cells collection.
For example, suppose that your GridView presents the following columns:
CONTACT NAME | CONTACT NUMBER | CUSTOMERID | ADDRESS LINE 1 | POST CODE
And you want the CUSTOMERID column not to be displayed. Since collections indexes are 0-based, your CUSTOMERID column's index is..........? That's right, 2!! Very good. Now... guess what you should put in there, to replace 'index_of_cell'??
Also, for posterity -- Clang (like GCC) accepts the -x
switch to set the language of the input files, for example,
$ clang -x c++ some_random_file.txt
This mailing list thread explains the difference between clang
and clang++
well: Difference between clang and clang++
When you do valueForKey:
you need to give it an NSString, whereas objectForKey:
can take any NSObject subclass as a key. This is because for Key-Value Coding, the keys are always strings.
In fact, the documentation states that even when you give valueForKey:
an NSString, it will invoke objectForKey:
anyway unless the string starts with an @
, in which case it invokes [super valueForKey:]
, which may call valueForUndefinedKey:
which may raise an exception.
git difftool tag/branch filename
In short, yes. But there are times when you might favor one vs. the other. Google "case switch vs. if else". There are some discussions already on SO too. Also, here is a good video that talks about it in the context of MATLAB:
http://blogs.mathworks.com/pick/2008/01/02/matlab-basics-switch-case-vs-if-elseif/
Personally, when I have 3 or more cases, I usually just go with case/switch.
You can try Marvin Framework. It provides an interface to work with cameras. Moreover, it also provides a set of real-time video processing features, like object tracking and filtering.
Take a look!
Real-time Video Processing Demo:
http://www.youtube.com/watch?v=D5mBt0kRYvk
You can use the source below. Just save a frame using MarvinImageIO.saveImage() every 5 second.
Webcam video demo:
public class SimpleVideoTest extends JFrame implements Runnable{
private MarvinVideoInterface videoAdapter;
private MarvinImage image;
private MarvinImagePanel videoPanel;
public SimpleVideoTest(){
super("Simple Video Test");
videoAdapter = new MarvinJavaCVAdapter();
videoAdapter.connect(0);
videoPanel = new MarvinImagePanel();
add(videoPanel);
new Thread(this).start();
setSize(800,600);
setVisible(true);
}
@Override
public void run() {
while(true){
// Request a video frame and set into the VideoPanel
image = videoAdapter.getFrame();
videoPanel.setImage(image);
}
}
public static void main(String[] args) {
SimpleVideoTest t = new SimpleVideoTest();
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
For those who just want to take a single picture:
WebcamPicture.java
public class WebcamPicture {
public static void main(String[] args) {
try{
MarvinVideoInterface videoAdapter = new MarvinJavaCVAdapter();
videoAdapter.connect(0);
MarvinImage image = videoAdapter.getFrame();
MarvinImageIO.saveImage(image, "./res/webcam_picture.jpg");
} catch(MarvinVideoInterfaceException e){
e.printStackTrace();
}
}
}
Looks like the solution as.numeric(levels(f))[f] no longer work with R 4.0.
Alternative solution:
factor2number <- function(x){
data.frame(levels(x), 1:length(levels(x)), row.names = 1)[x, 1]
}
factor2number(yourFactor)
For what it is worth, most scripting languages (like Perl) and non-static compile-time languages (like Pick) support automatic run-time dynamic String to (relatively arbitrary) object conversions. This CAN be accomplished in Java as well without losing type-safety and the good stuff statically-typed languages provide WITHOUT the nasty side-effects of some of the other languages that do evil things with dynamic casting. A Perl example that does some questionable math:
print ++($foo = '99'); # prints '100'
print ++($foo = 'a0'); # prints 'a1'
In Java, this is better accomplished (IMHO) by using a method I call "cross-casting". With cross-casting, reflection is used in a lazy-loaded cache of constructors and methods that are dynamically discovered via the following static method:
Object fromString (String value, Class targetClass)
Unfortunately, no built-in Java methods such as Class.cast() will do this for String to BigDecimal or String to Integer or any other conversion where there is no supporting class hierarchy. For my part, the point is to provide a fully dynamic way to achieve this - for which I don't think the prior reference is the right approach - having to code every conversion. Simply put, the implementation is just to cast-from-string if it is legal/possible.
So the solution is simple reflection looking for public Members of either:
STRING_CLASS_ARRAY = (new Class[] {String.class});
a) Member member = targetClass.getMethod(method.getName(),STRING_CLASS_ARRAY); b) Member member = targetClass.getConstructor(STRING_CLASS_ARRAY);
You will find that all of the primitives (Integer, Long, etc) and all of the basics (BigInteger, BigDecimal, etc) and even java.regex.Pattern are all covered via this approach. I have used this with significant success on production projects where there are a huge amount of arbitrary String value inputs where some more strict checking was needed. In this approach, if there is no method or when the method is invoked an exception is thrown (because it is an illegal value such as a non-numeric input to a BigDecimal or illegal RegEx for a Pattern), that provides the checking specific to the target class inherent logic.
There are some downsides to this:
1) You need to understand reflection well (this is a little complicated and not for novices). 2) Some of the Java classes and indeed 3rd-party libraries are (surprise) not coded properly. That is, there are methods that take a single string argument as input and return an instance of the target class but it isn't what you think... Consider the Integer class:
static Integer getInteger(String nm)
Determines the integer value of the system property with the specified name.
The above method really has nothing to do with Integers as objects wrapping primitives ints. Reflection will find this as a possible candidate for creating an Integer from a String incorrectly versus the decode, valueof and constructor Members - which are all suitable for most arbitrary String conversions where you really don't have control over your input data but just want to know if it is possible an Integer.
To remedy the above, looking for methods that throw Exceptions is a good start because invalid input values that create instances of such objects should throw an Exception. Unfortunately, implementations vary as to whether the Exceptions are declared as checked or not. Integer.valueOf(String) throws a checked NumberFormatException for example, but Pattern.compile() exceptions are not found during reflection lookups. Again, not a failing of this dynamic "cross-casting" approach I think so much as a very non-standard implementation for exception declarations in object creation methods.
If anyone would like more details on how the above was implemented, let me know but I think this solution is much more flexible/extensible and with less code without losing the good parts of type-safety. Of course it is always best to "know thy data" but as many of us find, we are sometimes only recipients of unmanaged content and have to do the best we can to use it properly.
Cheers.
URI (Uniform Resource Identifier) according to Wikipedia:
a string of characters used to identify a resource.
URL (Uniform Resource Locator) is a URI that implies an interaction mechanism with resource. for example https://www.google.com specifies the use of HTTP as the interaction mechanism. Not all URIs need to convey interaction-specific information.
URN (Uniform Resource Name) is a specific form of URI that has urn as it's scheme. For more information about the general form of a URI refer to https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Syntax
IRI (International Resource Identifier) is a revision to the definition of URI that allows us to use international characters in URIs.
Run cmd
and then run node server.js
. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)
The __init__
function is setting up all the member variables in the class. So once your bicluster is created you can access the member and get a value back:
mycluster = bicluster(...actual values go here...)
mycluster.left # returns the value passed in as 'left'
Check out the Python Docs for some info. You'll want to pick up an book on OO concepts to continue learning.
As mentioned by Zeeshan, the logrotate options size
, minsize
, maxsize
are triggers for rotation.
To better explain it. You can run logrotate as often as you like, but unless a threshold is reached such as the filesize being reached or the appropriate time passed, the logs will not be rotated.
The size options do not ensure that your rotated logs are also of the specified size. To get them to be close to the specified size you need to call the logrotate program sufficiently often. This is critical.
For log files that build up very quickly (e.g. in the hundreds of MB a day), unless you want them to be very large you will need to ensure logrotate is called often! this is critical.
Therefore to stop your disk filling up with multi-gigabyte log files you need to ensure logrotate is called often enough, otherwise the log rotation will not work as well as you want.
on Ubuntu, you can easily switch to hourly rotation by moving the script /etc/cron.daily/logrotate to /etc/cron.hourly/logrotate
Or add
*/5 * * * * /etc/cron.daily/logrotate
To your /etc/crontab file. To run it every 5 minutes.
The size
option ignores the daily, weekly, monthly time options. But minsize & maxsize take it into account.
The man page is a little confusing there. Here's my explanation.
minsize
rotates only when the file has reached an appropriate size and the set time period has passed. e.g. minsize 50MB + daily
If file reaches 50MB before daily time ticked over, it'll keep growing until the next day.
maxsize
will rotate when the log reaches a set size or the appropriate time has passed.
e.g. maxsize 50MB + daily.
If file is 50MB and we're not at the next day yet, the log will be rotated. If the file is only 20MB and we roll over to the next day then the file will be rotated.
size
will rotate when the log > size. Regardless of whether hourly/daily/weekly/monthly is specified. So if you have size 100M - it means when your log file is > 100M the log will be rotated if logrotate is run when this condition is true. Once it's rotated, the main log will be 0, and a subsequent run will do nothing.
So in the op's case. Specficially 50MB max I'd use something like the following:
/var/log/logpath/*.log {
maxsize 50M
hourly
missingok
rotate 8
compress
notifempty
nocreate
}
Which means he'd create 8hrs of logs max. And there would be 8 of them at no more than 50MB each. Since he's saying that he's getting multi gigabytes each day and assuming they build up at a fairly constant rate, and maxsize is used he'll end up with around close to the max reached for each file. So they will be likely close to 50MB each. Given the volume they build, he would need to ensure that logrotate is run often enough to meet the target size.
Since I've put hourly there, we'd need logrotate to be run a minimum of every hour. But since they build up to say 2 gigabytes per day and we want 50MB... assuming a constant rate that's 83MB per hour. So you can imagine if we run logrotate every hour, despite setting maxsize to 50 we'll end up with 83MB log's in that case. So in this instance set the running to every 30 minutes or less should be sufficient.
Ensure logrotate is run every 30 mins.
*/30 * * * * /etc/cron.daily/logrotate
import os
print os.getcwd() # Prints the current working directory
To set the working directory:
os.chdir('c:\\Users\\uname\\desktop\\python') # Provide the new path here
If you have a string like foo: 1, bar: 2
you can convert it to a valid obj with:
str
.split(',')
.map(x => x.split(':').map(y => y.trim()))
.reduce((a, x) => {
a[x[0]] = x[1];
return a;
}, {});
Thanks to niggler in #javascript for that.
Update with explanations:
const obj = 'foo: 1, bar: 2'
.split(',') // split into ['foo: 1', 'bar: 2']
.map(keyVal => { // go over each keyVal value in that array
return keyVal
.split(':') // split into ['foo', '1'] and on the next loop ['bar', '2']
.map(_ => _.trim()) // loop over each value in each array and make sure it doesn't have trailing whitespace, the _ is irrelavent because i'm too lazy to think of a good var name for this
})
.reduce((accumulator, currentValue) => { // reduce() takes a func and a beginning object, we're making a fresh object
accumulator[currentValue[0]] = currentValue[1]
// accumulator starts at the beginning obj, in our case {}, and "accumulates" values to it
// since reduce() works like map() in the sense it iterates over an array, and it can be chained upon things like map(),
// first time through it would say "okay accumulator, accumulate currentValue[0] (which is 'foo') = currentValue[1] (which is '1')
// so first time reduce runs, it starts with empty object {} and assigns {foo: '1'} to it
// second time through, it "accumulates" {bar: '2'} to it. so now we have {foo: '1', bar: '2'}
return accumulator
}, {}) // when there are no more things in the array to iterate over, it returns the accumulated stuff
console.log(obj)
Confusing MDN docs:
Demo: http://jsbin.com/hiduhijevu/edit?js,console
Function:
const str2obj = str => {
return str
.split(',')
.map(keyVal => {
return keyVal
.split(':')
.map(_ => _.trim())
})
.reduce((accumulator, currentValue) => {
accumulator[currentValue[0]] = currentValue[1]
return accumulator
}, {})
}
console.log(str2obj('foo: 1, bar: 2')) // see? works!
As the code below shows it, it works.
public <T> ResponseWrapper<T> makeRequest(URI uri, final Class<T> clazz) {
ResponseEntity<ResponseWrapper<T>> response = template.exchange(
uri,
HttpMethod.POST,
null,
new ParameterizedTypeReference<ResponseWrapper<T>>() {
public Type getType() {
return new MyParameterizedTypeImpl((ParameterizedType) super.getType(), new Type[] {clazz});
}
});
return response;
}
public class MyParameterizedTypeImpl implements ParameterizedType {
private ParameterizedType delegate;
private Type[] actualTypeArguments;
MyParameterizedTypeImpl(ParameterizedType delegate, Type[] actualTypeArguments) {
this.delegate = delegate;
this.actualTypeArguments = actualTypeArguments;
}
@Override
public Type[] getActualTypeArguments() {
return actualTypeArguments;
}
@Override
public Type getRawType() {
return delegate.getRawType();
}
@Override
public Type getOwnerType() {
return delegate.getOwnerType();
}
}
You will need Javascript to do this:
HTML
<input id="datefield" type='date' min='1899-01-01' max='2000-13-13'></input>
JS
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd
}
if(mm<10){
mm='0'+mm
}
today = yyyy+'-'+mm+'-'+dd;
document.getElementById("datefield").setAttribute("max", today);
This worked for me. Go to Project->Propertied->Target Frawork->Change frame work like 3.5 to 4.0
To add onto @fortran's answer, if you want to iterate over a list of keys key_list
as well as a list of values value_list
:
d = dict((key, value) for (key, value) in zip(key_list, value_list))
or
d = {(key, value) for (key, value) in zip(key_list, value_list)}
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyClass
{
public static void main(String args[])
{
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
String dateInString = "Wed Mar 14 15:30:00 EET 2018";
SimpleDateFormat formatterOut = new SimpleDateFormat("dd MMM yyyy");
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatterOut.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
here is your Date object date and the output is :
Wed Mar 14 13:30:00 UTC 2018
14 Mar 2018
If elem.find()
is not working for you, check that you are including JQuery script before angular script....
Simplest solution would be to use tool which allows you to directly specify ranges, like gnu shuf
shuf -i1-10 -n1
If you want to use $RANDOM
, it would be more precise to throw out the last 8 numbers in 0...32767, and just treat it as 0...32759, since taking 0...32767 mod 10 you get the following distribution
0-8 each: 3277
8-9 each: 3276
So, slightly slower but more precise would be
while :; do ran=$RANDOM; ((ran < 32760)) && echo $(((ran%10)+1)) && break; done
You can just create your own .white
class and add it to the glyphicon element.
.white, .white a {
color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>
You can simply use,
import json
json.loads(my_bytes_value)
Put houseAddress.get(i)
inside the brackets and call .toString()
function: i.e Please see below
for(int i = 0; i < houseAddress.size(); i++) {
System.out.print((houseAddress.get(i)).toString());
}
A query may fail for various reasons in which case both the mysql_* and the mysqli extension will return false
from their respective query functions/methods. You need to test for that error condition and handle it accordingly.
NOTE The mysql_ functions are deprecated and have been removed in php version 7.
Check $result
before passing it to mysql_fetch_array
. You'll find that it's false
because the query failed. See the mysql_query
documentation for possible return values and suggestions for how to deal with them.
$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
mysqli extension
procedural style:
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$result = mysqli_query($mysqli, "SELECT * FROM Users WHERE UserName LIKE '$username'");
// mysqli_query returns false if something went wrong with the query
if($result === FALSE) {
yourErrorHandler(mysqli_error($mysqli));
}
else {
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...
oo-style:
$username = $mysqli->escape_string($_POST['username']);
$result = $mysqli->query("SELECT * FROM Users WHERE UserName LIKE '$username'");
if($result === FALSE) {
yourErrorHandler($mysqli->error); // or $mysqli->error_list
}
else {
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...
using a prepared statement:
$stmt = $mysqli->prepare('SELECT * FROM Users WHERE UserName LIKE ?');
if ( !$stmt ) {
yourErrorHandler($mysqli->error); // or $mysqli->error_list
}
else if ( !$stmt->bind_param('s', $_POST['username']) ) {
yourErrorHandler($stmt->error); // or $stmt->error_list
}
else if ( !$stmt->execute() ) {
yourErrorHandler($stmt->error); // or $stmt->error_list
}
else {
$result = $stmt->get_result();
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...
These examples only illustrate what should be done (error handling), not how to do it. Production code shouldn't use or die
when outputting HTML, else it will (at the very least) generate invalid HTML. Also, database error messages shouldn't be displayed to non-admin users, as it discloses too much information.
display:block
takes the entire row(100%)of the screen ,it is always 100%of the screen size
display:inline-block takes up as much width as necessary ,it can be 1%-to 100% of the screen size
that's why we have div and span
Div default styling is display block :it takes the entire width of the screen
span default styling is display:inline block :span does not start on a new line and only takes up as much width as necessary
In Node as others have said, it's simple:
class DumbError extends Error {
constructor(foo = 'bar', ...params) {
super(...params);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, DumbError);
}
this.name = 'DumbError';
this.foo = foo;
this.date = new Date();
}
}
try {
let x = 3;
if (x < 10) {
throw new DumbError();
}
} catch (error) {
console.log(error);
}
The key error generally comes if the key doesn't match any of the dataframe column name 'exactly':
You could also try:
import csv
import pandas as pd
import re
with open (filename, "r") as file:
df = pd.read_csv(file, delimiter = ",")
df.columns = ((df.columns.str).replace("^ ","")).str.replace(" $","")
print(df.columns)
There is are multiple ways to execute the commands or script in the multiple remote Linux machines.
One simple & easiest way is via pssh (parallel ssh program)
pssh: is a program for executing ssh in parallel on a number of hosts. It provides features such as sending input to all of the processes, passing a password to ssh, saving the output to files, and timing out.
Example & Usage:
Connect to host1 and host2, and print "hello, world" from each:
pssh -i -H "host1 host2" echo "hello, world"
Run commands via a script on multiple servers:
pssh -h hosts.txt -P -I<./commands.sh
Usage & run a command without checking or saving host keys:
pssh -h hostname_ip.txt -x '-q -o StrictHostKeyChecking=no -o PreferredAuthentications=publickey -o PubkeyAuthentication=yes' -i 'uptime; hostname -f'
If the file hosts.txt has a large number of entries, say 100, then the parallelism option may also be set to 100 to ensure that the commands are run concurrently:
pssh -i -h hosts.txt -p 100 -t 0 sleep 10000
Options:
-I: Read input and sends to each ssh process.
-P: Tells pssh to display output as it arrives.
-h: Reads the host's file.
-H : [user@]host[:port] for single-host.
-i: Display standard output and standard error as each host completes
-x args: Passes extra SSH command-line arguments
-o option: Can be used to give options in the format used in the configuration file.(/etc/ssh/ssh_config) (~/.ssh/config)
-p parallelism: Use the given number as the maximum number of concurrent connections
-q Quiet mode: Causes most warning and diagnostic messages to be suppressed.
-t: Make connections time out after the given number of seconds. 0 means pssh will not timeout any connections
When ssh'ing to the remote machine, how to handle when it prompts for RSA fingerprint authentication.
Disable the StrictHostKeyChecking to handle the RSA authentication prompt.
-o StrictHostKeyChecking=no
Source: man pssh
Press i
or a
to get into insert mode, and type the message of choice
Press ESC
several times to get out of insert mode, or any other mode you might have run into by accident
to save, :wq
, :x
or ZZ
to exit without saving, :q!
or ZQ
To reload a file and undo all changes you have made...:
Press several times ESC
and then enter :e!
.
If you need to access this as a server-side control (e.g. you want to add data attributes to a link, as I did), then there is a way to do what you want; however, you don't use the Hyperlink or HtmlAnchor controls to do it. Create a literal control and then add in "Your Text" as the text for the literal control (or whatever else you need to do that way). It's hacky, but it works.
Try this:
valgrind --leak-check=full -v ./your_program
As long as valgrind is installed it will go through your program and tell you what's wrong. It can give you pointers and approximate places where your leaks may be found. If you're segfault'ing, try running it through gdb
.
The isinstance
built-in is the preferred way if you really must, but even better is to remember Python's motto: "it's easier to ask forgiveness than permission"!-) (It was actually Grace Murray Hopper's favorite motto;-). I.e.:
def my_print(text, begin, end):
"Print 'text' in UPPER between 'begin' and 'end' in lower"
try:
print begin.lower() + text.upper() + end.lower()
except (AttributeError, TypeError):
raise AssertionError('Input variables should be strings')
This, BTW, lets the function work just fine on Unicode strings -- without any extra effort!-)
Actually the problem is in pubspec.yaml,
I put all images to assets/images/
and
This wrong way
flutter:
uses-material-design: true
assets:
- images/
Correct
flutter:
uses-material-design: true
assets:
- assets/images/
Or you may do the following
$(this).animate({color:'black'},1000);
But you need to download the color plugin from here.
The answer is really easy: It's pretty safe to say that it won't be possible in the next two decades. Before that we will probably get good translation tools. The last time I checked, the AI guys were struggling to identify the same car on two photographs shot from a slightly altered angle. Take a look on how long it took them to get good enough OCR or speech recognition together. Those are recognition problems which can benefit greatly from dictionaries and are still far from having completely reliable solutions despite of the multi-million man months thrown at them.
That being said you could simply add an "offensive?" link next to user generated contend and have a mod cross check the incoming complaints.
edit:
I forgot something: IF you are going to implement some kind of filter, you will need a reliable one. If your solution would be 50% right, 2000 out of 4000 users with decent images will get blocked. Expect an outrage.
Hi instead of using hook API, you should use Higher-order component API as mentioned here
I'll modify the example in the documentation to suit your need for class component
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/styles';
import Button from '@material-ui/core/Button';
const styles = theme => ({
root: {
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
border: 0,
borderRadius: 3,
boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
color: 'white',
height: 48,
padding: '0 30px',
},
});
class HigherOrderComponentUsageExample extends React.Component {
render(){
const { classes } = this.props;
return (
<Button className={classes.root}>This component is passed to an HOC</Button>
);
}
}
HigherOrderComponentUsageExample.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(HigherOrderComponentUsageExample);
$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
ADD COLUMN `ping_status` INT(1) NOT NULL
AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";
I believe you need to have ADD COLUMN
and use AFTER
, not BEFORE
.
In case you want to place column at the beginning of a table, use the FIRST
statement:
$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
ADD COLUMN `ping_status` INT(1) NOT NULL
FIRST";
This simple mechanism you can use for detecting finishing of a thread without blocking in join method.
std::thread thread([&thread]() {
sleep(3);
thread.detach();
});
while(thread.joinable())
sleep(1);
You can use the title element as Phrogz indicated. There are also some good tooltips like jQuery's Tipsy http://onehackoranother.com/projects/jquery/tipsy/ (which can be used to replace all title elements), Bob Monteverde's nvd3 or even the Twitter's tooltip from their Bootstrap http://twitter.github.com/bootstrap/
Your syntax is pretty screwy.
Change this:
input:not(disabled)not:[type="submit"]:focus{
to:
input:not(:disabled):not([type="submit"]):focus{
Seems that many people don't realize :enabled
and :disabled
are valid CSS selectors...
The solution from the comments deserves it's own answer:
redis-cli --bigkeys
A few ideas:
HEAD
command instead of a full GET to see if it needs to download the full file again, and the server uses the timestamp to see.If you want to disable caching on your server, you can do something like:
Header set Expires "Thu, 19 Nov 1981 08:52:00 GM"
Header set Cache-Control "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"
Header set Pragma "no-cache"
In .htaccess
Following code returns full months between two dates by taking nr of days of partial months into account as well.
var monthDiff = function(d1, d2) {
if( d2 < d1 ) {
var dTmp = d2;
d2 = d1;
d1 = dTmp;
}
var months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
if( d1.getDate() <= d2.getDate() ) months += 1;
return months;
}
monthDiff(new Date(2015, 01, 20), new Date(2015, 02, 20))
> 1
monthDiff(new Date(2015, 01, 20), new Date(2015, 02, 19))
> 0
monthDiff(new Date(2015, 01, 20), new Date(2015, 01, 22))
> 0
While there's no way to connect to multiple servers as different users in a single instance of SSMS, what you're looking for is the following RUNAS syntax:
runas /netonly /user:domain\username program.exe
When you use the "/netonly" switch, you can log in using remote credentials on a domain that you're not currently a member of, even if there's no trust set up. It just tells runas that the credentials will be used for accessing remote resources - the application interacts with the local computer as the currently logged-in user, and interacts with remote computers as the user whose credentials you've given.
You'd still have to run multiple instances of SSMS, but at least you could connect as different windows users in each one.
runas /netonly /user:domain\username ssms.exe
Ugly, hackish, but should work:
select top(M + N - 1) * from TableName
except
select top(N - 1) * from TableName
int
and double
have different semantics. Consider division. 1/2
is 0
, 1.0/2.0
is 0.5
. In any given situation, one of those answers will be right and the other wrong.
That said, there are programming languages, such as JavaScript, in which 64-bit float is the only numeric data type. You have to explicitly truncate some division results to get the same semantics as Java int
. Languages such as Java that support integer types make truncation automatic for integer variables.
In addition to having different semantics from double
, int
arithmetic is generally faster, and the smaller size (32 bits vs. 64 bits) leads to more efficient use of caches and data transfer bandwidth.
It is likely a case of IIS 7 'handling' the HTTP OPTIONS response instead of your application specifying it. To determine this, in IIS7,
Go to your site's Handler Mappings.
Scroll down to 'OPTIONSVerbHandler'.
Change the 'ProtocolSupportModule' to 'IsapiHandler'
Set the executable: %windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll
Now, your config entries above should kick in when an HTTP OPTIONS verb is sent.
Alternatively you can respond to the HTTP OPTIONS verb in your BeginRequest method.
protected void Application_BeginRequest(object sender,EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if(HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000" );
HttpContext.Current.Response.End();
}
}
Get "adbd insecure" from google play store, it helps give write access to custom roms that have it secured my the manufacturers.
A mutex is used for serial access to a resource while a semaphore limits access to a resource up to a set number. You can think of a mutex as a semaphore with an access count of 1. Whatever you set your semaphore count to, that may threads can access the resource before the resource is blocked.
Made a jsFiddle just for you that solves this issue. simply set $dirty to true, but with a $timeout 0
so it runs after DOM was loaded.
Find it here: JsFiddle
$timeout(function () {
$scope.form.uName.$dirty = true;
}, 0);
If you want to select particular element use below code
var gridRowData = $("<your grid name>").data("kendoGrid");
var selectedItem = gridRowData.dataItem(gridRowData.select());
var quote = selectedItem["<column name>"];
You should initialize variables to None and then check it:
var1 = None
if var1 is None:
var1 = 4
Which can be written in one line as:
var1 = 4 if var1 is None else var1
or using shortcut (but checking against None is recommended)
var1 = var1 or 4
alternatively if you will not have anything assigned to variable that variable name doesn't exist and hence using that later will raise NameError
, and you can also use that knowledge to do something like this
try:
var1
except NameError:
var1 = 4
but I would advise against that.
There are millions of answers already, I wanted to add you don't need <mainClass>
if you don't need to add entryPoint to your application. For example APIs may not have necessarily have main
method.
<build>
<finalName>log-enrichment</finalName>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
mvn clean compile assembly:single
ll target/
total 35100
drwxrwx--- 1 root vboxsf 4096 Sep 29 16:25 ./
drwxrwx--- 1 root vboxsf 4096 Sep 29 16:25 ../
drwxrwx--- 1 root vboxsf 0 Sep 29 16:08 archive-tmp/
drwxrwx--- 1 root vboxsf 0 Sep 29 16:25 classes/
drwxrwx--- 1 root vboxsf 0 Sep 29 16:25 generated-sources/
drwxrwx--- 1 root vboxsf 0 Sep 29 16:25 generated-test-sources/
-rwxrwx--- 1 root vboxsf 35929841 Sep 29 16:10 log-enrichment-jar-with-dependencies.jar*
drwxrwx--- 1 root vboxsf 0 Sep 29 16:08 maven-status/
Here is what I would recommend.
It should conform to C89, and be completely portable. In particular, it works also on pipes and sockets on POSIXy systems.
The idea is that we read the input in large-ish chunks (READALL_CHUNK
), dynamically reallocating the buffer as we need it. We only use realloc()
, fread()
, ferror()
, and free()
:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
/* Size of each input chunk to be
read and allocate for. */
#ifndef READALL_CHUNK
#define READALL_CHUNK 262144
#endif
#define READALL_OK 0 /* Success */
#define READALL_INVALID -1 /* Invalid parameters */
#define READALL_ERROR -2 /* Stream error */
#define READALL_TOOMUCH -3 /* Too much input */
#define READALL_NOMEM -4 /* Out of memory */
/* This function returns one of the READALL_ constants above.
If the return value is zero == READALL_OK, then:
(*dataptr) points to a dynamically allocated buffer, with
(*sizeptr) chars read from the file.
The buffer is allocated for one extra char, which is NUL,
and automatically appended after the data.
Initial values of (*dataptr) and (*sizeptr) are ignored.
*/
int readall(FILE *in, char **dataptr, size_t *sizeptr)
{
char *data = NULL, *temp;
size_t size = 0;
size_t used = 0;
size_t n;
/* None of the parameters can be NULL. */
if (in == NULL || dataptr == NULL || sizeptr == NULL)
return READALL_INVALID;
/* A read error already occurred? */
if (ferror(in))
return READALL_ERROR;
while (1) {
if (used + READALL_CHUNK + 1 > size) {
size = used + READALL_CHUNK + 1;
/* Overflow check. Some ANSI C compilers
may optimize this away, though. */
if (size <= used) {
free(data);
return READALL_TOOMUCH;
}
temp = realloc(data, size);
if (temp == NULL) {
free(data);
return READALL_NOMEM;
}
data = temp;
}
n = fread(data + used, 1, READALL_CHUNK, in);
if (n == 0)
break;
used += n;
}
if (ferror(in)) {
free(data);
return READALL_ERROR;
}
temp = realloc(data, used + 1);
if (temp == NULL) {
free(data);
return READALL_NOMEM;
}
data = temp;
data[used] = '\0';
*dataptr = data;
*sizeptr = used;
return READALL_OK;
}
Above, I've used a constant chunk size, READALL_CHUNK
== 262144 (256*1024
). This means that in the worst case, up to 262145 chars are wasted (allocated but not used), but only temporarily. At the end, the function reallocates the buffer to the optimal size. Also, this means that we do four reallocations per megabyte of data read.
The 262144-byte default in the code above is a conservative value; it works well for even old minilaptops and Raspberry Pis and most embedded devices with at least a few megabytes of RAM available for the process. Yet, it is not so small that it slows down the operation (due to many read calls, and many buffer reallocations) on most systems.
For desktop machines at this time (2017), I recommend a much larger READALL_CHUNK
, perhaps #define READALL_CHUNK 2097152
(2 MiB).
Because the definition of READALL_CHUNK
is guarded (i.e., it is defined only if it is at that point in the code still undefined), you can override the default value at compile time, by using (in most C compilers) -DREADALL_CHUNK=2097152
command-line option -- but do check your compiler options for defining a preprocessor macro using command-line options.
For demo code that conforms to POSIX standard as described in Setting Terminal Modes Properly
and Serial Programming Guide for POSIX Operating Systems, the following is offered.
This code should execute correctly using Linux on x86 as well as ARM (or even CRIS) processors.
It's essentially derived from the other answer, but inaccurate and misleading comments have been corrected.
This demo program opens and initializes a serial terminal at 115200 baud for non-canonical mode that is as portable as possible.
The program transmits a hardcoded text string to the other terminal, and delays while the output is performed.
The program then enters an infinite loop to receive and display data from the serial terminal.
By default the received data is displayed as hexadecimal byte values.
To make the program treat the received data as ASCII codes, compile the program with the symbol DISPLAY_STRING, e.g.
cc -DDISPLAY_STRING demo.c
If the received data is ASCII text (rather than binary data) and you want to read it as lines terminated by the newline character, then see this answer for a sample program.
#define TERMINAL "/dev/ttyUSB0"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
int set_interface_attribs(int fd, int speed)
{
struct termios tty;
if (tcgetattr(fd, &tty) < 0) {
printf("Error from tcgetattr: %s\n", strerror(errno));
return -1;
}
cfsetospeed(&tty, (speed_t)speed);
cfsetispeed(&tty, (speed_t)speed);
tty.c_cflag |= (CLOCAL | CREAD); /* ignore modem controls */
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8; /* 8-bit characters */
tty.c_cflag &= ~PARENB; /* no parity bit */
tty.c_cflag &= ~CSTOPB; /* only need 1 stop bit */
tty.c_cflag &= ~CRTSCTS; /* no hardware flowcontrol */
/* setup for non-canonical mode */
tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
tty.c_oflag &= ~OPOST;
/* fetch bytes as they become available */
tty.c_cc[VMIN] = 1;
tty.c_cc[VTIME] = 1;
if (tcsetattr(fd, TCSANOW, &tty) != 0) {
printf("Error from tcsetattr: %s\n", strerror(errno));
return -1;
}
return 0;
}
void set_mincount(int fd, int mcount)
{
struct termios tty;
if (tcgetattr(fd, &tty) < 0) {
printf("Error tcgetattr: %s\n", strerror(errno));
return;
}
tty.c_cc[VMIN] = mcount ? 1 : 0;
tty.c_cc[VTIME] = 5; /* half second timer */
if (tcsetattr(fd, TCSANOW, &tty) < 0)
printf("Error tcsetattr: %s\n", strerror(errno));
}
int main()
{
char *portname = TERMINAL;
int fd;
int wlen;
char *xstr = "Hello!\n";
int xlen = strlen(xstr);
fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0) {
printf("Error opening %s: %s\n", portname, strerror(errno));
return -1;
}
/*baudrate 115200, 8 bits, no parity, 1 stop bit */
set_interface_attribs(fd, B115200);
//set_mincount(fd, 0); /* set to pure timed read */
/* simple output */
wlen = write(fd, xstr, xlen);
if (wlen != xlen) {
printf("Error from write: %d, %d\n", wlen, errno);
}
tcdrain(fd); /* delay for output */
/* simple noncanonical input */
do {
unsigned char buf[80];
int rdlen;
rdlen = read(fd, buf, sizeof(buf) - 1);
if (rdlen > 0) {
#ifdef DISPLAY_STRING
buf[rdlen] = 0;
printf("Read %d: \"%s\"\n", rdlen, buf);
#else /* display hex */
unsigned char *p;
printf("Read %d:", rdlen);
for (p = buf; rdlen-- > 0; p++)
printf(" 0x%x", *p);
printf("\n");
#endif
} else if (rdlen < 0) {
printf("Error from read: %d: %s\n", rdlen, strerror(errno));
} else { /* rdlen == 0 */
printf("Timeout from read\n");
}
/* repeat read to get full message */
} while (1);
}
For an example of an efficient program that provides buffering of received data yet allows byte-by-byte handing of the input, then see this answer.
I faced a similar problem, trying to test if jQuery is already present on a page, and if not force it's load, and then execute a function. I tried with @David Hellsing workaround, but with no chance for my needs. In fact, the onload
instruction was immediately evaluated, and then the $
usage inside this function was not yet possible (yes, the huggly "$ is not a function." ^^).
So, I referred to this article : https://developer.mozilla.org/fr/docs/Web/Events/load and attached a event listener to my script object.
var script = document.createElement('script');
script.type = "text/javascript";
script.addEventListener("load", function(event) {
console.log("script loaded :)");
onjqloaded();
});
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
For my needs, it works fine now. Hope this can help others :)
As an alternative to using UsedRange or providing an explicit range address, the AutoFilter.Range property can also specify the affected range.
ActiveSheet.AutoFilter.Range.Offset(1,0).Rows.SpecialCells(xlCellTypeVisible).Delete(xlShiftUp)
As used here, Offset causes the first row after the AutoFilter range to also be deleted. In order to avoid that, I would try using .Resize() after .Offset().
When you call loc
with a scalar value, you get a pd.Series
. That series will then have one dtype
. If you want to see the row as it is in the dataframe, you'll want to pass an array like indexer to loc
.
Wrap your index value with an additional pair of square brackets
print(df.loc[[159220]])
Just the same thing that Solaris 5.10 it works like this ./batchstart.sh
there is a trick I don´t know if your OS accept it use \\. batchstart.sh
instead. This double slash may help.
You can store the array using serialize
/unserialize
. With that solution they cannot easily be used from other programming languages, so you may consider using json_encode
/json_decode
instead (which gives you a widely supported format). Avoid using implode
/explode
for this since you'll probably end up with bugs or security flaws.
Note that this makes your table non-normalized, which may be a bad idea since you cannot easily query the data. Therefore consider this carefully before going forward. May you need to query the data for statistics or otherwise? Are there other reasons to normalize the data?
Also, don't save the raw $_POST
array. Someone can easily make their own web form and post data to your site, thereby sending a really large form which takes up lots of space. Save those fields you want and make sure to validate the data before saving it (so you won't get invalid values).
This may be what you are looking for:
body>div {_x000D_
background: #aaa;_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
body>div>div {_x000D_
flex-grow: 1;_x000D_
width: 33%;_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
body>div>div:nth-child(even) {_x000D_
background: #23a;_x000D_
}_x000D_
_x000D_
body>div>div:nth-child(odd) {_x000D_
background: #49b;_x000D_
}
_x000D_
<div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
</div>
_x000D_
Simply query the INFORMATION_SCHEMA:
USE INFORMATION_SCHEMA;
SELECT TABLE_NAME,
COLUMN_NAME,
CONSTRAINT_NAME,
REFERENCED_TABLE_NAME,
REFERENCED_COLUMN_NAME
FROM KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = "<your_database_name>"
AND TABLE_NAME = "<your_table_name>"
AND REFERENCED_COLUMN_NAME IS NOT NULL;
Step1. Install bulma package using npm
npm install --save bulma
Step2. Open angular.json and update following code
...
"styles": [
"node_modules/bulma/css/bulma.css",
"src/styles.scss"
],
...
That's it.
To easily expose Bulma’s tools, add stylePreprocessorOptions to angular.json.
...
"styles": [
"src/styles.scss",
"node_modules/bulma/css/bulma.css"
],
"stylePreprocessorOptions": {
"includePaths": [
"node_modules",
"node_modules/bulma/sass/utilities"
]
},
...
For disabling a button add css class disabled
to it . write
$("button").addClass('disabled')
You really want to do this
flog.write("\nCompany Name: "+ pCompanyName.encode('utf-8'))
This is the "encode late" strategy described in this unicode presentation (slides 32 through 35).
The easiest way to solve this problem is add the following FTP information to your wp-config.php
define('FS_METHOD', 'direct');
define('FTP_BASE', '/usr/home/username/public_html/my-site.example.com/wordpress/');
define('FTP_CONTENT_DIR', '/usr/home/username/public_html/my-site.example.com/wordpress/wp-content/');
define('FTP_PLUGIN_DIR ', '/usr/home/username/public_html/my-site.example.com/wordpress/wp-content/plugins/');
FTP_BASE is the full path to the "base"(ABSPATH) folder of the WordPress installation FTP_CONTENT_DIR is the full path to the wp-content folder of the WordPress installation. FTP_PLUGIN_DIR is the full path to the plugins folder of the WordPress installation.
Try using How to recover a dropped stash in Git? to find the stash you popped. I think there are always two commits for a stash, since it preserves the index and the working copy (so often the index commit will be empty). Then git show
them to see the diff and use patch -R
to unapply them.
This is how the regex look like:
import re
# "semicolon or (a comma followed by a space)"
pattern = re.compile(r";|, ")
# "(semicolon or a comma) followed by a space"
pattern = re.compile(r"[;,] ")
print pattern.split(text)
All tags must have enclosing tags. In my case, the hr and input elements weren't closed properly.
Parent Error was: JSX element 'div' has no corresponding closing tag, due to code below:
<hr class="my-4">
<input
type="password"
id="inputPassword"
class="form-control"
placeholder="Password"
required
>
Fix:
<hr class="my-4"/>
<input
type="password"
id="inputPassword"
class="form-control"
placeholder="Password"
required
/>
The parent elements will show errors due to child element errors. Therefore, start investigating from most inner elements up to the parent ones.
The port number is an unsigned 16-bit integer, so 65535.
? + L
? + K
Example of export in file with full path on Windows and in case your file has headers:
df.to_csv (r'C:\Users\John\Desktop\export_dataframe.csv', index = None, header=True)
For example, if you want to store the file in same directory where your script is, with utf-8 encoding and tab as separator:
df.to_csv(r'./export/dftocsv.csv', sep='\t', encoding='utf-8', header='true')
you should be using the .Value of the datetime parameter. All Nullable structs have a value property which returns the concrete type of the object. but you must check to see if it is null beforehand otherwise you will get a runtime error.
i.e:
datetime.Value
but check to see if it has a value first!
if (datetime.HasValue)
{
// work with datetime.Value
}
Yes:
<div style="background-image: url(../images/image.gif); height: 400px; width: 400px;">Text here</div>
deletes all the things
Welcome to 2017 ^_^
Okay, so if you're not opposed to trying out a new IDE you can do the following for free.
launch.json
to use "cwd"
and and "program"
fields using the {workspaceRoot}
macro"showDebuggerOutput"
and set it to true
"debug.allowBreakpointsEverywhere": true
vscode
; this is not the same as Visual Studio. It's free, light-weight, and generally positively regarded.View->Extensions
.vscode
and in there we'll but a file called launch.json
where we're going to store some config options.
launch.json
contents
{
"version": "0.2.0",
"configurations":
[
{
"name": "Debug Local File",
"type":"Ruby",
"request": "launch",
"cwd": "${workspaceRoot}",
"program": "{workspaceRoot}/../script_name.rb",
"args": [],
"showDebuggerOutput": true
}
]
}
File->Preferences->Settings
(or Ctrl, ) and scroll until you reach the Debug
section. Expand it and look for a field called "debug.allowBreakpointsEverywhere"
-- select that field and click on the little pencil-looking icon and set it to true
.After doing all that fun stuff, you should be able to set breakpoints and debug in a menu similar to this for mid-2017 and a darker theme: with all the fun stuff like your call stack, variable viewer, etc.
The biggest PITA is 1) installing the pre-reqs and 2) Remembering to configure the .vscode\launch.json
file. Only #2 should add any baggage to future projects, and you can just copy a generic enough config like the one listed above. There's probably a more general config location, but I don't know off the top of my head.
Random generator = new Random();
int i = generator.nextInt(10) + 1;
You could use "Dotfuscator Community Edition" - it comes by default in Visual Studio 2008 Professional. You can read about it at:
http://msdn.microsoft.com/en-us/library/ms227240%28VS.80%29.aspx
http://www.preemptive.com/dotfuscator.html
The "Professional" version of the product costs money but is better.
Do you really need your code obfuscated? Usually there is very little wrong with your application being decompiled, unless it is used for security purposes. If you are worried about people "stealing" your code, don't be; the vast majority of people looking at your code will be for learning purposes. Anyway, there is no totally effective obfuscation strategy for .NET - someone with enough skill will always be able to decompile/change you application.
You're looking for is called an IDENTITY column:
create table student (
sid integer not null GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1)
,sname varchar(30)
,PRIMARY KEY (sid)
);
A sequence is another option for doing this, but you need to determine which one is proper for your particular situation. Read this for more information comparing sequences to identity columns.
You can also use html to override the css locally. I was having a similar issue and this worked for me:
<html>
<body>
<h4>A nested List:</h4>
<ul style="PADDING-LEFT: 12px">
<li>Coffee</li>
<li>Tea
<ul>
<li>Black tea</li>
<li>Green tea</li>
</ul>
</li>
<li>Milk</li>
</ul>
</body>
</html>
I have same problem!
Found following in oracle site link text
As mentioned above, the 11.1 drivers by default convert SQL DATE to Timestamp when reading from the database. This always was the right thing to do and the change in 9i was a mistake. The 11.1 drivers have reverted to the correct behavior. Even if you didn't set V8Compatible in your application you shouldn't see any difference in behavior in most cases. You may notice a difference if you use getObject to read a DATE column. The result will be a Timestamp rather than a Date. Since Timestamp is a subclass of Date this generally isn't a problem. Where you might notice a difference is if you relied on the conversion from DATE to Date to truncate the time component or if you do toString on the value. Otherwise the change should be transparent.
If for some reason your app is very sensitive to this change and you simply must have the 9i-10g behavior, there is a connection property you can set. Set mapDateToTimestamp to false and the driver will revert to the default 9i-10g behavior and map DATE to Date.
You can add an alias
or a function
in your startup script file. Usually this is .bashrc
, .bash_login
or .profile
file in your home directory.
Since these files are hidden you will have to do an ls -a
to list them. If you don't have one you can create one.
If I remember correctly, when I had bought my Mac, the .bash_login
file wasn't there. I had to create it for myself so that I could put prompt info
, alias
, functions
, etc. in it.
Here are the steps if you would like to create one:
cd ~/
to go to your home foldertouch .bash_profile
to create your new file..bash_profile
with your favorite editor (or you can just type open -e .bash_profile
to open it in TextEdit.. .bash_profile
to reload .bash_profile
and update any alias you add.As of v 2.5, NUnit has the following method-level Assert
s for testing exceptions:
Assert.Throws, which will test for an exact exception type:
Assert.Throws<NullReferenceException>(() => someNullObject.ToString());
And Assert.Catch
, which will test for an exception of a given type, or an exception type derived from this type:
Assert.Catch<Exception>(() => someNullObject.ToString());
As an aside, when debugging unit tests which throw exceptions, you may want to prevent VS from breaking on the exception.
Edit
Just to give an example of Matthew's comment below, the return of the generic Assert.Throws
and Assert.Catch
is the exception with the type of the exception, which you can then examine for further inspection:
// The type of ex is that of the generic type parameter (SqlException)
var ex = Assert.Throws<SqlException>(() => MethodWhichDeadlocks());
Assert.AreEqual(1205, ex.Number);
Here is a different approach using mix-blend-mode: difference
, that will actually invert whatever the background is, not just a single colour:
div {_x000D_
background-image: linear-gradient(to right, red, yellow, green, cyan, blue, violet);_x000D_
}_x000D_
p {_x000D_
color: white;_x000D_
mix-blend-mode: difference;_x000D_
}
_x000D_
<div>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscit elit, sed do</p>_x000D_
</div>
_x000D_
use [[NSDate date] timeIntervalSince1970]
First, it's always worth noting that git reset --hard
is a potentially dangerous command, since it throws away all your uncommitted changes. For safety, you should always check that the output of git status
is clean (that is, empty) before using it.
Initially you say the following:
So I know that Git tracks changes I make to my application, and it holds on to them until I commit the changes, but here's where I'm hung up:
That's incorrect. Git only records the state of the files when you stage them (with git add
) or when you create a commit. Once you've created a commit which has your project files in a particular state, they're very safe, but until then Git's not really "tracking changes" to your files. (for example, even if you do git add
to stage a new version of the file, that overwrites the previously staged version of that file in the staging area.)
In your question you then go on to ask the following:
When I want to revert to a previous commit I use: git reset --hard HEAD And git returns: HEAD is now at 820f417 micro
How do I then revert the files on my hard drive back to that previous commit?
If you do git reset --hard <SOME-COMMIT>
then Git will:
master
) back to point at <SOME-COMMIT>
.<SOME-COMMIT>
.HEAD
points to your current branch (or current commit), so all that git reset --hard HEAD
will do is to throw away any uncommitted changes you have.
So, suppose the good commit that you want to go back to is f414f31
. (You can find that via git log
or any history browser.) You then have a few different options depending on exactly what you want to do:
git reset --hard f414f31
. However, this is rewriting the history of your branch, so you should avoid it if you've shared this branch with anyone. Also, the commits you did after f414f31
will no longer be in the history of your master
branch.Create a new commit that represents exactly the same state of the project as f414f31
, but just adds that on to the history, so you don't lose any history. You can do that using the steps suggested in this answer - something like:
git reset --hard f414f31
git reset --soft HEAD@{1}
git commit -m "Reverting to the state of the project at f414f31"
I'm using xdLocalStorage, this is a lightweight js library which implements LocalStorage interface and support cross domain storage by using iframe post message communication.( angularJS support )
I experienced that NodeJS is hashing the UTF-8 representation of the string. Other languages (like Python, PHP or PERL...) are hashing the byte string.
We can add binary argument to use the byte string.
const crypto = require("crypto");
function sha1(data) {
return crypto.createHash("sha1").update(data, "binary").digest("hex");
}
sha1("Your text ;)");
You can try with : "\xac", "\xd1", "\xb9", "\xe2", "\xbb", "\x93", etc...
sha1("\xac") //39527c59247a39d18ad48b9947ea738396a3bc47
sha1 = crypto.createHash("sha1").update("\xac", "binary").digest("hex") //39527c59247a39d18ad48b9947ea738396a3bc47
//without:
sha1 = crypto.createHash("sha1").update("\xac").digest("hex") //f50eb35d94f1d75480496e54f4b4a472a9148752
This question is very interesting for me because I have problems, when I run container after execution finishes immediately exit and I fixed with -it:
docker run -it -p 3000:3000 -v /app/node_modules -v $(pwd):/app <your_container_id>
And when I must automate it with docker compose:
version: '3'
services:
frontend:
stdin_open: true
tty: true
build:
context: .
dockerfile: Dockerfile.dev
ports:
- "3000:3000"
volumes:
- /app/node_modules
- .:/app
This makes the trick: stdin_open: true, tty: true
This is a project generated with create-react-app
Dockerfile.dev it looks this that:
FROM node:alpine
WORKDIR '/app'
COPY package.json .
RUN npm install
COPY . .
CMD ["npm", "run", "start"]
Hope this example will help other to run a frontend(react in example) into docker container.
You have to explicitly set the position of the parent container along with the position of the child container. The typical way to do that is something like this:
div.parent{
position: relative;
left: 0px; /* stick it wherever it was positioned by default */
top: 0px;
}
div.child{
position: absolute;
left: 10px;
top: 10px;
}
I had the same problem, getting the message "ImportError: No module named numpy".
I'm also using anaconda and found out that I needed to add numpy to the ENV I was using. You can check the packages you have in your environment with the command:
conda list
So, when I used that command, numpy was not displayed. If that is your case, you just have to add it, with the command:
conda install numpy
After I did that, the error with the import numpy
was gone
This works for me:
In link, to attribute has value:
to="/filter/arr?fruits=apple&fruits=banana"
Route can handle this:
path="/filter/:arr"
For Multiple arrays:
to="filter/arr?fruits=apple&fruits=banana&vegetables=potato&vegetables=onion"
Route stays same.
SCREENSHOT
Listen for the paste event and set a keyup event listener. On keyup, capture the value and remove the keyup event listener.
$('.inputTextArea').bind('paste', function (e){
$(e.target).keyup(getInput);
});
function getInput(e){
var inputText = $(e.target).val();
$(e.target).unbind('keyup');
}
As I understand it, "request timeout" means the ICMP packet reached from one host to the other host but the reply could not reach the requesting host. There may be more packet loss or some physical issue. "destination host unreachable" means there is no proper route defined between two hosts.
INSERT INTO wp_bp_activity
(
user_id,
component,
`type`,
`action`,
content,
primary_link,
item_id,
secondary_item_id,
date_recorded,
hide_sitewide,
mptt_left,
mptt_right
)
VALUES(
1,'activity','activity_update','<a title="admin" href="http://brandnewmusicreleases.com/social-network/members/admin/">admin</a> posted an update','<a title="242925_1" href="http://brandnewmusicreleases.com/social-network/wp-content/uploads/242925_1.jpg" class="buddyboss-pics-picture-link">242925_1</a>','http://brandnewmusicreleases.com/social-network/members/admin/',' ',' ','2012-06-22 12:39:07',0,0,0
)
Have a look at the UUID class bundled with Java 5 and later.
For example:
If you want to keep using sendSynchronousRequest i work in this solution:
FailCertificateDelegate *fcd=[[FailCertificateDelegate alloc] init];
NSURLConnection *c=[[NSURLConnection alloc] initWithRequest:request delegate:fcd startImmediately:NO];
[c setDelegateQueue:[[NSOperationQueue alloc] init]];
[c start];
NSData *d=[fcd getData];
you can see it here: Objective-C SSL Synchronous Connection
Using the rename function:
fs.rename(getFileName, __dirname + '/new_folder/' + getFileName);
where
getFilename = file.extension (old path)
__dirname + '/new_folder/' + getFileName
assumming that you want to keep the file name unchanged.
Here is the JSfiddle Demo
I changed your HTML and give your input textfield an id of value. I removed the passed param for your verifyorder function, and instead grab the content of your textfield by using document.getElementById(); then i convert the str into value with +order
so you can check if it's greater than zero:
<input type="text" maxlength="3" name="value" id='value' />
<input type="button" value="submit" onclick="verifyorder()" />
</p>
<p id="error"></p>
<p id="detspace"></p>
function verifyorder() {
var order = document.getElementById('value').value;
if (+order > 0) {
alert(+order);
return true;
}
else {
alert("Sorry, you need to enter a positive integer value, try again");
document.getElementById('error').innerHTML = "Sorry, you need to enter a positive integer value, try again";
}
}
You can use the str.split method.
>>> my_string = 'A,B,C,D,E'
>>> my_list = my_string.split(",")
>>> print my_list
['A', 'B', 'C', 'D', 'E']
If you want to convert it to a tuple, just
>>> print tuple(my_list)
('A', 'B', 'C', 'D', 'E')
If you are looking to append to a list, try this:
>>> my_list.append('F')
>>> print my_list
['A', 'B', 'C', 'D', 'E', 'F']
You can do a custom namespace of events.
$('span').bind('click.doStuff1',function(){doStuff1();});
$('span').bind('click.doStuff2',function(){doStuff2();});
Then, when you need to trigger them you can choose the order.
$('span').trigger('click.doStuff1').trigger('click.doStuff2');
or
$('span').trigger('click.doStuff2').trigger('click.doStuff1');
Also, just triggering click SHOULD trigger both in the order they were bound... so you can still do
$('span').trigger('click');
The RequestDispatcher
interface allows you to do a server side forward/include whereas sendRedirect()
does a client side redirect. In a client side redirect, the server will send back an HTTP status code of 302
(temporary redirect) which causes the web browser to issue a brand new HTTP GET
request for the content at the redirected location. In contrast, when using the RequestDispatcher
interface, the include/forward to the new resource is handled entirely on the server side.
Interfaces allow statically typed languages to support polymorphism. An Object Oriented purist would insist that a language should provide inheritance, encapsulation, modularity and polymorphism in order to be a fully-featured Object Oriented language. In dynamically-typed - or duck typed - languages (like Smalltalk,) polymorphism is trivial; however, in statically typed languages (like Java or C#,) polymorphism is far from trivial (in fact, on the surface it seems to be at odds with the notion of strong typing.)
Let me demonstrate:
In a dynamically-typed (or duck typed) language (like Smalltalk), all variables are references to objects (nothing less and nothing more.) So, in Smalltalk, I can do this:
|anAnimal|
anAnimal := Pig new.
anAnimal makeNoise.
anAnimal := Cow new.
anAnimal makeNoise.
That code:
makeNoise
to the pig.The same Java code would look something like this (making the assumption that Duck and Cow are subclasses of Animal:
Animal anAnimal = new Pig();
duck.makeNoise();
anAnimal = new Cow();
cow.makeNoise();
That's all well and good, until we introduce class Vegetable. Vegetables have some of the same behavior as Animal, but not all. For example, both Animal and Vegetable might be able to grow, but clearly vegetables don't make noise and animals cannot be harvested.
In Smalltalk, we can write this:
|aFarmObject|
aFarmObject := Cow new.
aFarmObject grow.
aFarmObject makeNoise.
aFarmObject := Corn new.
aFarmObject grow.
aFarmObject harvest.
This works perfectly well in Smalltalk because it is duck-typed (if it walks like a duck, and quacks like a duck - it is a duck.) In this case, when a message is sent to an object, a lookup is performed on the receiver's method list, and if a matching method is found, it is called. If not, some kind of NoSuchMethodError exception is thrown - but it's all done at runtime.
But in Java, a statically typed language, what type can we assign to our variable? Corn needs to inherit from Vegetable, to support grow, but cannot inherit from Animal, because it does not make noise. Cow needs to inherit from Animal to support makeNoise, but cannot inherit from Vegetable because it should not implement harvest. It looks like we need multiple inheritance - the ability to inherit from more than one class. But that turns out to be a pretty difficult language feature because of all the edge cases that pop up (what happens when more than one parallel superclass implement the same method?, etc.)
Along come interfaces...
If we make Animal and Vegetable classes, with each implementing Growable, we can declare that our Cow is Animal and our Corn is Vegetable. We can also declare that both Animal and Vegetable are Growable. That lets us write this to grow everything:
List<Growable> list = new ArrayList<Growable>();
list.add(new Cow());
list.add(new Corn());
list.add(new Pig());
for(Growable g : list) {
g.grow();
}
And it lets us do this, to make animal noises:
List<Animal> list = new ArrayList<Animal>();
list.add(new Cow());
list.add(new Pig());
for(Animal a : list) {
a.makeNoise();
}
The advantage to the duck-typed language is that you get really nice polymorphism: all a class has to do to provide behavior is provide the method. As long as everyone plays nice, and only sends messages that match defined methods, all is good. The downside is that the kind of error below isn't caught until runtime:
|aFarmObject|
aFarmObject := Corn new.
aFarmObject makeNoise. // No compiler error - not checked until runtime.
Statically-typed languages provide much better "programming by contract," because they will catch the two kinds of error below at compile-time:
// Compiler error: Corn cannot be cast to Animal.
Animal farmObject = new Corn();
farmObject makeNoise();
--
// Compiler error: Animal doesn't have the harvest message.
Animal farmObject = new Cow();
farmObject.harvest();
So....to summarize:
Interface implementation allows you to specify what kinds of things objects can do (interaction) and Class inheritance lets you specify how things should be done (implementation).
Interfaces give us many of the benefits of "true" polymorphism, without sacrificing compiler type checking.
This may be created sql injection point "SQL Injection Piggy-backed Queries". attackers able to append multiple malicious sql statements. so do not append user inputs directly to the queries.
Security considerations
The API functions mysqli_query() and mysqli_real_query() do not set a connection flag necessary for activating multi queries in the server. An extra API call is used for multiple statements to reduce the likeliness of accidental SQL injection attacks. An attacker may try to add statements such as ; DROP DATABASE mysql or ; SELECT SLEEP(999). If the attacker succeeds in adding SQL to the statement string but mysqli_multi_query is not used, the server will not execute the second, injected and malicious SQL statement.
After some searches in the android references, the newcomer QuadFlask Color Picker seems to be a technically and aesthetically good choice. Also it has Transparency slider and supports HEX coded colors.
Take a look:
QuadFlask Color Picker
int values[] = { 23, 1, 5, 78, 22, 4};
int sum = 0;
for (int i = 0; i < values.length; i++)
sum += values[i];
double average = ((double) sum) / values.length;
I had a similar problem, looking for grep/pattern regex and the "matched pattern found" as output.
At the end I used egrep (same regex on grep -e or -G didn't give me the same result of egrep) with the option -o
so, I think that could be something similar to (I'm NOT a regex Master) :
egrep -o "the*|this{1}|thoroughly{1}" filename
To answer the comment from weotch that Timothy Ryan Carpenter's answer doesn't account for cover
's centering of the background, I offer this quick CSS fix:
CSS:
margin-left: 50%;
transform: translateX(-50%);
Adding these two lines will center any element. Even better, all browsers that can handle HTML5 video also support CSS3 transformations, so this will always work.
The complete CSS looks like this.
#video-background {
position: absolute;
bottom: 0px;
right: 0px;
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
z-index: -1000;
overflow: hidden;
margin-left: 50%;
transform: translateX(-50%);
}
I'd have commented directly on Timothy's answer, but I don't have enough reputation to do so.
VB.Net code based implementation of kobusb's Border control solution. I used it to populate a ListBox of Button controls. The Button controls are created from MEF extensions. Each extension uses MEF's ExportMetaData attribute for a Description of the extension. The extensions are VisiFire charting objects. The user pushes a button, selected from the list of buttons, to execute the desired chart.
' Create a ListBox of Buttons, one button for each MEF charting component.
For Each c As Lazy(Of ICharts, IDictionary(Of String, Object)) In ext.ChartDescriptions
Dim brdr As New Border
brdr.BorderBrush = Brushes.Black
brdr.BorderThickness = New Thickness(2, 2, 2, 2)
brdr.CornerRadius = New CornerRadius(8, 8, 8, 8)
Dim btn As New Button
AddHandler btn.Click, AddressOf GenericButtonClick
brdr.Child = btn
brdr.Background = btn.Background
btn.Margin = brdr.BorderThickness
btn.Width = ChartsLBx.ActualWidth - 22
btn.BorderThickness = New Thickness(0, 0, 0, 0)
btn.Height = 22
btn.Content = c.Metadata("Description")
btn.Tag = c
btn.ToolTip = "Push button to see " & c.Metadata("Description").ToString & " chart"
Dim lbi As New ListBoxItem
lbi.Content = brdr
ChartsLBx.Items.Add(lbi)
Next
Public Event Click As RoutedEventHandler
Private Sub GenericButtonClick(sender As Object, e As RoutedEventArgs)
Dim btn As Button = DirectCast(sender, Button)
Dim c As Lazy(Of ICharts, IDictionary(Of String, Object)) = DirectCast(btn.Tag, Lazy(Of ICharts, IDictionary(Of String, Object)))
Dim w As Window = DirectCast(c.Value, Window)
Dim cc As ICharts = DirectCast(c.Value, ICharts)
c.Value.CreateChart()
w.Show()
End Sub
<System.ComponentModel.Composition.Export(GetType(ICharts))> _
<System.ComponentModel.Composition.ExportMetadata("Description", "Data vs. Time")> _
Public Class DataTimeChart
Implements ICharts
Public Sub CreateChart() Implements ICharts.CreateChart
End Sub
End Class
Public Interface ICharts
Sub CreateChart()
End Interface
Public Class Extensibility
Public Sub New()
Dim catalog As New AggregateCatalog()
catalog.Catalogs.Add(New AssemblyCatalog(GetType(Extensibility).Assembly))
'Create the CompositionContainer with the parts in the catalog
ChartContainer = New CompositionContainer(catalog)
Try
ChartContainer.ComposeParts(Me)
Catch ex As Exception
Console.WriteLine(ex.ToString)
End Try
End Sub
' must use Lazy otherwise instantiation of Window will hold open app. Otherwise must specify Shutdown Mode of "Shutdown on Main Window".
<ImportMany()> _
Public Property ChartDescriptions As IEnumerable(Of Lazy(Of ICharts, IDictionary(Of String, Object)))
End Class
The below code will give you list of all the rows:-
df[df['C'] != 'XYZ']
To store the values from the above code into a dataframe :-
newdf = df[df['C'] != 'XYZ']
A better solution is to use -webkit-columns:2;
http://jsfiddle.net/YMN7U/889/
ul { margin:0.5em auto;
-webkit-columns:2;
}
I made a small benchmark with BenchmarkDotNet to get a better understanding of "struct" benefit in numbers. I'm testing looping through array (or list) of structs (or classes). Creating those arrays or lists is out of the benchmark's scope - it is clear that "class" is more heavy will utilize more memory, and will involve GC.
So the conclusion is: be careful with LINQ and hidden structs boxing/unboxing and using structs for microoptimizations strictly stay with arrays.
P.S. Another benchmark about passing struct/class through call stack is there https://stackoverflow.com/a/47864451/506147
BenchmarkDotNet=v0.10.8, OS=Windows 10 Redstone 2 (10.0.15063)
Processor=Intel Core i5-2500K CPU 3.30GHz (Sandy Bridge), ProcessorCount=4
Frequency=3233542 Hz, Resolution=309.2584 ns, Timer=TSC
[Host] : Clr 4.0.30319.42000, 64bit RyuJIT-v4.7.2101.1
Clr : Clr 4.0.30319.42000, 64bit RyuJIT-v4.7.2101.1
Core : .NET Core 4.6.25211.01, 64bit RyuJIT
Method | Job | Runtime | Mean | Error | StdDev | Min | Max | Median | Rank | Gen 0 | Allocated |
---------------- |----- |-------- |----------:|----------:|----------:|----------:|----------:|----------:|-----:|-------:|----------:|
TestListClass | Clr | Clr | 5.599 us | 0.0408 us | 0.0382 us | 5.561 us | 5.689 us | 5.583 us | 3 | - | 0 B |
TestArrayClass | Clr | Clr | 2.024 us | 0.0102 us | 0.0096 us | 2.011 us | 2.043 us | 2.022 us | 2 | - | 0 B |
TestListStruct | Clr | Clr | 8.427 us | 0.1983 us | 0.2204 us | 8.101 us | 9.007 us | 8.374 us | 5 | - | 0 B |
TestArrayStruct | Clr | Clr | 1.539 us | 0.0295 us | 0.0276 us | 1.502 us | 1.577 us | 1.537 us | 1 | - | 0 B |
TestLinqClass | Clr | Clr | 13.117 us | 0.1007 us | 0.0892 us | 13.007 us | 13.301 us | 13.089 us | 7 | 0.0153 | 80 B |
TestLinqStruct | Clr | Clr | 28.676 us | 0.1837 us | 0.1534 us | 28.441 us | 28.957 us | 28.660 us | 9 | - | 96 B |
TestListClass | Core | Core | 5.747 us | 0.1147 us | 0.1275 us | 5.567 us | 5.945 us | 5.756 us | 4 | - | 0 B |
TestArrayClass | Core | Core | 2.023 us | 0.0299 us | 0.0279 us | 1.990 us | 2.069 us | 2.013 us | 2 | - | 0 B |
TestListStruct | Core | Core | 8.753 us | 0.1659 us | 0.1910 us | 8.498 us | 9.110 us | 8.670 us | 6 | - | 0 B |
TestArrayStruct | Core | Core | 1.552 us | 0.0307 us | 0.0377 us | 1.496 us | 1.618 us | 1.552 us | 1 | - | 0 B |
TestLinqClass | Core | Core | 14.286 us | 0.2430 us | 0.2273 us | 13.956 us | 14.678 us | 14.313 us | 8 | 0.0153 | 72 B |
TestLinqStruct | Core | Core | 30.121 us | 0.5941 us | 0.5835 us | 28.928 us | 30.909 us | 30.153 us | 10 | - | 88 B |
Code:
[RankColumn, MinColumn, MaxColumn, StdDevColumn, MedianColumn]
[ClrJob, CoreJob]
[HtmlExporter, MarkdownExporter]
[MemoryDiagnoser]
public class BenchmarkRef
{
public class C1
{
public string Text1;
public string Text2;
public string Text3;
}
public struct S1
{
public string Text1;
public string Text2;
public string Text3;
}
List<C1> testListClass = new List<C1>();
List<S1> testListStruct = new List<S1>();
C1[] testArrayClass;
S1[] testArrayStruct;
public BenchmarkRef()
{
for(int i=0;i<1000;i++)
{
testListClass.Add(new C1 { Text1= i.ToString(), Text2=null, Text3= i.ToString() });
testListStruct.Add(new S1 { Text1 = i.ToString(), Text2 = null, Text3 = i.ToString() });
}
testArrayClass = testListClass.ToArray();
testArrayStruct = testListStruct.ToArray();
}
[Benchmark]
public int TestListClass()
{
var x = 0;
foreach(var i in testListClass)
{
x += i.Text1.Length + i.Text3.Length;
}
return x;
}
[Benchmark]
public int TestArrayClass()
{
var x = 0;
foreach (var i in testArrayClass)
{
x += i.Text1.Length + i.Text3.Length;
}
return x;
}
[Benchmark]
public int TestListStruct()
{
var x = 0;
foreach (var i in testListStruct)
{
x += i.Text1.Length + i.Text3.Length;
}
return x;
}
[Benchmark]
public int TestArrayStruct()
{
var x = 0;
foreach (var i in testArrayStruct)
{
x += i.Text1.Length + i.Text3.Length;
}
return x;
}
[Benchmark]
public int TestLinqClass()
{
var x = testListClass.Select(i=> i.Text1.Length + i.Text3.Length).Sum();
return x;
}
[Benchmark]
public int TestLinqStruct()
{
var x = testListStruct.Select(i => i.Text1.Length + i.Text3.Length).Sum();
return x;
}
}
You would have to turn your font into a web font as shown in these SO questions:
However, you may run into copyright issues with this: Not every font allows distribution as a web font. Check your font license to see whether it is allowed.
One of the easiest free and legal ways to use web fonts is Google Web Fonts. However, sadly, they don't have Helvetica Neue in their portfolio.
One of the easiest non-free and legal ways is to purchase the font from a foundry that offers web licenses. I happen to know that the myFonts foundry does this; they even give you a full package with all the JavaScript and CSS pre-prepared. I'm sure other foundries do the same.
Edit: MyFonts have Helvetica neue in Stock, but apparently not with a web license. Check out this list of similar fonts of which some have a web license. Also, Ray Larabie has some nice fonts there, with web licenses, some of them are free.
I found another solution elsewhere; that is, to use
upper(@yourString)
but everyone here is saying that, in SQL Server, it doesn't matter because it's ignoring case anyway? I'm pretty sure our database is case-sensitive.
You can get a really nice, visual output of how your branches differ with this
git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr)%Creset' --abbrev-commit --date=relative master..branch-X
Don't forget about CSS3's 'nth-child' selector. If you know the index of the column you wish to align text to the right on, you can just specify
table tr td:nth-child(2) {
text-align: right;
}
In cases with large tables this can save you a lot of extra markup!
here's a fiddle for ya.... https://jsfiddle.net/w16c2nad/