System scope was only designed to deal with 'system' files; files sitting in some fixed location. Files in /usr/lib
, or ${java.home}
(e.g. tools.jar
). It wasn't designed to support miscellaneous .jar
files in your project.
The authors intentionally refused to make the pathname expansions work right for that to discourage you. As a result, in the short term you can use install:install-file
to install into the local repo, and then some day use a repo manager to share.
If you use eclipse, you simply type "import numpy" and eclipse will "complain" if doesn't find.
Doing
df.index = pd.to_datetime(df.index, errors='coerce')
the data type of the index has changed to
You should implement the method __eq__
:
class MyClass:
def __init__(self, foo, bar, name):
self.foo = foo
self.bar = bar
self.name = name
def __eq__(self,other):
if not isinstance(other,MyClass):
return NotImplemented
else:
#string lists of all method names and properties of each of these objects
prop_names1 = list(self.__dict__)
prop_names2 = list(other.__dict__)
n = len(prop_names1) #number of properties
for i in range(n):
if getattr(self,prop_names1[i]) != getattr(other,prop_names2[i]):
return False
return True
I think they using \n
anyway even couse it not visible, or maybe they using \r
. So just replace \n
or \r
with <br/>
You're almost correct, just misplaced a few quotes. Wrapping the whole thing in regular quotes will literally give you the string #demo + {this.state.id}
- you need to indicate which are variables and which are string literals. Since anything inside {}
is an inline JSX expression, you can do:
href={"#demo" + this.state.id}
This will use the string literal #demo
and concatenate it to the value of this.state.id
. This can then be applied to all strings. Consider this:
var text = "world";
And this:
{"Hello " + text + " Andrew"}
This will yield:
Hello world Andrew
You can also use ES6 string interpolation/template literals with ` (backticks) and ${expr}
(interpolated expression), which is closer to what you seem to be trying to do:
href={`#demo${this.state.id}`}
This will basically substitute the value of this.state.id
, concatenating it to #demo
. It is equivalent to doing: "#demo" + this.state.id
.
I'd just like to add a note to do two things at once - find a file that contains a string and then do a replace, using the find 'chaining' method:
find . -type f -iname \*.php -exec fgrep -l "www." {} \; -exec sed -i "s|www||g" {} \;
In this real case, remove the anachronistic 'www' from urls found in PHP files.
The 'fgrep -l' only triggers if it finds at least one match in a file, it produces no other output. Don't forget the '\;' separators!
Just linking the CSS worked for me. It may have been missing from my project entirely:
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
I figured out myself.
cmp
calls ComputeBetasAndNuHat
which returns a list which has objective
as minusloglik
So I can change the function cmp
to get this value.
In my case
[assembly: System.Resources.NeutralResourcesLanguage("ru-RU")]
in the AssemblyInfo.cs prevented things to work as usual.
You use new
to perform dynamic allocation. It returns a pointer that points to the dynamically allocated object.
You have no reason to use new
, since A
is an automatic variable. You can simply initialise A
using its constructor:
vector<vector<int> > A(dimension, vector<int>(dimension));
I had got this error, Linux system(Ubuntu) and This might happen when you run :
npm install
1) If the project is not present in your localdisk/computer, copy it to your computer and try again. So you get the permission to access folder (Just make sure you have access permission).
2) If you still get some warnings or errors, run:
npm audit fix
This will solve vulnerabilities in your dependencies and can help you fix a vulnerability by providing simple-to-run npm commands and recommendations for further troubleshooting.
Hope it helps!
Try
SELECT @@MICROSOFTVERSION / 0x01000000 AS MajorVersionNumber
For more information see: Querying for version/edition info
You cannot scroll images continuously using the HTML marquee tag - it must have JavaScript added for the continuous scrolling functionality.
There is a JavaScript plugin called crawler.js available on the dynamic drive forum for achieving this functionality. This plugin was created by John Davenport Scheuer and has been modified over time to suit new browsers.
I have also implemented this plugin into my blog to document all the steps to use this plugin. Here is the sample code:
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="assets/js/crawler.js" type="text/javascript" ></script>
</head>
<div id="mycrawler2" style="margin-top: -3px; " class="productswesupport">
<img src="assets/images/products/ie.png" />
<img src="assets/images/products/browser.png" />
<img src="assets/images/products/chrome.png" />
<img src="assets/images/products/safari.png" />
</div>
Here is the plugin configration:
marqueeInit({
uniqueid: 'mycrawler2',
style: {
},
inc: 5, //speed - pixel increment for each iteration of this marquee's movement
mouse: 'cursor driven', //mouseover behavior ('pause' 'cursor driven' or false)
moveatleast: 2,
neutral: 150,
savedirection: true,
random: true
});
public class Example extends JFrame {
public static final int WIDTH = 550;//Any Size
public static final int HEIGHT = 335;//Any Size
public Example(){
init();
}
private void init() {
try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
SwingUtilities.updateComponentTreeUI(this);
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
setSize(WIDTH, HEIGHT);
setLocation((int) (dimension.getWidth() / 2 - WIDTH / 2),
(int) (dimension.getHeight() / 2 - HEIGHT / 2));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
}
}
Here is the simplest solution to your query
$date=date_create("2013-03-15"); // or your date string
date_add($date,date_interval_create_from_date_string("40 days"));// add number of days
echo date_format($date,"Y-m-d"); //set date format of the result
JavaScript calculates right the floor of negative numbers and the remainder of non-integer numbers, following the mathematical definitions for them.
FLOOR is defined as "the largest integer number smaller than the parameter", thus:
REMAINDER is defined as the "left over" of a division (Euclidean arithmetic). When the dividend is not an integer, the quotient is usually also not an integer, i.e., there is no remainder, but if the quotient is forced to be an integer (and that's what happens when someone tries to get the remainder or modulus of a floating-point number), there will be a non-integer "left over", obviously.
JavaScript does calculate everything as expected, so the programmer must be careful to ask the proper questions (and people should be careful to answer what is asked!) Yarin's first question was NOT "what is the integer division of X by Y", but, instead, "the WHOLE number of times a given integer GOES INTO another". For positive numbers, the answer is the same for both, but not for negative numbers, because the integer division (dividend by divisor) will be -1 smaller than the times a number (divisor) "goes into" another (dividend). In other words, FLOOR will return the correct answer for an integer division of a negative number, but Yarin didn't ask that!
gammax answered correctly, that code works as asked by Yarin. On the other hand, Samuel is wrong, he didn't do the maths, I guess, or he would have seen that it does work (also, he didn't say what was the divisor of his example, but I hope it was 3):
Remainder = X % Y = -100 % 3 = -1
GoesInto = (X - Remainder) / Y = (-100 - -1) / 3 = -99 / 3 = -33
By the way, I tested the code on Firefox 27.0.1, it worked as expected, with positive and negative numbers and also with non-integer values, both for dividend and divisor. Example:
-100.34 / 3.57: GoesInto = -28, Remainder = -0.3800000000000079
Yes, I noticed, there is a precision problem there, but I didn't had time to check it (I don't know if it's a problem with Firefox, Windows 7 or with my CPU's FPU). For Yarin's question, though, which only involves integers, the gammax's code works perfectly.
you need to add it to Foo's prototype:
function Foo(){}
Foo.prototype.bar = function(){}
var x = new Foo()
x.bar()
Add to application.properties
### to enable
spring.jpa.show-sql=true
### to make the printing SQL beautify
spring.jpa.properties.hibernate.format_sql=true
This the simplest way to print the SQL queries though it doesn't log the parameters of prepared statements. And its is not recommended since its not such as optimized logging framework.
Add to application.properties
### logs the SQL queries
logging.level.org.hibernate.SQL=DEBUG
### logs the prepared statement parameters
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
### to make the printing SQL beautify
spring.jpa.properties.hibernate.format_sql=true
By specifying above properties, logs entries will be sent to the configured log appender such as log-back or log4j.
Set the keyboard and a validator
String numberValidator(String value) {
if(value == null) {
return null;
}
final n = num.tryParse(value);
if(n == null) {
return '"$value" is not a valid number';
}
return null;
}
new TextFormField(
keyboardType: TextInputType.number,
validator: numberValidator,
textAlign: TextAlign.right
...
select translate(description,'\\t','') from myTable;
Translates the input string by replacing the characters present in the from string with the corresponding characters in the to string. This is similar to the translate function in PostgreSQL. If any of the parameters to this UDF are NULL, the result is NULL as well. (Available as of Hive 0.10.0, for string types)
Char/varchar support added as of Hive 0.14.0
You can use this small library: https://github.com/ledfusion/php-rest-curl
Making a call is as simple as:
// GET
$result = RestCurl::get($URL, array('id' => 12345678));
// POST
$result = RestCurl::post($URL, array('name' => 'John'));
// PUT
$result = RestCurl::put($URL, array('$set' => array('lastName' => "Smith")));
// DELETE
$result = RestCurl::delete($URL);
And for the $result variable:
Hope it helps
Describe Formatted/Extended will show the data definition of the table in hive
hive> describe Formatted dbname.tablename;
You can add the ProgressBar
to listview footer:
private ListView listview;
private ProgressBar progressBar;
...
progressBar = (ProgressBar) LayoutInflater.from(this).inflate(R.layout.progress_bar, null);
listview.addFooterView(progressBar);
layout/progress_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<ProgressBar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/load_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true"
/>
when the data is loaded to the adapter view call:
listview.removeFooterView(progressBar);
I just tried the same and came up with following solution:
public enum Countries {
TEXAS,
FLORIDA,
OKLAHOMA,
KENTUCKY;
private static Countries[] list = Countries.values();
public static Countries getCountry(int i) {
return list[i];
}
public static int listGetLastIndex() {
return list.length - 1;
}
}
The class has it's own values saved inside an array, and I use the array to get the enum at indexposition. As mentioned above arrays begin to count from 0, if you want your index to start from '1' simply change these two methods to:
public static String getCountry(int i) {
return list[(i - 1)];
}
public static int listGetLastIndex() {
return list.length;
}
Inside my Main I get the needed countries-object with
public static void main(String[] args) {
int i = Countries.listGetLastIndex();
Countries currCountry = Countries.getCountry(i);
}
which sets currCountry to the last country, in this case Countries.KENTUCKY.
Just remember this code is very affected by ArrayOutOfBoundsExceptions if you're using hardcoded indicies to get your objects.
"If I want two columns for anything over 768px, should I apply both classes?"
This should be as simple as:
<div class="row">
<div class="col-sm-6"></div>
<div class="col-sm-6"></div>
</div>
No need to add the col-lg-6
too.
Try this:
@echo off
copy "C:\Remoting.config-Training" "C:\Remoting.config"
start C:\ThirdParty.exe
exit
Remember, Objective-C is a superset of C, so typecasting works as it does in C:
myEditController = [[SelectionListViewController alloc] init];
((SelectionListViewController *)myEditController).list = listOfItems;
Yes, just format your strings in the standard String.format()
way.
See the method Context.getString(int, Object...)
and the Android or Java Formatter
documentation.
In your case, the string definition would be:
<string name="timeFormat">%1$d minutes ago</string>
Deploy Flask on a real web server, rather than with the built-in (development) server.
See the Deployment Options chapter of the Flask documentation. Servers like Nginx and Apache both can handle setting up HTTPS servers rather than HTTP servers for your site.
The standalone WSGI servers listed would typically be deployed behind Nginx and Apache in a proxy-forwarding configuration, where the front-end server handles the SSL encryption for you still.
#include <unistd.h>
int usleep(useconds_t useconds); //pass in microseconds
If your margin is set on the body, then setting the background color of the html tag should color the margin area
html { background-color: black; }
body { margin:50px; background-color: white; }
Or as dmackerman suggestions, set a margin of 0, but a border of the size you want the margin to be and set the border-color
You need to call the
$.parseJSON();
For example:
...
success: function(data){
var json = $.parseJSON(data); // create an object with the key of the array
alert(json.html); // where html is the key of array that you want, $response['html'] = "<a>something..</a>";
},
error: function(data){
var json = $.parseJSON(data);
alert(json.error);
} ...
see this in http://api.jquery.com/jQuery.parseJSON/
if you still have the problem of slashes: search for security.magicquotes.disabling.php or: function.stripslashes.php
Note:
This answer here is for those who try to use $.ajax
with the dataType
property set to json
and even that got the wrong response type. Defining the header('Content-type: application/json');
in the server may correct the problem, but if you are returning text/html
or any other type, the $.ajax
method should convert it to json
. I make a test with older versions of jQuery and only after version 1.4.4
the $.ajax
force to convert any content-type to the dataType
passed. So if you have this problem, try to update your jQuery version.
I took the idiot route. Added these to the end of /etc/profile
for environment in `find /etc/environments.d -type f`
do
. $environment
done
created a folder /etc/environments create a file in it called "oracle" or "whatever" and added the stuff I needed set globally to it.
/etc$ cat /etc/environments.d/Oracle
export PATH=$PATH:/Library/Oracle/instantclient_11_2
export DYLD_LIBRARY_PATH=/Library/Oracle/instantclient_11_2
export SQLPATH=/Library/Oracle/instantclient_11_2
export PATH=$PATH:/Library/Oracle/instantclient_11_2
export TNS_ADMIN=/Library/Oracle/instantclient_11_2/network/admin
If a class, or anything derived from it, might hold the last live reference to an object with a finalizer, then either GC.SuppressFinalize(this)
or GC.KeepAlive(this)
should be called on the object after any operation that might be adversely affected by that finalizer, thus ensuring that the finalizer won't run until after that operation is complete.
The cost of GC.KeepAlive()
and GC.SuppressFinalize(this)
are essentially the same in any class that doesn't have a finalizer, and classes that do have finalizers should generally call GC.SuppressFinalize(this)
, so using the latter function as the last step of Dispose()
may not always be necessary, but it won't be wrong.
You'll have to benchmark, obviously, but over JDBC issuing multiple inserts will be much faster if you use a PreparedStatement rather than a Statement.
Although the previous answers all seem to say that you can just move the directory and there are no absolute paths in the .git structure. I found this to be untrue when using git from Cygwin.
When I moved my git repo (in fact I restored it from a backup, but to a different drive as my drive structure changed on my new system). I got an error message like
fatal: Invalid path '<part_of_the_original_repo_path>': No such file or directory
I used grep to find that in my .git/config file in the [core] section is a worktree variable which holds the absolute path of my git repo. Changing this fixed the problem for me.
there are several ways. You can use this method:
start = @selected_date.beginning_of_day
end = @selected_date.end_of_day
@comments = Comment.where("DATE(created_at) BETWEEN ? AND ?", start, end)
Or this:
@comments = Comment.where(:created_at => @selected_date.beginning_of_day..@selected_date.end_of_day)
if you are on Windows
sqlplus / as sysdba
Now you are logged with SYS user and you can do anything you want (query DBA_USERS to find out your username, or change any user password). You can not see the old password, you can only change it.
matrix multiplication, see the following example:
> A <- matrix (c(1,3,4, 5,8,9, 1,3,3), 3,3)
> A
[,1] [,2] [,3]
[1,] 1 5 1
[2,] 3 8 3
[3,] 4 9 3
>
> B <- matrix (c(2,4,5, 8,9,2, 3,4,5), 3,3)
>
> B
[,1] [,2] [,3]
[1,] 2 8 3
[2,] 4 9 4
[3,] 5 2 5
>
>
> A %*% B
[,1] [,2] [,3]
[1,] 27 55 28
[2,] 53 102 56
[3,] 59 119 63
> B %*% A
[,1] [,2] [,3]
[1,] 38 101 35
[2,] 47 128 43
[3,] 31 86 26
Also see:
http://en.wikipedia.org/wiki/Matrix_multiplication
If this does not follow the size of matrix rule you will get the error:
> A <- matrix(c(1,2,3,4,5,6), 3,2)
> A
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
> B <- matrix (c(3,1,3,4,4,4,4,4,3), 3,3)
> B
[,1] [,2] [,3]
[1,] 3 4 4
[2,] 1 4 4
[3,] 3 4 3
> A%*%B
Error in A %*% B : non-conformable arguments
Firstly pull the remote changes to your local using the following command:
git pull origin branchname --allow-unrelated-histories
** branchname is master in my case.
When the pull command done, conflict occurs. You should solve the conflicts. I use Android Studio to solve conflicts.
When conflicts solved, merge is done!
Now you can safely push.
You could just write it out in multiline like this,
$ cat dict.go
package main
import "fmt"
func main() {
items := map[string]interface{}{
"foo": map[string]int{
"strength": 10,
"age": 2000,
},
"bar": map[string]int{
"strength": 20,
"age": 1000,
},
}
for key, value := range items {
fmt.Println("[", key, "] has items:")
for k,v := range value.(map[string]int) {
fmt.Println("\t-->", k, ":", v)
}
}
}
And the output:
$ go run dict.go
[ foo ] has items:
--> strength : 10
--> age : 2000
[ bar ] has items:
--> strength : 20
--> age : 1000
Two ways
System.getProperty("user.dir");
or this
File currentDirFile = new File(".");
String helper = currentDirFile.getAbsolutePath();
String currentDir = helper.substring(0, helper.length() - currentDirFile.getCanonicalPath().length());//this line may need a try-catch block
The idea is to get the current folder with ".", and then fetch the absolute position to it and remove the filename from it, so from something like
/home/shark/eclipse/workspace/project/src/com/package/name/bin/Class.class
when you remove Class.class you'd get
/home/shark/eclipse/workspace/project/src/com/package/name/bin/
which is kinda what you want.
This is my JavaScript implementation of Algorithm P (Polar method for normal deviates) from Section 3.4.1 of Donald Knuth's book The Art of Computer Programming:
function normal_random(mean,stddev)
{
var V1
var V2
var S
do{
var U1 = Math.random() // return uniform distributed in [0,1[
var U2 = Math.random()
V1 = 2*U1-1
V2 = 2*U2-1
S = V1*V1+V2*V2
}while(S >= 1)
if(S===0) return 0
return mean+stddev*(V1*Math.sqrt(-2*Math.log(S)/S))
}
As +Volatility and yourself pointed out, sets are unordered. If you need the elements to be in order, just call sorted
on the set:
>>> y = [1, 1, 6, 6, 6, 6, 6, 8, 8]
>>> sorted(set(y))
[1, 6, 8]
Ideally, a hashtable is O(1)
. The problem is if two keys are not equal, however they result in the same hash.
For example, imagine the strings "it was the best of times it was the worst of times" and "Green Eggs and Ham" both resulted in a hash value of 123
.
When the first string is inserted, it's put in bucket 123. When the second string is inserted, it would see that a value already exists for bucket 123
. It would then compare the new value to the existing value, and see they are not equal. In this case, an array or linked list is created for that key. At this point, retrieving this value becomes O(n)
as the hashtable needs to iterate through each value in that bucket to find the desired one.
For this reason, when using a hash table, it's important to use a key with a really good hash function that's both fast and doesn't often result in duplicate values for different objects.
Make sense?
Adobe Illustrator uses bezier curves like SVG, and for circles it creates four points. You can create a circle with two elliptical arc commands...but then for a circle in SVG I would use a <circle />
:)
You always need an else
in an inline if:
a = 1 if b else 0
But an easier way to do it would be a = int(b)
.
You can achieve this using a cursor but the performance is much slower than whileloop.. Here's the code:
set nocount on
declare cur cursor local fast_forward for
(select filepath from Directory)
open cur;
declare @fullpath varchar(250);
declare @isExists int;
fetch from cur into @fullpath
while @@FETCH_STATUS = 0
begin
exec xp_fileexist @fullpath, @isExists out
if @isExists = 1
print @fullpath + char(9) + char(9) + 'file exists'
else
print @fullpath + char(9) + char(9) + 'file does not exists'
fetch from cur into @fullpath
end
close cur
deallocate cur
or you can put it in a tempTable if you want to integrate it in your frontend..
create proc GetFileStatus as
begin
set nocount on
create table #tempFileStatus(FilePath varchar(300),FileStatus varchar(30))
declare cur cursor local fast_forward for
(select filepath from Directory)
open cur;
declare @fullpath varchar(250);
declare @isExists int;
fetch from cur into @fullpath
while @@FETCH_STATUS = 0
begin
exec xp_fileexist @fullpath, @isExists out
if @isExists = 1
insert into #tempFileStatus values(@fullpath,'File exist')
else
insert into #tempFileStatus values(@fullpath,'File does not exists')
fetch from cur into @fullpath
end
close cur
deallocate cur
select * from #tempFileStatus
drop table #tempFileStatus
end
then call it using:
exec GetFileStatus
Google TOS have been relaxed a bit in April 2014. Now it states:
"Don’t misuse our Services. For example, don’t interfere with our Services or try to access them using a method other than the interface and the instructions that we provide."
So the passage about "automated means" and scripts is gone now. It evidently still is not the desired (by google) way of accessing their services, but I think it is now formally open to interpretation of what exactly an "interface" is and whether it makes any difference as of how exactly returned HTML is processed (rendered or parsed). Anyhow, I have written a Java convenience library and it is up to you to decide whether to use it or not:
From the doc.
The webbrowser module provides a high-level interface to allow displaying Web-based documents to users. Under most circumstances, simply calling the open() function from this module will do the right thing.
You have to import the module and use open()
function. This will open https://nabinkhadka.com.np in the browser.
To open in new tab:
import webbrowser
webbrowser.open('https://nabinkhadka.com.np', new = 2)
Also from the doc.
If new is 0, the url is opened in the same browser window if possible. If new is 1, a new browser window is opened if possible. If new is 2, a new browser page (“tab”) is opened if possible
So according to the value of new, you can either open page in same browser window or in new tab etc.
Also you can specify as which browser (chrome, firebox, etc.) to open. Use get() function for this.
Try this if you don't want to use the UDF function.
SELECT COLUMN1, TRY_CONVERT(xml, COLUMN2).value('.', 'nvarchar(max)') as COL2, COLUMN3
FROM DBO.TABLENAME
To remove the image in ImageView use:
title_image.setImageResource(-1);
it works for me
window.open is a method; you can open new window, and can customize it. window.location.href is just a property of the current window.
I am using the very popular class "org.apache.commons.lang.BooleanUtils"
This method is tested by many users and safe. Have fun. Usage:
boolean result =BooleanUtils.xor(new boolean[]{true,false});
I'm going to give you the answers from what I've just went through on Windows Server 2008 R2 which is a 64 bit operating system. The application suite of libraries I was given were developed using .net 3.5 x86 with the older DLL libraries and I was stuck because I had installed the newer x64 clients from oracle.
What I found was the following: Install the latest x64 client from Oracle for Windows Server 2008. I believe this would be the 2.7.0 client. When you select the installation, make sure you do custom and select the .NET libraries. Configure your tnsnames files and test your tnsping against your data source.
Next, if you are running a 32 bit application, install the same version of the client for 32 bit. Also, follow the same installation routine, and select the same home.
When your finished, you will find that you have a single app/product with two client directories (Client1 and Client2).
If you navigate to the windows/assemblies directory you will find that you have a reference to the Oracle.DataAccess.dll (x2) with one for x86 and one for AMD64.
Now, depending on if you have developers or are developing on the machine yourself, you may be ok here, however, if they are using older drivers, then you need to perform one last step.
Navigate to the app\name\product\version\client_1\odp.net\publisher policy\2.x directory. Included in here are two policy files. use gacutil /i to install the Policy.2.111.Oracle.DataAccess.dll into the GAC. This will redirect legacy oracle ODP calls to the newer versions. So, if someone developed with the 10g client, it will now work with the 11 client.
FYI -- Some may be installing the latest ODP.NET with the 2.111.7.20. The main oracle client itself comes with 2.111.7.0 .. I've not had any success with the 7.20 but have no issues with the 7.0 client.
Yes, simply use something like:
ul {
padding-left: 10px;
}
And it will bump each successive ul
by 10 pixels.
If you have python with a version >= 2.6 you can simply use
import multiprocessing
multiprocessing.cpu_count()
http://docs.python.org/library/multiprocessing.html#multiprocessing.cpu_count
On my machine this only works in bin/idea.vmoptions
, adding the setting in ~/Library/Preferences/IntelliJIdea12/idea.vmoptions
causes the IDEA to hang during startup.
This will work..
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
Make sure that the value of the column is really NULL and not an empty string or 0.
If you are using sakila-db from mysql website, It's very easy on the Linux platform just follow the below-mentioned steps, After downloading the zip file of sakila-db, extract it. Now you will have two files, one is sakila-schema.sql and the other one is sakila-data.sql.
Please take care that extracted files are present in home directory.
A few comments:
import sun.misc.*;
Don't do this. It is non-standard and not guaranteed to be the same between implementations. There are other libraries with Base64 conversion available.
byte[] encVal = c.doFinal(Data.getBytes());
You are relying on the default character encoding here. Always specify what character encoding you are using: byte[] encVal = c.doFinal(Data.getBytes("UTF-8"));
Defaults might be different in different places.
As @thegrinner pointed out, you need to explicitly check the length of your byte arrays. If there is a discrepancy, then compare them byte by byte to see where the difference is creeping in.
When I was trying to accomplish something very similar, I ended up doing something along these lines:
wp-content/themes/resources/functions.php
add_action('init', 'my_php_function');
function my_php_function() {
if (stripos($_SERVER['REQUEST_URI'], 'page-with-custom-php') !== false) {
// add desired php code here
}
}
First you should ensure that your command object is not null. Then you should set the CommandText property of the command to your sql query. Finally you should store the return value in an object variable and check if it is null before using it:
command = new OracleCommand(connection)
command.CommandText = sql
object userNameObj = command.ExecuteScalar()
if (userNameObj != null)
string getUserName = userNameObj.ToString()
...
I'm not sure about the VB syntax but you get the idea.
Since Java7 you can simply use FileNameExtensionFilter(String description, String... extensions)
A simple JFileChooser analog to the example would be:
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Text files", "txt"));
I know the question was answered long ago, but this is actually the simplest solution.
looks like you're better off systeming out to system("grep \"$QUERY\"")
since that script won't be particularly high performance either way. Otherwise http://php.net/manual/en/function.file.php shows you how to loop over lines and you can use http://php.net/manual/en/function.strstr.php for finding matches.
Just the same way as you would do in command console. Copy exactly those commands in the batch file.
All of the following assume that your cursor is on the first line:
Using normal mappings:
3Shift+J
Using Ex commands:
:,+2j
Which is an abbreviation of
:.,.+2 join
Which can also be entered by the following shortcut:
3:j
An even shorter Ex command:
:j3
I had a similar problem, and most of these solutions are close but no cigar. Here is what works in its simplest form:
.select2-selection {
min-height: 10px !important;
}
You can set the min-height to what ever you want. The height will expand as needed. I personally found the padding a bit unbalanced, and the font too big, so I added those here also.
You can use .change
for what you want
$("input[@name='lom']").change(function(){
// Do something interesting here
});
as of jQuery 1.3
you no longer need the '@'. Correct way to select is:
$("input[name='lom']")
Yes, You can use gcc to compile your asm code. Use -c for compilation like this:
gcc -c file.S -o file.o
This will give object code file named file.o. To invoke linker perform following after above command:
gcc file.o -o file
Just another alternative using sp_executesql (tested only in SQL 2016). As previous posts noticed, atomicity must be handled elsewhere.
CREATE FUNCTION [dbo].[fn_get_service_version_checksum2]
(
@ServiceId INT
)
RETURNS INT
AS
BEGIN
DECLARE @Checksum INT;
SELECT @Checksum = dbo.fn_get_service_version(@ServiceId);
DECLARE @LatestVersion INT = (SELECT MAX(ServiceVersion) FROM [ServiceVersion] WHERE ServiceId = @ServiceId);
-- Check whether the current version already exists and that it's the latest version.
IF EXISTS(SELECT TOP 1 1 FROM [ServiceVersion] WHERE ServiceId = @ServiceId AND [Checksum] = @Checksum AND ServiceVersion = @LatestVersion)
RETURN @LatestVersion;
-- Insert the new version to the table.
EXEC sp_executesql N'
INSERT INTO [ServiceVersion] (ServiceId, ServiceVersion, [Checksum], [Timestamp])
VALUES (@ServiceId, @LatestVersion + 1, @Checksum, GETUTCDATE());',
N'@ServiceId INT = NULL, @LatestVersion INT = NULL, @Checksum INT = NULL',
@ServiceId = @ServiceId,
@LatestVersion = @LatestVersion,
@Checksum = @Checksum
;
RETURN @LatestVersion + 1;
END;
Here is another alternative. It will of course give you a bad result if the input char is not ascii. I've not perf tested it but I think it would be pretty fast:
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetAsciiVal(string s, int index) {
return GetAsciiVal(s[index]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetAsciiVal(char c) {
return unchecked(c & 0xFF);
}
You just need to turn SSL off to send your request.
Proxy and others come with various errors.
I had the same issue and reason was penny. Wrong profile and certificate was selected in build settings. I only had did this before few days. So, you do not need to enable "automatic" inside xcode. Check profiles inside your build settings before doing it.
Make sure that types in the function declaration are declared first.
/* start of the header file */
.
.
.
struct intr_frame{...}; //must be first!
.
.
.
void kill (struct intr_frame *);
.
.
.
/* end of the header file */
I want to present performance of different approaches, on Python 3.4, Linux x64. Excerpt from line profiler:
Line # Hits Time Per Hit % Time Line Contents
==============================================================
(...)
823 1508 11334 7.5 41.6 yday = int(period_end.strftime('%j'))
824 1508 2492 1.7 9.1 yday = period_end.toordinal() - date(period_end.year, 1, 1).toordinal() + 1
825 1508 1852 1.2 6.8 yday = (period_end - date(period_end.year, 1, 1)).days + 1
826 1508 5078 3.4 18.6 yday = period_end.timetuple().tm_yday
(...)
So most efficient is
yday = (period_end - date(period_end.year, 1, 1)).days
What you are seeing is a parameterized query. They are frequently used when executing dynamic SQL from a program.
For example, instead of writing this (note: pseudocode):
ODBCCommand cmd = new ODBCCommand("SELECT thingA FROM tableA WHERE thingB = 7")
result = cmd.Execute()
You write this:
ODBCCommand cmd = new ODBCCommand("SELECT thingA FROM tableA WHERE thingB = ?")
cmd.Parameters.Add(7)
result = cmd.Execute()
This has many advantages, as is probably obvious. One of the most important: the library functions which parse your parameters are clever, and ensure that strings are escaped properly. For example, if you write this:
string s = getStudentName()
cmd.CommandText = "SELECT * FROM students WHERE (name = '" + s + "')"
cmd.Execute()
What happens when the user enters this?
Robert'); DROP TABLE students; --
(Answer is here)
Write this instead:
s = getStudentName()
cmd.CommandText = "SELECT * FROM students WHERE name = ?"
cmd.Parameters.Add(s)
cmd.Execute()
Then the library will sanitize the input, producing this:
"SELECT * FROM students where name = 'Robert''); DROP TABLE students; --'"
Not all DBMS's use ?
. MS SQL uses named parameters, which I consider a huge improvement:
cmd.Text = "SELECT thingA FROM tableA WHERE thingB = @varname"
cmd.Parameters.AddWithValue("@varname", 7)
result = cmd.Execute()
4 ways get English alphabet in Console:
public void ShowEnglishAlphabet()
{
var firstLetter = 'a';
var endLetter = 'z';
for (var letter = firstLetter; letter <= endLetter; letter++)
{
Console.WriteLine($"{letter}-{letter.ToString().ToUpper()}");
}
}
public void ShowEnglishAlphabetFromUnicodeTableDecNumber()
{
var firstLetter = 97;
var endLetter = 122;
for (var letterNumberUnicodeTable = firstLetter;
letterNumberUnicodeTable <= endLetter; letterNumberUnicodeTable++)
{
Console.WriteLine($"{(char)letterNumberUnicodeTable}-
{((char)letterNumberUnicodeTable).ToString().ToUpper()}");
}
}
public void ShowEnglishAlphabetUnicodeTableEscapeSequence()
{
var firstLetter = '\u0061';
var endLetter = '\u007A';
for (var letterNumberUnicodeTable = firstLetter;
letterNumberUnicodeTable <= endLetter; letterNumberUnicodeTable++)
{
Console.WriteLine($"{letterNumberUnicodeTable}-
{letterNumberUnicodeTable.ToString().ToUpper()}");
}
}
public void ShowEnglishAlphabetUnicodeTableLinq()
{
var alphabets = Enumerable.Range('a', 26).Select(letter =>
((char)letter).ToString()).ToList();
foreach (var letter in alphabets)
{
Console.WriteLine($"{letter}-{letter.ToUpper()}");
}
}
Source location should be the URL (relative to the css file or full web location), not a file system full path, for example:
background: url("http://localhost/media/css/static/img/sprites/buttons-v3-10.png");
background: url("static/img/sprites/buttons-v3-10.png");
Alternatively, you can try to use file:///
protocol prefix.
i don t know what solution is better, but i use this:
String[] ext = "*.ext1|*.ext2".Split('|');
List<String> files = new List<String>();
foreach (String tmp in ext)
{
files.AddRange(Directory.GetFiles(dir, tmp, SearchOption.AllDirectories));
}
#container {
background-image: url("../images/layout/bg.png");
background-repeat: no-repeat;
background-size: 100% 100%;
height: 100vh;
margin: 3px auto 0;
position: relative;
}
This is a little longer than some but this is what I use to match IPv4 addresses. Simple with no compromises.
^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$
You can't have bare words in the code, that's the reason why they created variables (your code will fail with NameError
).
The code you provided would create a database table named month
(plus whatever prefix django adds to that), because that's the name of the CharField
.
But there are better ways to create the particular choices you want. See a previous Stack Overflow question.
import calendar
tuple((m, m) for m in calendar.month_name[1:])
Generally this problem occurs when you are modifying the keys very oftenly. Based on the server it might take some time to update the new key that you have generated and pasted in the server. So after generating the key and pasting in the server, wait for 3 to 4 hours and then try. The problem should be solved. It happened with me.
You might be missing this:
services.AddScoped<IDependencyTwoThatIsDependentOnDependencyOne, DependencyTwoThatIsDependentOnDependencyOne>();
You're not supplying it with an array in your example. The following compiles fine:
public @interface SampleAnnotation {
String[] sampleValues();
}
public class Values {
public static final String val0 = "A";
public static final String val1 = "B";
@SampleAnnotation(sampleValues={ val0, val1 })
public void foo() {
}
}
Right click on folder.
Click Properties
Click Security Tab. You will see something like this:
Check/uncheck whatever access you need to grant to the account
Click Apply button and then OK.
Date.prototype.AddDays = function (days) {
days = parseInt(days, 10);
return new Date(this.valueOf() + 1000 * 60 * 60 * 24 * days);
}
Example
var dt = new Date();
console.log(dt.AddDays(-30));
console.log(dt.AddDays(-10));
console.log(dt.AddDays(-1));
console.log(dt.AddDays(0));
console.log(dt.AddDays(1));
console.log(dt.AddDays(10));
console.log(dt.AddDays(30));
Result
2017-09-03T15:01:37.213Z
2017-09-23T15:01:37.213Z
2017-10-02T15:01:37.213Z
2017-10-03T15:01:37.213Z
2017-10-04T15:01:37.213Z
2017-10-13T15:01:37.213Z
2017-11-02T15:01:37.213Z
Putting this before the command seems to work NODE_TLS_REJECT_UNAUTHORIZED=0
.
ex: NODE_TLS_REJECT_UNAUTHORIZED=0 npm ...
It would be best to figure out how to make node see self signed certificate as valid. strict-ssl suggestion above didn't work for me for some reason. If you understand the security implications and need a temporary quick fix, this is what I found in some random github issues during Google search of the error.
. first step delete db.sqlite3 file . go to terminal and run commands:
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver
. go to admin page
every thing ok now.Java has a method for this, "convertStringArrayToIntArray".
String numbers = sc.nextLine();
int[] intArray = convertStringArrayToIntArray(numbers.split(", "));
int match_position=text.indexOf(match);
This puts the functionality into a method named function, allowing for your code to encapsulate it or for the method to be made a jquery extension. Just used on my code, works perfectly
var nOffsetTop = /* whatever value, set from wherever */;
var nOffsetLeft = /* whatever value, set from wherever */;
$(input).datepicker
(
beforeShow : function(oInput, oInst)
{
AlterPostion(oInput, oInst, nOffsetTop, nOffsetLeft);
}
);
/* can be converted to extension, or whatever*/
var AlterPosition = function(oInput, oItst, nOffsetTop, nOffsetLeft)
{
var divContainer = oInst.dpDiv;
var oElem = $(this);
oInput = $(oInput);
setTimeout(function()
{
divContainer.css
({
top : (nOffsetTop >= 0 ? "+=" + nOffsetTop : "-=" + (nOffsetTop * -1)),
left : (nOffsetTop >= 0 ? "+=" + nOffsetLeft : "-=" + (nOffsetLeft * -1))
});
}, 10);
}
Exact same thing, just omit the -c
option. Apache's docs on it here.
htpasswd /etc/apache2/.htpasswd newuser
Also, htpasswd
typically isn't run as root. It's typically owned by either the web server, or the owner of the files being served. If you're using root to edit it instead of logging in as one of those users, that's acceptable (I suppose), but you'll want to be careful to make sure you don't accidentally create a file as root (and thus have root own it and no one else be able to edit it).
Add this WRITE_EXTERNAL_STORAGE permission to your applications manifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="your.company.package"
android:versionCode="1"
android:versionName="0.1">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<!-- ... -->
</application>
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
You should always check for availability first. A snippet from the official android documentation on external storage.
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
At last but not least forget about the FileOutputStream
and use a FileWriter
instead. More information on that class form the FileWriter javadoc. You'll might want to add some more error handling here to inform the user.
// get external storage file reference
FileWriter writer = new FileWriter(getExternalStorageDirectory());
// Writes the content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
You can't access a MySQL DB from Android natively. EDIT: Actually you may be able to use JDBC, but it is not recommended (or may not work?) ... see Android JDBC not working: ClassNotFoundException on driver
See
http://www.helloandroid.com/tutorials/connecting-mysql-database
Android cannot connect directly to the database server. Therefore we need to create a simple web service that will pass the requests to the database and will return the response.
http://codeoncloud.blogspot.com/2012/03/android-mysql-client.html
For most [good] users this might be fine. But imagine you get a hacker that gets a hold of your program. I've decompiled my own applications and its scary what I've seen. What if they get your username / password to your database and wreak havoc? Bad.
According to pip documentation at
http://pip.readthedocs.org/en/stable/user_guide/#configuration
You will need to specify the default install location within a pip.ini file, which, also according to the website above is usually located as follows
On Unix and Mac OS X the configuration file is: $HOME/.pip/pip.conf
On Windows, the configuration file is: %HOME%\pip\pip.ini
The %HOME% is located in C:\Users\Bob
on windows assuming your name is Bob
On linux the $HOME
directory can be located by using cd ~
You may have to create the pip.ini
file when you find your pip directory. Within your pip.ini
or pip.config
you will then need to put (assuming your on windows) something like
[global]
target=C:\Users\Bob\Desktop
Except that you would replace C:\Users\Bob\Desktop
with whatever path you desire. If you are on Linux you would replace it with something like /usr/local/your/path
After saving the command would then be
pip install pandas
However, the program you install might assume it will be installed in a certain directory and might not work as a result of being installed elsewhere.
I just had this issue and the problem was that I was inside a directory and not at the top level. Once I moved to the top level it worked.
As you mentioned android:editable is deprecated. android:inputType="none" should be used instead but it does not work due to a bug (https://code.google.com/p/android/issues/detail?id=2854)
But you can achieve the same thing by using focusable.
Via XML:
<EditText ...
android:focusable="false"
</EditText>
From code:
((EditText) findViewById(R.id.LoginNameEditText)).setFocusable(false);
Bear in mind that you may need to include a version number too as you could be using either:
font-family: 'Font Awesome 5 Pro';
or
font-family: 'Font Awesome 5 Free';
In my case this error was caused by hot reloading, while introducing new classes. In that stage of the project, use normal watchers to compile your code.
See this post of mine about "Error creating window handle" and how it relates to USER Objects and the Desktop Heap. I provide some solutions.
Sometimes, a row contain double quote column. When csv reader try read this row, not understood end of column and fire this raise. Solution is below:
reader = csv.reader(cf, quoting=csv.QUOTE_MINIMAL)
node -v
will show you the current version.npm -v
will show you the current version.brew link --overwrite --dry-run node
will force the link and overwrite all conflicting files.brew install node
do a fresh installation.brew update
brew upgrade node
brew link --overwrite node
or
brew link node
In case anyone wants to return the Name of the Model property for binding the error message in a strongly typed view.
List<ErrorResult> Errors = new List<ErrorResult>();
foreach (KeyValuePair<string, ModelState> modelStateDD in ViewData.ModelState)
{
string key = modelStateDD.Key;
ModelState modelState = modelStateDD.Value;
foreach (ModelError error in modelState.Errors)
{
ErrorResult er = new ErrorResult();
er.ErrorMessage = error.ErrorMessage;
er.Field = key;
Errors.Add(er);
}
}
This way you can actually tie the error in with the field that threw the error.
This is more a comment to previous Thomas Mueller's post rather than an answer, but haven't got enough reputation for it. Another way of getting the connection if you are Spring JDBC Template is using the following:
jdbcTemplate.getDataSource().getConnection();
So on debug mode if you add to the "Expressions" view in Eclipse it will open the browser showing you the H2 Console:
org.h2.tools.Server.startWebServer(jdbcTemplate.getDataSource().getConnection());
Old question, but still no good up-to-date answer with insight imo.
As jQuery uses Javascript wording for events and handlers, but does its own undocumented, but different interpretation of those, let me first shed light on the difference from the pure Javascript viewpoint:
enter/over
gets a corresponding leave/out
(possibly late/jumpy)mouseenter/mouseleave
mouseenter/mouseleave
cycle (i.e. no events fire)mouseenter/mouseleave
event cyclesmouseenter/mouseleave
could look like, you end up with with something like mouseover/mouseout
mouseover/mouseout
mouseout
on the previously sampled elementmouseover
on the new elementtarget/relatedTarget
indicate new and previous element$(event.target).closest(...)
suits your needsNot-so-trivial mouseover/mouseout
example:
$('.side-menu, .top-widget')
.on('mouseover mouseout', event => {
const target = event.type === 'mouseover' ? event.target : event.relatedTarget;
const thing = $(target).closest('[data-thing]').attr('data-thing') || 'default';
// do something with `thing`
});
These days, all browsers support mouseover/mouseout
and mouseenter/mouseleave
natively. Nevertheless, jQuery does not register your handler to mouseenter/mouseleave
, but silently puts them on a wrappers around mouseover/mouseout
as the code below exposes.
The emulation is unnecessary, imperfect and a waste of CPU cycles: it filters out mouseover/mouseout
events that a mouseenter/mouseleave
would not get, but the target
is messed. The real mouseenter/mouseleave
would give the handler element as target, the emulation might indicate children of that element, i.e. whatever the mouseover/mouseout
carried.
For that reason I do not use jQuery for those events, but e.g.:
$el[0].addEventListener('mouseover', e => ...);
const list = document.getElementById('log');
const outer = document.getElementById('outer');
const $outer = $(outer);
function log(tag, event) {
const li = list.insertBefore(document.createElement('li'), list.firstChild);
// only jQuery handlers have originalEvent
const e = event.originalEvent || event;
li.append(`${tag} got ${e.type} on ${e.target.id}`);
}
outer.addEventListener('mouseenter', log.bind(null, 'JSmouseenter'));
$outer.on('mouseenter', log.bind(null, '$mouseenter'));
_x000D_
div {
margin: 20px;
border: solid black 2px;
}
#inner {
min-height: 80px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div id=outer>
<ul id=log>
</ul>
</div>
</body>
_x000D_
Note: For delegate handlers never use jQuery’s “delegate handlers with selector registration”. (Reason in another answer.) Use this (or similar):
$(parent).on("mouseover", e => {
if ($(e.target).closest('.gold').length) {...};
});
instead of
$(parent).on("mouseover", '.gold', e => {...});
You can call it like that:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var person = { name: 'Joe Blow' };
function myfunction() {
document.write(person.name);
}
</script>
</head>
<body>
<script type="text/javascript">
myfunction();
</script>
</body>
</html>
The result should be page with the only content: Joe Blow
Look here: http://jsfiddle.net/HWreP/
Best regards!
When can I realistically except to observe a performance improvement after using
noexcept
? In particular, give an example of code for which a C++ compiler is able to generate better machine code after the addition of noexcept.
Um, never? Is never a time? Never.
noexcept
is for compiler performance optimizations in the same way that const
is for compiler performance optimizations. That is, almost never.
noexcept
is primarily used to allow "you" to detect at compile-time if a function can throw an exception. Remember: most compilers don't emit special code for exceptions unless it actually throws something. So noexcept
is not a matter of giving the compiler hints about how to optimize a function so much as giving you hints about how to use a function.
Templates like move_if_noexcept
will detect if the move constructor is defined with noexcept
and will return a const&
instead of a &&
of the type if it is not. It's a way of saying to move if it is very safe to do so.
In general, you should use noexcept
when you think it will actually be useful to do so. Some code will take different paths if is_nothrow_constructible
is true for that type. If you're using code that will do that, then feel free to noexcept
appropriate constructors.
In short: use it for move constructors and similar constructs, but don't feel like you have to go nuts with it.
You can do:
if not (u0 <= u <= u0+step):
u0 = u0+ step # change the condition until it is satisfied
else:
do sth. # condition is satisfied
Using a loop:
while not (u0 <= u <= u0+step):
u0 = u0+ step # change the condition until it is satisfied
do sth. # condition is satisfied
mcilist = (from mci in mcilist select mci).Distinct().ToList();
You can specify a DOM attribute that can be used to allow the directive to define a function on the parent scope. The parent scope can then call this method like any other. Here's a plunker. And below is the relevant code.
clearfn
is an attribute on the directive element into which the parent scope can pass a scope property which the directive can then set to a function that accomplish's the desired behavior.
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<style>
my-box{
display:block;
border:solid 1px #aaa;
min-width:50px;
min-height:50px;
padding:.5em;
margin:1em;
outline:0px;
box-shadow:inset 0px 0px .4em #aaa;
}
</style>
</head>
<body ng-controller="mycontroller">
<h1>Call method on directive</h1>
<button ng-click="clear()">Clear</button>
<my-box clearfn="clear" contentEditable=true></my-box>
<script>
var app = angular.module('myapp', []);
app.controller('mycontroller', function($scope){
});
app.directive('myBox', function(){
return {
restrict: 'E',
scope: {
clearFn: '=clearfn'
},
template: '',
link: function(scope, element, attrs){
element.html('Hello World!');
scope.clearFn = function(){
element.html('');
};
}
}
});
</script>
</body>
</html>
I got the same error message when I forgot to log in to the company firewall, before performing a POST request through a proxy.
you need to take 2 (hex) chars at the same time... then calculate the int value and after that make the char conversion like...
char d = (char)intValue;
do this for every 2chars in the hex string
this works if the string chars are only 0-9A-F:
#include <stdio.h>
#include <string.h>
int hex_to_int(char c){
int first = c / 16 - 3;
int second = c % 16;
int result = first*10 + second;
if(result > 9) result--;
return result;
}
int hex_to_ascii(char c, char d){
int high = hex_to_int(c) * 16;
int low = hex_to_int(d);
return high+low;
}
int main(){
const char* st = "48656C6C6F3B";
int length = strlen(st);
int i;
char buf = 0;
for(i = 0; i < length; i++){
if(i % 2 != 0){
printf("%c", hex_to_ascii(buf, st[i]));
}else{
buf = st[i];
}
}
}
You can do this:
@Override
protected Dialog onCreateDialog(int id) {
String messageDialog;
String valueOK;
String valueCancel;
String titleDialog;
switch (id) {
case id:
titleDialog = itemTitle;
messageDialog = itemDescription
valueOK = "OK";
return new AlertDialog.Builder(HomeView.this).setTitle(titleDialog).setPositiveButton(valueOK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.d(this.getClass().getName(), "AlertItem");
}
}).setMessage(messageDialog).create();
and then call to
showDialog(numbreOfItem);
Actually, there is some possibility to send a table data from one PostgreSQL database to another. I use the procedural language plperlu (unsafe Perl procedural language) for it.
Description (all was done on a Linux server):
Create plperlu language in your database A
Then PostgreSQL can join some Perl modules through series of the following commands at the end of postgresql.conf for the database A:
plperl.on_init='use DBI;'
plperl.on_init='use DBD::Pg;'
You build a function in A like this:
CREATE OR REPLACE FUNCTION send_data( VARCHAR )
RETURNS character varying AS
$BODY$
my $command = $_[0] || die 'No SQL command!';
my $connection_string =
"dbi:Pg:dbname=your_dbase;host=192.168.1.2;port=5432;";
$dbh = DBI->connect($connection_string,'user','pass',
{AutoCommit=>0,RaiseError=>1,PrintError=>1,pg_enable_utf8=>1,}
);
my $sql = $dbh-> prepare( $command );
eval { $sql-> execute() };
my $error = $dbh-> state;
$sql-> finish;
if ( $error ) { $dbh-> rollback() } else { $dbh-> commit() }
$dbh-> disconnect();
$BODY$
LANGUAGE plperlu VOLATILE;
And then you can call the function inside database A:
SELECT send_data( 'INSERT INTO jm (jm) VALUES (''zzzzzz'')' );
And the value "zzzzzz" will be added into table "jm" in database B.
Responding to an earlier comment, you can change the background by variable in the "container" example if the CSS is in your php page and not in the css style sheet.
$bgimage = '[some image url];
background-image: url('<?php echo $bgimage; ?>');
Pure javascript solution with scrollIntoView() function:
document.getElementById('title1').scrollIntoView({block: 'start', behavior: 'smooth'});
_x000D_
<h2 id="title1">Some title</h2>
_x000D_
P.S. 'smooth' parameter now works from Chrome 61 as julien_c mentioned in the comments.
You can do it using the "collapse" directive: http://jsfiddle.net/iscrow/Es4L3/ (check the two "Note" in the HTML).
<!-- Note: set the initial collapsed state and change it when clicking -->
<a ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed" class="btn btn-navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">Title</a>
<!-- Note: use "collapse" here. The original "data-" settings are not needed anymore. -->
<div collapse="navCollapsed" class="nav-collapse collapse navbar-responsive-collapse">
<ul class="nav">
That is, you need to store the collapsed state in a variable, and changing the collapsed also by (simply) changing the value of that variable.
Release 0.14 added a uib-
prefix to components:
https://github.com/angular-ui/bootstrap/wiki/Migration-guide-for-prefixes
Change: collapse
to uib-collapse
.
My understanding is very simple below.
Factory: You simply create an object inside of the factory and return it.
Service:
You just have a standard function that uses this keyword to define a function.
Provider:
There is a $get
object that you define and it can be used to get the object that returns data.
Register with the NotificationCenter in viewDidLoad
to be notified when the app returns from background
NotificationCenter.default.addObserver(self, selector: #selector(doSomething), name: UIApplication.willEnterForegroundNotification, object: nil)
Implement the method that should be called.
@objc private func doSomething() {
// Do whatever you want, for example update your view.
}
You can remove the observer once the ViewController
is destroyed. This is only required below iOS9 and macOS 10.11
deinit {
NotificationCenter.default.removeObserver(self)
}
<div className="welcomer" style={{ backgroundImage: url(${myImage}) }}></div>
.welcomer
using CSS so that you can see your image in the desired size.I've made basic black launch screens that will make the app scale properly on the iPhone 6 and iPhone 6+:
If you already have a LaunchImage in your .xcassett, open it, switch to the third tab in the right menu in Xcode and tick the iOS 8.0 iPhone images to add them to the existing set. Then drag the images over:
Gulp will do the job for watching your sass files and also adding paths of other file with includePaths. example:
gulp.task('sass', function() {
return gulp.src('scss/app.scss')
.pipe($.sass({
includePaths: sassPaths
})
.pipe(gulp.dest('css'));
});
The dot itself is not an operator, .^
is.
The .^
is a pointwise¹ (i.e. element-wise) power, as .*
is the pointwise product.
.^
Array power.A.^B
is the matrix with elementsA(i,j)
to theB(i,j)
power. The sizes ofA
andB
must be the same or be compatible.
C.f.
¹) Hence the dot.
To expand on the answer I came here to get a better understanding so I wrote this that can explain it and helped me too.
It has the setlocal DisableDelayedExpansion
in there so you can locally set this as you wish between the setlocal EnableDelayedExpansion
and it.
@echo off
title %~nx0
for /f "tokens=*" %%A in ("Some Thing") do (
setlocal EnableDelayedExpansion
set z=%%A
echo !z! Echoing the assigned variable in setlocal scope.
echo %%A Echoing the variable in local scope.
setlocal DisableDelayedExpansion
echo !z! &rem !z! Neither of these now work, which makes sense.
echo %z% &rem ECHO is off. Neither of these now work, which makes sense.
echo %%A Echoing the variable in its local scope, will always work.
)
A similar question has been asked on the Google group: http://groups.google.com/group/google-maps-js-api-v3/browse_thread/thread/e6448fc197c3c892
The zoom levels are discrete, with the scale doubling in each step. So in general you cannot fit the bounds you want exactly (unless you are very lucky with the particular map size).
Another issue is the ratio between side lengths e.g. you cannot fit the bounds exactly to a thin rectangle inside a square map.
There's no easy answer for how to fit exact bounds, because even if you are willing to change the size of the map div, you have to choose which size and corresponding zoom level you change to (roughly speaking, do you make it larger or smaller than it currently is?).
If you really need to calculate the zoom, rather than store it, this should do the trick:
The Mercator projection warps latitude, but any difference in longitude always represents the same fraction of the width of the map (the angle difference in degrees / 360). At zoom zero, the whole world map is 256x256 pixels, and zooming each level doubles both width and height. So after a little algebra we can calculate the zoom as follows, provided we know the map's width in pixels. Note that because longitude wraps around, we have to make sure the angle is positive.
var GLOBE_WIDTH = 256; // a constant in Google's map projection
var west = sw.lng();
var east = ne.lng();
var angle = east - west;
if (angle < 0) {
angle += 360;
}
var zoom = Math.round(Math.log(pixelWidth * 360 / angle / GLOBE_WIDTH) / Math.LN2);
You don't need to use regex, LIKE
is sufficient:
WHERE my_field LIKE '[a-zA-Z][a-zA-Z]%'
Assuming that by "alphabetical" you mean only latin characters, not anything classified as alphabetical in Unicode.
Note - if your collation is case sensitive, it's important to specify the range as [a-zA-Z]
. [a-z]
may exclude A
or Z
. [A-Z]
may exclude a
or z
.
Revers CountDown timer with hours minutes and seconds
public void reverseTimer(int Seconds, final TextView tv) {
new CountDownTimer(Seconds * 1000 + 1000, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000);
int hours = seconds / (60 * 60);
int tempMint = (seconds - (hours * 60 * 60));
int minutes = tempMint / 60;
seconds = tempMint - (minutes * 60);
tv.setText("TIME : " + String.format("%02d", hours)
+ ":" + String.format("%02d", minutes)
+ ":" + String.format("%02d", seconds));
}
public void onFinish() {
tv.setText("Completed");
}
}.start();
}
For me, adding <script>window.print();</script>
to the end of the page worked.
I didn't need the type="text/javascript"
attribute, or even for the page to be wrapped in a <body>
tag. However, all of my previous attempts to intuitively use the answers suggested here, of just writing window.onload=window.print
or longer versions such as window.onload=()=>window.print();
did not work, and of course calling print on the newly created window does not wait for the contents to load.
If you want to fix vbs associations type
regsvr32 vbscript.dll
regsvr32 jscript.dll
regsvr32 wshext.dll
regsvr32 wshom.ocx
regsvr32 wshcon.dll
regsvr32 scrrun.dll
Also if you can't use vbs due to management then convert your script to a vb.net program which is designed to be easy, is easy, and takes 5 minutes.
Big difference is functions and subs are both called using brackets rather than just functions.
So the compilers are installed on all computers with .NET installed.
See this article here on how to make a .NET exe. Note the sample is for a scripting host. You can't use this, you have to put your vbs code in as .NET code.
Here's a method I wrote for a "run all JUnits under a package". You should be able to adapt it to your needs.
private static void findClassesInJar(List<String> classFiles, String path) throws IOException {
final String[] parts = path.split("\\Q.jar\\\\E");
if (parts.length == 2) {
String jarFilename = parts[0] + ".jar";
String relativePath = parts[1].replace(File.separatorChar, '/');
JarFile jarFile = new JarFile(jarFilename);
final Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
final String entryName = entry.getName();
if (entryName.startsWith(relativePath)) {
classFiles.add(entryName.replace('/', File.separatorChar));
}
}
}
}
Edit: Ah, in that case, you might want this snippet as well (same use case :) )
private static File findClassesDir(Class<?> clazz) {
try {
String path = clazz.getProtectionDomain().getCodeSource().getLocation().getFile();
final String codeSourcePath = URLDecoder.decode(path, "UTF-8");
final String thisClassPath = new File(codeSourcePath, clazz.getPackage().getName().repalce('.', File.separatorChar));
} catch (UnsupportedEncodingException e) {
throw new AssertionError("impossible", e);
}
}
$('IFRAME#currentElement').get(0).contentDocument.location.reload()
I found I way to flip only the background not whole element after seeing a clue to flip in Alex's answer. Thanks alex for your answer
HTML
<div class="prev"><a href="">Previous</a></div>
<div class="next"><a href="">Next</a></div>
CSS
.next a, .prev a {
width:200px;
background:#fff
}
.next {
float:left
}
.prev {
float:right
}
.prev a:before, .next a:before {
content:"";
width:16px;
height:16px;
margin:0 5px 0 0;
background:url(http://i.stack.imgur.com/ah0iN.png) no-repeat 0 0;
display:inline-block
}
.next a:before {
margin:0 0 0 5px;
transform:scaleX(-1);
}
See example here http://jsfiddle.net/qngrf/807/
I realize this question is extremely old, but for anyone looking for a solution specific to PostgreSQL, it's:
CREATE TEMP TABLE tmp_table AS SELECT * FROM original_table LIMIT 0;
Note, the temp table will be put into a schema like pg_temp_3.
This will create a temporary table that will have all of the columns (without indexes) and without the data, however depending on your needs, you may want to then delete the primary key:
ALTER TABLE pg_temp_3.tmp_table DROP COLUMN primary_key;
If the original table doesn't have any data in it to begin with, you can leave off the "LIMIT 0".
If you have many columns and want to print all but not the three cloumns in the last, then this might help
awk '{ $NF="";$(NF-1)="";$(NF-2)="" ; print $0 }'
In your database upload file, add the followin line before any line:
SET NAMES utf8;
And your problem should be solved.
Go to installed updates and just uninstall Internet Explorer 11 Windows update. It works for me.
UPDATE totals
SET total = total + 1
WHERE name = 'bill';
If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:
UPDATE totals
SET total = total + 1
WHERE name = 'bill'
AND total = 203;
Cleaned up @Wazime solution a little. Works great as a general solution.
$(document).on('shown.bs.dropdown', '.table-responsive', function (e) {
// The .dropdown container
var $container = $(e.target);
// Find the actual .dropdown-menu
var $dropdown = $container.find('.dropdown-menu');
if ($dropdown.length) {
// Save a reference to it, so we can find it after we've attached it to the body
$container.data('dropdown-menu', $dropdown);
} else {
$dropdown = $container.data('dropdown-menu');
}
$dropdown.css('top', ($container.offset().top + $container.outerHeight()) + 'px');
$dropdown.css('left', $container.offset().left + 'px');
$dropdown.css('position', 'absolute');
$dropdown.css('display', 'block');
$dropdown.appendTo('body');
});
$(document).on('hide.bs.dropdown', '.table-responsive', function (e) {
// Hide the dropdown menu bound to this button
$(e.target).data('dropdown-menu').css('display', 'none');
});
List<T>.Add
adds a single element. Instead, use List<T>.AddRange
to add multiple values.
Additionally, List<T>.AddRange
takes an IEnumerable<T>
, so you don't need to convert tripDetails
into a List<TripDetails>
, you can pass it directly, e.g.:
tripDetailsCollection.AddRange(tripDetails);
Try
var someDate = new Date();
var duration = 2; //In Days
someDate.setTime(someDate.getTime() + (duration * 24 * 60 * 60 * 1000));
Using setDate() to add a date wont solve your problem, try adding some days to a Feb month, if you try to add new days to it, it wont result in what you expected.
I think this will do it:
SELECT * FROM MyTable WHERE mydate > now()::date - 365;
var context = new DatabaseEntities();
var t = new test //Make sure you have a table called test in DB
{
ID = Guid.NewGuid(),
name = "blah",
};
context.test.Add(t);
context.SaveChanges();
Should do it
A quick extension method:
public static void IfNotNull<T>(this T obj, Action<T> action, Action actionIfNull = null) where T : class {
if(obj != null) {
action(obj);
} else if ( actionIfNull != null ) {
actionIfNull();
}
}
example:
string str = null;
str.IfNotNull(s => Console.Write(s.Length));
str.IfNotNull(s => Console.Write(s.Length), () => Console.Write("null"));
or alternatively:
public static TR IfNotNull<T, TR>(this T obj, Func<T, TR> func, Func<TR> ifNull = null) where T : class {
return obj != null ? func(obj) : (ifNull != null ? ifNull() : default(TR));
}
example:
string str = null;
Console.Write(str.IfNotNull(s => s.Length.ToString());
Console.Write(str.IfNotNull(s => s.Length.ToString(), () => "null"));
Remove lib from Podfile, then pod install
again.
How to ignore new files
Globally
Add the path(s) to your file(s) which you would like to ignore to your .gitignore
file (and commit them). These file entries will also apply to others checking out the repository.
Locally
Add the path(s) to your file(s) which you would like to ignore to your .git/info/exclude
file. These file entries will only apply to your local working copy.
How to ignore changed files (temporarily)
In order to ignore changed files to being listed as modified, you can use the following git command:
git update-index --assume-unchanged <file>
To revert that ignorance use the following command:
git update-index --no-assume-unchanged <file>
Using array_key_exists() on objects is Deprecated in php 7.4
Instead either isset() or property_exists() should be used
reference : php.net
This work for me
rm .git/logs/refs/remotes/origin/master
Swift 4, simply use:
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return range.location < 10
}
You can use this code to insert some items into a combo box with text and value.
C#
private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
combox.Items.Insert(0, "Copenhagen");
combox.Items.Insert(1, "Tokyo");
combox.Items.Insert(2, "Japan");
combox.Items.Insert(0, "India");
}
XAML
<ComboBox x:Name="combox" SelectionChanged="ComboBox_SelectionChanged_1"/>
def update():
import time
while True:
print 'Hello World!'
time.sleep(5)
That'll run as a function. The while True:
makes it run forever. You can always take it out of the function if you need.
I am currently responsible for an Excel application with a lot of legacy code. One of the slowest pieces of this code was looping through 500 Rows in 6 Columns, setting conditional formatting formulae for each. The formulae are to identify where the cell contents are non-blank but do not form part of a Named Range, therefore referring twice to the cell itself, originally written as:
=AND(COUNTIF(<rangename>,<cellref>)=0,<cellref><>"")
Obviously the overheads would be much reduced by updating all Cells in each Column (Range) at once. However, as noted above, using ADDRESS(ROW(),COLUMN(),n) does not work in this circumstance, i.e. this does not work:
=AND(COUNTIF(<rangename>,ADDRESS(ROW(),COLUMN(),1))=0,ADDRESS(ROW(),COLUMN(),1)<>"")
I experimented extensively with a blank workbook and could find no way around this, using various alternatives such as ISBLANK. In the end, to get around this, I created two User-Defined Functions (using a tip I found elsewhere on this site):
Public Function returnCellContent() As Variant
returnCellContent = Application.Caller.Value
End Function
Public Function Cell_HasContent() As Boolean
If Application.Caller.Value = "" Then
Cell_HasContent = False
Else
Cell_HasContent = True
End If
End Function
The conditional formula is now:
=AND(COUNTIF(<rangename>,returnCellContent()=0,Cell_HasContent())
which works fine.
This has sped the code up, in Excel 2010, from 5s to 1s. Because this code is run whenever data is loaded into the application, this saving is significant and noticeable to the user. It's also a lot cleaner and reusable.
I've taken the time to post this because I could not find any answers on this site or elsewhere that cover all of the circumstances, whilst I'm sure that there are others who could benefit from the above approach, potentially with much larger numbers of cells to update.
My Experience with this issue using WPF C# coping to clipboard and System.Threading.ThreadStateException
is here with my code that worked correctly with all browsers:
Thread thread = new Thread(() => Clipboard.SetText("String to be copied to clipboard"));
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
thread.Join();
credits to this post here
But this works only on localhost, so don't try this on a server, as it's not going to work.
On server-side, I did it by using zeroclipboard
. The only way, after a lot of research.
You can make:
(Some basic code) # Use "#" after a line and use:
<#
for more lines
...
...
...
..
.
#>
This works for Windows:
CMD> start vscode://file/o:/git/libzmq/builds/msvc/vs2017/libzmq.sln
But if the filepath has spaces, normally one would add double quotes around it, like this:
CMD> start "vscode://file/o:/git/lib zmq/builds/msvc/vs2017/libzmq.sln"
But this messes up with start, which can take a double-quoted title, so it will create a window with this name as the title and not open the project.
CMD> start "title" "vscode://file/o:/git/lib zmq/builds/msvc/vs2017/libzmq.sln"
Assuming you have a test.json
file with the following content:
{"67790": {"1": {"kwh": 319.4}}}
Then, the code below will load
the json file, update the data inside using dict.update()
and dump
into the test.json
file:
import json
a_dict = {'new_key': 'new_value'}
with open('test.json') as f:
data = json.load(f)
data.update(a_dict)
with open('test.json', 'w') as f:
json.dump(data, f)
Then, in test.json
, you'll have:
{"new_key": "new_value", "67790": {"1": {"kwh": 319.4}}}
Hope this is what you wanted.
Open the installed visual studio software and click the Help menu select the About Microsoft Visual studio--> Get the visual studio Version
It's Works
.ts -> pi = 3.1415
.html -> {{ pi | number : '1.0-2' }}
Ouput -> 3.14
https://stackblitz.com/edit/angular-e8g2pt?file=src/app/app.component.html
this works for me!!! thanks!!
Get the path of running Apache
$ ps -ef | grep apache
apache 12846 14590 0 Oct20 ? 00:00:00 /usr/sbin/apache2
Append -V
argument to the path
$ /usr/sbin/apache2 -V | grep SERVER_CONFIG_FILE
-D SERVER_CONFIG_FILE="/etc/apache2/apache2.conf"
Reference:
http://commanigy.com/blog/2011/6/8/finding-apache-configuration-file-httpd-conf-location
You can use this simple method after setting up your connection:
private void getAgentInfo(string key)//"key" is your search paramter inside database
{
con.Open();
string sqlquery = "SELECT * FROM TableName WHERE firstname = @fName";
SqlCommand command = new SqlCommand(sqlquery, con);
SqlDataReader sReader;
command.Parameters.Clear();
command.Parameters.AddWithValue("@fName", key);
sReader = command.ExecuteReader();
while (sReader.Read())
{
textBoxLastName.Text = sReader["Lastname"].ToString(); //SqlDataReader
//["LastName"] the name of your column you want to retrieve from DB
textBoxAge.Text = sReader["age"].ToString();
//["age"] another column you want to retrieve
}
con.Close();
}
Now you can pass the key to this method by your textBoxFirstName like:
getAgentInfo(textBoxFirstName.Text);
Here's my take on the problem. I create AbsoluteLayout
overlay which contains Info Window (a regular view with every bit of interactivity and drawing capabilities). Then I start Handler
which synchronizes the info window's position with position of point on the map every 16 ms. Sounds crazy, but actually works.
Demo video: https://www.youtube.com/watch?v=bT9RpH4p9mU (take into account that performance is decreased because of emulator and video recording running simultaneously).
Code of the demo: https://github.com/deville/info-window-demo
An article providing details (in Russian): http://habrahabr.ru/post/213415/
Maybe we should help you with a big misunderstanding on your side first: PHP is (like ASP.NET or whatever you used to far) a server side language while javascript is client side.
This means that PHP will run on your webserver and create a HTML page dynamically which is then sent to the browser. Javascript in turn is embedded (either directly or as a referenced file) into this HTML page and runs in the browser.
Maybe you can now understand why your approach so far could never work out.
You could use string.chars().mapToObj(e -> new String(new char[] {e}));
, though this is quite lengthy and only works with java 8. Here are a few more methods:
string.split(""); (Has an extra whitespace character at the beginning of the array if used before Java 8)
string.split("|");
string.split("(?!^)");
Arrays.toString(string.toCharArray()).substring(1, string.length() * 3 + 1).split(", ");
The last one is just unnecessarily long, it's just for fun!
I copied and pasted your script into a .py file. I ran it as-is with Python 2.7.10 and received the same syntax error. I also tried the script in Python 3.5 and received the following output:
File "print_strings_on_same_line.py", line 16
print fiveYears
^
SyntaxError: Missing parentheses in call to 'print'
Then, I modified the last line where it prints the number of births as follows:
currentPop = 312032486
oneYear = 365
hours = 24
minutes = 60
seconds = 60
# seconds in a single day
secondsInDay = hours * minutes * seconds
# seconds in a year
secondsInYear = secondsInDay * oneYear
fiveYears = secondsInYear * 5
#Seconds in 5 years
print fiveYears
# fiveYears in seconds, divided by 7 seconds
births = fiveYears // 7
print "If there was a birth every 7 seconds, there would be: " + str(births) + " births"
The output was (Python 2.7.10):
157680000
If there was a birth every 7 seconds, there would be: 22525714 births
I hope this helps.
The problem got resolved when I edited the file /etc/bashrc
with same contents as in /etc/profiles
and in /etc/profiles.d/limits.sh
and did a re-login.
Until CSS's flexbox becomes more mainstream, you can always just absolutely position the sidebar, sticking it zero pixels away from the top and bottom, then set a margin on your main container to compensate.
JSFiddle
HTML
<section class="sidebar">I'm a sidebar.</section>
<section class="main">I'm the main section.</section>
CSS
section.sidebar {
width: 250px;
position: absolute;
top: 0;
bottom: 0;
background-color: green;
}
section.main { margin-left: 250px; }
Note: This is an über simple way to do this but you'll find bottom
does not mean "bottom of page," but "bottom of window." The sidebar will probably abrubtly end if your main content scrolls down.
Usage: If you're going to store information that you want to access on different web pages, you can use SessionState
If you want to store information that you want to access from the same page, then you can use Viewstate
Storage The Viewstate is stored within the page itself (in encrypted text), while the Sessionstate is stored in the server.
The SessionState will clear in the following conditions
Starting in MongoDB 3.4, you can use the $sortByCount
aggregation.
Groups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group.
https://docs.mongodb.com/manual/reference/operator/aggregation/sortByCount/
For example:
db.contest.aggregate([
{ $sortByCount: "$province" }
]);
wanna add to main answer above
I tried to follow it but my recyclerView began to stretch every item to a screen
I had to add next line after inflating for reach to goal
itemLayoutView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
I already added these params by xml but it didnot work correctly
and with this line all is ok
With JDBC, that error usually occurs because your JDBC driver implements an older version of the JDBC API than the one included in your JRE. These older versions are fine so long as you don't try and use a method that appeared in the newer API.
I'm not sure what version of JDBC setBinaryStream
appeared in. It's been around for a while, I think.
Regardless, your JDBC driver version (10.2.0.4.0) is quite old, I recommend upgrading it to the version that was released with 11g (download here), and try again.
If you want to check on just one RadioButton
you can use the isChecked
function
if(radioButton.isChecked())
{
// is checked
}
else
{
// not checked
}
and if you have a RadioGroup
you can use
if (radioGroup.getCheckedRadioButtonId() == -1)
{
// no radio buttons are checked
}
else
{
// one of the radio buttons is checked
}
Python 2.*
int
s take either 4 or 8 bytes (32 or 64 bits), depending on your Python build. sys.maxint
(2**31-1
for 32-bit ints, 2**63-1
for 64-bit ints) will tell you which of the two possibilities obtains.
In Python 3, int
s (like long
s in Python 2) can take arbitrary sizes up to the amount of available memory; sys.getsizeof
gives you a good indication for any given value, although it does also count some fixed overhead:
>>> import sys
>>> sys.getsizeof(0)
12
>>> sys.getsizeof(2**99)
28
If, as other answers suggests, you're thinking about some string representation of the integer value, then just take the len
of that representation, be it in base 10 or otherwise!
You are trying to insert data that is larger than allowed for the column logo
.
Use following data types as per your need
TINYBLOB : maximum length of 255 bytes
BLOB : maximum length of 65,535 bytes
MEDIUMBLOB : maximum length of 16,777,215 bytes
LONGBLOB : maximum length of 4,294,967,295 bytes
Use LONGBLOB
to avoid this exception.
If you are like me whose Java Control Panel does not show Security slider under Security Tab to change security level from High to Medium then follow these instructions: Java known bug: security slider not visible.
After installation, the checkbox to enable/disable Java and the security level slider do not appear in the Java Control Panel Security tab. This can occur with 7u10 and above.
This is due to a conflict that Java 7u10 and above have with standalone installations of JavaFX. Example: If Java 7u5 and JavaFX 2.1.1 are installed and if Java is updated to 7u11, the Java Control Panel does not show the checkbox or security slider.
It is recommended to uninstall all versions of Java and JavaFX before installing Java 7u10 and above.
Please follow the steps below for resolving this issue.
1. Remove all versions of Java and JavaFX through the Windows Uninstall Control Panel. Instructions on uninstalling Java.
2. Run the Microsoft uninstall utility to repair corrupted registry keys that prevents programs from being completely uninstalled or blocking new installations and updates.
3. Download and install the Windows offline installer package.
Well, first of all, you're wasting memory with the new HashMap
creation call. Your second line completely disregards the reference to this created hashmap, making it then available to the garbage collector. So, don't do that, use:
private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");
Secondly, the compiler is complaining that you cast the object to a HashMap
without checking if it is a HashMap
. But, even if you were to do:
if(getApplicationContext().getBean("someMap") instanceof HashMap) {
private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");
}
You would probably still get this warning. The problem is, getBean
returns Object
, so it is unknown what the type is. Converting it to HashMap
directly would not cause the problem with the second case (and perhaps there would not be a warning in the first case, I'm not sure how pedantic the Java compiler is with warnings for Java 5). However, you are converting it to a HashMap<String, String>
.
HashMaps are really maps that take an object as a key and have an object as a value, HashMap<Object, Object>
if you will. Thus, there is no guarantee that when you get your bean that it can be represented as a HashMap<String, String>
because you could have HashMap<Date, Calendar>
because the non-generic representation that is returned can have any objects.
If the code compiles, and you can execute String value = map.get("thisString");
without any errors, don't worry about this warning. But if the map isn't completely of string keys to string values, you will get a ClassCastException
at runtime, because the generics cannot block this from happening in this case.
Just add this after jQuery loads and before your code.
$(window).ajaxComplete(function () {console.log('Ajax Complete'); });
$(window).ajaxError(function (data, textStatus, jqXHR) {console.log('Ajax Error');
console.log('data: ' + data);
console.log('textStatus: ' + textStatus);
console.log('jqXHR: ' + jqXHR); });
$(window).ajaxSend(function () {console.log('Ajax Send'); });
$(window).ajaxStart(function () {console.log('Ajax Start'); });
$(window).ajaxStop(function () {console.log('Ajax Stop'); });
$(window).ajaxSuccess(function () {console.log('Ajax Success'); });
If anyone like me likes chainable data manipulation using the pandas dot notation (like piping), then the following may be useful:
df3 = df3.query('~index.duplicated()')
This enables chaining statements like this:
df3.assign(C=2).query('~index.duplicated()').mean()
def jsonFile = new File('File Path');
JsonSlurper jsonSlurper = new JsonSlurper();
def parseJson = jsonSlurper.parse(jsonFile)
String json = JsonOutput.toJson(parseJson)
def prettyJson = JsonOutput.prettyPrint(json)
println(prettyJson)
If you are using Spring you can use StringUtils.join()
method which also allows you to specify prefix and suffix.
String s = StringUtils.collectionToDelimitedString(fieldRoles.keySet(),
"\n", "<value>", "</value>");
I had a similar problem going through a tutorial.
# git mv README README.markdown
fatal: bad source, source=README, destination=README.markdown
I included the filetype in the source file:
# git mv README.rdoc README.markdown
and it worked perfectly. Don't forget to commit the changes with i.e.:
# git commit -a -m "Improved the README"
Sometimes it is simple little things like that, that piss us off. LOL
This helped in my case:
options: {
responsive: true,
scales: {
yAxes: [{
display: true,
ticks: {
min:0,
max:100
}
}]
}
}
Maybe you have run into this problem: net::ERR_INSECURE_RESPONSE
You need to check the encryption algorithms supported by your server. For example for apache you can configure the cipher suite this way: cipher suite.
Which version of chrome are you running and what is the server serving your APIs?
Go in your manifest and find the your activity then add this code:
android:theme="@android:style/Theme.NoTitleBar"
above line hide your Actionbar
.
If you need to other feature you can see other options with (CLR + SPC).
cond? statementA: statementB
Equals to:
if (cond)
statementA
else
statementB
For your case, you may just delete all "if". If you totally use if-else instead of ?:. Don't mix them together.
Until PHP 5.3, const
could not be used in the global scope. You could only use this from within a class. This should be used when you want to set some kind of constant option or setting that pertains to that class. Or maybe you want to create some kind of enum.
define
can be used for the same purpose, but it can only be used in the global scope. It should only be used for global settings that affect the entire application.
An example of good const
usage is to get rid of magic numbers. Take a look at PDO's constants. When you need to specify a fetch type, you would type PDO::FETCH_ASSOC
, for example. If consts were not used, you'd end up typing something like 35
(or whatever FETCH_ASSOC
is defined as). This makes no sense to the reader.
An example of good define
usage is maybe specifying your application's root path or a library's version number.
If you don't mind mutating x
,
x.update(y) or x
Simple, readable, performant. You know update()
always returns None
, which is a false value. So the above expression will always evaluate to x
, after updating it.
Most mutating methods in the standard library (like .update()
) return None
by convention, so this kind of pattern will work on those too. However, if you're using a dict subclass or some other method that doesn't follow this convention, then or
may return its left operand, which may not be what you want. Instead, you can use a tuple display and index, which works regardless of what the first element evaluates to (although it's not quite as pretty):
(x.update(y), x)[-1]
If you don't have x
in a variable yet, you can use lambda
to make a local without using an assignment statement. This amounts to using lambda
as a let expression, which is a common technique in functional languages, but maybe unpythonic.
(lambda x: x.update(y) or x)({'a': 1, 'b': 2})
Although it's not that different from the following use of the new walrus operator (Python 3.8+ only):
(x := {'a': 1, 'b': 2}).update(y) or x
If you do want a copy, PEP 584 style x | y
is the most Pythonic on 3.9+. If you must support older versions, PEP 448 style {**x, **y}
is easiest for 3.5+. But if that's not available in your (even older) Python version, the let pattern works here too.
(lambda z: z.update(y) or z)(x.copy())
(That is, of course, nearly equivalent to (z := x.copy()).update(y) or z
, but if your Python version is new enough for that, then the PEP 448 style will be available.)
str.strip
is the best approach for this situation, but more_itertools.strip
is also a general solution that strips both leading and trailing elements from an iterable:
Code
import more_itertools as mit
iterables = ["231512-n\n"," 12091231000-n00000","alphanum0000", "00alphanum"]
pred = lambda x: x in {"0", "\n", " "}
list("".join(mit.strip(i, pred)) for i in iterables)
# ['231512-n', '12091231000-n', 'alphanum', 'alphanum']
Details
Notice, here we strip both leading and trailing "0"
s among other elements that satisfy a predicate. This tool is not limited to strings.
See also docs for more examples of
more_itertools.strip
: strip both endsmore_itertools.lstrip
: strip the left endmore_itertools.rstrip
: strip the right endmore_itertools
is a third-party library installable via > pip install more_itertools
.
if(jQuery('#frmTest input[type=checkbox]:checked').length) { … }
This is now built in Laravel 5.5 https://laravel.com/docs/5.5/blade#switch-statements
So far this has been the most helpful source of information regarding this I could find. Apparently the numbers do NOT reperesent load average in %: http://forum.xda-developers.com/showthread.php?t=1495763
Is this the expected behavior?
the json_encode()
only works with UTF-8 encoded data.
maybe you can get an answer to convert it here: cyrillic-characters-in-phps-json-encode
you can get value of checkbox and status by
$('.i-checks').on('ifChanged', function(event) {
alert('checked = ' + event.target.checked);
alert('value = ' + event.target.value);
});
if you have any problem with the library you can use Microsoft.Data.Sqlite;
public static DataTable GetData(string connectionString, string query)
{
DataTable dt = new DataTable();
Microsoft.Data.Sqlite.SqliteConnection connection;
Microsoft.Data.Sqlite.SqliteCommand command;
connection = new Microsoft.Data.Sqlite.SqliteConnection("Data Source= YOU_PATH_BD.sqlite");
try
{
connection.Open();
command = new Microsoft.Data.Sqlite.SqliteCommand(query, connection);
dt.Load(command.ExecuteReader());
connection.Close();
}
catch
{
}
return dt;
}
you can add NuGet Package Microsoft.Data.Sqlite
Use an overloaded method without the out parameter to call the one with the out parameter for C# 6.0 and lower. I'm not sure why a C# 7.0 for .NET Core is even the correct answer for this thread when it was specifically asked if C# 4.0 can have an optional out parameter. The answer is NO!
Above comments are both solid responses, however note that they aren't thread safe. If you are writing to the console with multiple threads, changing colors will add a race condition that can create some strange looking output. It is simple to fix though:
public class ConsoleWriter
{
private static object _MessageLock= new object();
public void WriteMessage(string message)
{
lock (_MessageLock)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine(message);
Console.ResetColor();
}
}
}
<span style="color:#ffffff; font-size:18px; line-height:35px; font-family: Calibri;">Our Activities </span>
This works for me well:) As it has been already mentioned above "The font tag has been deprecated, at least in XHTML. It always safe to use span tag. font may not give you desire results, at least in my case it didn't.