function bookmark(title, url) {
if (window.sidebar) {
// Firefox
window.sidebar.addPanel(title, url, '');
}
else if (window.opera && window.print)
{
// Opera
var elem = document.createElement('a');
elem.setAttribute('href', url);
elem.setAttribute('title', title);
elem.setAttribute('rel', 'sidebar');
elem.click(); //this.title=document.title;
}
else if (document.all)
{
// ie
window.external.AddFavorite(url, title);
}
}
I used this & works great in IE, FF, Netscape. Chrome, Opera and safari do not support it!
The only way to add any book marks in MobileSafari (including ones on the home screen) is with the builtin UI, and that Apples does not provide anyway to do this from scripts within a page. In fact, I am pretty sure there is no mechanism for doing this on the desktop version of Safari either.
I have faced some problems with rel="sidebar". when I add it in link tag bookmarking will work on FF but stop working in other browser. so I fix that by adding rel="sidebar" dynamic by code:
jQuery('.bookmarkMeLink').click(function() {
if (window.sidebar && window.sidebar.addPanel) {
// Mozilla Firefox Bookmark
window.sidebar.addPanel(document.title,window.location.href,'');
}
else if(window.sidebar && jQuery.browser.mozilla){
//for other version of FF add rel="sidebar" to link like this:
//<a id="bookmarkme" href="#" rel="sidebar" title="bookmark this page">Bookmark This Page</a>
jQuery(this).attr('rel', 'sidebar');
}
else if(window.external && ('AddFavorite' in window.external)) {
// IE Favorite
window.external.AddFavorite(location.href,document.title);
} else if(window.opera && window.print) {
// Opera Hotlist
this.title=document.title;
return true;
} else {
// webkit - safari/chrome
alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');
}
});
Just to sum it up, 3 solutions:
Now, what I was wondering was which one is the fastest? I'm guessing on average the first one.
I'm using python 3.4, requests 2.19.1:
'urllib3' is the logger to get now (no longer 'requests.packages.urllib3'). Basic logging will still happen without setting http.client.HTTPConnection.debuglevel
I just want to expand on queen3's suggestion, applying the following does the trick:
editoptions: {
dataInit: function(element) {
$(element).attr("readonly", "readonly");
}
}
Scenario #1:
Solution:
colModel:[
{ name:'providerUserId',
index:'providerUserId',
width:100,editable:true,
editrules:{required:true},
editoptions:{
dataInit: function(element) {
jq(element).attr("readonly", "readonly");
}
}
},
],
The providerUserId is visible in the grid and visible when editing the form. But you cannot edit the contents.
Scenario #2:
Solution:
colModel:[
{name:'providerUserId',
index:'providerUserId',
width:100,editable:true,
editrules:{
required:true,
edithidden:true
},
hidden:true,
editoptions:{
dataInit: function(element) {
jq(element).attr("readonly", "readonly");
}
}
},
]
Notice in both instances I'm using jq to reference jquery, instead of the usual $. In my HTML I have the following script to modify the variable used by jQuery:
<script type="text/javascript">
var jq = jQuery.noConflict();
</script>
Yes, cd; and cd - would work. The reason It can see is that, directory is being deleted from any other terminal or any other program and recreate it. So i-node entry is modified so program can not access old i-node entry.
I had the same issue because I had 2 .git
folders in the working directory.
Your problem may be caused by the same thing, so I recommend checking to see if you have multiple .git
folders, and, if so, deleting one of them.
That allowed me to upload the project successfully.
You basically have two options, either define it as a service, or place it on your root scope. I would suggest that you make a service out of it to avoid polluting the root scope. You create a service and make it available in your controller like this:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
foo: function() {
alert("I'm foo!");
}
};
});
myApp.controller('MainCtrl', ['$scope', 'myService', function($scope, myService) {
$scope.callFoo = function() {
myService.foo();
}
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="callFoo()">Call foo</button>
</body>
</html>
If that's not an option for you, you can add it to the root scope like this:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
$rootScope.globalFoo = function() {
alert("I'm global foo!");
};
});
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="globalFoo()">Call global foo</button>
</body>
</html>
That way, all of your templates can call globalFoo()
without having to pass it to the template from the controller.
For the parent:
display: flex;
You should add some prefixes http://css-tricks.com/using-flexbox/
Edit: Only drawback is IE as usual, IE9 does not support flex. http://caniuse.com/flexbox
Edit 2: As @toddsby noted, align items is for parent, and its default value actually is stretch. If you want a different value for child, there is align-self property.
Edit 3: jsFiddle: https://jsfiddle.net/bv71tms5/2/
For Windows users:
Set-ExecutionPolicy RemoteSigned -scope CurrentUser
iex (new-object net.webclient).downloadstring('https://get.scoop.sh')
scoop install gradle
Cython
It seems that the goto answer for this is Cython. I'm really surprised no one else mentioned this yet? Here's the home page: https://cython.org
In a nutshell, this transforms your python into C and compiles it, thus making it as well protected as any "normal" compiled distributable C program.
There are limitations though. I haven't explored them in depth myself, because as I started to read about them, I dropped the idea for my own purposes. But it might still work for yours. Essentially, you can't use Python to the fullest, with the dynamic awesomeness it offers. One major issue that jumped out at me, was that keyword parameters are not usable :( You must write function calls using positional parameters only. I didn't confirm this, but I doubt you can use conditional imports, or evals. I'm not sure how polymorphism is handled...
Anyway, if you aren't trying to obfuscate a huge code base after the fact, or ideally if you have the use of Cython in mind to begin with, this is a very notable option.
Somewhat simplified (and what worked for me) way that worked for me (based on all the above)
Note that dependencies hierarchy can go deeper then one level
Get dependencies of your package
$ apt-cache depends mongodb | grep Depends:
Depends: mongodb-dev
Depends: mongodb-server
Get urls:
sudo apt-get --print-uris --yes -d --reinstall install mongodb-org mongodb-org-server mongodb-org-shell mongodb-org-tools | grep "http://" | awk '{print$1}' | xargs -I'{}' echo {} | tee files.list
wget --input-file files.list
Use these methods inside of an Activity
.
isDestroyed()
Added in Api 17
Returns true if the final onDestroy() call has been made on the Activity, so this instance is now dead.
isFinishing()
Added in Api 1
Check to see whether this activity is in the process of finishing, either because you called finish() on it or someone else has requested that it finished. This is often used in onPause() to determine whether the activity is simply pausing or completely finishing.
A common mistake with AsyncTask
is to capture a strong reference to the host Activity
(or Fragment
):
class MyActivity extends Activity {
private AsyncTask<Void, Void, Void> myTask = new AsyncTask<Void, Void, Void>() {
// Don't do this! Inner classes implicitly keep a pointer to their
// parent, which in this case is the Activity!
}
}
This is a problem because AsyncTask
can easily outlive the parent Activity
, for example if a configuration change happens while the task is running.
The right way to do this is to make your task a static
class, which does not capture the parent, and holding a weak reference to the host Activity
:
class MyActivity extends Activity {
static class MyTask extends AsyncTask<Void, Void, Void> {
// Weak references will still allow the Activity to be garbage-collected
private final WeakReference<MyActivity> weakActivity;
MyTask(MyActivity myActivity) {
this.weakActivity = new WeakReference<>(myActivity);
}
@Override
public Void doInBackground(Void... params) {
// do async stuff here
}
@Override
public void onPostExecute(Void result) {
// Re-acquire a strong reference to the activity, and verify
// that it still exists and is active.
MyActivity activity = weakActivity.get();
if (activity == null
|| activity.isFinishing()
|| activity.isDestroyed()) {
// activity is no longer valid, don't do anything!
return;
}
// The activity is still valid, do main-thread stuff here
}
}
}
Any collection that you iterate over with foreach may not be modified during iteration.
So while you're running a foreach over rankings, you cannot modify its elements, add new ones or delete any.
Call getActivity() method inside the onActivityCreated()
I have a similar case: wanting my *.jar
file to access a file in a directory next to said *.jar
file. Refer to THIS ANSWER as well.
My file structure is:
./ - the root of your program
|__ *.jar
|__ dir-next-to-jar/some.txt
I'm able to load a file (say, some.txt
) to an InputStream inside the *.jar
file with the following:
InputStream stream = null;
try{
stream = ThisClassName.class.getClass().getResourceAsStream("/dir-next-to-jar/some.txt");
}
catch(Exception e) {
System.out.print("error file to stream: ");
System.out.println(e.getMessage());
}
Then do whatever you will with the stream
How about something like this ...
var l1 = new List<int>() { 1,2,3,4,5,2,2,2,4,4,4,1 };
var g = l1.GroupBy( i => i );
foreach( var grp in g )
{
Console.WriteLine( "{0} {1}", grp.Key, grp.Count() );
}
Edit per comment: I will try and do this justice. :)
In my example, it's a Func<int, TKey>
because my list is ints. So, I'm telling GroupBy how to group my items. The Func takes a int and returns the the key for my grouping. In this case, I will get an IGrouping<int,int>
(a grouping of ints keyed by an int). If I changed it to (i => i.ToString()
) for example, I would be keying my grouping by a string. You can imagine a less trivial example than keying by "1", "2", "3" ... maybe I make a function that returns "one", "two", "three" to be my keys ...
private string SampleMethod( int i )
{
// magically return "One" if i == 1, "Two" if i == 2, etc.
}
So, that's a Func that would take an int and return a string, just like ...
i => // magically return "One" if i == 1, "Two" if i == 2, etc.
But, since the original question called for knowing the original list value and it's count, I just used an integer to key my integer grouping to make my example simpler.
date
as background dedicated processIn order to make this kind of translation a lot quicker...
In this post, you will find
bc
, rot13
, sed
...).fifo=$HOME/.fifoDate-$$
mkfifo $fifo
exec 5> >(exec stdbuf -o0 date -f - +%s >$fifo 2>&1)
echo now 1>&5
exec 6< $fifo
rm $fifo
read -t 1 -u 6 now
echo $now
This must output current UNIXTIME. From there, you could compare
time for i in {1..5000};do echo >&5 "now" ; read -t 1 -u6 ans;done
real 0m0.298s
user 0m0.132s
sys 0m0.096s
and:
time for i in {1..5000};do ans=$(date +%s -d "now");done
real 0m6.826s
user 0m0.256s
sys 0m1.364s
From more than 6 seconds to less than a half second!!(on my host).
You could check echo $ans
, replace "now"
by "2019-25-12 20:10:00"
and so on...
Optionaly, you could, once requirement of date subprocess ended:
exec 5>&- ; exec 6<&-
Instead of running 1 fork by date to convert, run date
just 1 time and do all convertion with same process (this could become a lot quicker)!:
date -f - +%s <<eof
Apr 17 2014
May 21 2012
Mar 8 00:07
Feb 11 00:09
eof
1397685600
1337551200
1520464020
1518304140
Sample:
start1=$(LANG=C ps ho lstart 1)
start2=$(LANG=C ps ho lstart $$)
dirchg=$(LANG=C date -r .)
read -p "A date: " userdate
{ read start1 ; read start2 ; read dirchg ; read userdate ;} < <(
date -f - +%s <<<"$start1"$'\n'"$start2"$'\n'"$dirchg"$'\n'"$userdate" )
Then now have a look:
declare -p start1 start2 dirchg userdate
(may answer something like:
declare -- start1="1518549549" declare -- start2="1520183716" declare -- dirchg="1520601919" declare -- userdate="1397685600"
This was done in one execution!
We just need one fifo:
mkfifo /tmp/myDateFifo
exec 7> >(exec stdbuf -o0 /bin/date -f - +%s >/tmp/myDateFifo)
exec 8</tmp/myDateFifo
rm /tmp/myDateFifo
(Note: As process is running and all descriptors are opened, we could safely remove fifo's filesystem entry.)
Then now:
LANG=C ps ho lstart 1 $$ >&7
read -u 8 start1
read -u 8 start2
LANG=C date -r . >&7
read -u 8 dirchg
read -p "Some date: " userdate
echo >&7 $userdate
read -u 8 userdate
We could buid a little function:
mydate() {
local var=$1;
shift;
echo >&7 $@
read -u 8 $var
}
mydate start1 $(LANG=C ps ho lstart 1)
echo $start1
newConnector
functionWith functions for connecting MySQL/MariaDB
, PostgreSQL
and SQLite
...
You may find them in different version on GitHub, or on my site: download or show.
wget https://raw.githubusercontent.com/F-Hauri/Connector-bash/master/shell_connector.bash
. shell_connector.bash
newConnector /bin/date '-f - +%s' @0 0
myDate "2018-1-1 12:00" test
echo $test
1514804400
Nota: On GitHub, functions and test are separated files. On my site test are run simply if this script is not sourced.
# Exit here if script is sourced
[ "$0" = "$BASH_SOURCE" ] || { true;return 0;}
Perl approach:
perl -ne 'if($i<1000) { print; } else { print STDERR;}; $i++;' in 1> in.new 2> out && mv in.new in
You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run
ALTER USER <user> quota unlimited on <tablespace name>;
or
ALTER USER <user> quota 100M on <tablespace name>;
as a DBA user (depending on how much space you need / want to grant).
If you want to interpret $replace
, you should not use single quotes since they prevent variable substitution.
Try:
echo $LINE | sed -e "s/12345678/${replace}/g"
Transcript:
pax> export replace=987654321
pax> echo X123456789X | sed "s/123456789/${replace}/"
X987654321X
pax> _
Just be careful to ensure that ${replace}
doesn't have any characters of significance to sed
(like /
for instance) since it will cause confusion unless escaped. But if, as you say, you're replacing one number with another, that shouldn't be a problem.
you can follow BaseAdapter
and create your custome Xml
file and bind it with you BaseAdpter
and populate it with Listview
see here need to change xml
file as Require.
I think that forcing a class or an instance to be a singleton is overkill. Personally, I like to define a normal instantiable class, a semi-private reference, and a simple factory function.
class NothingSpecial:
pass
_the_one_and_only = None
def TheOneAndOnly():
global _the_one_and_only
if not _the_one_and_only:
_the_one_and_only = NothingSpecial()
return _the_one_and_only
Or if there is no issue with instantiating when the module is first imported:
class NothingSpecial:
pass
THE_ONE_AND_ONLY = NothingSpecial()
That way you can write tests against fresh instances without side effects, and there is no need for sprinkling the module with global statements, and if needed you can derive variants in the future.
Look at the DefaultTableModel for a simple model that you can use:
http://java.sun.com/javase/6/docs/api/javax/swing/table/DefaultTableModel.html
This extends the AbstractTableModel, but should be sufficient for basic purposes. You can always extend AbstractTableModel and create your own. Make sure you set it on the JTable as well.
http://java.sun.com/javase/6/docs/api/javax/swing/table/AbstractTableModel.html
Look at the basic Sun tutorial for more information on using the JTable with the table model:
http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#data
What I do is use Object.keys() to return a list of all the keys and then get the length of that
Object.keys(dictionary).length
Here is some code for fixing filters. For example, if you turn on filters in your sheet, then you add a column, then you want the new column to also be covered by a filter.
Private Sub AddOrFixFilters()
ActiveSheet.UsedRange.Select
' turn off filters if on, which forces a reset in case some columns weren't covered by the filter
If ActiveSheet.AutoFilterMode Then
Selection.AutoFilter
End If
' turn filters back on, auto-calculating the new columns to filter
Selection.AutoFilter
End Sub
I was hung up on this because I was specifying my public key file in
scp -i [private key file path]
When I caught that mistake and changed it to the private key path instead, I was all set.
You could change the compiler settings to accept Java 6 syntax but generate Java 5 output (as I remember). And set the "Generated class files compatibility" a bit lower if needed by your runtime. Update: I checked Eclipse, but it complains if I set source compatibility to 1.6 and class compatibility to 1.5. If 1.6 is not allowed I usually manually comment out the offending @Override annotations in the source (which doesn't help your case).
Update2: If you do only manual build, you could write a small program which copies the original project into a new one, strips @Override annotations from the java sources and you just hit Clean project in Eclipse.
How to get the First and Last Record of DB in c#.
SELECT TOP 1 *
FROM ViewAttendenceReport
WHERE EmployeeId = 4
AND AttendenceDate >='1/18/2020 00:00:00'
AND AttendenceDate <='1/18/2020 23:59:59'
ORDER BY Intime ASC
UNION
SELECT TOP 1 *
FROM ViewAttendenceReport
WHERE EmployeeId = 4
AND AttendenceDate >='1/18/2020 00:00:00'
AND AttendenceDate <='1/18/2020 23:59:59'
ORDER BY OutTime DESC;
if you want to redirect it to some other url lets google.com then make your like as
happy to help other says rikin <a href="//google.com">happy to help other says rikin</a>
this will remove self site url form the href.
Above methods will remove your output file data whenever you run above nohup command.
To Append output in user defined file you can use >>
in nohup command.
nohup your_command >> filename.out &
This command will append all output in your file without removing old data.
I had issues getting through a form because of this error.
I used Ctrl+Click to click the submit button and navigate through the form as usual.
SyntaxError: Unexpected token o in JSON
This also happens when you forget to use the await
keyword for a method that returns JSON data.
For example:
async function returnJSONData()
{
return "{\"prop\": 2}";
}
var json_str = returnJSONData();
var json_obj = JSON.parse(json_str);
will throw an error because of the missing await
. What is actually returned is a Promise
[object], not a string
.
To fix just add await as you're supposed to:
var json_str = await returnJSONData();
This should be pretty obvious, but the error is called on JSON.parse
, so it's easy to miss if there's some distance between your await
method call and the JSON.parse
call.
From CREATE FUNCTION
:
When a parameter of the function has a default value, the keyword
DEFAULT
must be specified when the function is called to retrieve the default value. This behavior is different from using parameters with default values in stored procedures in which omitting the parameter also implies the default value.
So you need to do:
SELECT dbo.fCalculateEstimateDate(647,DEFAULT)
I don't believe the currently accepted answer is correct. For example, I have the following .htaccess
file in the root of a virtual server (apache 2.4):
<Files "reminder.php">
require all denied
require host localhost
require ip 127.0.0.1
require ip xxx.yyy.zzz.aaa
</Files>
This prevents external access to reminder.php
which is in a subdirectory.
I have a similar .htaccess
file on my Apache 2.2 server with the same effect:
<Files "reminder.php">
Order Deny,Allow
Deny from all
Allow from localhost
Allow from 127.0.0.1
Allow from xxx.yyy.zzz.aaa
</Files>
I don't know for sure but I suspect it's the attempt to define the subdirectory specifically in the .htaccess
file, viz <Files ./inscription/log.txt>
which is causing it to fail. It would be simpler to put the .htaccess
file in the same directory as log.txt
i.e. in the inscription
directory and it will work there.
You must use the right tool to do the right thing, and Python was not designed to be obfuscated. It's the contrary; everything is open or easy to reveal or modify in Python because that's the language's philosophy.
If you want something you can't see through, look for another tool. This is not a bad thing, it is important that several different tools exist for different usages.
Even compiled programs can be reverse-engineered so don't think that you can fully protect any code. You can analyze obfuscated PHP, break the flash encryption key, etc. Newer versions of Windows are cracked every time.
You cannot prevent somebody from misusing your code, but you can easily discover if someone does. Therefore, it's just a casual legal issue.
Nowadays, business models tend to go for selling services instead of products. You cannot copy a service, pirate nor steal it. Maybe it's time to consider to go with the flow...
The difference between creating an array with the implicit array and the array constructor is subtle but important.
When you create an array using
var a = [];
You're telling the interpreter to create a new runtime array. No extra processing necessary at all. Done.
If you use:
var a = new Array();
You're telling the interpreter, I want to call the constructor "Array
" and generate an object. It then looks up through your execution context to find the constructor to call, and calls it, creating your array.
You may think "Well, this doesn't matter at all. They're the same!". Unfortunately you can't guarantee that.
Take the following example:
function Array() {
this.is = 'SPARTA';
}
var a = new Array();
var b = [];
alert(a.is); // => 'SPARTA'
alert(b.is); // => undefined
a.push('Woa'); // => TypeError: a.push is not a function
b.push('Woa'); // => 1 (OK)
In the above example, the first call will alert 'SPARTA' as you'd expect. The second will not. You will end up seeing undefined. You'll also note that b contains all of the native Array object functions such as push
, where the other does not.
While you may expect this to happen, it just illustrates the fact that []
is not the same as new Array()
.
It's probably best to just use []
if you know you just want an array. I also do not suggest going around and redefining Array...
You can use the CSS3 Linear Gradient property along with your background-image like this:
#landing-wrapper {
display:table;
width:100%;
background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
background-position:center top;
height:350px;
}
Here's a demo:
#landing-wrapper {_x000D_
display: table;_x000D_
width: 100%;_x000D_
background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
background-position: center top;_x000D_
height: 350px;_x000D_
color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
In case you have still the error after providing component dialog class in entryComponents
, try to restart ng serve
- it worked for me.
:%s/\r\+//g
In Vim, that strips all carriage returns, and leaves only newlines.
For changing the text color in navbar you can use inline css as;
<a style="color: #3c6afc" href="#">
On Mac, the python standard library has a module called EasyDialogs
. There is also a (ctypes based) windows version at http://www.averdevelopment.com/python/EasyDialogs.html
If it matters to you: it uses native dialogs and doesn't depend on Tkinter like the already mentioned easygui
, but it might not have as much features.
Default initial capacity of the HashMap
takes is 16 and load factor is 0.75f (i.e 75% of current map size). The load factor represents at what level the HashMap
capacity should be doubled.
For example product of capacity and load factor as 16 * 0.75 = 12
. This represents that after storing the 12th key – value pair into the HashMap
, its capacity becomes 32.
For Mac users
I found out one more way: You can check if /usr/local/var/run/nginx.pid
exists. If it is - nginx is running. Useful way for scripting.
Example:
if [ -f /usr/local/var/run/nginx.pid ]; then
echo "Nginx is running"
fi
<%
String redirectURL = "http://whatever.com/myJSPFile.jsp";
response.sendRedirect(redirectURL);
%>
To reset all the input fields in a modal use the following.
$(".modal-body input").val("")
Convert to array of chars ? Sort ? Convert back to String:
String s = "edcba";
char[] c = s.toCharArray(); // convert to array of chars
java.util.Arrays.sort(c); // sort
String newString = new String(c); // convert back to String
System.out.println(newString); // "abcde"
With redis-cli
:
FLUSHDB - Removes data from your connection's CURRENT database.
FLUSHALL - Removes data from ALL databases.
You may also have a look on Runtyper - a tool that performs type checking of operands in ===
(and other operations).
For your example, if you have strict comparison x === y
and x = 123, y = "123"
, it will automatically check typeof x, typeof y
and show warning in console:
Strict compare of different types: 123 (number) === "123" (string)
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.
int arr[10] = {0, 5, 3, 64};
arr[4] = 5;
EDIT: So I was asked to explain what's happening when you do:
int arr[10] = {0, 5, 3, 64};
you create an array with 10 elements and you allocate values for the first 4 elements of the array.
Also keep in mind that arr
starts at index arr[0]
and ends at index arr[9]
- 10 elements
arr[0] has value 0;
arr[1] has value 5;
arr[2] has value 3;
arr[3] has value 64;
after that the array contains garbage values / zeroes because you didn't allocated any other values
But you could still allocate 6 more values so when you do
arr[4] = 5;
you allocate the value 5 to the fifth element of the array.
You could do this until you allocate values for the last index of the arr
that is arr[9]
;
Sorry if my explanation is choppy, but I have never been good at explaining things.
I know this question is older but I was looking thru the answers and thought that I might be able to expand on the "dynamic" portion of the problem and possibly help someone out.
First and foremost I built this solution to solve a problem a couple of coworkers were having with inconstant and large data sets needing to be pivoted quickly.
This solution requires the creation of a stored procedure so if that is out of the question for your needs please stop reading now.
This procedure is going to take in the key variables of a pivot statement to dynamically create pivot statements for varying tables, column names and aggregates. The Static column is used as the group by / identity column for the pivot(this can be stripped out of the code if not necessary but is pretty common in pivot statements and was necessary to solve the original issue), the pivot column is where the end resultant column names will be generated from, and the value column is what the aggregate will be applied to. The Table parameter is the name of the table including the schema (schema.tablename) this portion of the code could use some love because it is not as clean as I would like it to be. It worked for me because my usage was not publicly facing and sql injection was not a concern. The Aggregate parameter will accept any standard sql aggregate 'AVG', 'SUM', 'MAX' etc. The code also defaults to MAX as an aggregate this is not necessary but the audience this was originally built for did not understand pivots and were typically using max as an aggregate.
Lets start with the code to create the stored procedure. This code should work in all versions of SSMS 2005 and above but I have not tested it in 2005 or 2016 but I can not see why it would not work.
create PROCEDURE [dbo].[USP_DYNAMIC_PIVOT]
(
@STATIC_COLUMN VARCHAR(255),
@PIVOT_COLUMN VARCHAR(255),
@VALUE_COLUMN VARCHAR(255),
@TABLE VARCHAR(255),
@AGGREGATE VARCHAR(20) = null
)
AS
BEGIN
SET NOCOUNT ON;
declare @AVAIABLE_TO_PIVOT NVARCHAR(MAX),
@SQLSTRING NVARCHAR(MAX),
@PIVOT_SQL_STRING NVARCHAR(MAX),
@TEMPVARCOLUMNS NVARCHAR(MAX),
@TABLESQL NVARCHAR(MAX)
if isnull(@AGGREGATE,'') = ''
begin
SET @AGGREGATE = 'MAX'
end
SET @PIVOT_SQL_STRING = 'SELECT top 1 STUFF((SELECT distinct '', '' + CAST(''[''+CONVERT(VARCHAR,'+ @PIVOT_COLUMN+')+'']'' AS VARCHAR(50)) [text()]
FROM '+@TABLE+'
WHERE ISNULL('+@PIVOT_COLUMN+','''') <> ''''
FOR XML PATH(''''), TYPE)
.value(''.'',''NVARCHAR(MAX)''),1,2,'' '') as PIVOT_VALUES
from '+@TABLE+' ma
ORDER BY ' + @PIVOT_COLUMN + ''
declare @TAB AS TABLE(COL NVARCHAR(MAX) )
INSERT INTO @TAB EXEC SP_EXECUTESQL @PIVOT_SQL_STRING, @AVAIABLE_TO_PIVOT
SET @AVAIABLE_TO_PIVOT = (SELECT * FROM @TAB)
SET @TEMPVARCOLUMNS = (SELECT replace(@AVAIABLE_TO_PIVOT,',',' nvarchar(255) null,') + ' nvarchar(255) null')
SET @SQLSTRING = 'DECLARE @RETURN_TABLE TABLE ('+@STATIC_COLUMN+' NVARCHAR(255) NULL,'+@TEMPVARCOLUMNS+')
INSERT INTO @RETURN_TABLE('+@STATIC_COLUMN+','+@AVAIABLE_TO_PIVOT+')
select * from (
SELECT ' + @STATIC_COLUMN + ' , ' + @PIVOT_COLUMN + ', ' + @VALUE_COLUMN + ' FROM '+@TABLE+' ) a
PIVOT
(
'+@AGGREGATE+'('+@VALUE_COLUMN+')
FOR '+@PIVOT_COLUMN+' IN ('+@AVAIABLE_TO_PIVOT+')
) piv
SELECT * FROM @RETURN_TABLE'
EXEC SP_EXECUTESQL @SQLSTRING
END
Next we will get our data ready for the example. I have taken the data example from the accepted answer with the addition of a couple of data elements to use in this proof of concept to show the varied outputs of the aggregate change.
create table temp
(
date datetime,
category varchar(3),
amount money
)
insert into temp values ('1/1/2012', 'ABC', 1000.00)
insert into temp values ('1/1/2012', 'ABC', 2000.00) -- added
insert into temp values ('2/1/2012', 'DEF', 500.00)
insert into temp values ('2/1/2012', 'DEF', 1500.00) -- added
insert into temp values ('2/1/2012', 'GHI', 800.00)
insert into temp values ('2/10/2012', 'DEF', 700.00)
insert into temp values ('2/10/2012', 'DEF', 800.00) -- addded
insert into temp values ('3/1/2012', 'ABC', 1100.00)
The following examples show the varied execution statements showing the varied aggregates as a simple example. I did not opt to change the static, pivot, and value columns to keep the example simple. You should be able to just copy and paste the code to start messing with it yourself
exec [dbo].[USP_DYNAMIC_PIVOT] 'date','category','amount','dbo.temp','sum'
exec [dbo].[USP_DYNAMIC_PIVOT] 'date','category','amount','dbo.temp','max'
exec [dbo].[USP_DYNAMIC_PIVOT] 'date','category','amount','dbo.temp','avg'
exec [dbo].[USP_DYNAMIC_PIVOT] 'date','category','amount','dbo.temp','min'
This execution returns the following data sets respectively.
If SET time_zone or SET GLOBAL time_zone does not work, you can change as below:
Change timezone system, example: ubuntu... $ sudo dpkg-reconfigure tzdata
Restart the server or you can restart apache2 and mysql (/etc/init.d/mysql restart)
Here's a one-liner slim way for layering text on top of an input in jQuery using ES6 syntax.
$('.input-group > input').focus(e => $(e.currentTarget).parent().find('.placeholder').hide()).blur(e => { if (!$(e.currentTarget).val()) $(e.currentTarget).parent().find('.placeholder').show(); });
_x000D_
* {
font-family: sans-serif;
}
.input-group {
position: relative;
}
.input-group > input {
width: 150px;
padding: 10px 0px 10px 25px;
}
.input-group > .placeholder {
position: absolute;
top: 50%;
left: 25px;
transform: translateY(-50%);
color: #929292;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group">
<span class="placeholder">Username</span>
<input>
</div>
_x000D_
function checkCase(c){
var u = c.toUpperCase();
return (c.toLowerCase() === u ? -1 : (c === u ? 1 : 0));
};
Based on Sonic Beard comment to the main answer. I changed the logic in the result:
0: Lowercase
1: Uppercase
-1: neither
In my case CFLAGS = -O0 -g -Wall -I. -mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=soft
has helped. As you can see, i used it for my stm32f407.
Using Firebase's Query API, you might be tempted to try this:
// !!! THIS WILL NOT WORK !!!
ref
.orderBy('genre')
.startAt('comedy').endAt('comedy')
.orderBy('lead') // !!! THIS LINE WILL RAISE AN ERROR !!!
.startAt('Jack Nicholson').endAt('Jack Nicholson')
.on('value', function(snapshot) {
console.log(snapshot.val());
});
But as @RobDiMarco from Firebase says in the comments:
multiple
orderBy()
calls will throw an error
So my code above will not work.
I know of three approaches that will work.
What you can do is execute one orderBy().startAt()./endAt()
on the server, pull down the remaining data and filter that in JavaScript code on your client.
ref
.orderBy('genre')
.equalTo('comedy')
.on('child_added', function(snapshot) {
var movie = snapshot.val();
if (movie.lead == 'Jack Nicholson') {
console.log(movie);
}
});
If that isn't good enough, you should consider modifying/expanding your data to allow your use-case. For example: you could stuff genre+lead into a single property that you just use for this filter.
"movie1": {
"genre": "comedy",
"name": "As good as it gets",
"lead": "Jack Nicholson",
"genre_lead": "comedy_Jack Nicholson"
}, //...
You're essentially building your own multi-column index that way and can query it with:
ref
.orderBy('genre_lead')
.equalTo('comedy_Jack Nicholson')
.on('child_added', function(snapshot) {
var movie = snapshot.val();
console.log(movie);
});
David East has written a library called QueryBase that helps with generating such properties.
You could even do relative/range queries, let's say that you want to allow querying movies by category and year. You'd use this data structure:
"movie1": {
"genre": "comedy",
"name": "As good as it gets",
"lead": "Jack Nicholson",
"genre_year": "comedy_1997"
}, //...
And then query for comedies of the 90s with:
ref
.orderBy('genre_year')
.startAt('comedy_1990')
.endAt('comedy_2000')
.on('child_added', function(snapshot) {
var movie = snapshot.val();
console.log(movie);
});
If you need to filter on more than just the year, make sure to add the other date parts in descending order, e.g. "comedy_1997-12-25"
. This way the lexicographical ordering that Firebase does on string values will be the same as the chronological ordering.
This combining of values in a property can work with more than two values, but you can only do a range filter on the last value in the composite property.
A very special variant of this is implemented by the GeoFire library for Firebase. This library combines the latitude and longitude of a location into a so-called Geohash, which can then be used to do realtime range queries on Firebase.
Yet another alternative is to do what we've all done before this new Query API was added: create an index in a different node:
"movies"
// the same structure you have today
"by_genre"
"comedy"
"by_lead"
"Jack Nicholson"
"movie1"
"Jim Carrey"
"movie3"
"Horror"
"by_lead"
"Jack Nicholson"
"movie2"
There are probably more approaches. For example, this answer highlights an alternative tree-shaped custom index: https://stackoverflow.com/a/34105063
If none of these options work for you, but you still want to store your data in Firebase, you can also consider using its Cloud Firestore database.
Cloud Firestore can handle multiple equality filters in a single query, but only one range filter. Under the hood it essentially uses the same query model, but it's like it auto-generates the composite properties for you. See Firestore's documentation on compound queries.
In Bootstrap 3 'dropdown.js' provides us with the various events that are triggered.
click.bs.dropdown
show.bs.dropdown
shown.bs.dropdown
etc
Other solution: Set initial after creating the form:
form.fields['tank'].initial = 123
This should work for you. Infact the one which you are thinking will also work:-
.......
DECLARE @returnvalue INT
EXEC @returnvalue = SP_One
.....
You must use the Invoke-Command cmdlet to launch this external program. Normally it works without an effort.
If you need more than one command you should use the Invoke-Expression cmdlet with the -scriptblock
option.
Example for CoffeeScript
:
test = (str, callback) ->
data = "Input values"
$.ajax
type: "post"
url: "http://www.mydomain.com/ajaxscript"
data: data
success: callback
test (data, textStatus, xhr) ->
alert data + "\t" + textStatus
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<form method="post" id="form_content" action="Javascript:void(0);">
<button id="desc" name="desc" value="desc" style="display:none;">desc</button>
<button id="asc" name="asc" value="asc">asc</button>
<input type='hidden' id='check' value=''/>
</form>
<div id="demoajax"></div>
<script>
numbers = '';
$('#form_content button').click(function(){
$('#form_content button').toggle();
numbers = this.id;
function_two(numbers);
});
function function_two(numbers){
if (numbers === '')
{
$('#check').val("asc");
}
else
{
$('#check').val(numbers);
}
//alert(sort_var);
$.ajax({
url: 'test.php',
type: 'POST',
data: $('#form_content').serialize(),
success: function(data){
$('#demoajax').show();
$('#demoajax').html(data);
}
});
return false;
}
$(document).ready(function_two());
</script>
After many false starts and dead ends, I'm finally able to deploy website code with just "git push remote" thanks to this article.
The author's post-update script is only one line long and his solution doesn't require .htaccess configuration to hide the Git repo as some others do.
A couple of stumbling blocks if you're deploying this on an Amazon EC2 instance;
1) If you use sudo to create the bare destination repository, you have to change the owner of the repo to ec2-user or the push will fail. (Try "chown ec2-user:ec2-user repo.")
2) The push will fail if you don't pre-configure the location of your amazon-private-key.pem, either in /etc/ssh/ssh_config as an IdentityFile parameter or in ~/.ssh/config using the "[Host] - HostName - IdentityFile - User" layout described here...
...HOWEVER if Host is configured in ~/.ssh/config and different than HostName the Git push will fail. (That's probably a Git bug)
I'd fought with this a long time $('#myelement').val(x)
just wasn't working ... until I realized the #
construction requires an ID, not a NAME. So if ".val(x)
doesn't work!" is your problem, check your element and be sure it has an ID!
It's an embarrassing gotcha, but I felt I had to share to save others much hair-tearing.
<Button fx:id="closeButton" onAction="#closeButtonAction">
In your controller class:
@FXML private javafx.scene.control.Button closeButton;
@FXML
private void closeButtonAction(){
// get a handle to the stage
Stage stage = (Stage) closeButton.getScene().getWindow();
// do what you have to do
stage.close();
}
First of all store $date=$_POST['your date field name'];
insert into **Your_Table Name** values('$date',**other fields**);
You must contain date in single cote (' ')
I hope it is helps.
The minus sign (-) can convert positive numbers to negative numbers and negative numbers to positive numbers. x=-y
is visual sugar for x=(y*-1)
.
var y = -100;
var x =- y;
No JS needed really ...
Just add a type
attribute to the button with a value of button
<Button type="button" color="primary" onClick={this.onTestClick}>primary</Button>
By default, button elements are of the type "submit" which causes them to submit their enclosing form element (if any). Changing the type
to "button" prevents that.
A few steps I follow, if Eclipse is working slow:
Open current working project and close the remaining project. If there is any any dependency among them, just open while running. If all are Maven projects, then with miner local change in pom files, you can make them individual projects also. If you are working on independent projects, then always work on any one project in a workspace. Don't keep multiple projects in single workspace.
Change the type filters. It facilitates to specify particular packages to refer always.
As per my experience, don't change memory JVM parameters. It causes a lot of unknown issues except when you have sound knowledge of JVM parameters.
Un-check auto build always. Particulary, Maven project's auto build is useless.
Close all the files opened, just open current working files.
Use Go Into Work sets. Instead of complete workbench.
Most of the components of your application you can implement and test in standalone also. Learn how to run in standalone without need of server deploy, this makes your work simple and fast. -- Recently, I worked on hibernate entities for my project, two days, I did on server. i.e. I changed in entities and again build and deployed on the server, it killing it all my time. So, then I created a simple JPA standalone application, and I completed my work very fast.
Note that each of the code samples below may throw IOException
. Try/catch/finally blocks have been omitted for brevity. See this tutorial for information about exception handling.
Note that each of the code samples below will overwrite the file if it already exists
Creating a text file:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
Creating a binary file:
byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();
Java 7+ users can use the Files
class to write to files:
Creating a text file:
List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, StandardCharsets.UTF_8);
//Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
Creating a binary file:
byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);
This image presents both orientation(Landscape/Portrait)
To get MaxX and MaxY, read on.
For Android device screen coordinates, below concept will work.
Display mdisp = getWindowManager().getDefaultDisplay();
Point mdispSize = new Point();
mdisp.getSize(mdispSize);
int maxX = mdispSize.x;
int maxY = mdispSize.y;
EDIT:- ** **for devices supporting android api level older than 13. Can use below code.
Display mdisp = getWindowManager().getDefaultDisplay();
int maxX= mdisp.getWidth();
int maxY= mdisp.getHeight();
(x,y) :-
1) (0,0) is top left corner.
2) (maxX,0) is top right corner
3) (0,maxY) is bottom left corner
4) (maxX,maxY) is bottom right corner
here maxX and maxY are screen maximum height and width in pixels, which we have retrieved in above given code.
I came across this issue recently, and i'm using Typescript. If you're using Typescript like I am, then you need to import assets like so:
<img src="@/assets/images/logo.png" alt="">
This is essentially the same thing. Use whatever you find more convenient.
You can use ImportRow
method to copy Row from DataTable to DataTable with the same schema:
var row = SourceTable.Rows[RowNum];
DestinationTable.ImportRow(row);
Update:
With your new Edit, I believe:
var desRow = dataTable.NewRow();
var sourceRow = dataTable.Rows[rowNum];
desRow.ItemArray = sourceRow.ItemArray.Clone() as object[];
will work
ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
Try it like this
public OnClickListener moreListener = new OnClickListener() {
@Override
public void onClick(View v) {
adapter = null;
myStringArray1.add("Andrea");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
};
this solved it to me:
sudo apt-get update
sudo apt-get install libglfw3
sudo apt-get install libglfw3-dev
taken from https://github.com/glfw/glfw/issues/808
You're probably returning an object that's on the stack. That is, return_Object()
probably looks like this:
Object& return_Object()
{
Object object_to_return;
// ... do stuff ...
return object_to_return;
}
If this is what you're doing, you're out of luck - object_to_return
has gone out of scope and been destructed at the end of return_Object
, so myObject
refers to a non-existent object. You either need to return by value, or return an Object
declared in a wider scope or new
ed onto the heap.
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None
All byte code is 8-bit based. (That's why its called BYTE code) All the instructions are a multiple of 8-bits in size. We develop on 32-bit machines and run our servers with 64-bit JVM.
Could you give some detail of the problem you are facing? Then we might have a chance of helping you. Otherwise we would just be guessing what the problem is you are having.
To add to the answers above: if you want to stop Dyno using admin panel, the current solution on free tier:
Hope this helps.
There is a better way to do this:
If the array $arr_options contains the existing array.
$arr_new_input['name'] = [
'type' => 'text',
'label' => 'First name',
'show' => true,
'required' => true
];
$arr_options += $arr_new_input;
Warning: $arr_options must exist. if $arr_options already has a ['name'] it wil be overwritten.
Hope this helps.
Here's a way to create a flexible generator that allows you to add some rules:
function generatePassword(length, rules) {
if (!length || length == undefined) {
length = 8;
}
if (!rules || rules == undefined) {
rules = [
{chars: "abcdefghijklmnopqrstuvwxyz", min: 3}, // As least 3 lowercase letters
{chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", min: 2}, // At least 2 uppercase letters
{chars: "0123456789", min: 2}, // At least 2 digits
{chars: "!@#$&*?|%+-_./:;=()[]{}", min: 1} // At least 1 special char
];
}
var allChars = "", allMin = 0;
rules.forEach(function(rule) {
allChars += rule.chars;
allMin += rule.min;
});
if (length < allMin) {
length = allMin;
}
rules.push({chars: allChars, min: length - allMin});
var pswd = "";
rules.forEach(function(rule) {
if (rule.min > 0) {
pswd += shuffleString(rule.chars, rule.min);
}
});
return shuffleString(pswd);
}
function shuffleString(str, maxlength) {
var shuffledString = str.split('').sort(function(){return 0.5-Math.random()}).join('');
if (maxlength > 0) {
shuffledString = shuffledString.substr(0, maxlength);
}
return shuffledString;
}
var pswd = generatePassword(15, [
{chars: "abcdefghijklmnopqrstuvwxyz", min: 4}, // As least 4 lowercase letters
{chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", min: 1}, // At least 1 uppercase letters
{chars: "0123456789", min: 3}, // At least 3 digits
{chars: "!@#$&*?|%+-_./:;=()[]{}", min: 2} // At least 2 special chars
]);
console.log(pswd, pswd.length);
also you can open more than two page try this
`<a href="http://www.microsoft.com" target="_blank" onclick="window.open('http://www.google.com'); window.open('http://www.yahoo.com');">Click Here</a>`
Adding this answer for people like me for whom a TRUE/FALSE answer is perfectly acceptable
OR(IF(ISNUMBER(SEARCH($G$1:$G$7,A1)),TRUE,FALSE))
or case-sensitive
OR(IF(ISNUMBER(FIND($G$1:$G$7,A1)),TRUE,FALSE))
Where the range for the search terms is G1:G7
Remember to press CTRL+SHIFT+ENTER
Bootstrap comes with many pre-build classes and one of them is class="text-left"
. Please call this class whenever needed. :-)
A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:
So we need three divs:
First let us define the CSS:
#hider
{
position:absolute;
top: 0%;
left: 0%;
width:1600px;
height:2000px;
margin-top: -800px; /*set to a negative number 1/2 of your height*/
margin-left: -500px; /*set to a negative number 1/2 of your width*/
/*
z- index must be lower than pop up box
*/
z-index: 99;
background-color:Black;
//for transparency
opacity:0.6;
}
#popup_box
{
position:absolute;
top: 50%;
left: 50%;
width:10em;
height:10em;
margin-top: -5em; /*set to a negative number 1/2 of your height*/
margin-left: -5em; /*set to a negative number 1/2 of your width*/
border: 1px solid #ccc;
border: 2px solid black;
z-index:100;
}
It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
Here comes the java Script:
$(document).ready(function () {
//hide hider and popup_box
$("#hider").hide();
$("#popup_box").hide();
//on click show the hider div and the message
$("#showpopup").click(function () {
$("#hider").fadeIn("slow");
$('#popup_box').fadeIn("slow");
});
//on click hide the message and the
$("#buttonClose").click(function () {
$("#hider").fadeOut("slow");
$('#popup_box').fadeOut("slow");
});
});
And finally the HTML:
<div id="hider"></div>
<div id="popup_box">
Message<br />
<a id="buttonClose">Close</a>
</div>
<div id="content">
Page's main content.<br />
<a id="showpopup">ClickMe</a>
</div>
I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.
I was facing this issue even after supplying all required datasource properties in application.properties. Then I realized that properties configuration class was not getting scanned by Spring boot because it was in different package hierarchy compared to my Spring boot Application.java and hence no properties were applied to datasource object. I changed the package name of my properties configuration class and it started working.
Something like this: call_from_terminal.py
# call_from_terminal.py
# Ex to run from terminal
# ip='"hi"'
# python -c "import call_from_terminal as cft; cft.test_term_fun(${ip})"
# or
# fun_name='call_from_terminal'
# python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
def test_term_fun(ip):
print ip
This works in bash.
$ ip='"hi"' ; fun_name='call_from_terminal'
$ python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
hi
It is important to recognize that the copyright laws have changed and that for non-US sources, especially after the USA joining the Berne Convention on March 1, 1989, copyright registration in not necessary for enforcement of a copyright notice.
Here is a resumé quoted from the Cornell University Law School (copied on March 4, 2015 from https://www.law.cornell.edu/wex/copyright:
"Copyright
copyright: an overview
The U.S. Copyright Act, 17 U.S.C. §§ 101 - 810, is Federal legislation enacted by Congress under its Constitutional grant of authority to protect the writings of authors. See U.S. Constitution, Article I, Section 8. Changing technology has led to an ever expanding understanding of the word "writings." The Copyright Act now reaches architectural design, software, the graphic arts, motion pictures, and sound recordings. See § 106. As of January 1, 1978, all works of authorship fixed in a tangible medium of expression and within the subject matter of copyright were deemed to fall within the exclusive jurisdiction of the Copyright Act regardless of whether the work was created before or after that date and whether published or unpublished. See § 301. See also preemption.
The owner of a copyright has the exclusive right to reproduce, distribute, perform, display, license, and to prepare derivative works based on the copyrighted work. See § 106. The exclusive rights of the copyright owner are subject to limitation by the doctrine of "fair use." See § 107. Fair use of a copyrighted work for purposes such as criticism, comment, news reporting, teaching, scholarship, or research is not copyright infringement. To determine whether or not a particular use qualifies as fair use, courts apply a multi-factor balancing test. See § 107.
Copyright protection subsists in original works of authorship fixed in any tangible medium of expression from which they can be perceived, reproduced, or otherwise communicated, either directly or with the aid of a machine or device. See § 102. Copyright protection does not extend to any idea, procedure, process, system, method of operation, concept, principle, or discovery. For example, if a book is written describing a new system of bookkeeping, copyright protection only extends to the author's description of the bookkeeping system; it does not protect the system itself. See Baker v. Selden, 101 U.S. 99 (1879).
According to the Copyright Act of 1976, registration of copyright is voluntary and may take place at any time during the term of protection. See § 408. Although registration of a work with the Copyright Office is not a precondition for protection, an action for copyright infringement may not be commenced until the copyright has been formally registered with the Copyright Office. See § 411.
Deposit of copies with the Copyright Office for use by the Library of Congress is a separate requirement from registration. Failure to comply with the deposit requirement within three months of publication of the protected work may result in a civil fine. See § 407. The Register of Copyrights may exempt certain categories of material from the deposit requirement.
In 1989 the U.S. joined the Berne Convention for the Protection of Literary and Artistic Works. In accordance with the requirements of the Berne Convention, notice is no longer a condition of protection for works published after March 1, 1989. This change to the notice requirement applies only prospectively to copies of works publicly distributed after March 1, 1989.
The Berne Convention also modified the rule making copyright registration a precondition to commencing a lawsuit for infringement. For works originating from a Berne Convention country, an infringement action may be initiated without registering the work with the U.S. Copyright Office. However, for works of U.S. origin, registration prior to filing suit is still required.
The federal agency charged with administering the act is the Copyright Office of the Library of Congress. See § 701 of the act. Its regulations are found in Parts 201 - 204 of title 37 of the Code of Federal Regulations."
You can use the target and source properties on the javac tag to set a target runtime. The example below will compile any source code to target version 1.4 on any compiler that supports version 1.4 or later.
<javac compiler="classic" taskname="javac" includeAntRuntime="no" fork=" deprecation="true" target="1.4" source="1.4" srcdir="${src}" destdir="${classes}">
Note: The 'srcdir' and 'destdir' are property values set else where in the build script,
e.g. <property name="classes" value="c:/classes" />
Try this:
printf '\n%s\n' 'I want this on a new line!'
That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.
quantity=38; price=142.15; description='advanced widget'
$ printf '%8d%10.2f %s\n' "$quantity" "$price" "$description"
38 142.15 advanced widget
It seems like what you're looking for is a variant on the CSS Holy Grail Layout, but in two columns. Check out the resources at this answer for more information.
I'd like to add the following:
1. IsNumeric('0x89f') => true
2. IsNumeric('075') => true
Positive hex numbers start with 0x
and negative hex numbers start with -0x
.
Positive oct numbers start with 0
and negative oct numbers start with -0
.
This one takes most of what has already been mentioned into consideration, but includes hex and octal numbers, negative scientific, Infinity and has removed decimal scientific (4e3.2
is not valid).
function IsNumeric(input){
var RE = /^-?(0|INF|(0[1-7][0-7]*)|(0x[0-9a-fA-F]+)|((0|[1-9][0-9]*|(?=[\.,]))([\.,][0-9]+)?([eE]-?\d+)?))$/;
return (RE.test(input));
}
You could use advanced options to run Google tests.
To run only some unit tests you could use --gtest_filter=Test_Cases1*
command line option with value that accepts the *
and ?
wildcards for matching with multiple tests. I think it will solve your problem.
UPD:
Well, the question was how to run specific test cases. Integration of gtest with your GUI is another thing, which I can't really comment, because you didn't provide details of your approach. However I believe the following approach might be a good start:
--gtest_list_tests
--gtest_filter
Hope it's working for you
function GetSelectedItem()
{
var index = document.getElementById(select1).selectedIndex;
alert("value =" + document.getElementById(select1).value); // show selected value
alert("text =" + document.getElementById(select1).options[index].text); // show selected text
}
The annotation @JoinColumn
indicates that this entity is the owner of the relationship (that is: the corresponding table has a column with a foreign key to the referenced table), whereas the attribute mappedBy
indicates that the entity in this side is the inverse of the relationship, and the owner resides in the "other" entity. This also means that you can access the other table from the class which you've annotated with "mappedBy" (fully bidirectional relationship).
In particular, for the code in the question the correct annotations would look like this:
@Entity
public class Company {
@OneToMany(mappedBy = "company",
orphanRemoval = true,
fetch = FetchType.LAZY,
cascade = CascadeType.ALL)
private List<Branch> branches;
}
@Entity
public class Branch {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "companyId")
private Company company;
}
Check if your OS is Windows 7 Service Pack 1.. use "winver" to verify.
I tried a mouse move solution too, and it likewise didn't work. This was my solution, to quickly toggle Scroll Lock every 4 minutes:
Clear-Host
Echo "Keep-alive with Scroll Lock..."
$WShell = New-Object -com "Wscript.Shell"
while ($true)
{
$WShell.sendkeys("{SCROLLLOCK}")
Start-Sleep -Milliseconds 100
$WShell.sendkeys("{SCROLLLOCK}")
Start-Sleep -Seconds 240
}
I used Scroll Lock because that's one of the most useless keys on the keyboard. Also could be nice to see it briefly blink every now and then. This solution should work for just about everyone, I think.
See also:
I had the same problem. But What I did is I imported the .java files and then I went to Search->File-> and then changed the package name to whatever package it should belong in this way I fixed a lot of java files which otherwise would require to go to every file and change them manually.
I am using visual studio 2010 to make a program on SMSC Server. What you have to do is go to build-->publish. you will be asked be asked to few simple things and the location where you want to store your application, browse the location where you want to put it.
I hope this is what you are looking for
Always : If you always want vertical scrollbar, use overflow-y: scroll;
<div style="overflow-y: scroll;">
......
</div>
When needed: If you only want vertical scrollbar when needed, use overflow-y: auto;
(You need to specify a height in this case)
<div style="overflow-y: auto; height:150px; ">
....
</div>
This should work for you:
Dim oShell
Dim iValue
Set oShell = CreateObject("WScript.Shell")
iValue = oShell.RegRead("HKLM\SOFTWARE\SOMETHINGSOMETHING")
For those coming here to debug this error in Chrome 73, one possibility is because Chrome 73 onwards disallows cross-origin requests in content scripts.
More reading:
This affects many Chrome extension authors, who now need to scramble to fix the extensions because Chrome thinks "Our data shows that most extensions will not be affected by this change."
(it has nothing to do with your app code)
UPDATE: I fixed the CORs issue but I still see this error. I suspect it is Chrome's fault here.
Here is a component that incorporates much of this by lovasoa: https://github.com/lovasoa/react-contenteditable/blob/master/index.js
He shims the event in the emitChange
emitChange: function(evt){
var html = this.getDOMNode().innerHTML;
if (this.props.onChange && html !== this.lastHtml) {
evt.target = { value: html };
this.props.onChange(evt);
}
this.lastHtml = html;
}
I'm using a similar approach successfully
Its defined in RFC 2045 as a special padding character if fewer than 24 bits are available at the end of the encoded data.
yes i have done that on several rooted machines i set a debian linux on a sdcard by dd. i copy this script http://jeanmichel.gens.free.fr/etc/install on /system/bin
i have not yet succeed to run a Xserver but i can use xwindows binaries through the android Xserver application
i can run update my debian with apt-get upgrade , run an apache server with PHP , run a ssh server and all binaries on a terminal including user management i have also a problem with semaphores handling please contact me if you have any trouble
You should check the value of your line of code like adding checking length of it.
if(len(a['Names'].str.contains('Mel'))>0):
print("Name Present")
The ng-dirty
class tells you that the form has been modified by the user, whereas the ng-pristine
class tells you that the form has not been modified by the user. So ng-dirty
and ng-pristine
are two sides of the same story.
The classes are set on any field, while the form has two properties, $dirty
and $pristine
.
You can use the $scope.form.$setPristine()
function to reset a form to pristine state (please note that this is an AngularJS 1.1.x feature).
If you want a $scope.form.$setPristine()
-ish behavior even in 1.0.x branch of AngularJS, you need to roll your own solution (some pretty good ones can be found here). Basically, this means iterating over all form fields and setting their $dirty
flag to false
.
Hope this helps.
for HttpClient always use HttpRequestInterceptor for example
httclient.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(HttpRequest arg0, HttpContext context) throws HttpException, IOException {
AuthState state = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
if (state.getAuthScheme() == null) {
BasicScheme scheme = new BasicScheme();
CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
Credentials credentials = credentialsProvider.getCredentials(AuthScope.ANY);
if (credentials == null) {
System.out.println("Credential >>" + credentials);
throw new HttpException();
}
state.setAuthScope(AuthScope.ANY);
state.setAuthScheme(scheme);
state.setCredentials(credentials);
}
}
}, 0);
also you can use this Extension method
public static List<int> SplitToIntList(this string list, char separator = ',')
{
return list.Split(separator).Select(Int32.Parse).ToList();
}
usage:
var numberListString = "1, 2, 3, 4";
List<int> numberList = numberListString.SplitToIntList(',');
You need to use the files
parameter to send a multipart form POST request even when you do not need to upload any files.
From the original requests source:
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
...
:param files: (optional) Dictionary of ``'name': file-like-objects``
(or ``{'name': file-tuple}``) for multipart encoding upload.
``file-tuple`` can be a 2-tuple ``('filename', fileobj)``,
3-tuple ``('filename', fileobj, 'content_type')``
or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``,
where ``'content-type'`` is a string
defining the content type of the given file
and ``custom_headers`` a dict-like object
containing additional headers to add for the file.
The relevant part is: file-tuple can be a
2-tuple
, 3-tuple
or a
4-tuple
.
Based on the above, the simplest multipart form request that includes both files to upload and form fields will look like this:
multipart_form_data = {
'file2': ('custom_file_name.zip', open('myfile.zip', 'rb')),
'action': (None, 'store'),
'path': (None, '/path1')
}
response = requests.post('https://httpbin.org/post', files=multipart_form_data)
print(response.content)
☝ Note the None
as the first argument in the tuple for plain text fields — this is a placeholder for the filename field which is only used for file uploads, but for text fields passing None
as the first parameter is required in order for the data to be submitted.
If you need to post multiple fields with the same name then instead of a dictionary you can define your payload as a list (or a tuple) of tuples:
multipart_form_data = (
('file2', ('custom_file_name.zip', open('myfile.zip', 'rb'))),
('action', (None, 'store')),
('path', (None, '/path1')),
('path', (None, '/path2')),
('path', (None, '/path3')),
)
If the above API is not pythonic enough for you, then consider using requests toolbelt (pip install requests_toolbelt
) which is an extension of the core requests module that provides support for file upload streaming as well as the MultipartEncoder which can be used instead of files
, and which also lets you define the payload as a dictionary, tuple or list.
MultipartEncoder
can be used both for multipart requests with or without actual upload fields. It must be assigned to the data
parameter.
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
multipart_data = MultipartEncoder(
fields={
# a file upload field
'file': ('file.zip', open('file.zip', 'rb'), 'text/plain')
# plain text fields
'field0': 'value0',
'field1': 'value1',
}
)
response = requests.post('http://httpbin.org/post', data=multipart_data,
headers={'Content-Type': multipart_data.content_type})
If you need to send multiple fields with the same name, or if the order of form fields is important, then a tuple or a list can be used instead of a dictionary:
multipart_data = MultipartEncoder(
fields=(
('action', 'ingest'),
('item', 'spam'),
('item', 'sausage'),
('item', 'eggs'),
)
)
You could look into this: http://www.codeproject.com/KB/showcase/pdfrasterizer.aspx It's not completely free, but it looks very nice.
Alex
On Linux we can use subprocess module
import subprocess
cmd = ['xrandr']
cmd2 = ['grep', '*']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
p2 = subprocess.Popen(cmd2, stdin=p.stdout, stdout=subprocess.PIPE)
p.stdout.close()
resolution_string, junk = p2.communicate()
resolution = resolution_string.split()[0]
resolution = resolution.decode("utf-8")
width = int(resolution.split("x")[0].strip())
heigth = int(resolution.split("x")[1].strip())
The above answers illustrate the reason for this java.net.SocketException: Broken pipe
: the other end closed the connection. I would like to share experience what happened when I encountered it:
Content-Type
header is mistakenly set larger than request body actually is (in fact there was no body at all)Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
java.net.SocketTimeoutException: null
java.net.SocketException: Broken pipe
because client closed it.Sometimes, tomcat does not throw broken pip exception, because timeout exception close the connection, why such a difference is confusing me too.
var fileName = req.files.upload.name;
var arr = fileName.split('.');
var extension = arr[length-1];
Chrome Extensions don't allow you to have inline JavaScript (documentation).
The same goes for Firefox WebExtensions (documentation).
You are going to have to do something similar to this:
Assign an ID to the link (<a onClick=hellYeah("xxx")>
becomes <a id="link">
), and use addEventListener
to bind the event. Put the following in your popup.js
file:
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('link');
// onClick's logic below:
link.addEventListener('click', function() {
hellYeah('xxx');
});
});
popup.js
should be loaded as a separate script file:
<script src="popup.js"></script>
Press Ctrl + T on the method name (rather than F3). This gives the type hierarchy as a pop-up so is slightly faster than using F4 and the type hierarchy view.
Also, when done on a method, subtypes that don't implement/override the method will be greyed out, and when you double click on a class in the list it will take you straight to the method in that class.
! is a logical NOT operator, it's a boolean operator that will invert something to its opposite.
Although you can bypass the parentheses of the invoked function by using the BANG (!) before the function, it will still invert the return, which might not be what you wanted. As in the case of an IEFE, it would return undefined, which when inverted becomes the boolean true.
Instead, use the closing parenthesis and the BANG (!) if needed.
// I'm going to leave the closing () in all examples as invoking the function with just ! and () takes away from what's happening.
(function(){ return false; }());
=> false
!(function(){ return false; }());
=> true
!!(function(){ return false; }());
=> false
!!!(function(){ return false; }());
=> true
Other Operators that work...
+(function(){ return false; }());
=> 0
-(function(){ return false; }());
=> -0
~(function(){ return false; }());
=> -1
Combined Operators...
+!(function(){ return false; }());
=> 1
-!(function(){ return false; }());
=> -1
!+(function(){ return false; }());
=> true
!-(function(){ return false; }());
=> true
~!(function(){ return false; }());
=> -2
~!!(function(){ return false; }());
=> -1
+~(function(){ return false; }());
+> -1
Please explain why same ng-model
is used? And what value is passed through ng- model
and how it is passed? To be more specific, if I use console.log(color)
what would be the output?
I added the following aliases to my .gitconfig
file. This allows me to delete branches with or without specifying the branch name. Branch name is defaulted to the current branch if no argument is passed in.
[alias]
branch-name = rev-parse --abbrev-ref HEAD
rm-remote-branch = !"f() { branch=${1-$(git branch-name)}; git push origin :$branch; }; f"
rm-local-branch = !"f() { branch=${1-$(git branch-name)}; git checkout master; git branch -d $branch; }; f"
rm-branch-fully = !"f() { branch=${1-$(git branch-name)}; git rm-local-branch $branch; git rm-remote-branch $branch; }; f"
I just turn off my windows firewall and it worked for me. You can also try different versions of npm.
string strName = "vernie";
string[] strNamesArray = { "roger", "vernie", "joel" };
if (strNamesArray.Any(x => x == strName))
{
// do some action here if true...
}
Following on from my other comment, here's a batch file which displays the current JRE or JDK based on the registry values.
It's different from the other solutions in instances where java is installed, but not on the PATH
.
@ECHO off
SET KIT=JavaSoft\Java Runtime Environment
call:ReadRegValue VER "HKLM\Software\%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE
SET KIT=Wow6432Node\JavaSoft\Java Runtime Environment
call:ReadRegValue VER "HKLM\Software\%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE
SET KIT=JavaSoft\Java Development Kit
call:ReadRegValue VER "HKLM\Software\%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE
SET KIT=Wow6432Node\JavaSoft\Java Development Kit
call:ReadRegValue VER "HKLM\Software\%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE
ECHO Failed to find Java
GOTO :EOF
:FoundJRE
call:ReadRegValue JAVAPATH "HKLM\Software\%KIT%\%VER%" "JavaHome"
ECHO %JAVAPATH%
GOTO :EOF
:ReadRegValue
SET key=%2%
SET name=%3%
SET "%~1="
SET reg=reg
IF DEFINED ProgramFiles(x86) (
IF EXIST %WINDIR%\sysnative\reg.exe SET reg=%WINDIR%\sysnative\reg.exe
)
FOR /F "usebackq tokens=3* skip=1" %%A IN (`%reg% QUERY %key% /v %name% 2^>NUL`) DO SET "%~1=%%A %%B"
GOTO :EOF
%>%
is similar to pipe in Unix. For example, in
a <- combined_data_set %>% group_by(Outlet_Identifier) %>% tally()
the output of combined_data_set
will go into group_by
and its output will go into tally
, then the final output is assigned to a
.
This gives you handy and easy way to use functions in series without creating variables and storing intermediate values.
Yes. you can't remember all the shortcuts. You will forget many of them for sure. In this way, you can recall it and get the work done quickly.
Press Ctrl+3
And type whatever the hell you want :) It's a shortcut for shortcuts
this.myForm.reset();
This is all enough...You can get the desired output
You may also consider the following solution:
let sum = options.set0.concat(options.set1);
const codeHTML = '<ol>' + sum.reduce((html, item) => {
return html + "<li>" + item + "</li>";
}, "") + '</ol>';
document.querySelector("#list").innerHTML = codeHTML;
I've used this process to attach a 3rd party Jar to an Android project in IDEA.
The library should now be recognised.
SIMPLE SOLUTION
File file = new File("F:/ABC.TXT");
FileWriter fileWriter = new FileWriter(file,true);
filewriter.write("\r\n");
If you just want to know the content without a format (e.g. for debuging purpose) I use this:
echo json_encode($anArray);
This will show it as a JSON which is pretty human readable.
This code seems to work:
private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
TabItem selectedTab = e.AddedItems[0] as TabItem; // Gets selected tab
if (selectedTab.Name == "Tab1")
{
// Do work Tab1
}
else if (selectedTab.Name == "Tab2")
{
// Do work Tab2
}
}
There is no this
pointer in a static method. (I don't believe this code will even compile.)
You shouldn't be doing these things in a static method like main()
; set things up in a constructor. I didn't compile or run this to see if it actually works, but give it a try.
public class Calc extends JFrame implements ActionListener {
private Button button1;
public Calc()
{
super();
this.setSize(100, 100);
this.setVisible(true);
this.button1 = new JButton("1");
this.button1.addActionListener(this);
this.add(button1);
}
public static void main(String[] args) {
Calc calc = new Calc();
calc.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1)
}
}
Convert your x-axis data from text to datetime.datetime
, use datetime.strptime
:
>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
datetime.datetime(2012, 5, 31, 19, 0)
This is an example of how to plot data once you have an array of datetimes:
import matplotlib.pyplot as plt
import datetime
import numpy as np
x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)
plt.plot(x,y)
plt.show()
a.txt
this is line 1
this is line 2
code:
Python 3.4.0 (default, Mar 20 2014, 22:43:40)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']
I'm on Linux, but I guess you just use \r\n
on Windows and it would also work
Try putting \
at the end of each line before copying it.
Example:
echo "Hello world" && \
script_b.sh
echo $?
The exit code ($?
) is now the full sequence of commands, and not just the last command.
import { Component, Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'timePipe'
})
export class TimeValuePipe implements PipeTransform {
transform(value: any, args?: any): any {
var hoursMinutes = value.split(/[.:]/);
var hours = parseInt(hoursMinutes[0], 10);
var minutes = hoursMinutes[1] ? parseInt(hoursMinutes[1], 10) : 0;
console.log('hours ', hours);
console.log('minutes ', minutes/60);
return (hours + minutes / 60).toFixed(2);
}
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular';
order = [
{
"order_status": "Still at Shop",
"order_id": "0:02"
},
{
"order_status": "On the way",
"order_id": "02:29"
},
{
"order_status": "Delivered",
"order_id": "16:14"
},
{
"order_status": "Delivered",
"order_id": "07:30"
}
]
}
Invoke this module in App.Module.ts file.
According to the Android developers guide for android.hardware.Camera
, they state:
We recommend using the new android.hardware.camera2 API for new applications.
On the information page about android.hardware.camera2
, (linked above), it is stated:
The android.hardware.camera2 package provides an interface to individual camera devices connected to an Android device. It replaces the deprecated Camera class.
When you check that documentation you'll find that the implementation of these 2 Camera API's are very different.
For example getting camera orientation on android.hardware.camera
@Override
public int getOrientation(final int cameraId) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
return info.orientation;
}
Versus android.hardware.camera2
@Override
public int getOrientation(final int cameraId) {
try {
CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
String[] cameraIds = manager.getCameraIdList();
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraIds[cameraId]);
return characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
} catch (CameraAccessException e) {
// TODO handle error properly or pass it on
return 0;
}
}
This makes it hard to switch from one to another and write code that can handle both implementations.
Note that in this single code example I already had to work around the fact that the olde camera API works with int
primitives for camera IDs while the new one works with String
objects. For this example I quickly fixed that by using the int as an index in the new API. If the camera's returned aren't always in the same order this will already cause issues. Alternative approach is to work with String objects and String representation of the old int cameraIDs which is probably safer.
Now to work around this huge difference you can implement an interface first and reference that interface in your code.
Here I'll list some code for that interface and the 2 implementations. You can limit the implementation to what you actually use of the camera API to limit the amount of work.
In the next section I'll quickly explain how to load one or another.
The interface wrapping all you need, to limit this example I only have 2 methods here.
public interface CameraSupport {
CameraSupport open(int cameraId);
int getOrientation(int cameraId);
}
Now have a class for the old camera hardware api:
@SuppressWarnings("deprecation")
public class CameraOld implements CameraSupport {
private Camera camera;
@Override
public CameraSupport open(final int cameraId) {
this.camera = Camera.open(cameraId);
return this;
}
@Override
public int getOrientation(final int cameraId) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
return info.orientation;
}
}
And another one for the new hardware api:
public class CameraNew implements CameraSupport {
private CameraDevice camera;
private CameraManager manager;
public CameraNew(final Context context) {
this.manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
}
@Override
public CameraSupport open(final int cameraId) {
try {
String[] cameraIds = manager.getCameraIdList();
manager.openCamera(cameraIds[cameraId], new CameraDevice.StateCallback() {
@Override
public void onOpened(CameraDevice camera) {
CameraNew.this.camera = camera;
}
@Override
public void onDisconnected(CameraDevice camera) {
CameraNew.this.camera = camera;
// TODO handle
}
@Override
public void onError(CameraDevice camera, int error) {
CameraNew.this.camera = camera;
// TODO handle
}
}, null);
} catch (Exception e) {
// TODO handle
}
return this;
}
@Override
public int getOrientation(final int cameraId) {
try {
String[] cameraIds = manager.getCameraIdList();
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraIds[cameraId]);
return characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
} catch (CameraAccessException e) {
// TODO handle
return 0;
}
}
}
Now to load either your CameraOld
or CameraNew
class you'll have to check the API level since CameraNew
is only available from api level 21.
If you have dependency injection set up already you can do so in your module when providing the CameraSupport
implementation. Example:
@Module public class CameraModule {
@Provides
CameraSupport provideCameraSupport(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return new CameraNew(context);
} else {
return new CameraOld();
}
}
}
If you don't use DI you can just make a utility or use Factory pattern to create the proper one. Important part is that the API level is checked.
Just a few minutes ago i was facing the same problem. I got the problem that is after just placing your jQuery start the other jQuery scripting. After all it will work fine.
Use LayoutParams (as explained already). However be careful which LayoutParams to choose. According to https://stackoverflow.com/a/11971553/3184778 "you need to use the one that relates to the PARENT of the view you're working on, not the actual view"
If for example the TextView is inside a TableRow, then you need to use TableRow.LayoutParams instead of RelativeLayout or LinearLayout
Update: This function only avoids copy if it can, hence this is not the correct answer for this question. unutbu's answer is the right one.
a = a.astype(numpy.float32, copy=False)
numpy astype has a copy flag. Why shouldn't we use it ?
Easy and simple solution for MAC
My Issue was
cordova build android
ANDROID_HOME=/Users/jerilkuruvila/Library/Android/sdk
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_65.jdk/Contents/Home
Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK.
Looked here: /Users/jerilkuruvila/Library/Android/sdk/tools/templates/gradle/wrapper
Solution
jerilkuruvila@Jerils-ENIAC tools $ cd templates
-bash: cd: mkdir: No such file or directory
jerilkuruvila@Jerils-ENIAC tools $ mkdir templates
jerilkuruvila@Jerils-ENIAC tools $ cp -rf gradle templates/
jerilkuruvila@Jerils-ENIAC tools $ chmod a+x templates/
cordova build android again working now !!!
How i solved
# yum update
# yum install -y https://centos7.iuscommunity.org/ius-release.rpm
# yum install -y python36u python36u-libs python36u-devel python36u-pip
# pip3.6 install pipenv
I hope it will help Someone to resolve "gcc" issue.
Try this:
window.onmousewheel = document.onmousewheel = null
window.ontouchmove = null
window.onwheel = null
following Killercam'answer, My code
private void dgvProducts_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
dgvProducts.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
and :
private void dgvProducts_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (dgvProducts.DataSource != null)
{
if (dgvProducts.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "True")
{
//do something
}
else
{
//do something
}
}
}
Easy:
SELECT question_id, wm_concat(element_id) as elements
FROM questions
GROUP BY question_id;
Pesonally tested on 10g ;-)
From http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php
You can simply request https://graph.facebook.com/me?access_token=xxxxxxxxxxxxxxxxx if you get an error, the token is invalid. If you get a JSON object with an id property then it is valid.
Unfortunately this will only tell you if your token is valid, not if it came from your app.
Sometimes it is due to the master table is dropped (maybe by disabling foreign_key_checks), but the foreign key CONSTRAINT still exists in other tables. In my case I had dropped the table and tried to recreate it, but it was throwing the same error for me.
So try dropping all the foreign key CONSTRAINTs from all the tables if there are any and then update or create the table.
A bit simpler one-liner:
import os
from itertools import product, chain
chain.from_iterable([[os.sep.join(w) for w in product([i[0]], i[2])] for i in os.walk(dir)])
According to spark documentation "where()
is an alias for filter()
"
filter(condition)
Filters rows using the given condition.
where()
is an alias for filter()
.
Parameters: condition – a Column
of types.BooleanType
or a string of SQL expression.
>>> df.filter(df.age > 3).collect()
[Row(age=5, name=u'Bob')]
>>> df.where(df.age == 2).collect()
[Row(age=2, name=u'Alice')]
>>> df.filter("age > 3").collect()
[Row(age=5, name=u'Bob')]
>>> df.where("age = 2").collect()
[Row(age=2, name=u'Alice')]
Execute the workbench.action.reloadWindow
command.
There are some ways to do so:
Open the command palette (Ctrl + Shift + P) and execute the command:
>Reload Window
Define a keybinding for the command (for example CTRL+F5) in keybindings.json
:
[
{
"key": "ctrl+f5",
"command": "workbench.action.reloadWindow",
"when": "editorTextFocus"
}
]
Another possible solution, above solution failed for me in parsing query string params.
var regex = new RegExp("^(http[s]?:\\/\\/(www\\.)?|ftp:\\/\\/(www\\.)?|www\\.){1}([0-9A-Za-z-\\.@:%_\+~#=]+)+((\\.[a-zA-Z]{2,3})+)(/(.)*)?(\\?(.)*)?");
if(regex.test("http://google.com")){
alert("Successful match");
}else{
alert("No match");
}
In this solution please feel free to modify [-0-9A-Za-z\.@:%_\+~#=
, to match the domain/sub domain name. In this solution query string parameters are also taken care.
If you are not using RegEx
, then from the expression replace \\
by \
.
Hope this helps.
401 means "Unauthorized", so there must be something with your credentials.
I think that java URL
does not support the syntax you are showing. You could use an Authenticator instead.
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(login, password.toCharArray());
}
});
and then simply invoking the regular url, without the credentials.
The other option is to provide the credentials in a Header:
String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encoded);
PS: It is not recommended to use that Base64Encoder but this is only to show a quick solution. If you want to keep that solution, look for a library that does. There are plenty.
If you are testing this on your local WAMP you might need to set up the temporary folder for file uploads. You can do this in your PHP.ini file:
upload_tmp_dir = "c:\mypath\mytempfolder\"
You will need to grant permissions on the folder to allow the upload to take place - the permission you need to grant vary based on your operating system.
With Yglu Structural Templating, your example can be written:
foo: !()
!? $.propname:
type: number
default: !? $.default
bar:
!apply .foo:
propname: "some_prop"
default: "some default"
Disclaimer: I am the author or Yglu.
Both are of same concept but in atomic boolean it will provide atomicity to the operation in case the cpu switch happens in between.
I searched for a solution to parse very large files (gbs) line by line using a stream. All the third-party libraries and examples did not suit my needs since they processed the files not line by line (like 1 , 2 , 3 , 4 ..) or read the entire file to memory
The following solution can parse very large files, line by line using stream & pipe. For testing I used a 2.1 gb file with 17.000.000 records. Ram usage did not exceed 60 mb.
First, install the event-stream package:
npm install event-stream
Then:
var fs = require('fs')
, es = require('event-stream');
var lineNr = 0;
var s = fs.createReadStream('very-large-file.csv')
.pipe(es.split())
.pipe(es.mapSync(function(line){
// pause the readstream
s.pause();
lineNr += 1;
// process line here and call s.resume() when rdy
// function below was for logging memory usage
logMemoryUsage(lineNr);
// resume the readstream, possibly from a callback
s.resume();
})
.on('error', function(err){
console.log('Error while reading file.', err);
})
.on('end', function(){
console.log('Read entire file.')
})
);
Please let me know how it goes!
The following will return true if the element is an input:
$("#elementId").is("input")
or you can use the following to get the name of the tag:
$("#elementId").get(0).tagName
Another JS solution from: https://www.w3resource.com/javascript-exercises/javascript-array-exercise-8.php
Can try this too:
let arr =['pear', 'apple', 'orange', 'apple'];
function findMostFrequent(arr) {
let mf = 1;
let m = 0;
let item;
for (let i = 0; i < arr.length; i++) {
for (let j = i; j < arr.length; j++) {
if (arr[i] == arr[j]) {
m++;
if (m > mf) {
mf = m;
item = arr[i];
}
}
}
m = 0;
}
return item;
}
findMostFrequent(arr); // apple
If all else fails, try "Clean Storage" via the app's System Settings.
Since you're talking about financial figures, you DO NOT WANT to use floating-point arithmetic. You're better off using Decimal.
>>> from decimal import Decimal
>>> Decimal("33.505")
Decimal('33.505')
Text output formatting with new-style format()
(defaults to half-even rounding):
>>> print("financial return of outcome 1 = {:.2f}".format(Decimal("33.505")))
financial return of outcome 1 = 33.50
>>> print("financial return of outcome 1 = {:.2f}".format(Decimal("33.515")))
financial return of outcome 1 = 33.52
See the differences in rounding due to floating-point imprecision:
>>> round(33.505, 2)
33.51
>>> round(Decimal("33.505"), 2) # This converts back to float (wrong)
33.51
>>> Decimal(33.505) # Don't init Decimal from floating-point
Decimal('33.50500000000000255795384873636066913604736328125')
Proper way to round financial values:
>>> Decimal("33.505").quantize(Decimal("0.01")) # Half-even rounding by default
Decimal('33.50')
It is also common to have other types of rounding in different transactions:
>>> import decimal
>>> Decimal("33.505").quantize(Decimal("0.01"), decimal.ROUND_HALF_DOWN)
Decimal('33.50')
>>> Decimal("33.505").quantize(Decimal("0.01"), decimal.ROUND_HALF_UP)
Decimal('33.51')
Remember that if you're simulating return outcome, you possibly will have to round at each interest period, since you can't pay/receive cent fractions, nor receive interest over cent fractions. For simulations it's pretty common to just use floating-point due to inherent uncertainties, but if doing so, always remember that the error is there. As such, even fixed-interest investments might differ a bit in returns because of this.
This is ugly as all hell, but always produces correct arithmetic rounding.
public double ArithRound(double number,int places){
string numberFormat = "###.";
numberFormat = numberFormat.PadRight(numberFormat.Length + places, '#');
return double.Parse(number.ToString(numberFormat));
}
Use ord
when reading reading bytes:
byte_binary = bin(ord(f.read(1))) # Add [2:] to remove the "0b" prefix
Or
Using str.format()
:
'{:08b}'.format(ord(f.read(1)))
A classic "or" would be |
. For example, ab|de
would match either side of the expression.
However, for something like your case you might want to use the ?
quantifier, which will match the previous expression exactly 0 or 1 times (1 times preferred; i.e. it's a "greedy" match). Another (probably more relyable) alternative would be using a custom character group:
\d+\s+[A-Z\s]+\s+[A-Z][A-Za-z]+
This pattern will match:
\d+
: One or more numbers.\s+
: One or more whitespaces.[A-Z\s]+
: One or more uppercase characters or space characters\s+
: One or more whitespaces.[A-Z][A-Za-z\s]+
: An uppercase character followed by at least one more character (uppercase or lowercase) or whitespaces.If you'd like a more static check, e.g. indeed only match ABC
and A ABC
, then you can combine a (non-matching) group and define the alternatives inside (to limit the scope):
\d (?:ABC|A ABC) Street
Or another alternative using a quantifier:
\d (?:A )?ABC Street
git remote set-url --push origin
should work, as you mentioned, but you need to explicitly provide the url instead of an alternative remote name, e.g.
git remote set-url --push origin [email protected]:contributor/repo.git
You can confirm whether this worked by doing a git remote -v
. E.g.
? ~/go/src/github.com/stretchr/testify/ master git remote -v
fork [email protected]:contributor/testify.git (fetch)
fork [email protected]:contributor/testify.git (push)
origin [email protected]:stretchr/testify (fetch)
origin [email protected]:contributor/testify.git (push)
If you don't want to import the calendar
module, a simple two-step function can also be:
import datetime
def last_day_of_month(any_day):
# this will never fail
# get close to the end of the month for any day, and add 4 days 'over'
next_month = any_day.replace(day=28) + datetime.timedelta(days=4)
# subtract the number of remaining 'overage' days to get last day of current month, or said programattically said, the previous day of the first of next month
return next_month - datetime.timedelta(days=next_month.day)
Outputs:
>>> for month in range(1, 13):
... print last_day_of_month(datetime.date(2012, month, 1))
...
2012-01-31
2012-02-29
2012-03-31
2012-04-30
2012-05-31
2012-06-30
2012-07-31
2012-08-31
2012-09-30
2012-10-31
2012-11-30
2012-12-31
You can have awk
do it all without using cut
:
awk '{print substr($7,index($7,"=")+1)}' inputfile
You could use split()
instead of substr(index())
.
If you have 2 beans of the same class autowired to one class you shoud use @Qualifier
(Spring Autowiring @Qualifier example).
But it seems like your problem comes from incorrect Java Syntax.
Your object should start with lower case letter
SuggestionService suggestion;
Your setter should start with lower case as well and object name should be with Upper case
public void setSuggestion(final Suggestion suggestion) {
this.suggestion = suggestion;
}
You are missing JUnit 5 platform launcher with group: 'org.junit.platform', name: 'junit-platform-launcher'
Just add in ur POM:
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
</dependency>
This is a shorter and hopefully clearer answer... Yes, the endpoint is the URL where your service can be accessed by a client application. The same web service can have multiple endpoints, for example in order to make it available using different protocols.
This answer is for anyone encountering pdfs with images and needing to use OCR. I could not find a workable off-the-shelf solution; nothing that gave me the accuracy I needed.
Here are the steps I found to work.
Use pdfimages
from https://poppler.freedesktop.org/ to turn the pages of the pdf into images.
Use Tesseract to detect rotation and ImageMagick mogrify
to fix it.
Use OpenCV to find and extract tables.
Use OpenCV to find and extract each cell from the table.
Use OpenCV to crop and clean up each cell so that there is no noise that will confuse OCR software.
Use Tesseract to OCR each cell.
Combine the extracted text of each cell into the format you need.
I wrote a python package with modules that can help with those steps.
Repo: https://github.com/eihli/image-table-ocr
Docs & Source: https://eihli.github.io/image-table-ocr/pdf_table_extraction_and_ocr.html
Some of the steps don't require code, they take advantage of external tools like pdfimages
and tesseract
. I'll provide some brief examples for a couple of the steps that do require code.
This link was a good reference while figuring out how to find tables. https://answers.opencv.org/question/63847/how-to-extract-tables-from-an-image/
import cv2
def find_tables(image):
BLUR_KERNEL_SIZE = (17, 17)
STD_DEV_X_DIRECTION = 0
STD_DEV_Y_DIRECTION = 0
blurred = cv2.GaussianBlur(image, BLUR_KERNEL_SIZE, STD_DEV_X_DIRECTION, STD_DEV_Y_DIRECTION)
MAX_COLOR_VAL = 255
BLOCK_SIZE = 15
SUBTRACT_FROM_MEAN = -2
img_bin = cv2.adaptiveThreshold(
~blurred,
MAX_COLOR_VAL,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY,
BLOCK_SIZE,
SUBTRACT_FROM_MEAN,
)
vertical = horizontal = img_bin.copy()
SCALE = 5
image_width, image_height = horizontal.shape
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (int(image_width / SCALE), 1))
horizontally_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, horizontal_kernel)
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, int(image_height / SCALE)))
vertically_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, vertical_kernel)
horizontally_dilated = cv2.dilate(horizontally_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (40, 1)))
vertically_dilated = cv2.dilate(vertically_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (1, 60)))
mask = horizontally_dilated + vertically_dilated
contours, hierarchy = cv2.findContours(
mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE,
)
MIN_TABLE_AREA = 1e5
contours = [c for c in contours if cv2.contourArea(c) > MIN_TABLE_AREA]
perimeter_lengths = [cv2.arcLength(c, True) for c in contours]
epsilons = [0.1 * p for p in perimeter_lengths]
approx_polys = [cv2.approxPolyDP(c, e, True) for c, e in zip(contours, epsilons)]
bounding_rects = [cv2.boundingRect(a) for a in approx_polys]
# The link where a lot of this code was borrowed from recommends an
# additional step to check the number of "joints" inside this bounding rectangle.
# A table should have a lot of intersections. We might have a rectangular image
# here though which would only have 4 intersections, 1 at each corner.
# Leaving that step as a future TODO if it is ever necessary.
images = [image[y:y+h, x:x+w] for x, y, w, h in bounding_rects]
return images
This is very similar to 2, so I won't include all the code. The part I will reference will be in sorting the cells.
We want to identify the cells from left-to-right, top-to-bottom.
We’ll find the rectangle with the most top-left corner. Then we’ll find all of the rectangles that have a center that is within the top-y and bottom-y values of that top-left rectangle. Then we’ll sort those rectangles by the x value of their center. We’ll remove those rectangles from the list and repeat.
def cell_in_same_row(c1, c2):
c1_center = c1[1] + c1[3] - c1[3] / 2
c2_bottom = c2[1] + c2[3]
c2_top = c2[1]
return c2_top < c1_center < c2_bottom
orig_cells = [c for c in cells]
rows = []
while cells:
first = cells[0]
rest = cells[1:]
cells_in_same_row = sorted(
[
c for c in rest
if cell_in_same_row(c, first)
],
key=lambda c: c[0]
)
row_cells = sorted([first] + cells_in_same_row, key=lambda c: c[0])
rows.append(row_cells)
cells = [
c for c in rest
if not cell_in_same_row(c, first)
]
# Sort rows by average height of their center.
def avg_height_of_center(row):
centers = [y + h - h / 2 for x, y, w, h in row]
return sum(centers) / len(centers)
rows.sort(key=avg_height_of_center)
Try the following
double hours = (b-a).TotalHours;
If you just want the hour difference excluding the difference in days you can use the following
int hours = (b-a).Hours;
The difference between these two properties is mainly seen when the time difference is more than 1 day. The Hours property will only report the actual hour difference between the two dates. So if two dates differed by 100 years but occurred at the same time in the day, hours would return 0. But TotalHours will return the difference between in the total amount of hours that occurred between the two dates (876,000 hours in this case).
The other difference is that TotalHours will return fractional hours. This may or may not be what you want. If not, Math.Round can adjust it to your liking.
For encoding to base64 in Angular2, you can use btoa() function.
Example:-
console.log(btoa("stringAngular2"));
// Output:- c3RyaW5nQW5ndWxhcjI=
For decoding from base64 in Angular2, you can use atob() function.
Example:-
console.log(atob("c3RyaW5nQW5ndWxhcjI="));
// Output:- stringAngular2
Press Ctrl + Alt + O.
A dialog box will appear with a few options. You can choose to have the dialog box not appear again in the future if you wish, setting a default behavior.
You should run:
pip install protobuf
That will install Google protobuf and after that you can run that Python script.
As per this link.
If you want to hide panel on button click, write below code in JButton Action. I assume you want to hide jpanel1.
jpanel1.setVisible(false);
You need to identify your sections and then style them with CSS. In this case, this might work:
HTML
<div id="blueRectangle"></div>
CSS
#blueRectangle {
background: #4679BD;
min-height: 50px;
//width: 100%;
}
Only working solution i've made by my self.
Here is my UIViewController subclass https://github.com/comonitos/ios7_overlaping
1 Subclass from UIViewController
2 Subclass your window.rootViewController from that class.
3 Voila!
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
CGRect screen = [[UIScreen mainScreen] bounds];
if (self.navigationController) {
CGRect frame = self.navigationController.view.frame;
frame.origin.y = 20;
frame.size.height = screen.size.height - 20;
self.navigationController.view.frame = frame;
} else {
if ([self respondsToSelector: @selector(containerView)]) {
UIView *containerView = (UIView *)[self performSelector: @selector(containerView)];
CGRect frame = containerView.frame;
frame.origin.y = 20;
frame.size.height = screen.size.height - 20;
containerView.frame = frame;
} else {
CGRect frame = self.view.frame;
frame.origin.y = 20;
frame.size.height = screen.size.height - 20;
self.view.frame = frame;
}
}
}
}
4 Add this to make your status bar white Just right after the [self.window makeKeyAndVisible]; !!!
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
// Assume x, y, and diameter are instance variables.
Ellipse2D.Double circle = new Ellipse2D.Double(x, y, diameter, diameter);
g2d.fill(circle);
...
}
Here are some docs about paintComponent (link).
You should override that method in your JPanel and do something similar to the code snippet above.
In your ActionListener you should specify x, y, diameter
and call repaint()
.
MySQL unique and primary keys serve to identify rows. There can be only one Primary key in a table but one or more unique keys. Key is just index.
for more details you can check http://www.geeksww.com/tutorials/database_management_systems/mysql/tips_and_tricks/mysql_primary_key_vs_unique_key_constraints.php
to convert mysql to mssql try this and see http://gathadams.com/2008/02/07/convert-mysql-to-ms-sql-server/
In newer hibernate jars, you can find the required jpa file under "hibernate-search-5.8.0.Final\dist\lib\provided\hibernate-jpa-2.1-api-1.0.0.Final". You have to add this jar file into your project java build path. This will most probably solve the issue.
temperature = input("What's the current temperature in your city? (please use the format ??C or ???F) >>> ")
### warning... the result from input will <str> on Python 3.x only
### in the case of Python 2.x, the result from input is the variable type <int>
### for the <str> type as the result for Python 2.x it's neccessary to use the another: raw_input()
temp_int = int(temperature[:-1]) # 25 <int> (as example)
temp_str = temperature[-1:] # "C" <str> (as example)
if temp_str.lower() == 'c':
print("Your temperature in Fahrenheit is: {}".format( (9/5 * temp_int) + 32 ) )
elif temp_str.lower() == 'f':
print("Your temperature in Celsius is: {}".format( ((5/9) * (temp_int - 32)) ) )
Refering to @BoltClock answer, here is my solution for a more complex recursive method:
http://jsfiddle.net/gx7so2tq/2/
It might not be the most pretty solution but it works fine for me and is quite flexible.
I use two data objects defining the container:
data-select-all="chapter1"
and the elements itself:
data-select-some="chapter1"
Both having the same value. The combination of both data-objects within one checkbox allows sublevels, which are scanned recursively. Therefore two "helper" functions are needed to prevent the change-trigger.
$("#div_element").load('script.php');
demo: http://sandbox.phpcode.eu/g/2ecbe/3
whole code:
<div id="submit">ajax</div>
<div id="div_element"></div>
<script>
$('#submit').click(function(event){
$("#div_element").load('script.php?html=some_arguments');
});
</script>
add this in web.config file
<configuration>
<appSettings>
<add key="ConnectionString" value="Your connection string which contains database id and password"/>
</appSettings>
</configuration>
.cs file
public ConnectionObjects()
{
string connectionstring= ConfigurationManager.AppSettings["ConnectionString"].ToString();
}
Hope this helps.
Your code is not doing what I think you think it is doing. The line for item in z:
will iterate through z
, each time making item
equal to one single element of z
. The original item
list is therefore overwritten before you've done anything with it.
I think you want something like this:
item = [0,1,2,3,4,5,6,7,8,9]
for element in item:
if element not in z:
print element
But you could easily do this like:
[x for x in item if x not in z]
or (if you don't mind losing duplicates of non-unique elements):
set(item) - set(z)
i recently experienced this issue when i was trying to build and suddenly the laptop battery ran out of charge. I just removed all the servers from eclipse and then restore it. after doing that, i re-built the war file and it worked.
Use moment-timezone
moment(date).tz('Europe/Berlin').format(format)
Before being able to access a particular timezone, you will need to load it like so (or using alternative methods described here)
moment.tz.add('Europe/Berlin|CET CEST CEMT|-10 -20 -30')
JavaScript's object literal syntax, which is typically used to instantiate objects (seriously, no one uses new Object
or new Array
), is as follows:
var obj = {
'key': 'value',
'another key': 'another value',
anUnquotedKey: 'more value!'
};
For arrays it's:
var arr = [
'value',
'another value',
'even more values'
];
If you need objects within objects, that's fine too:
var obj = {
'subObject': {
'key': 'value'
},
'another object': {
'some key': 'some value',
'another key': 'another value',
'an array': [ 'this', 'is', 'ok', 'as', 'well' ]
}
}
This convenient method of being able to instantiate static data is what led to the JSON data format.
JSON is a little more picky, keys must be enclosed in double-quotes, as well as string values:
{"foo":"bar", "keyWithIntegerValue":123}
I was Working with Elastic SQL plugin. Query is done with GET method using cURL as below:
curl -XGET http://localhost:9200/_sql/_explain -H 'Content-Type: application/json' \
-d 'SELECT city.keyword as city FROM routes group by city.keyword order by city'
I exposed a custom port at public server, doing a reverse proxy with Basic Auth set.
This code, works fine plus Basic Auth Header:
$host = 'http://myhost.com:9200';
$uri = "/_sql/_explain";
$auth = "john:doe";
$data = "SELECT city.keyword as city FROM routes group by city.keyword order by city";
function restCurl($host, $uri, $data = null, $auth = null, $method = 'DELETE'){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host.$uri);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($method == 'POST')
curl_setopt($ch, CURLOPT_POST, 1);
if ($auth)
curl_setopt($ch, CURLOPT_USERPWD, $auth);
if (strlen($data) > 0)
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$resp = curl_exec($ch);
if(!$resp){
$resp = (json_encode(array(array("error" => curl_error($ch), "code" => curl_errno($ch)))));
}
curl_close($ch);
return $resp;
}
$resp = restCurl($host, $uri); //DELETE
$resp = restCurl($host, $uri, $data, $auth, 'GET'); //GET
$resp = restCurl($host, $uri, $data, $auth, 'POST'); //POST
$resp = restCurl($host, $uri, $data, $auth, 'PUT'); //PUT
This is my code:
try {_x000D_
String folderPath = "../" + filePath.trim() + "/";_x000D_
logger.info("Path: " + folderPath);_x000D_
File folder = new File(folderPath);_x000D_
File[] listOfFiles = folder.listFiles();_x000D_
int length = listOfFiles.length;_x000D_
logger.info("So luong files: " + length);_x000D_
ArrayList<CdrFileBO> lstFile = new ArrayList< CdrFileBO>();_x000D_
_x000D_
if (listOfFiles != null && length > 0) {_x000D_
int count = 0;_x000D_
for (int i = 0; i < length; i++) {_x000D_
if (listOfFiles[i].isFile()) {_x000D_
lstFile.add(new CdrFileBO(listOfFiles[i]));_x000D_
}_x000D_
}_x000D_
Collections.sort(lstFile);_x000D_
for (CdrFileBO bo : lstFile) {_x000D_
//String newName = START_NAME + "_" + getSeq(SEQ_START) + "_" + DateSTR + ".s";_x000D_
String newName = START_NAME + DateSTR + getSeq(SEQ_START) + ".DAT";_x000D_
SEQ_START = SEQ_START + 1;_x000D_
bo.getFile().renameTo(new File(folderPath + newName));_x000D_
logger.info("newName: " + newName);_x000D_
logger.info("Next file: " + getSeq(SEQ_START));_x000D_
}_x000D_
_x000D_
}_x000D_
} catch (Exception ex) {_x000D_
logger.error(ex);_x000D_
ex.printStackTrace();_x000D_
}
_x000D_
Why don't you build a DataTable
first then assign it to the DataGridView
as DataSource
:
DataTable table4DataSource=new DataTable();
table4DataSource.Columns.Add("col00");
table4DataSource.Columns.Add("col01");
table4DataSource.Columns.Add("col02");
...
(add your rows, manually, in a circle or via a DataReader
from a database table)
(assign the datasource)
dtGrdViewGrid.DataSource = table4DataSource;
and then use:
(dtGrdViewGrid.DataSource as DataTable).DefaultView.RowFilter = "col00 = '" + textBoxSearch.Text+ "'";
dtGrdViewGrid.Refresh();
You can even put this piece of code within your textbox_textchange
event and your filtered values will be showing as you write.
While @Eli is quite correct that there usually isn't much of a need to do it, it is possible. savefig
takes a bbox_inches
argument that can be used to selectively save only a portion of a figure to an image.
Here's a quick example:
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')
ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')
# Save the full figure...
fig.savefig('full_figure.png')
# Save just the portion _inside_ the second axis's boundaries
extent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)
# Pad the saved area by 10% in the x-direction and 20% in the y-direction
fig.savefig('ax2_figure_expanded.png', bbox_inches=extent.expanded(1.1, 1.2))
The full figure:
Area inside the second subplot:
Area around the second subplot padded by 10% in the x-direction and 20% in the y-direction:
Invoke it from the shell, with an argument like /?
or --help
. Those are the usual help switches.
You can create button in a simple way, such as:
Button button = new Button();
button.Click += new EventHandler(button_Click);
protected void button_Click (object sender, EventArgs e)
{
Button button = sender as Button;
// identify which button was clicked and perform necessary actions
}
But event probably will not fire, because the element/elements must be recreated at every postback or you will lose the event handler.
I tried this solution that verify that ViewState is already Generated and recreate elements at every postback,
for example, imagine you create your button on an event click:
protected void Button_Click(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) != "true")
{
CreateDynamicElements();
}
}
on postback, for example on page load, you should do this:
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) == "true") {
CreateDynamicElements();
}
}
In CreateDynamicElements() you can put all the elements you need, such as your button.
This worked very well for me.
public void CreateDynamicElements(){
Button button = new Button();
button.Click += new EventHandler(button_Click);
}
NA is a special value in R, do not mix up the NA value with the "NA" string. Depending on the way the data was imported, your "NA" and "NULL" cells may be of various type (the default behavior is to convert "NA" strings to NA values, and let "NULL" strings as is).
If using read.table() or read.csv(), you should consider the "na.strings" argument to do clean data import, and always work with real R NA values.
An example, working in both cases "NULL" and "NA" cells :
DF <- read.csv("file.csv", na.strings=c("NA", "NULL"))
new_DF <- subset(DF, is.na(DF$Var2))
Try using
git push --set-upstream origin <branch_name>
Otherwise
use
git push -u
will tell you what needs to be done.
This also works on MAC OS:
Press for select specific Tab: Control + 1 or Control 2, Control 3, etc.
Press for show/select all posible Tabs: Control + Tab.
If you don't want to use List:
var foos = new List<Foo>(array);
foos.RemoveAt(index);
return foos.ToArray();
You could try this extension method that I haven't actually tested:
public static T[] RemoveAt<T>(this T[] source, int index)
{
T[] dest = new T[source.Length - 1];
if( index > 0 )
Array.Copy(source, 0, dest, 0, index);
if( index < source.Length - 1 )
Array.Copy(source, index + 1, dest, index, source.Length - index - 1);
return dest;
}
And use it like:
Foo[] bar = GetFoos();
bar = bar.RemoveAt(2);