The reason Python 3.5 environment is unable to import Tensorflow is that Anaconda does not store the tensorflow package in the same environment.
One solution is to create a new separate environment in Anaconda dedicated to TensorFlow with its own Spyder
conda create -n newenvt anaconda python=3.5
activate newenvt
and then install tensorflow into newenvt
I found this primer helpful
My system version: ubuntu 20.04 LTS.
I solved this by generate a new MOK and enroll it into shim.
Without disable of Secure Boot, although it also really works for me.
Simply execute this command and follow what it suggests:
sudo update-secureboot-policy --enroll-key
According to ubuntu's wiki: How can I do non-automated signing of drivers
"Wokbench.panel.defaultLocation": "right"
Open settings using CTRL+.
, search for terminal
and you should see this setting at the top. From the drop down below the settings explanation, choose right. See the screenshot below.
Another special case:
I had the problem using tox. So my program ran fine, but unittests via tox kept complaining. After installing packages (needed for the program) you need to additionally specify the packages used in the unittests in the tox.ini
[testenv]
deps =
package1
package2
...
Firstly make sure that you have installed python 2.7 or higher
Open Command Prompt as administrator and change directory to python and then change directory to Scripts by typing cd Scripts then type pip.exe and now you can install modules Step by Step:
Open Cmd
type in "cd \" and then enter
type in "cd python2.7" and then enter
Note that my python version is 2.7 so my directory is that so use your python folder here...
type in "cd Scripts" and enter
Now enter this "pip.exe"
Now it prompts you to install modules
I would suggest adding class no-js
to your html to nest your CSS selectors under it like:
.loading {
display: none;
}
.no-js .loading {
display: block;
//....
}
and when you finish loading your credit code remove it:
$('html').removeClass('no-js');
This will hide your loading spinner as there's no no-js
class in html it means you already loaded your credit code
I had the same issue. I solved it by running the command in a different python version. I tried python3 filename.py
. Earlier i was using Python 2.7.
Another possibility is that the file from which something is imported may contain BOM (Byte Order Mark). It can be solved by opening the file in some editor which supports multiple encoding like VSCode (Notepad++) and saving in a different encoding statndard like ANSI, UTF-8(without BOM).
You're declaring a virtual
function and not defining it:
virtual void calculateCredits();
Either define it or declare it as:
virtual void calculateCredits() = 0;
Or simply:
virtual void calculateCredits() { };
Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table
On Debian 7 Wheezy, I had to do:
pip install --upgrade dnspython
even if python-dns package was installed.
If you want to have cd functionality (assuming shell=True) and still want to change the directory in terms of the Python script, this code will allow 'cd' commands to work.
import subprocess
import os
def cd(cmd):
#cmd is expected to be something like "cd [place]"
cmd = cmd + " && pwd" # add the pwd command to run after, this will get our directory after running cd
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # run our new command
out = p.stdout.read()
err = p.stderr.read()
# read our output
if out != "":
print(out)
os.chdir(out[0:len(out) - 1]) # if we did get a directory, go to there while ignoring the newline
if err != "":
print(err) # if that directory doesn't exist, bash/sh/whatever env will complain for us, so we can just use that
return
The issue is that you are trying to have multiple statements in an if
without using {}
.
What you currently have is interpreted like:
if( choice==5 )
{
System.out.println( ... );
}
break;
else
{
//...
}
You really want:
if( choice==5 )
{
System.out.println( ... );
break;
}
else
{
//...
}
Also, as Farce has stated, it would be better to use else if
for all the conditions instead of if
because if choice==1
, it will still go through and check if choice==5
, which would fail, and it will still go into your else block.
if( choice==1 )
//...
else if( choice==2 )
//...
else if( choice==3 )
//...
else if( choice==4 )
//...
else if( choice==5 )
{
//...
}
else
//...
A more elegant solution would be using a switch
statement. However, break
only breaks from the most inner "block" unless you use labels. So you want to label your loop and break from that if the case is 5:
LOOP:
for(;;)
{
System.out.println("---> Your choice: ");
choice = input.nextInt();
switch( choice )
{
case 1:
playGame();
break;
case 2:
loadGame();
break;
case 2:
options();
break;
case 4:
credits();
break;
case 5:
System.out.println("End of Game\n Thank you for playing with us!");
break LOOP;
default:
System.out.println( ... );
}
}
Instead of labeling the loop, you could also use a flag to tell the loop to stop.
bool finished = false;
while( !finished )
{
switch( choice )
{
// ...
case 5:
System.out.println( ... )
finished = true;
break;
// ...
}
}
You need to import the module datetime
first:
>>> import datetime
After that it works:
>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2013, 11, 12)
Verify current version of python by:
$ python --version
then check python is symbolic link to which file.
$ ll /usr/bin/python
Output Ex:
lrwxrwxrwx 1 root root 9 Jun 16 2014 /usr/bin/python -> python2.7*
Check other available versions of python:
$ ls /usr/bin/python*
Output Ex:
/usr/bin/python /usr/bin/python2.7-config /usr/bin/python3.4 /usr/bin/python3.4m-config /usr/bin/python3.6m /usr/bin/python3m
/usr/bin/python2 /usr/bin/python2-config /usr/bin/python3.4-config /usr/bin/python3.6 /usr/bin/python3.6m-config /usr/bin/python3m-config
/usr/bin/python2.7 /usr/bin/python3 /usr/bin/python3.4m /usr/bin/python3.6-config /usr/bin/python3-config /usr/bin/python-config
If want to change current version of python to 3.6 version edit file ~/.bashrc:
vim ~/.bashrc
add below line in the end of file and save:
alias python=/usr/local/bin/python3.6
To install pip for python 3.6
$ sudo apt-get install python3.6 python3.6-dev
$ sudo curl https://bootstrap.pypa.io/ez_setup.py -o - | sudo python3.6
$ sudo easy_install pip
On Success, check current version of pip:
$ pip3 -V
Output Ex:
pip 1.5.4 from /usr/lib/python3/dist-packages (python 3.6)
In my case charset, datatype every thing was correct. After investigation I found that in parent table there was no index on foreign key column. Once added problem got solved.
I had the same problem and discovered that Pygame
doesn't work for Python3 at least on the Mac OS, but I also have Tython2
installed in my computer as you probably do too, so when I use Pygame
, I switch the path so that it uses python2 instead of python3. I use Sublime Text as my text editor so I just go to
Tools
> Build Systems
> New Build System
and enter the following:
{
"cmd": ["/usr/local/bin/python", "-u", "$file"],
}
instead of
{
"cmd": ["/usr/local/bin/python3", "-u", "$file"],
}
in my case. And when I'm not using pygame
, I simply change the path back so that I can use Python3.
The normal way to install Python libraries is with pip. Your way of installing it for Python 3.2 works because it's the system Python, and that's the way to install things for system-provided Pythons on Debian-based systems.
If your Python 3.3 is system-provided, you should probably use a similar command. Otherwise you should probably use pip.
I took my Python 3.3 installation, created a virtualenv and run pip install in it, and that seems to have worked as expected:
$ virtualenv-3.3 testenv
$ cd testenv
$ bin/pip install numpy
blablabl
$ bin/python3
Python 3.3.2 (default, Jun 17 2013, 17:49:21)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>>
Straight from the horse's mouth:
If you prefer to have dict-like view of the attributes, you can use the standard Python idiom,
vars()
:>>> parser = argparse.ArgumentParser() >>> parser.add_argument('--foo') >>> args = parser.parse_args(['--foo', 'BAR']) >>> vars(args) {'foo': 'BAR'}
— The Python Standard Library, 16.4.4.6. The Namespace object
Use decode
:
print(curses.version.decode())
# 2.2
If you're using Angular's ng-repeat to populate the table hackel's jquery snippet will not work by placing it in the document load event. You'll need to run the snippet after angular has finished rendering the table.
To trigger an event after ng-repeat has rendered try this directive:
var app = angular.module('myapp', [])
.directive('onFinishRender', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
$timeout(function () {
scope.$emit('ngRepeatFinished');
});
}
}
}
});
Complete example in angular: http://jsfiddle.net/ADukg/6880/
I got the directive from here: Use AngularJS just for routing purposes
Python, at startup, loads a bunch of values into sys.path
(which is "implemented" via a list of strings), including:
$PYTHONPATH
rcfiles
)$PYTHONPATH
is only one part of the eventual value of sys.path
.
If you're after the value of sys.path
, the best way would be to ask Python (thanks @Codemonkey):
python -c "import sys; print sys.path"
If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user
, picked from your example), then the syntax is quite simple:
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin('a.user', 'u')
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
Since you are applying a condition on the joined result here, using a LEFT JOIN
or simply JOIN
is the same.
If no association is available, then the query looks like following
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin(
'User\Entity\User',
'u',
\Doctrine\ORM\Query\Expr\Join::WITH,
'a.user = u.id'
)
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
This will produce a resultset that looks like following:
array(
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
// ...
)
The Python import mechanism works, really, so, either:
Don't know if you solved the problem but if anyone has this problem in future.
$python
>>import numpy
>>print(numpy)
Go to the location printed and delete the numpy
installation found there. You can then use pip
or easy_install
I was getting the same type of error, and I found that the console is not capable of displaying the string in another language. Hence I made the below code changes to set default_charset as UTF-8.
data_head = [('\x81\xa1\x8fo\x89\xef\x82\xa2\x95\xdb\x8f\xd8\x90\xa7\x93x\x81\xcb3\x8c\x8e\x8cp\x91\xb1\x92\x86(\x81\x86\x81\xde\x81\x85)\x81\xa1\x8f\x89\x89\xf1\x88\xc8\x8aO\x81A\x82\xa8\x8b\xe0\x82\xcc\x90S\x94z\x82\xcd\x88\xea\x90\xd8\x95s\x97v\x81\xa1\x83}\x83b\x83v\x82\xcc\x82\xa8\x8e\x8e\x82\xb5\x95\xdb\x8c\xaf\x82\xc5\x8fo\x89\xef\x82\xa2\x8am\x92\xe8\x81\xa1', 'shift_jis')]
default_charset = 'UTF-8' #can also try 'ascii' or other unicode type
print ''.join([ unicode(lin[0], lin[1] or default_charset) for lin in data_head ])
Also, you can do:
b = list(a)
This will work for any sequence, even those that don't support indexers and slices...
Here is the syntax to create a trigger:
CREATE TRIGGER trigger_name
ON { table | view }
[ WITH ENCRYPTION ]
{
{ { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
[ WITH APPEND ]
[ NOT FOR REPLICATION ]
AS
[ { IF UPDATE ( column )
[ { AND | OR } UPDATE ( column ) ]
[ ...n ]
| IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask )
{ comparison_operator } column_bitmask [ ...n ]
} ]
sql_statement [ ...n ]
}
}
If you want to use On Update you only can do it with the IF UPDATE ( column )
section. That's not possible to do what you are asking.
create view view_clients_credit_usage as
select client_id, sum(credits_used) as credits_used
from credit_usage
group by client_id
create view view_credit_status as
select
credit_orders.client_id,
sum(credit_orders.number_of_credits) as purchased,
ifnull(t1.credits_used,0) as used
from credit_orders
left outer join view_clients_credit_usage as t1 on t1.client_id = credit_orders.client_id
where credit_orders.payment_status='Paid'
group by credit_orders.client_id)
After looking on the accepted answer I realized that if know size of required vector then we have to use a loop to initialize every element
But I found new to do this using default_structure_element like following...
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
typedef struct subject {
string name;
int marks;
int credits;
}subject;
int main(){
subject default_subject;
default_subject.name="NONE";
default_subject.marks = 0;
default_subject.credits = 0;
vector <subject> sub(10,default_subject); // default_subject to initialize
//to check is it initialised
for(ll i=0;i<sub.size();i++) {
cout << sub[i].name << " " << sub[i].marks << " " << sub[i].credits << endl;
}
}
Then I think its good to way to initialize a vector of the struct, isn't it?
Python 3.9 adds the zoneinfo
module so now only the standard library is needed!
from zoneinfo import ZoneInfo
from datetime import datetime
unaware = datetime(2020, 10, 31, 12)
Attach a timezone:
>>> unaware.replace(tzinfo=ZoneInfo('Asia/Tokyo'))
datetime.datetime(2020, 10, 31, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='Asia/Tokyo'))
>>> str(_)
'2020-10-31 12:00:00+09:00'
Attach the system's local timezone:
>>> unaware.replace(tzinfo=ZoneInfo('localtime'))
datetime.datetime(2020, 10, 31, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='localtime'))
>>> str(_)
'2020-10-31 12:00:00+01:00'
Subsequently it is properly converted to other timezones:
>>> unaware.replace(tzinfo=ZoneInfo('localtime')).astimezone(ZoneInfo('Asia/Tokyo'))
datetime.datetime(2020, 10, 31, 20, 0, tzinfo=backports.zoneinfo.ZoneInfo(key='Asia/Tokyo'))
>>> str(_)
'2020-10-31 20:00:00+09:00'
Wikipedia list of available time zones
Windows has no system time zone database, so here an extra package is needed:
pip install tzdata
There is a backport to allow use of zoneinfo
in Python 3.6 to 3.8:
pip install backports.zoneinfo
Then:
from backports.zoneinfo import ZoneInfo
I was also facing the same problem and solved through making column as nullable using "?" operator.
Sequnce = db.mstquestionbanks.Where(x => x.IsDeleted == false && x.OrignalFormID == OriginalFormIDint).Select(x=><b>(int?)x.Sequence</b>).Max().ToString();
Sometimes null is returned.
sudo apt-get install python3-tk
So appearantly many seems to have had this issue (me including) and I found the fault to be that Tkinter wasn't installed on my system when python was compiled.
This post describes how to solve the problem by:
sudo apt-get install tk-dev
(for deb) or sudo pacman -S tk
(for arch/manjaro)This worked wonders for me.
You need to use the matplotlib API directly rather than going through the pylab interface. There's a good example here:
http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html
If a class doesn't have any constructor provided by programmer, then java compiler will add a default constructor with out parameters which will call super class constructor internally with super() call. This is called as default constructor.
In your case, there is no default constructor as you are adding them programmatically. If there are no constructors added by you, then compiler generated default constructor will look like this.
public Module()
{
super();
}
Note: In side default constructor, it will add super() call also, to call super class constructor.
Purpose of adding default constructor:
Constructor's duty is to initialize instance variables, if there are no instance variables you could choose to remove constructor from your class. But when you are inheriting some class it is your class responsibility to call super class constructor to make sure that super class initializes all its instance variables properly.
That's why if there are no constructors, java compiler will add a default constructor and calls super class constructor.
it is control + p in Mac os in python 3.4 IDEL
If you are using push to push the data to the option.series dynamically .. just use
options.series = [];
to clear it.
options.series = [];
$("#change").click(function(){
}
Add CDATA to your string resource
Strings.xml
<string name="txtCredits"><![CDATA[<a href=\"http://www.google.com\">Google</a>]]></string>
If you're able to control the xml file, try adding a bit more information to the beginning of the file:
<?xml version="1.0" encoding="UTF-16" standalone="no"?>
Unofficial 64-bit installers for NumPy and SciPy are available at http://www.lfd.uci.edu/~gohlke/pythonlibs/
Make sure that you download & install the packages (aka. wheels) that match your CPython version and bitness (ie. cp35
= Python v3.5; win_amd64
= x86_64).
You'll want to install NumPy first; From a CMD prompt with administrator privileges for a system-wide (aka. Program Files) install:
C:\>pip install numpy-<version>+mkl-cp<ver-spec>-cp<ver-spec>m-<cpu-build>.whl
Or include the --user
flag to install to the current user's application folder (Typically %APPDATA%\Python
on Windows) from a non-admin CMD prompt:
C:\>pip install --user numpy-<version>+mkl-cp<ver-spec>-cp<ver-spec>m-<cpu-build>.whl
Then do the same for SciPy:
C:\>pip install [--user] scipy-<version>-cp<ver-spec>-cp<ver-spec>m-<cpu-build>.whl
Don't forget to replace <version>
, <ver-spec>
, and <cpu-build>
appropriately if you copy & paste any of these examples. And also that you must use the numpy & scipy packages from the ifd.uci.edu link above (or else you will get errors if you try to mix & match incompatible packages -- uninstall any conflicting packages first [ie. pip list
]).
The accepted answer already mentions PEP 238. I just want to add a quick look behind the scenes for those interested in what's going on without reading the whole PEP.
Python maps operators like +
, -
, *
and /
to special functions, such that e.g. a + b
is equivalent to
a.__add__(b)
Regarding division in Python 2, there is by default only /
which maps to __div__
and the result is dependent on the input types (e.g. int
, float
).
Python 2.2 introduced the __future__
feature division
, which changed the division semantics the following way (TL;DR of PEP 238):
/
maps to __truediv__
which must "return a reasonable approximation of
the mathematical result of the division" (quote from PEP 238)//
maps to __floordiv__
, which should return the floored result of /
With Python 3.0, the changes of PEP 238 became the default behaviour and there is no more special method __div__
in Python's object model.
If you want to use the same code in Python 2 and Python 3 use
from __future__ import division
and stick to the PEP 238 semantics of /
and //
.
Have you installed it?
On debian/ubuntu:
aptitude install python-numpy
On windows:
http://sourceforge.net/projects/numpy/files/NumPy/
On other systems:
http://sourceforge.net/projects/numpy/files/NumPy/
$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install
my python is build from source, the cause is missing options when exec configure python version:3.7.4
./configure --enable-loadable-sqlite-extensions --enable-optimizations
make
make install
fixed
Summing up what others have said, as of Python 3, Ellipsis is essentially another singleton constant similar to None
, but without a particular intended use. Existing uses include:
Callable[..., int]
or Tuple[str, ...]
)Possible uses could include:
None
is a valid optionYou set an element's id by setting its corresponding property:
myPara.id = ID;
If you're using greasemonkey, it's possible the page isn't ready for the javascript yet. You may need to use window.onReady.
var inputs;
function doThisWhenReady() {
inputs = document.getElementsByTagName('input');
//Other code here...
}
window.onReady = doThisWhenReady;
I got this error message when "/" from my URL is missing . Hope this help someone.
ex: actual URL is "https://www.myweb.com/login" .My URL which "https://www.myweb.comlogin" caused this error
Is it really necessary for you to get a physical path?
For example, ImageView.setImageURI()
and ContentResolver.openInputStream()
allow you to access the contents of a file without knowing its real path.
You can make a batch file, that will open your emulator directly without opening Android Studio. If you are using Windows:
Open Notepad
New file
Copy the next lines into your file:
cd /d C:\Users\%username%\AppData\Local\Android\sdk\tools
emulator @[YOUR_EMULATOR_DEVICE_NAME]
Notes:
Replace [YOUR_EMULATOR_DEVICE_NAME]
with the device name you created in emulator
To get the device name go to: C:\Users\%username%\AppData\Local\Android\sdk\tools
Run cmd
and type: emulator -list-avds
Copy the device name and paste it in the batch file
Save the file as emulator.bat
and close
Now double click on emulator.bat
and you got the emulator running!
You can use ANSI colour codes.
use these functions.
enum c_color{BLACK=30,RED=31,GREEN=32,YELLOW=33,BLUE=34,MAGENTA=35,CYAN=36,WHITE=37};
enum c_decoration{NORMAL=0,BOLD=1,FAINT=2,ITALIC=3,UNDERLINE=4,RIVERCED=26,FRAMED=51};
void pr(const string str,c_color color,c_decoration decoration=c_decoration::NORMAL){
cout<<"\033["<<decoration<<";"<<color<<"m"<<str<<"\033[0m";
}
void prl(const string str,c_color color,c_decoration decoration=c_decoration::NORMAL){
cout<<"\033["<<decoration<<";"<<color<<"m"<<str<<"\033[0m"<<endl;
}
You have to use the NotifyIcon control from System.Windows.Forms, or alternatively you can use the Notify Icon API provided by Windows API. WPF Provides no such equivalent, and it has been requested on Microsoft Connect several times.
I have code on GitHub which uses System.Windows.Forms
NotifyIcon Component from within a WPF application, the code can be viewed at https://github.com/wilson0x4d/Mubox/blob/master/Mubox.QuickLaunch/AppWindow.xaml.cs
Here are the summary bits:
Create a WPF Window with ShowInTaskbar=False, and which is loaded in a non-Visible State.
At class-level:
private System.Windows.Forms.NotifyIcon notifyIcon = null;
During OnInitialize():
notifyIcon = new System.Windows.Forms.NotifyIcon();
notifyIcon.Click += new EventHandler(notifyIcon_Click);
notifyIcon.DoubleClick += new EventHandler(notifyIcon_DoubleClick);
notifyIcon.Icon = IconHandles["QuickLaunch"];
During OnLoaded():
notifyIcon.Visible = true;
And for interaction (shown as notifyIcon.Click and DoubleClick above):
void notifyIcon_Click(object sender, EventArgs e)
{
ShowQuickLaunchMenu();
}
From here you can resume the use of WPF Controls and APIs such as context menus, pop-up windows, etc.
It's that simple. You don't exactly need a WPF Window to host to the component, it's just the most convenient way to introduce one into a WPF App (as a Window is generally the default entry point defined via App.xaml), likewise, you don't need a WPF Wrapper or 3rd party control, as the SWF component is guaranteed present in any .NET Framework installation which also has WPF support since it's part of the .NET Framework (which all current and future .NET Framework versions build upon.) To date, there is no indication from Microsoft that SWF support will be dropped from the .NET Framework anytime soon.
Hope that helps.
It's a little cheese that you have to use a pre-3.0 Framework Component to get a tray-icon, but understandably as Microsoft has explained it, there is no concept of a System Tray within the scope of WPF. WPF is a presentation technology, and Notification Icons are an Operating System (not a "Presentation") concept.
This is using Gson in Kotlin
val listString = "[uno,dos,tres,cuatro,cinco]"
val gson = Gson()
val lista = gson.fromJson(listString , Array<String>::class.java).toList()
Log.e("GSON", lista[0])
You can also use npm package called esm which allows you to use ES6 modules in Node.js. It needs no configuration. With esm you will be able to use export/import in your JavaScript files.
Run the following command on your terminal
yarn add esm
or
npm install esm
After that, you need to require this package when starting your server with node. For example if your node server runs index.js file, you would use the command
node -r esm index.js
You can also add it in your package.json file like this
{
"name": "My-app",
"version": "1.0.0",
"description": "Some Hack",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node -r esm index.js"
},
}
Then run this command from the terminal to start your node server
npm start
Check this link for more details.
Assuming the column is set to support NULL as a value:
UPDATE YOUR_TABLE
SET column = NULL
Be aware of the database NULL handling - by default in SQL Server, NULL is an INT. So if the column is a different data type you need to CAST/CONVERT NULL to the proper data type:
UPDATE YOUR_TABLE
SET column = CAST(NULL AS DATETIME)
...assuming column
is a DATETIME data type in the example above.
Just catch your exception and do proper exception handling:
if (cost !=null && !"".equals(cost) ){
try {
Integer intCost = Integer.parseInt(cost);
List<Book> books = bookService . findBooksCheaperThan(intCost);
} catch (NumberFormatException e) {
System.out.println("This is not a number");
System.out.println(e.getMessage());
}
}
As far as I know, the order of the repositories in your pom.xml will also decide the order of the repository access.
As for configuring repositories in settings.xml, I've read that the order of repositories is interestingly enough the inverse order of how the repositories will be accessed.
Here a post where someone explains this curiosity:
http://community.jboss.org/message/576851
There is no data types for that.. You need to store it as VARCHAR or TEXT only.. jsonObject.toString();
Try this
SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID=@id", con);
cmd.Parameters.AddWithValue("id", id.Text);
If you are using python3 on windows then you might do this as well
pip3 install tensorflow==1.4
you may select any version from "(from versions: 1.2.0rc2, 1.2.0, 1.2.1, 1.3.0rc0, 1.3.0rc1, 1.3.0rc2, 1.3.0, 1.4.0rc0, 1.4.0rc1, 1.4.0, 1.5.0rc0, 1.5.0rc1, 1.5.0, 1.5.1, 1.6.0rc0, 1.6.0rc1, 1.6.0, 1.7.0rc0, 1.7.0rc1, 1.7.0)"
I did this when I wanted to downgrade from 1.7 to 1.4
However trivial this might be, check your Java installation. For me, rt.jar was missing.
I found this after fiddling for half a day with Eclipse settings and getting nowhere. Desperate, I finally decided to try compiling the project from the command line. I wasn't expecting to see anything wrong since I thought it's an Eclipse issue but to my astonishment I saw this:
Error occurred during initialization of VM
java/lang/NoClassDefFoundError: java/lang/Object
I don't know what happened to my Java installation and where did rt.jar go. Anyway this comes as a reminder to go through the fail checklist and tick all the boxes no matter how unbelievable they are. It would have saved me a lot of time.
I used the onscroll
event at the element with the scrollbar. When triggered in IE, I added the following validation:
onscroll="if (document.activeElement==this) ignoreHideOptions()"
I had a lot of trouble getting this to work. Dummy me, don't forget that old page - even for sub-requests - gets cached in your browser. Maybe obvious, but clear your browsers cache. After that, one can also use Header set Cache-Control "no-store"
This was helpful to me while testing.
My issue was, i am unable to create a view with my "scott" user in oracle 11g edition. So here is my solution for this
Error in my case
SQL>create view v1 as select * from books where id=10;
insufficient privileges.
Solution
1)open your cmd and change your directory to where you install your oracle database. in my case i was downloaded in E drive so my location is E:\app\B_Amar\product\11.2.0\dbhome_1\BIN> after reaching in the position you have to type sqlplus sys as sysdba
E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba
2) Enter password: here you have to type that password that you give at the time of installation of oracle software.
3) Here in this step if you want create a new user then you can create otherwise give all the privileges to existing user.
for creating new user
SQL> create user abc identified by xyz;
here abc is user and xyz is password.
giving all the privileges to abc user
SQL> grant all privileges to abc;
grant succeeded.
if you are seen this message then all the privileges are giving to the abc user.
4) Now exit from cmd, go to your SQL PLUS and connect to the user i.e enter your username & password.Now you can happily create view.
In My case
in cmd E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba
SQL> grant all privileges to SCOTT;
grant succeeded.
Now I can create views.
try this:
string.Format("{0:HH:mm:ss tt}", DateTime.Now);
for further details you can check it out : How do you get the current time of day?
Although the accepted response is a good answer, it overlooks failure scenarios. curl
will return 000
if there is an error in the request or there is a connection failure.
url='http://localhost:8080/'
status=$(curl --head --location --connect-timeout 5 --write-out %{http_code} --silent --output /dev/null ${url})
[[ $status == 500 ]] || [[ $status == 000 ]] && echo restarting ${url} # do start/restart logic
Note: this goes a little beyond the requested 500
status check to also confirm that curl
can even connect to the server (i.e. returns 000
).
Create a function from it:
failureCode() {
local url=${1:-http://localhost:8080}
local code=${2:-500}
local status=$(curl --head --location --connect-timeout 5 --write-out %{http_code} --silent --output /dev/null ${url})
[[ $status == ${code} ]] || [[ $status == 000 ]]
}
Test getting a 500
:
failureCode http://httpbin.org/status/500 && echo need to restart
Test getting error/connection failure (i.e. 000
):
failureCode http://localhost:77777 && echo need to start
Test not getting a 500
:
failureCode http://httpbin.org/status/400 || echo not a failure
s = set([1,2,3])
print [ x for x in iter(s) ]
System.Environment.TickCount and the System.Diagnostics.Stopwatch class are two that work well for finer resolution and straightforward usage.
See Also:
There are several ways to define "Balanced". The main goal is to keep the depths of all nodes to be O(log(n))
.
It appears to me that the balance condition you were talking about is for AVL tree.
Here is the formal definition of AVL tree's balance condition:
For any node in AVL, the height of its left subtree differs by at most 1 from the height of its right subtree.
Next question, what is "height"?
The "height" of a node in a binary tree is the length of the longest path from that node to a leaf.
There is one weird but common case:
People define the height of an empty tree to be
(-1)
.
For example, root's left child is null
:
A (Height = 2)
/ \
(height =-1) B (Height = 1) <-- Unbalanced because 1-(-1)=2 >1
\
C (Height = 0)
Two more examples to determine:
Yes, A Balanced Tree Example:
A (h=3)
/ \
B(h=1) C (h=2)
/ / \
D (h=0) E(h=0) F (h=1)
/
G (h=0)
No, Not A Balanced Tree Example:
A (h=3)
/ \
B(h=0) C (h=2) <-- Unbalanced: 2-0 =2 > 1
/ \
E(h=1) F (h=0)
/ \
H (h=0) G (h=0)
I had same problem and eventually found out that in file build.gradle the version does not match the version of buildTools in my installed sdk. (because I imported project done at home on different computed with updated sdk)
before:
build.gradle(app): buildToolsVersion "24.0.2"
Android\sdk\build-tools: file "25.0.1"
fixed: build.gradle(app): buildToolsVersion "25.0.1"
Then just sync your project with gradle files and it should work.
On Windows when you are using PowerShell you have to enclose all parameters with quotes.
So if you want to create a maven webapp archetype you would do as follows:
Prerequisites:
Howto:
Note: This is tested only on windows 10 powershell
use this coding
io.sockets.on('connection', function (socket) {
socket.on('mousemove', function (data) {
socket.broadcast.emit('moving', data);
});
this socket.broadcast.emit() will emit everthing in the function except to the server which is emitting
def reverse(text):
rev = ""
final = ""
for a in range(0,len(text)):
rev = text[len(text)-a-1]
final = final + rev
return final
$resource("../rest/api"}).get();
returns an object.
$resource("../rest/api").query();
returns an array.
You must use :
return $resource('../rest/api.php?method=getTask&q=*').query();
More info
To find a compiler, you'll have 1 per .net version installed, type in a command prompt.
dir c:\Windows\Microsoft.NET\vbc.exe /a/s
Windows Forms
For a Windows Forms version (no console window and we don't get around to actually creating any forms - though you can if you want).
Compile line in a command prompt.
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe "%userprofile%\desktop\VBS2Exe.vb"
Text for VBS2EXE.vb
Imports System.Windows.Forms
Partial Class MyForm : Inherits Form
Private Sub InitializeComponent()
End Sub
Public Sub New()
InitializeComponent()
End Sub
Public Shared Sub Main()
Dim sc as object
Dim Scrpt as string
sc = createObject("MSScriptControl.ScriptControl")
Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34)
With SC
.Language = "VBScript"
.UseSafeSubset = False
.AllowUI = True
End With
sc.addcode(Scrpt)
End Sub
End Class
Using these optional parameters gives you an icon and manifest. A manifest allows you to specify run as normal, run elevated if admin, only run elevated.
/win32icon: Specifies a Win32 icon file (.ico) for the default Win32 resources.
/win32manifest: The provided file is embedded in the manifest section of the output PE.
In theory, I have UAC off so can't test, but put this text file on the desktop and call it vbs2exe.manifest, save as UTF-8.
The command line
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" "%userprofile%\desktop\VBS2Exe.vb"
The manifest
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1"
manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0"
processorArchitecture="*" name="VBS2EXE" type="win32" />
<description>Script to Exe</description>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security> <requestedPrivileges>
<requestedExecutionLevel level="requireAdministrator"
uiAccess="false" /> </requestedPrivileges>
</security> </trustInfo> </assembly>
Hopefully it will now ONLY run as admin.
Give Access To a Host's Objects
Here's an example giving the vbscript access to a .NET object.
Imports System.Windows.Forms
Partial Class MyForm : Inherits Form
Private Sub InitializeComponent()
End Sub
Public Sub New()
InitializeComponent()
End Sub
Public Shared Sub Main()
Dim sc as object
Dim Scrpt as string
sc = createObject("MSScriptControl.ScriptControl")
Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34) & ":msgbox meScript.state"
With SC
.Language = "VBScript"
.UseSafeSubset = False
.AllowUI = True
.addobject("meScript", SC, true)
End With
sc.addcode(Scrpt)
End Sub
End Class
To Embed version info
Download vbs2exe.res file from https://skydrive.live.com/redir?resid=E2F0CE17A268A4FA!121 and put on desktop.
Download ResHacker from http://www.angusj.com/resourcehacker
Open vbs2exe.res file in ResHacker. Edit away. Click Compile button. Click File menu - Save.
Type
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" /win32resource:"%userprofile%\desktop\VBS2Exe.res" "%userprofile%\desktop\VBS2Exe.vb"
You can set the headers in PHP by using:
<?php
//set headers to NOT cache a page
header("Cache-Control: no-cache, must-revalidate"); //HTTP 1.1
header("Pragma: no-cache"); //HTTP 1.0
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
//or, if you DO want a file to cache, use:
header("Cache-Control: max-age=2592000"); //30days (60sec * 60min * 24hours * 30days)
?>
Note that the exact headers used will depend on your needs (and if you need to support HTTP 1.0 and/or HTTP 1.1)
You can change your model method to property and use it in serializer with this approach.
class Foo(models.Model):
. . .
@property
def my_field(self):
return stuff
. . .
class FooSerializer(ModelSerializer):
my_field = serializers.ReadOnlyField(source='my_field')
class Meta:
model = Foo
fields = ('my_field',)
Edit: With recent versions of rest framework (I tried 3.3.3), you don't need to change to property. Model method will just work fine.
fs.statSync(path, function(err, stat){
if(err == null) {
console.log('File exists');
//code when all ok
}else if (err.code == "ENOENT") {
//file doesn't exist
console.log('not file');
}
else {
console.log('Some other error: ', err.code);
}
});
Because the * is a shell construct. Python is literally looking for a file named "*" in the directory /home/me/test. Use listdir to get a list of the files first and then call remove on each one.
In case you need to parse it from a file, I find the best solution to use a HashMap<String, String>
to use it inside your java code for better manipultion.
Try out this code:
public HashMap<String, String> myMethodName() throws FileNotFoundException
{
String path = "absolute path to your file";
BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
Gson gson = new Gson();
HashMap<String, String> json = gson.fromJson(bufferedReader, HashMap.class);
return json;
}
Please install App Script for Ionic 3 Solution npm i -D -E @ionic/app-scripts
std::vector<int> return_vector(void)
{
std::vector<int> tmp {1,2,3,4,5};
return tmp;
}
std::vector<int> &&rval_ref = return_vector();
The first example returns a temporary which is caught by rval_ref
. That temporary will have its life extended beyond the rval_ref
definition and you can use it as if you had caught it by value. This is very similar to the following:
const std::vector<int>& rval_ref = return_vector();
except that in my rewrite you obviously can't use rval_ref
in a non-const manner.
std::vector<int>&& return_vector(void)
{
std::vector<int> tmp {1,2,3,4,5};
return std::move(tmp);
}
std::vector<int> &&rval_ref = return_vector();
In the second example you have created a run time error. rval_ref
now holds a reference to the destructed tmp
inside the function. With any luck, this code would immediately crash.
std::vector<int> return_vector(void)
{
std::vector<int> tmp {1,2,3,4,5};
return std::move(tmp);
}
std::vector<int> &&rval_ref = return_vector();
Your third example is roughly equivalent to your first. The std::move
on tmp
is unnecessary and can actually be a performance pessimization as it will inhibit return value optimization.
The best way to code what you're doing is:
std::vector<int> return_vector(void)
{
std::vector<int> tmp {1,2,3,4,5};
return tmp;
}
std::vector<int> rval_ref = return_vector();
I.e. just as you would in C++03. tmp
is implicitly treated as an rvalue in the return statement. It will either be returned via return-value-optimization (no copy, no move), or if the compiler decides it can not perform RVO, then it will use vector's move constructor to do the return. Only if RVO is not performed, and if the returned type did not have a move constructor would the copy constructor be used for the return.
I payed attention that lots of people are looking for strtolower()
in JavaScript. They are expecting the same function name as in other languages, that's why this post is here.
I would recommend using native Javascript function
"SomE StriNg".toLowerCase()
Here's the function that behaves exactly the same as PHP's one (for those who are porting PHP code into js)
function strToLower (str) {
return String(str).toLowerCase();
}
Just use resize: none
textarea {
resize: none;
}
You can also decide to resize your textareas only horizontal or vertical, this way:
textarea { resize: vertical; }
textarea { resize: horizontal; }
Finally,
resize: both
enables the resize grabber.
It is not possible. Otherwise you may need to use Silverlight or Flash upload control.
What is Spring for? I will answer that question shortly, but first, let's take another look at the example by victor hugo. It's not a great example because it doesn't justify the need for a new framework.
public class BaseView {
protected UserLister userLister;
public BaseView() {
userLister = new UserListerDB(); // only line of code that needs changing
}
}
public class SomeView extends BaseView {
public SomeView() {
super();
}
public void render() {
List<User> users = userLister.getUsers();
view.render(users);
}
}
Done! So now even if you have hundreds or thousands of views, you still just need to change the one line of code, as in the Spring XML approach. But changing a line of code still requires recompiling as opposed to editing XML you say? Well my fussy friend, use Ant and script away!
So what is Spring for? It's for:
Further reading: http://discuss.joelonsoftware.com/?joel.3.219431.12
To extend trigoman's answer (full credits to him) to work with POST (could also make work with PUT etc):
app.use('/api', function(req, res) {
var url = 'YOUR_API_BASE_URL'+ req.url;
var r = null;
if(req.method === 'POST') {
r = request.post({uri: url, json: req.body});
} else {
r = request(url);
}
req.pipe(r).pipe(res);
});
The most rapid option is to hand out MS Access or SQL Sever Management Studio (there's a free express edition) along with a read only account.
PHP is simple and has a well earned reputation for getting stuff done. PHP is excellent for copying and pasting code, and you can iterate insanely fast in PHP. PHP can lead to hard-to-maintain applications, and it can be difficult to set up a visual debugger.
Given that you use SQL Server, ASP.NET is also a good option. This is somewhat harder to setup; you'll need an IIS server, with a configured application. Iterations are a bit slower. ASP.NET is easier to maintain and Visual Studio is the best visual debugger around.
Here is a function I did to return a list with a string(s) inbetween string1 and string2 searched.
def GetListOfSubstrings(stringSubject,string1,string2):
MyList = []
intstart=0
strlength=len(stringSubject)
continueloop = 1
while(intstart < strlength and continueloop == 1):
intindex1=stringSubject.find(string1,intstart)
if(intindex1 != -1): #The substring was found, lets proceed
intindex1 = intindex1+len(string1)
intindex2 = stringSubject.find(string2,intindex1)
if(intindex2 != -1):
subsequence=stringSubject[intindex1:intindex2]
MyList.append(subsequence)
intstart=intindex2+len(string2)
else:
continueloop=0
else:
continueloop=0
return MyList
#Usage Example
mystring="s123y123o123pp123y6"
List = GetListOfSubstrings(mystring,"1","y68")
for x in range(0, len(List)):
print(List[x])
output:
mystring="s123y123o123pp123y6"
List = GetListOfSubstrings(mystring,"1","3")
for x in range(0, len(List)):
print(List[x])
output:
2
2
2
2
mystring="s123y123o123pp123y6"
List = GetListOfSubstrings(mystring,"1","y")
for x in range(0, len(List)):
print(List[x])
output:
23
23o123pp123
Since Ubuntu 16.04 includes snapd
by default.
So, the easiest way to install the stable version is
$ sudo snap install intellij-idea-community --classic
$ sudo snap install intellij-idea-ultimate --classic
For the latest version use channel --edge
$ sudo snap install intellij-idea-community --classic --edge
Here is the list of all channels https://snapcraft.io/intellij-idea-ultimate (drop down 'All versions').
--classic
The --classic option is required because the IntelliJ IDEA snap requires full access to the system, like a traditionally packaged application.
[https://www.jetbrains.com/help/idea/install-and-set-up-product.html#install-on-linux-with-snaps]
--edge
--edge Install from the edge channel [http://manpages.ubuntu.com/manpages/bionic/man1/snap.1.html]
Note: Snap, also work a few major distributions: Arch, Debian, Fedora, openSUSE, Linux Mint,...
If the size of the string is fixed, you might find easier to use an array of chars. If you have to do this a lot, it will be a tiny bit faster too.
char[] chars = new char[3];
chars[0] = 'i';
chars[1] = 'c';
chars[2] = 'e';
return new String(chars);
Also, I noticed in your original question, you use the Char class. If your chars are not nullable, it is better to use the lowercase char type.
Different way of counting by using bisect module:
>>> from bisect import bisect
>>> j = [4, 5, 6, 7, 1, 3, 7, 5]
>>> j.sort()
>>> b = 5
>>> index = bisect(j,b) #Find that index value
>>> print len(j)-index
3
Now Microsoft is migrating to open-source - see CoreFX (GitHub).
According to the Cloudera documentation - What's New in CDH 5.7.0 it includes Spark 1.6.0.
This post helped me. Thanks a lot.
On Linux (Ubuntu 12.10) I needed to run
sudo apt-get install ruby
sudo apt-get install rubygems
sudo apt-get install ruby-dev
before I could succesfully run
sudo gem install jekyll
I'd like to supplement BalusC's answer with the mapping rules and an example.
Mapping rules from Servlet 2.5 specification:
In our example, there're three servlets. / is the default servlet installed by us. Tomcat installs two servlets to serve jsp and jspx. So to map http://host:port/context/hello
To map http://host:port/context/hello.jsp
Since iOS 9, you need to add "App Transport Security Settings" to your info.plist file and allow "Allow Arbitrary Loads" before making request to non-secure HTTP web service. I had this issue in one of my app.
Maybe this will help someone. I was using a nested app. project.appname and I actually had project and project.appname in INSTALLED_APPS. Removing project from INSTALLED_APPS allowed the changes to be detected.
Here is another one liner:
[[ -d /tmp/test ]] && rm -r /tmp/test
summation
and your other functions are defined after they're used in main
, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.
You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.
Either move the function bodies before main
, or include method signatures before main
, e.g.:
#include <stdio.h>
int summation(int *, int *, int *);
int main()
{
// ...
Use net use
or New-PSDrive
to create a new drive:
New-PsDrive: create a new PsDrive only visible in PowerShell environment:
New-PSDrive -Name Y -PSProvider filesystem -Root \\ServerName\Share
Copy-Item BigFile Y:\BigFileCopy
Net use: create a new drive visible in all parts of the OS.
Net use y: \\ServerName\Share
Copy-Item BigFile Y:\BigFileCopy
That's the for each loop syntax. It is looping through each object in the collection returned by objectListing.getObjectSummaries()
.
The correct solution is a FullText Search (if you can use it) https://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html
This nearly does what you want:
SELECT * FROM buckets WHERE bucketname RLIKE '(Stylus|2100)+.*(Stylus|2100)+';
SELECT * FROM buckets WHERE bucketname RLIKE '(Stylus|2100|photo)+.*(Stylus|2100|photo)+.*(Stylus|2100|photo)+.*';
But this will also match "210021002100" which is not great.
You basically need to run the installation again to rebuild the master
database with the new collation. You cannot change the entire server's collation any other way.
See:
Update: if you want to change the collation of a database, you can get the current collation using this snippet of T-SQL:
SELECT name, collation_name
FROM sys.databases
WHERE name = 'test2' -- put your database name here
This will yield a value something like:
Latin1_General_CI_AS
The _CI
means "case insensitive" - if you want case-sensitive, use _CS
in its place:
Latin1_General_CS_AS
So your T-SQL command would be:
ALTER DATABASE test2 -- put your database name here
COLLATE Latin1_General_CS_AS -- replace with whatever collation you need
You can get a list of all available collations on the server using:
SELECT * FROM ::fn_helpcollations()
You can see the server's current collation using:
SELECT SERVERPROPERTY ('Collation')
I'm didn't totally follow, but to add an action listener, you just call addActionListener (from Abstract Button). If this doesn't totally answer your question, can you provide some more details?
I am using Jackson 1.9.7 and I found that doing the following does not solve my serialization/deserialization timezone issue:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
objectMapper.setDateFormat(dateFormat);
Instead of "2014-02-13T20:09:09.859Z" I get "2014-02-13T08:09:09.859+0000" in the JSON message which is obviously incorrect. I don't have time to step through the Jackson library source code to figure out why this occurs, however I found that if I just specify the Jackson provided ISO8601DateFormat
class to the ObjectMapper.setDateFormat
method the date is correct.
Except this doesn't put the milliseconds in the format which is what I want so I sub-classed the ISO8601DateFormat
class and overrode the format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition)
method.
/**
* Provides a ISO8601 date format implementation that includes milliseconds
*
*/
public class ISO8601DateFormatWithMillis extends ISO8601DateFormat {
/**
* For serialization
*/
private static final long serialVersionUID = 2672976499021731672L;
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition)
{
String value = ISO8601Utils.format(date, true);
toAppendTo.append(value);
return toAppendTo;
}
}
I give you the answer in both Objective C and Swift.Before that I want to say
If we use the
dequeueReusableCellWithIdentifier:forIndexPath:
,we must register a class or nib file using the registerNib:forCellReuseIdentifier: or registerClass:forCellReuseIdentifier: method before calling this method as Apple Documnetation Says
So we add registerNib:forCellReuseIdentifier: or registerClass:forCellReuseIdentifier:
Once we registered a class for the specified identifier and a new cell must be created, this method initializes the cell by calling its initWithStyle:reuseIdentifier: method. For nib-based cells, this method loads the cell object from the provided nib file. If an existing cell was available for reuse, this method calls the cell’s prepareForReuse method instead.
in viewDidLoad method we should register the cell
Objective C
OPTION 1:
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
OPTION 2:
[self.tableView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellReuseIdentifier:@"cell"];
in above code nibWithNibName:@"CustomCell"
give your nib name instead of my nib name CustomCell
SWIFT
OPTION 1:
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
OPTION 2:
tableView.registerNib(UINib(nibName: "NameInput", bundle: nil), forCellReuseIdentifier: "Cell")
in above code nibName:"NameInput"
give your nib name
Array: [1, 2, 3, 4]
Result: ["foo1", "foo2", "foo3", "foo4"]
Array.prototype.map()
Keep original arrayconst originalArr = ["Iron", "Super", "Ant", "Aqua"];
const modifiedArr = originalArr.map(name => `${name}man`);
console.log( "Original: %s", originalArr );
console.log( "Modified: %s", modifiedArr );
_x000D_
Array.prototype.forEach()
Override original arrayconst originalArr = ["Iron", "Super", "Ant", "Aqua"];
originalArr.forEach((name, index) => originalArr[index] = `${name}man`);
console.log( "Overridden: %s", originalArr );
_x000D_
UPDATE
syntax is wrongWHERE
clause to target your specific rowChange
UPDATE `access_users`
(`contact_first_name`,`contact_surname`,`contact_email`,`telephone`)
VALUES (:firstname, :surname, :telephone, :email)
to
UPDATE `access_users`
SET `contact_first_name` = :firstname,
`contact_surname` = :surname,
`contact_email` = :email,
`telephone` = :telephone
WHERE `user_id` = :user_id -- you probably have some sort of id
SELECT ID from bugs WHERE user=Me ORDER BY CREATED_STAMP DESC; BY CREATED_STAMP DESC fetches those data at index first which last created.
I hope it will resolve your problem
This should do the trick:
$($.parseJSON(data.msg)).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#combobox');
Here's the distinction between ajax
and getJSON
(from the jQuery documentation):
[getJSON] is a shorthand Ajax function, which is equivalent to:
$.ajax({ url: url, dataType: 'json', data: data, success: callback });
EDIT: To be clear, part of the problem was that the server's response was returning a json object that looked like this:
{
"msg": '[{"value":"1","label":"xyz"}, {"value":"2","label":"abc"}]'
}
...So that msg
property needed to be parsed manually using $.parseJSON()
.
Update August 2019
In Android Studio 3.5 Instant Run was replaced with Apply Changes. And it works in different way: APK is not modified on the fly anymore but instead runtime instrumentation is used to redefine classes on the fly (more info). So since Android Studio 3.5 instant run settings are replaced with Deployment (Settings -> Build, Execution, Deployment -> Deployment):
I don't like to see the {id}
part of the URLs overlap with sub-resources, as an id
could theoretically be anything and there would be ambiguity. It is mixing different concepts (identifiers and sub-resource names).
Similar issues are often seen in enum
constants or folder structures, where different concepts are mixed (for example, when you have folders Tigers
, Lions
and Cheetahs
, and then also a folder called Animals
at the same level -- this makes no sense as one is a subset of the other).
In general I think the last named part of an endpoint should be singular if it deals with a single entity at a time, and plural if it deals with a list of entities.
So endpoints that deal with a single user:
GET /user -> Not allowed, 400
GET /user/{id} -> Returns user with given id
POST /user -> Creates a new user
PUT /user/{id} -> Updates user with given id
DELETE /user/{id} -> Deletes user with given id
Then there is separate resource for doing queries on users, which generally return a list:
GET /users -> Lists all users, optionally filtered by way of parameters
GET /users/new?since=x -> Gets all users that are new since a specific time
GET /users/top?max=x -> Gets top X active users
And here some examples of a sub-resource that deals with a specific user:
GET /user/{id}/friends -> Returns a list of friends of given user
Make a friend (many to many link):
PUT /user/{id}/friend/{id} -> Befriends two users
DELETE /user/{id}/friend/{id} -> Unfriends two users
GET /user/{id}/friend/{id} -> Gets status of friendship between two users
There is never any ambiguity, and the plural or singular naming of the resource is a hint to the user what they can expect (list or object). There are no restrictions on id
s, theoretically making it possible to have a user with the id new
without overlapping with a (potential future) sub-resource name.
RHT pretty much has it. Or you could use a RowSetDynaClass and let someone else do all the work :)
You can do that simple with Files.size(new File(filename).toPath())
.
Note, difflib.SequenceMatcher
only finds the longest contiguous matching subsequence, this is often not what is desired, for example:
>>> a1 = "Apple"
>>> a2 = "Appel"
>>> a1 *= 50
>>> a2 *= 50
>>> SequenceMatcher(None, a1, a2).ratio()
0.012 # very low
>>> SequenceMatcher(None, a1, a2).get_matching_blocks()
[Match(a=0, b=0, size=3), Match(a=250, b=250, size=0)] # only the first block is recorded
Finding the similarity between two strings is closely related to the concept of pairwise sequence alignment in bioinformatics. There are many dedicated libraries for this including biopython. This example implements the Needleman Wunsch algorithm:
>>> from Bio.Align import PairwiseAligner
>>> aligner = PairwiseAligner()
>>> aligner.score(a1, a2)
200.0
>>> aligner.algorithm
'Needleman-Wunsch'
Using biopython or another bioinformatics package is more flexible than any part of the python standard library since many different scoring schemes and algorithms are available. Also, you can actually get the matching sequences to visualise what is happening:
>>> alignment = next(aligner.align(a1, a2))
>>> alignment.score
200.0
>>> print(alignment)
Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-
|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-
App-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-el
innerHTML explanation with example:
The innerHTML manipulates the HTML content of an element(get or set). In the example below if you click on the Change Content link it's value will be updated by using innerHTML property of anchor link Change Content
Example:
<a id="example" onclick='testFunction()'>Change Content</a>_x000D_
_x000D_
<script>_x000D_
function testFunction(){_x000D_
// change the content using innerHTML_x000D_
document.getElementById("example").innerHTML = "This is dummy content";_x000D_
_x000D_
// get the content using innerHTML_x000D_
alert(document.getElementById("example").innerHTML)_x000D_
_x000D_
}_x000D_
</script>_x000D_
_x000D_
UNION ALL
once, aggregate once:
SELECT sum(hours) AS total_hours
FROM (
SELECT hours FROM resource
UNION ALL
SELECT hours FROM "projects-time" -- illegal name without quotes in most RDBMS
) x
You can also create a borderless window, and make the borders and title bar yourself
In currently latest JDK6 release/build (b27), the Scanner
has a smaller buffer (1024 chars) as opposed to the BufferedReader
(8192 chars), but it's more than sufficient.
As to the choice, use the Scanner
if you want to parse the file, use the BufferedReader
if you want to read the file line by line. Also see the introductory text of their aforelinked API documentations.
nextXxx()
methods in Scanner
class. The characters you are reading on your screen now each have a numerical value. In the ASCII format, for example, the letter 'A' is 65, 'B' is 66, and so on. If you look at a table of characters available in ASCII you will see that it isn't much use for someone who wishes to write something in Mandarin, Arabic, or Japanese. For characters / words from those languages to be displayed we needed another system of encoding them to and from numbers stored in computer memory.
UTF-8 is just one of the encoding methods that were invented to implement this requirement. It lets you write text in all kinds of languages, so French accents will appear perfectly fine, as will text like this
???? ????? (Bzia zbasa), ???????, Ç'kemi, ???, and even right-to-left writing such as this ?????? ?????
If you copy and paste the above text into notepad and then try to save the file as ANSI (another format) you will receive a warning that saving in this format will lose some of the formatting. Accept it, then re-load the text file and you'll see something like this
???? ????? (Bzia zbasa), ???????, Ç'kemi, ???, and even right-to-left writing such as this ?????? ?????
You can also try issuing the command while in your home directory.
U can try java.util.Date
library like this way-
int no_of_day_to_add = 1;
Date today = new Date();
Date tomorrow = new Date( today.getYear(), today.getMonth(), today.getDate() + no_of_day_to_add );
Change value of no_of_day_to_add
as you want.
I have set value of no_of_day_to_add
to 1
because u wanted only one day to add.
More can be found in this documentation.
I'm suprised ProGuard hasn't been mentioned here. It's one of the most mature products around.
ProGuard is a free Java class file shrinker, optimizer, obfuscator, and preverifier. It detects and removes unused classes, fields, methods, and attributes. It optimizes bytecode and removes unused instructions. It renames the remaining classes, fields, and methods using short meaningless names. Finally, it preverifies the processed code for Java 6 or for Java Micro Edition.
Some uses of ProGuard are:
- Creating more compact code, for smaller code archives, faster transfer across networks, faster loading, and smaller memory footprints.
- Making programs and libraries harder to reverse-engineer.
- Listing dead code, so it can be removed from the source code.
- Retargeting and preverifying existing class files for Java 6 or higher, to take full advantage of their faster class loading.
Here example for list dead code: https://www.guardsquare.com/en/products/proguard/manual/examples#deadcode
Very simple -
npm config set registry https://path-to-your-registry/
It actually sets registry = "https://path-to-your-registry"
this line to /Users/<ur-machine-user-name>/.npmrc
All the value you have set explicitly or have been set by default can be seen by - npm config list
You need to add style="overflow-y:scroll;"
to the div tag. (This will force a scrollbar on the vertical).
If you only want a scrollbar when needed, just do overflow-y:auto;
Simply should be normalized chain and run a replacement codes:
var str = "Letras Á É Í Ó Ú Ñ - á é í ó ú ñ...";
console.log (str.normalize ("NFKD").replace (/[\u0300-\u036F]/g, ""));
// Letras A E I O U N - a e i o u n...
See normalize
Then you can use this function:
function noTilde (s) {
if (s.normalize != undefined) {
s = s.normalize ("NFKD");
}
return s.replace (/[\u0300-\u036F]/g, "");
}
This maybe too late but No one provided a clear explanation of how the algorithm works
The idea of Dijkstra is simple, let me show this with the following pseudocode.
Dijkstra partitions all nodes into two distinct sets. Unsettled and settled. Initially all nodes are in the unsettled set, e.g. they must be still evaluated.
At first only the source node is put in the set of settledNodes. A specific node will be moved to the settled set if the shortest path from the source to a particular node has been found.
The algorithm runs until the unsettledNodes set is empty. In each iteration it selects the node with the lowest distance to the source node out of the unsettledNodes set. E.g. It reads all edges which are outgoing from the source and evaluates each destination node from these edges which are not yet settled.
If the known distance from the source to this node can be reduced when the selected edge is used, the distance is updated and the node is added to the nodes which need evaluation.
Please note that Dijkstra also determines the pre-successor of each node on its way to the source. I left that out of the pseudo code to simplify it.
Credits to Lars Vogel
CircularProgressBarBlue.xaml
<UserControl
x:Class="CircularProgressBarBlue"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="Transparent"
Name="progressBar">
<UserControl.Resources>
<Storyboard x:Key="spinning" >
<DoubleAnimation
Storyboard.TargetName="SpinnerRotate"
Storyboard.TargetProperty="(RotateTransform.Angle)"
From="0"
To="360"
RepeatBehavior="Forever"/>
</Storyboard>
</UserControl.Resources>
<Grid
x:Name="LayoutRoot"
Background="Transparent"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<Image Source="C:\SpinnerImage\BlueSpinner.png" RenderTransformOrigin="0.5,0.5" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Image.RenderTransform>
<RotateTransform
x:Name="SpinnerRotate"
Angle="0"/>
</Image.RenderTransform>
</Image>
</Grid>
CircularProgressBarBlue.xaml.cs
using System;
using System.Windows;
using System.Windows.Media.Animation;
/// <summary>
/// Interaction logic for CircularProgressBarBlue.xaml
/// </summary>
public partial class CircularProgressBarBlue
{
private Storyboard _sb;
public CircularProgressBarBlue()
{
InitializeComponent();
StartStoryBoard();
IsVisibleChanged += CircularProgressBarBlueIsVisibleChanged;
}
void CircularProgressBarBlueIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (_sb == null) return;
if (e != null && e.NewValue != null && (((bool)e.NewValue)))
{
_sb.Begin();
_sb.Resume();
}
else
{
_sb.Stop();
}
}
void StartStoryBoard()
{
try
{
_sb = (Storyboard)TryFindResource("spinning");
if (_sb != null)
_sb.Begin();
}
catch
{ }
}
}
SQLite is database engine, .sqlite
or .db
should be a database. If you don't need to program anything, you can use a GUI like sqlitebrowser or anything like that to view the database contents.
There is also spatialite, https://www.gaia-gis.it/fossil/spatialite_gui/index
Regardless of your situation, heres a working demo that creates markers on the map based on an array of addresses.
Javascript code embedded aswell:
$(document).ready(function () {
var map;
var elevator;
var myOptions = {
zoom: 1,
center: new google.maps.LatLng(0, 0),
mapTypeId: 'terrain'
};
map = new google.maps.Map($('#map_canvas')[0], myOptions);
var addresses = ['Norway', 'Africa', 'Asia','North America','South America'];
for (var x = 0; x < addresses.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
new google.maps.Marker({
position: latlng,
map: map
});
});
}
});
You want to use the .getline function in cin.
#include <iostream>
using namespace std;
int main () {
char name[256], title[256];
cout << "Enter your name: ";
cin.getline (name,256);
cout << "Enter your favourite movie: ";
cin.getline (title,256);
cout << name << "'s favourite movie is " << title;
return 0;
}
Took the example from here. Check it out for more info and examples.
All HIVE
managed tables are stored in the below HDFS
location.
hadoop fs -ls /user/hive/warehouse/databasename.db/tablename
If your Pycharm 2016.1.4v and higher you should use
"default path" /K "<path-to-your-activate.bat>"
don't forget quotes
The simplest way of doing this would be to add
include_directories(${CMAKE_SOURCE_DIR}/inc)
link_directories(${CMAKE_SOURCE_DIR}/lib)
add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # libbar.so is found in ${CMAKE_SOURCE_DIR}/lib
The modern CMake version that doesn't add the -I and -L
flags to every compiler invocation would be to use imported libraries:
add_library(bar SHARED IMPORTED) # or STATIC instead of SHARED
set_target_properties(bar PROPERTIES
IMPORTED_LOCATION "${CMAKE_SOURCE_DIR}/lib/libbar.so"
INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_SOURCE_DIR}/include/libbar"
)
set(FOO_SRCS "foo.cpp")
add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # also adds the required include path
If setting the INTERFACE_INCLUDE_DIRECTORIES
doesn't add the path, older versions of CMake also allow you to use target_include_directories(bar PUBLIC /path/to/include)
. However, this no longer works with CMake 3.6 or newer.
Here's a function to escape HTML:
function escapeHtml(str)
{
var map =
{
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return str.replace(/[&<>"']/g, function(m) {return map[m];});
}
And to decode:
function decodeHtml(str)
{
var map =
{
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'"
};
return str.replace(/&|<|>|"|'/g, function(m) {return map[m];});
}
{% with ''|center:n as range %}
{% for _ in range %}
{{ forloop.counter }}
{% endfor %}
{% endwith %}
Forgive the flippancy, but if you are doing REST over HTTP then RFC7231 describes exactly what behaviour is expected from GET, PUT, POST and DELETE.
Update (Jul 3 '14):
The HTTP spec intentionally does not define what is returned from POST or DELETE. The spec only defines what needs to be defined. The rest is left up to the implementer to choose.
You can solve this problem using this code:
if(!empty($_GET['variable from which you get']))
{
$_SESSION['something']= $_GET['variable from which you get'];
}
So you get the variable from a GET form, you will store in the $_SESSION['whatever']
variable just once when $_GET['variable from which you get']
is set and if it is empty $_SESSION['something']
will store the old parameter
What you are asking for is a specialized form of compression. xdelta3 was designed for this particular kind of compression, and there's a python binding for it, but you could probably get away with using zlib directly. You'd want to use zlib.compressobj
and zlib.decompressobj
with the zdict
parameter set to your "base word", e.g. afrykanerskojezyczny
.
Caveats are zdict
is only supported in python 3.3 and higher, and it's easiest to code if you have the same "base word" for all your diffs, which may or may not be what you want.
sys.dm_exec_procedure_stats contains the information about the execution functions, constraints and Procedures etc. But the life time of the row has a limit, The moment the execution plan is removed from the cache the entry will disappear.
Use [yourDatabaseName]
GO
SELECT
SCHEMA_NAME(sysobject.schema_id),
OBJECT_NAME(stats.object_id),
stats.last_execution_time
FROM
sys.dm_exec_procedure_stats stats
INNER JOIN sys.objects sysobject ON sysobject.object_id = stats.object_id
WHERE
sysobject.type = 'P'
ORDER BY
stats.last_execution_time DESC
This will give you the list of the procedures recently executed.
If you want to check if a perticular stored procedure executed recently
SELECT
SCHEMA_NAME(sysobject.schema_id),
OBJECT_NAME(stats.object_id),
stats.last_execution_time
FROM
sys.dm_exec_procedure_stats stats
INNER JOIN sys.objects sysobject ON sysobject.object_id = stats.object_id
WHERE
sysobject.type = 'P'
and (sysobject.object_id = object_id('schemaname.procedurename')
OR sysobject.name = 'procedurename')
ORDER BY
stats.last_execution_time DESC
function news_get_by_id ( $news_id )
{
$this->db->select('*');
$this->db->select("DATE_FORMAT( date, '%d.%m.%Y' ) as date_human", FALSE );
$this->db->select("DATE_FORMAT( date, '%H:%i') as time_human", FALSE );
$this->db->from('news');
$this->db->where('news_id', $news_id );
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
$row = $query->row_array();
return $row;
}
}
This
My solution that would work on Chrome, Firefox, IE9, IE10 (Change the degrees as per your requirement):
.rotate-text {
-webkit-transform: rotate(270deg);
-moz-transform: rotate(270deg);
-ms-transform: rotate(270deg);
-o-transform: rotate(270deg);
transform: rotate(270deg);
filter: none; /*Mandatory for IE9 to show the vertical text correctly*/
}
This is an old question, but it is worth noting that you can now use setnames
from the data.table
package.
library(data.table)
setnames(DF, "oldName", "newName")
# or since the data.frame in question is just one column:
setnames(DF, "newName")
# And for reference's sake, in general (more than once column)
nms <- c("col1.name", "col2.name", etc...)
setnames(DF, nms)
By default, np.genfromtxt
uses dtype=float
: that's why you string columns are converted to NaNs because, after all, they're Not A Number...
You can ask np.genfromtxt
to try to guess the actual type of your columns by using dtype=None
:
>>> from StringIO import StringIO
>>> test = "a,1,2\nb,3,4"
>>> a = np.genfromtxt(StringIO(test), delimiter=",", dtype=None)
>>> print a
array([('a',1,2),('b',3,4)], dtype=[('f0', '|S1'),('f1', '<i8'),('f2', '<i8')])
You can access the columns by using their name, like a['f0']
...
Using dtype=None
is a good trick if you don't know what your columns should be. If you already know what type they should have, you can give an explicit dtype
. For example, in our test, we know that the first column is a string, the second an int, and we want the third to be a float. We would then use
>>> np.genfromtxt(StringIO(test), delimiter=",", dtype=("|S10", int, float))
array([('a', 1, 2.0), ('b', 3, 4.0)],
dtype=[('f0', '|S10'), ('f1', '<i8'), ('f2', '<f8')])
Using an explicit dtype
is much more efficient than using dtype=None
and is the recommended way.
In both cases (dtype=None
or explicit, non-homogeneous dtype
), you end up with a structured array.
[Note: With dtype=None
, the input is parsed a second time and the type of each column is updated to match the larger type possible: first we try a bool, then an int, then a float, then a complex, then we keep a string if all else fails. The implementation is rather clunky, actually. There had been some attempts to make the type guessing more efficient (using regexp), but nothing that stuck so far]
You might also try giving the full path to the binary you're trying to run. That solved my problem when trying to use ImageMagick
.
You can't.
Interfaces define contracts that other objects implement and therefore have no state that needs to be initialized.
If you have some state that needs to be initialized, you should consider using an abstract base class instead.
One option is to put the subquery in a LEFT JOIN
:
select sum ( t.graduates ) - t1.summedGraduates
from table as t
left join
(
select sum ( graduates ) summedGraduates, id
from table
where group_code not in ('total', 'others' )
group by id
) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates
Perhaps a better option would be to use SUM
with CASE
:
select sum(case when group_code = 'total' then graduates end) -
sum(case when group_code not in ('total','others') then graduates end)
from yourtable
To print a vector which possibly has complex numbers-
fprintf('Answer: %s\n', sprintf('%d ', num2str(x)));
Was thinking about comment by @JohnShedletsky on the accepted answer regarding (paraphrase):
you should be able to to this in O(subset.Length), rather than O(originalList.Length)
Basically, you should be able to generate subset
random indices and then pluck them from the original list.
public static class EnumerableExtensions {
public static Random randomizer = new Random(); // you'd ideally be able to replace this with whatever makes you comfortable
public static IEnumerable<T> GetRandom<T>(this IEnumerable<T> list, int numItems) {
return (list as T[] ?? list.ToArray()).GetRandom(numItems);
// because ReSharper whined about duplicate enumeration...
/*
items.Add(list.ElementAt(randomizer.Next(list.Count()))) ) numItems--;
*/
}
// just because the parentheses were getting confusing
public static IEnumerable<T> GetRandom<T>(this T[] list, int numItems) {
var items = new HashSet<T>(); // don't want to add the same item twice; otherwise use a list
while (numItems > 0 )
// if we successfully added it, move on
if( items.Add(list[randomizer.Next(list.Length)]) ) numItems--;
return items;
}
// and because it's really fun; note -- you may get repetition
public static IEnumerable<T> PluckRandomly<T>(this IEnumerable<T> list) {
while( true )
yield return list.ElementAt(randomizer.Next(list.Count()));
}
}
If you wanted to be even more efficient, you would probably use a HashSet
of the indices, not the actual list elements (in case you've got complex types or expensive comparisons);
And to make sure we don't have any collisions, etc.
[TestClass]
public class RandomizingTests : UnitTestBase {
[TestMethod]
public void GetRandomFromList() {
this.testGetRandomFromList((list, num) => list.GetRandom(num));
}
[TestMethod]
public void PluckRandomly() {
this.testGetRandomFromList((list, num) => list.PluckRandomly().Take(num), requireDistinct:false);
}
private void testGetRandomFromList(Func<IEnumerable<int>, int, IEnumerable<int>> methodToGetRandomItems, int numToTake = 10, int repetitions = 100000, bool requireDistinct = true) {
var items = Enumerable.Range(0, 100);
IEnumerable<int> randomItems = null;
while( repetitions-- > 0 ) {
randomItems = methodToGetRandomItems(items, numToTake);
Assert.AreEqual(numToTake, randomItems.Count(),
"Did not get expected number of items {0}; failed at {1} repetition--", numToTake, repetitions);
if(requireDistinct) Assert.AreEqual(numToTake, randomItems.Distinct().Count(),
"Collisions (non-unique values) found, failed at {0} repetition--", repetitions);
Assert.IsTrue(randomItems.All(o => items.Contains(o)),
"Some unknown values found; failed at {0} repetition--", repetitions);
}
}
}
If you want the file upload control to Limit the types of files user can upload on a button click then this is the way..
<script type="text/JavaScript">
<!-- Begin
function TestFileType( fileName, fileTypes ) {
if (!fileName) return;
dots = fileName.split(".")
//get the part AFTER the LAST period.
fileType = "." + dots[dots.length-1];
return (fileTypes.join(".").indexOf(fileType) != -1) ?
alert('That file is OK!') :
alert("Please only upload files that end in types: \n\n" + (fileTypes.join(" .")) + "\n\nPlease select a new file and try again.");
}
// -->
</script>
You can then call the function from an event like the onClick of the above button, which looks like:
onClick="TestFileType(this.form.uploadfile.value, ['gif', 'jpg', 'png', 'jpeg']);"
You can change this to: PDF
and XLS
You can see it implemented over here: Demo
onSelect doesn't work well in ng-repeat, so I made another version using event bind
html
<tr ng-repeat="product in products">
<td>
<input type="text" ng-model="product.startDate" class="form-control date-picker" data-date-format="yyyy-mm-dd" datepicker/>
</td>
</tr>
script
angular.module('app', []).directive('datepicker', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
element.datepicker();
element.bind('blur keyup change', function(){
var model = attrs.ngModel;
if (model.indexOf(".") > -1) scope[model.replace(/\.[^.]*/, "")][model.replace(/[^.]*\./, "")] = element.val();
else scope[model] = element.val();
});
}
};
});
Oracle's error message should be somewhat longer. It usually looks like this:
ORA-00001: unique constraint (TABLE_UK1) violated
The name in parentheses is the constrait name. It tells you which constraint was violated.
I just discovered that there is a cleaner way to do your
new Thread(new Runnable() {
public void run() {
//Do whatever
}
}).start();
(At least in Java 8), you can use a lambda expression to shorten it to:
new Thread(() -> {
//Do whatever
}).start();
As simple as making a function in JS!
As you can see, the import command did work but is showing errors because it tried to locate the resources in vendor.css and couldn't find them
You should also upload your project structure and ensure that there aren't any path issues. Also, you could include the css file in the index.html or the Component template and webpack loader would extract it when built
This answer was written in 2010. The API it uses has since been retired. It is kept for historical interest only.
Search for it.
Make sure include_entities
is set to true to get hashtag results. See Tweet Entities
Returns 5 mixed results with Twitter.com user IDs plus entities for the term "blue angels":
GET http://search.twitter.com/search.json?q=blue%20angels&rpp=5&include_entities=true&with_twitter_user_id=true&result_type=mixed
check the python version you have installed by using command python --version
check for the Tk module installed correctly from following code
sudo apt-get install python3-tk
Check if you are using open-source OS then
check the tkinter module in the following path /home/python/site-packages/tkinter change the path accordingly your system
Found a good post on this and thought I'd share. Check it out HERE
Basically.
You can create the following class and IComparer Classes
public class Widget {
public string Name = string.Empty;
public int Size = 0;
public Widget(string name, int size) {
this.Name = name;
this.Size = size;
}
}
public class WidgetNameSorter : IComparer<Widget> {
public int Compare(Widget x, Widget y) {
return x.Name.CompareTo(y.Name);
}
}
public class WidgetSizeSorter : IComparer<Widget> {
public int Compare(Widget x, Widget y) {
return x.Size.CompareTo(y.Size);
}
}
Then If you have an IList, you can sort it like this.
List<Widget> widgets = new List<Widget>();
widgets.Add(new Widget("Zeta", 6));
widgets.Add(new Widget("Beta", 3));
widgets.Add(new Widget("Alpha", 9));
widgets.Sort(new WidgetNameSorter());
widgets.Sort(new WidgetSizeSorter());
But Checkout this site for more information... Check it out HERE
My Team built a command line tool for uploading artifacts to nexus 3.x repository, Maybe it's will be helpful for you - Maven Artifacts Uploader
I like to do it with a static method in the second activity:
private static final String EXTRA_GAME_ID = "your.package.gameId";
public static void start(Context context, String gameId) {
Intent intent = new Intent(context, SecondActivity.class);
intent.putExtra(EXTRA_GAME_ID, gameId);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
...
Intent intent = this.getIntent();
String gameId = intent.getStringExtra(EXTRA_GAME_ID);
}
Then from your first activity (and for anywhere else), you just do:
SecondActivity.start(this, "the.game.id");
At least you can change your loop from a busy-wait to a slow poll. For example:
while (!isExcelInteractive())
{
Console.WriteLine("Excel is busy");
await Task.Delay(25);
}
Try this:
df = spark.createDataFrame([('2018-07-27 10:30:00',)], ['Date_col'])
df.select(from_unixtime(unix_timestamp(df.Date_col, 'yyyy-MM-dd HH:mm:ss')).alias('dt_col'))
df.show()
+-------------------+
| Date_col|
+-------------------+
|2018-07-27 10:30:00|
+-------------------+
You can write a VBScript script to get the file version info:
VersionInfo.vbs
set args = WScript.Arguments
Set fso = CreateObject("Scripting.FileSystemObject")
WScript.Echo fso.GetFileVersion(args(0))
Wscript.Quit
You can call this from the command line like this:
cscript //nologo VersionInfo.vbs C:\Path\To\MyFile.dll
Scala class same as Java Class but scala not gives you any entry method in class, like main method in java. The main method associated with object keyword. You can think of the object keyword as creating a singleton object of a class that is defined implicitly.
more information check this article class and object keyword in scala programming
Here's an answer that gives the switch-or-launch behaviour of Start, without the Command Prompt window. It does have the drawback that it can be fooled by an Explorer window that has a folder of the same name elsewhere opened. I might fix that by diving into the child windows and looking for the actual path, I need to figure out how to navigate that.
Usage (requires "Windows Script Host Object Model" in your project's References):
Dim mShell As wshShell
mDocPath = whatever_path & "\" & lastfoldername
mExplorerPath = mShell.ExpandEnvironmentStrings("%SystemRoot%") & "\Explorer.exe"
If Not SwitchToFolder(lastfoldername) Then
Shell PathName:=mExplorerPath & " """ & mDocPath & """", WindowStyle:=vbNormalFocus
End If
Module:
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
(ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" _
(ByVal hWnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" _
(ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare Function BringWindowToTop Lib "user32" _
(ByVal lngHWnd As Long) As Long
Function SwitchToFolder(pFolder As String) As Boolean
Dim hWnd As Long
Dim mRet As Long
Dim mText As String
Dim mWinClass As String
Dim mWinTitle As String
SwitchToFolder = False
hWnd = FindWindowEx(0, 0&, vbNullString, vbNullString)
While hWnd <> 0 And SwitchToFolder = False
mText = String(100, Chr(0))
mRet = GetClassName(hWnd, mText, 100)
mWinClass = Left(mText, mRet)
If mWinClass = "CabinetWClass" Then
mText = String(100, Chr(0))
mRet = GetWindowText(hWnd, mText, 100)
If mRet > 0 Then
mWinTitle = Left(mText, mRet)
If UCase(mWinTitle) = UCase(pFolder) Or _
UCase(Right(mWinTitle, Len(pFolder) + 1)) = "\" & UCase(pFolder) Then
BringWindowToTop hWnd
SwitchToFolder = True
End If
End If
End If
hWnd = FindWindowEx(0, hWnd, vbNullString, vbNullString)
Wend
End Function
Unlike some browsers, Java follows the HTTPS specification strictly when it comes to the server identity verification (RFC 2818, Section 3.1) and IP addresses.
When using a host name, it's possible to fall back to the Common Name in the Subject DN of the server certificate, instead of using the Subject Alternative Name.
When using an IP address, there must be a Subject Alternative Name entry (of type IP address, not DNS name) in the certificate.
You'll find more details about the specification and how to generate such a certificate in this answer.
Just use the spread parameter to make the shadow smaller:
.shadow {_x000D_
-webkit-box-shadow: 0 6px 4px -4px black;_x000D_
-moz-box-shadow: 0 6px 4px -4px black;_x000D_
box-shadow: 0 6px 4px -4px black;_x000D_
}
_x000D_
<div class="shadow">Some content</div>
_x000D_
Live demo: http://dabblet.com/gist/a8f8ba527f5cff607327
To not see any shadow on the sides, the (absolute value of the) spread radius (4th parameter) needs to be the same as the blur radius (3rd parameter).
let's say on the command-line you have:
C:\> C:\Documents and Settings\fred\My Documents\Downloads\google-python-exercises
\google-python-exercises\hello.py John
to make it easier to read, let's just shorten this to:
C:\> hello.py John
argv
represents all the items that come along via the command-line input, but counting starts at zero (0) not one (1): in this case, "hello.py
" is element 0, "John
" is element 1
in other words, sys.argv[0] == 'hello.py'
and sys.argv[1] == 'John'
... but look, how many elements is this? 2, right! so even though the numbers are 0 and 1, there are 2 elements here.
len(sys.argv) >= 2
just checks whether you entered at least two elements. in this case, we entered exactly 2.
now let's translate your code into English:
define main() function:
if there are at least 2 elements on the cmd-line:
set 'name' to the second element located at index 1, e.g., John
otherwise there is only 1 element... the program name, e.g., hello.py:
set 'name' to "World" (since we did not get any useful user input)
display 'Hello' followed by whatever i assigned to 'name'
so what does this mean? it means that if you enter:
hello.py
", the code outputs "Hello World
" because you didn't give a namehello.py John
", the code outputs "Hello John
" because you didhello.py John Paul
", the code still outputs "Hello John
" because it does not save nor use sys.argv[2]
, which was "Paul
" -- can you see in this case that len(sys.argv) == 3
because there are 3 elements in the sys.argv
list?Use:
import color
class Color(color.Color):
...
If this were Python 2.x, you would also want to derive color.Color
from object
, to make it a new-style class:
class Color(object):
...
This is not necessary in Python 3.x.
Step 1:
npm install jquery
Step 2:
touch loader.js
Somewhere in your project folder
Step 3:
//loader.js
window.$ = window.jQuery = require('jquery')
Step 4:
Import the loader into your root file before you import the files which require jQuery
//App.js
import '<pathToYourLoader>/loader.js'
Step 5:
Now use jQuery anywhere in your code:
//SomeReact.js
class SomeClass extends React.Compontent {
...
handleClick = () => {
$('.accor > .head').on('click', function(){
$('.accor > .body').slideUp();
$(this).next().slideDown();
});
}
...
export default SomeClass
Simple usage of GDB, to debug coredump files:
gdb <executable_path> <coredump_file_path>
A coredump file for a "process" gets created as a "core.pid" file.
After you get inside the GDB prompt (on execution of the above command), type:
...
(gdb) where
This will get you with the information, of the stack, where you can analayze the cause of the crash/fault. Other command, for the same purposes is:
...
(gdb) bt full
This is the same as above. By convention, it lists the whole stack information (which ultimately leads to the crash location).
1.
$(this).parent().attr("id");
2.
There must be a large number of ways! One could be to hide an element that contains the answer, e.g.
<div>
Volume = <input type="text" />
<button type="button">Check answer</button>
<span style="display: hidden">3.93e-6</span>
<div></div>
</div>
And then have similar jQuery code to the above to grab that:
$("button").click(function ()
{
var correct = Number($(this).parent().children("span").text());
validate ($(this).siblings("input").val(),correct);
$(this).siblings("div").html(feedback);
});
bear in mind that if you put the answer in client code then they can see it :) The best way to do this is to validate it server-side, but for an app with limited scope this may not be a problem.
You need to open TCP port 8787 in the ec2 Security Group. Also need to open the same port on the EC2 instance's firewall.
Visual Studio 2017 Debug symbol "speed-up" options, assuming you haven't gone crazy on option-customization already:
Tools -> Options -> Debugging -> Symbols
C:\dbg_symbols
or %USERPROFILE%\dbg_symbols
1A and 2 are the most important steps. 1B and 1C are just helpful changes to help you keep track of your symbols.
After your app has loaded all the symbols at least once and debugging didn't prematurely terminate, those symbols should be quickly loaded the next time debug runs.
I've noticed that if I cancel a debug-run, I have to reload those symbols, as I'm guessing they're "cleaned" up if newly introduced and suddenly cancelled. I understand the core rationale for that kind of flow, but in this case it seems poorly thought out.
Try this as root (maybe you can use sudo
or su
):
/etc/init.d/postgresql restart
Without any argument the script also gives you a hint on how to restart a specific version
[Uqbar@Feynman ~] /etc/init.d/postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force-reload|status} [version ...]
Similarly, in case you have it, you can also use the service
tool:
[Uqbar@Feynman ~] service postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force reload|status} [version ...]
Please, pay attention to the optional [version ...]
trailing argument.
That's meant to allow you, the user, to act on a specific version, in case you were running multiple ones. So you can restart version X while keeping version Y and Z untouched and running.
Finally, in case you are running systemd, then you can use systemctl
like this:
[support@Feynman ~] systemctl status postgresql
? postgresql.service - PostgreSQL database server
Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; vendor preset: disabled)
Active: active (running) since Wed 2017-11-14 12:33:35 CET; 7min ago
...
You can replace status
with stop
, start
or restart
as well as other actions. Please refer to the documentation for full details.
In order to operate on multiple concurrent versions, the syntax is slightly different. For example to stop v12
and reload v13
you can run:
systemctl stop postgresql-12.service
systemctl reload postgresql-13.service
Thanks to @Jojo for pointing me to this very one.
Finally Keep in mind that root
permissions may be needed for non-informative tasks as in the other cases seen earlier.
It is simple: if recv()
returns 0 bytes; you will not receive any more data on this connection. Ever. You still might be able to send.
It means that your non-blocking socket have to raise an exception (it might be system-dependent) if no data is available but the connection is still alive (the other end may send).
I tried to use the \x00 and it didn't work for me when using C# and Regex. I had success with the following:
//The hexidecimal 0x0 is the null character
mystring.Contains(Convert.ToChar(0x0).ToString() );
// This will replace the character
mystring = mystring.Replace(Convert.ToChar(0x0).ToString(), "");
{
"files.useExperimentalFileWatcher" : true
}
in Code -> Preferences -> Settings
Tested with Visual Studio Code Version 1.26.1 on mac and win
You don't appear to understand what still reachable
means.
Anything still reachable
is not a leak. You don't need to do anything about it.
I make a link. A link is a link. A link navigates to another page. That is what links are for and everybody understands that. So Method 3 is the only correct method in my book.
I wouldn't want my link to look like a button at all, and when I do, I still think functionality is more important than looks.
Buttons are less accessible, not only due to the need of Javascript, but also because tools for the visually impaired may not understand this Javascript enhanced button well.
Method 4 would work as well, but it is more a trick than a real functionality. You abuse a form to post 'nothing' to this other page. It's not clean.
My complete code as below is working well:
package ripon.java.mail;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail
{
public static void main(String [] args)
{
// Sender's email ID needs to be mentioned
String from = "[email protected]";
String pass ="test123";
// Recipient's email ID needs to be mentioned.
String to = "[email protected]";
String host = "smtp.gmail.com";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.user", from);
properties.put("mail.smtp.password", pass);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
It looks like the JavaScript error your getting is probably being caused by
password: {
required:true,
rangelenght:[4.20]
},
As the [4.20]
should be [4,20]
, which i'd guess is throwing off the validation code in additional-methods
hence giving the type error's you posted.
Edit: As others have noted in the below comments rangelenght
is also misspelled & jquery.validate.js
library appears to be missing (assuming its not compiled in to one of your other assets)
Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.
import java.sql.*;
public class UserLogin
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// C:\\databaseFileName.accdb" - location of your database
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";
// specify url, username, pasword - make sure these are valid
Connection conn = DriverManager.getConnection(url, "username", "password");
System.out.println("Connection Succesfull");
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
(untested) something like this may do the job
WITH
base AS
(
select * -- get the table
from sometable
order by name -- in the desired order
),
twenty AS
(
select * -- get the first 30 rows
from base
where rownum < 30
order by name -- in the desired order
)
select * -- then get rows 21 .. 30
from twenty
where rownum > 20
order by name -- in the desired order
There is also the analytic function rank, that you can use to order by.
You have to overwrite the file. In C++:
#include <fstream>
std::ofstream("test.txt", std::ios::out).close();
You can directly plot the lines you want by feeding the plot
command with the corresponding data (boundaries of the segments):
plot([x1, x2], [y1, y2], color='k', linestyle='-', linewidth=2)
(of course you can choose the color, line width, line style, etc.)
From your example:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")
# draw vertical line from (70,100) to (70, 250)
plt.plot([70, 70], [100, 250], 'k-', lw=2)
# draw diagonal line from (70, 90) to (90, 200)
plt.plot([70, 90], [90, 200], 'k-')
plt.show()
class Item < ActiveRecord::Base
def status
self[:status] or ACTIVE
end
before_save{ self.status ||= ACTIVE }
end
Just in case someone is using Bootstrap 4. It seems we can no longer use .modal-backdrop.in
, but must now use .modal-backdrop.show
. Fade effect preserved.
.modal-backdrop.show {
opacity: 0.7;
}
This will get your buttons and labels next to each other, at least. I believe the second part can't be done in css alone, and will need javascript. I found a page that might help you with that part as well, but I don't have time right now to try it out: http://www.webmasterworld.com/forum83/6942.htm
<style type="text/css">
.input input {
float: left;
}
.input label {
margin: 5px;
}
</style>
<div class="input radio">
<fieldset>
<legend>What color is the sky?</legend>
<input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1" />
<label for="SubmitQuestion1">A strange radient green.</label>
<input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2" />
<label for="SubmitQuestion2">A dark gloomy orange</label>
<input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3" />
<label for="SubmitQuestion3">A perfect glittering blue</label>
</fieldset>
</div>
You cannot override a function with different parameters, only you are allowed to change the functionality of the overridden method.
//Compiler Microsoft (R) .NET Framework 4.5
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
//Overriding & overloading
namespace polymorpism
{
public class Program
{
public static void Main(string[] args)
{
drowButn calobj = new drowButn();
BtnOverride calobjOvrid = new BtnOverride();
Console.WriteLine(calobj.btn(5.2, 6.6).ToString());
//btn has compleately overrided inside this calobjOvrid object
Console.WriteLine(calobjOvrid.btn(5.2, 6.6).ToString());
//the overloaded function
Console.WriteLine(calobjOvrid.btn(new double[] { 5.2, 6.6 }).ToString());
Console.ReadKey();
}
}
public class drowButn
{
//same add function overloading to add double type field inputs
public virtual double btn(double num1, double num2)
{
return (num1 + num2);
}
}
public class BtnOverride : drowButn
{
//same add function overrided and change its functionality
//(this will compleately replace the base class function
public override double btn(double num1, double num2)
{
//do compleatly diffarant function then the base class
return (num1 * num2);
}
//same function overloaded (no override keyword used)
// this will not effect the base class function
public double btn(double[] num)
{
double cal = 0;
foreach (double elmnt in num)
{
cal += elmnt;
}
return cal;
}
}
}
You can attach a "proper" Bitbucket account password to your account. Go to https://id.atlassian.com/manage/change-password (sign in using your Google account) and then enter a new password in both the old and new password boxes. Now you can use your email address and this new password to access your account on the command line.
Note: App passwords are the official way of doing this (per @Christian Tingino's answer), but IMO they don't work very nicely. No way of changing the password, and they are big unwieldly things to type into the command line.
my 2 cents
def getResponseCode(url):
conn = urllib.request.urlopen(url)
return conn.getcode()
if getResponseCode(url) != 200:
print('Wrong URL')
else:
print('Good URL')
Try this:
var value;
for (var key in dictionary) {
value = dictionary[key];
// your code here...
}
If you're running ubuntu container directly without a local Dockerfile you can ssh into the container and enable root control by entering su
then apt-get install -y wget
I could successfully integrate Pagination in
spring-data-jpa-2.1.6
as follows.
@Query(
value = “SELECT * FROM Users”,
countQuery = “SELECT count(*) FROM Users”,
nativeQuery = true)
Page<User> findAllUsersWithPagination(Pageable pageable);
If you don't have another time interval bigger than days:
int days = (int) (milliseconds / (1000*60*60*24));
If you have weeks too:
int days = (int) ((milliseconds / (1000*60*60*24)) % 7);
int weeks = (int) (milliseconds / (1000*60*60*24*7));
It's probably best to avoid using months and years if possible, as they don't have a well-defined fixed length. Strictly speaking neither do days: daylight saving means that days can have a length that is not 24 hours.
Have them try to write a program that can evaluate arbitrary simple arithmetic expressions. This is a simple problem to understand but as you start getting deeper into it a lot of basic parsing starts to make sense.
Insert Selected column with condition
INSERT INTO where_to_insert (col_1,col_2) SELECT col1, col2 FROM from_table WHERE condition;
Copy all data from one table to another with the same column name.
INSERT INTO where_to_insert
SELECT * FROM from_table WHERE condition;
Example
<div ng-controller="ExampleController">
<form name="myform">
Name: <input type="text" ng-model="user.name" /><br>
Email: <input type="email" ng-model="user.email" /><br>
</form>
</div>
<script>
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
//if form is not valid then return the form.
if(!$scope.myform.$valid) {
return;
}
}]);
</script>
webView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
return super.onJsAlert(view, url, message, result);
}
});
Try this, it should work if you have configured your view resolver properly
return "redirect:/index.html";
You can specify the style
of the plotted line when calling df.plot
:
df.plot(x='col_name_1', y='col_name_2', style='o')
The style
argument can also be a dict
or list
, e.g.:
import numpy as np
import pandas as pd
d = {'one' : np.random.rand(10),
'two' : np.random.rand(10)}
df = pd.DataFrame(d)
df.plot(style=['o','rx'])
All the accepted style formats are listed in the documentation of matplotlib.pyplot.plot
.
For gmail these settings worked for me, the ServicePointManager.SecurityProtocol line was necessary. Because I has setup 2 step verification I needed get a App Password from google app password generator.
SmtpClient mailer = new SmtpClient();
mailer.Host = "smtp.gmail.com";
mailer.Port = 587;
mailer.EnableSsl = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
This error is cause by security clutches between the web application and your java. To resolve it, look into your java setting under control panel. Move the security level to a medium.
If you don't have the source code and API documentation, the machine code is all there is, you need to disassemble the dll library using something like IDA Pro , another option is use the trial version of PE Explorer.
PE Explorer provides a Disassembler. There is only one way to figure out the parameters: run the disassembler and read the disassembly output. Unfortunately, this task of reverse engineering the interface cannot be automated.
PE Explorer comes bundled with descriptions for 39 various libraries, including the core Windows® operating system libraries (eg. KERNEL32, GDI32, USER32, SHELL32, WSOCK32), key graphics libraries (DDRAW, OPENGL32) and more.
(source: heaventools.com)
In pyspark,SparkSql syntax:
where column_n like 'xyz%'
might not work.
Use:
where column_n RLIKE '^xyz'
This works perfectly fine.
Adding margins to a button makes it wider so that les buttons fit in the grid system. If only a visual effect is important, then give the button a white border with [style="margin:0px; border:solid white;"] This leaves the button width unaffected.
You need to install the Visual C++ libraries: http://www.microsoft.com/en-us/download/details.aspx?id=30679
$("input[placeholder]").focusin(function () {
$(this).data('place-holder-text', $(this).attr('placeholder')).attr('placeholder', '');
})
.focusout(function () {
$(this).attr('placeholder', $(this).data('place-holder-text'));
});
Yes, as it was properly explained above, it's enough to iterate up to Math.floor of a number's square root to check its primality (because sqrt
covers all possible cases of division; and Math.floor
, because any integer above sqrt
will already be beyond its range).
Here is a runnable JavaScript code snippet that represents a simple implementation of this approach – and its "runtime-friendliness" is good enough for handling pretty big numbers (I tried checking both prime and not prime numbers up to 10**12, i.e. 1 trillion, compared results with the online database of prime numbers and encountered no errors or lags even on my cheap phone):
function isPrime(num) {
if (num % 2 === 0 || num < 3 || !Number.isInteger(num)) {
return num === 2;
} else {
const sqrt = Math.floor(Math.sqrt(num));
for (let i = 3; i <= sqrt; i += 2) {
if (num % i === 0) {
return false;
}
}
return true;
}
}
_x000D_
<label for="inp">Enter a number and click "Check!":</label><br>
<input type="number" id="inp"></input>
<button onclick="alert(isPrime(+document.getElementById('inp').value) ? 'Prime' : 'Not prime')" type="button">Check!</button>
_x000D_
Create some public Properties on your sub-form like so
public string ReturnValue1 {get;set;}
public string ReturnValue2 {get;set;}
then set this inside your sub-form ok button click handler
private void btnOk_Click(object sender,EventArgs e)
{
this.ReturnValue1 = "Something";
this.ReturnValue2 = DateTime.Now.ToString(); //example
this.DialogResult = DialogResult.OK;
this.Close();
}
Then in your frmHireQuote form, when you open the sub-form
using (var form = new frmImportContact())
{
var result = form.ShowDialog();
if (result == DialogResult.OK)
{
string val = form.ReturnValue1; //values preserved after close
string dateString = form.ReturnValue2;
//Do something here with these values
//for example
this.txtSomething.Text = val;
}
}
Additionaly if you wish to cancel out of the sub-form you can just add a button to the form and set its DialogResult to Cancel
and you can also set the CancelButton property of the form to said button - this will enable the escape key to cancel out of the form.
As @HarlemSquirrel posted, it is the best and I think the correct solution.
But, to answer the OP specific problem, it should be something like the following command, as he doesn't want to recreate ALL services in the docker-compose.yml
file, but only the nginx
one:
docker-compose up -d --force-recreate --no-deps --build nginx
Options description:
Options:
-d Detached mode: Run containers in the background,
print new container names. Incompatible with
--abort-on-container-exit.
--force-recreate Recreate containers even if their configuration
and image haven't changed.
--build Build images before starting containers.
--no-deps Don't start linked services.
Try this org.codehaus.jettison.json.JSONObject.quote("your string")
.
Download it here: http://mvnrepository.com/artifact/org.codehaus.jettison/jettison
Just had a similar problem when exporting from dataframe to arcgis table and stumbled on a solution from usgs (https://my.usgs.gov/confluence/display/cdi/pandas.DataFrame+to+ArcGIS+Table). In short your problem has a similar solution:
df
A B C
ID
1 NaN 0.2 NaN
2 NaN NaN 0.5
3 NaN 0.2 0.5
4 0.1 0.2 NaN
5 0.1 0.2 0.5
6 0.1 NaN 0.5
7 0.1 NaN NaN
np_data = np.array(np.rec.fromrecords(df.values))
np_names = df.dtypes.index.tolist()
np_data.dtype.names = tuple([name.encode('UTF8') for name in np_names])
np_data
array([( nan, 0.2, nan), ( nan, nan, 0.5), ( nan, 0.2, 0.5),
( 0.1, 0.2, nan), ( 0.1, 0.2, 0.5), ( 0.1, nan, 0.5),
( 0.1, nan, nan)],
dtype=(numpy.record, [('A', '<f8'), ('B', '<f8'), ('C', '<f8')]))
Define extension: String+Extension.ts
interface String {
toBoolean(): boolean
}
String.prototype.toBoolean = function (): boolean {
switch (this) {
case 'true':
case '1':
case 'on':
case 'yes':
return true
default:
return false
}
}
And import in any file where you want to use it '@/path/to/String+Extension'
Any solution work only if List a list(of string)
If you have a generic list of your own Objects like list(of car) where car has n properties, you must loop the PropertiesInfo of each car object.
Look at: http://www.csharptocsharp.com/generate-csv-from-generic-list
@Test
public void testToStringToMap() {
Map<String,String> expected = new HashMap<>();
expected.put("first_name", "naresh");
expected.put("last_name", "kumar");
expected.put("gender", "male");
String mapString = expected.toString();
Map<String, String> actual = Arrays.stream(mapString.replace("{", "").replace("}", "").split(","))
.map(arrayData-> arrayData.split("="))
.collect(Collectors.toMap(d-> ((String)d[0]).trim(), d-> (String)d[1]));
expected.entrySet().stream().forEach(e->assertTrue(actual.get(e.getKey()).equals(e.getValue())));
}
Try to uncheck the CheckBox “Use Managed Compatibility Mode” in
Tools => Options => Debugging => General
It worked for me.
window.alert = null;
alert('test'); // fail
delete window.alert; // true
alert('test'); // win
window
is an instance of DOMWindow
, and by setting something to window.alert
, the correct implementation is being "shadowed", i.e. when accessing alert
it is first looking for it on the window
object. Usually this is not found, and it then goes up the prototype chain to find the native implementation. However, when manually adding the alert
property to window
it finds it straight away and does not need to go up the prototype chain. Using delete window.alert
you can remove the window own property and again expose the prototype implementation of alert
. This may help explain:
window.hasOwnProperty('alert'); // false
window.alert = null;
window.hasOwnProperty('alert'); // true
delete window.alert;
window.hasOwnProperty('alert'); // false
You should look into XPath. Once you start using it, you'll find its a lot more efficient and easier to code than iterating through lists. It also lets you directly get the things you want.
Then the code would be something similar to
string attrVal = doc.SelectSingleNode("/MyConfiguration/@SuperNumber").Value;
Note that XPath 3.0 became a W3C Recommendation on April 8, 2014.
Sounds like you're expecting size_t
to be the same as unsigned long
(possibly 64 bits) when it's actually an unsigned int
(32 bits). Try using %zu
in both cases.
I'm not entirely certain though.
LocalDate.parse(
"01-23-2017" ,
DateTimeFormatter.ofPattern( "MM-dd-uuuu" )
)
I have a java.util.Date in the format yyyy-mm-dd
As other mentioned, the Date
class has no format. It has a count of milliseconds since the start of 1970 in UTC. No strings attached.
The other Answers use troublesome old legacy date-time classes, now supplanted by the java.time classes.
If you have a java.util.Date
, convert to a Instant
object. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = myUtilDate.toInstant();
The other Answers ignore the crucial issue of time zone. Determining a date requires a time zone. For any given moment, the date varies around the globe by zone. A few minutes after midnight in Paris France is a new day, while still “yesterday” in Montréal Québec.
Define the time zone by which you want context for your Instant
.
ZoneId z = ZoneId.of( "America/Montreal" );
Apply the ZoneId
to get a ZonedDateTime
.
ZonedDateTime zdt = instant.atZone( z );
LocalDate
If you only care about the date without a time-of-day, extract a LocalDate
.
LocalDate localDate = zdt.toLocalDate();
To generate a string in standard ISO 8601 format, YYYY-MM-DD, simply call toString
. The java.time classes use the standard formats by default when generating/parsing strings.
String output = localDate.toString();
2017-01-23
If you want a MM-DD-YYYY format, define a formatting pattern.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" );
String output = localDate.format( f );
Note that the formatting pattern codes are case-sensitive. The code in the Question incorrectly used mm
(minute of hour) rather than MM
(month of year).
Use the same DateTimeFormatter
object for parsing. The java.time classes are thread-safe, so you can keep this object around and reuse it repeatedly even across threads.
LocalDate localDate = LocalDate.parse( "01-23-2017" , f );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
You may use iframe as described in https://developers.google.com/youtube/iframe_api_reference
I am not following the google advises exactly but this is the code I am using and it is working fine
public class CWebVideoView {
private String url;
private Context context;
private WebView webview;
private static final String HTML_TEMPLATE = "webvideo.html";
public CWebVideoView(Context context, WebView webview) {
this.webview = webview;
this.context = context;
webview.setBackgroundColor(0);
webview.getSettings().setJavaScriptEnabled(true);
}
public void load(String url){
this.url = url;
String data = readFromfile(HTML_TEMPLATE, context);
data = data.replace("%1", url);
webview.loadData(data, "text/html", "UTF-8");
}
public String readFromfile(String fileName, Context context) {
StringBuilder returnString = new StringBuilder();
InputStream fIn = null;
InputStreamReader isr = null;
BufferedReader input = null;
try {
fIn = context.getResources().getAssets().open(fileName, Context.MODE_WORLD_READABLE);
isr = new InputStreamReader(fIn);
input = new BufferedReader(isr);
String line = "";
while ((line = input.readLine()) != null) {
returnString.append(line);
}
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (isr != null)
isr.close();
if (fIn != null)
fIn.close();
if (input != null)
input.close();
} catch (Exception e2) {
e2.getMessage();
}
}
return returnString.toString();
}
public void reload() {
if (url!=null){
load(url);
}
}
}
in /assets I have a file called webvideo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
iframe { border: 0; position:fixed; width:100%; height:100%; bgcolor="#000000"; }
body { margin: 0; bgcolor="#000000"; }
</style>
</head>
<body>
<iframe src="%1" frameborder="0" allowfullscreen></iframe>
</body>
</html>
and now I define a webview inside my main layout
<WebView
android:id="@+id/video"
android:visibility="gone"
android:background="#000000"
android:layout_centerInParent="true"
android:layout_width="match_parent"
android:layout_height="match_parent" />
and I use CWebVideoView inside my activity
videoView = (WebView) view.findViewById(R.id.video);
videoView.setVisibility(View.VISIBLE);
cWebVideoView = new CWebVideoView(context, videoView);
cWebVideoView.load(url);
You can add a TextView
to your linear layout programmatically like this:
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.mylayout);
TextView txt1 = new TextView(MyClass.this);
linearLayout.setBackgroundColor(Color.TRANSPARENT);
linearLayout.addView(txt1);
I realize you mentioned SQL browsing, but everything else in your question makes me want to suggest you also consider DB4O, which is a great, simple object DB.
strScriptFullname = WScript.ScriptFullName
strScriptPath = Left(strScriptFullname, InStrRev(strScriptFullname,"\"))
Short Answer: use android:gravity
or setGravity()
to control gravity of all child views of a container; use android:layout_gravity
or setLayoutParams()
to control gravity of an individual view in a container.
Long story: to control gravity in a linear layout container such as LinearLayout
or RadioGroup
, there are two approaches:
1) To control the gravity of ALL child views of a LinearLayout
container (as you did in your book), use android:gravity
(not android:layout_gravity
) in layout XML file or setGravity()
method in code.
2) To control the gravity of a child view in its container, use android:layout_gravity
XML attribute. In code, one needs to get the LinearLayout.LayoutParams
of the view and set its gravity. Here is a code example that set a button to bottom in a horizontally oriented container:
import android.widget.LinearLayout.LayoutParams;
import android.view.Gravity;
...
Button button = (Button) findViewById(R.id.MyButtonId);
// need to cast to LinearLayout.LayoutParams to access the gravity field
LayoutParams params = (LayoutParams)button.getLayoutParams();
params.gravity = Gravity.BOTTOM;
button.setLayoutParams(params);
For horizontal LinearLayout
container, the horizontal gravity of its child view is left-aligned one after another and cannot be changed. Setting android:layout_gravity
to center_horizontal
has no effect. The default vertical gravity is center (or center_vertical) and can be changed to top or bottom. Actually the default layout_gravity
value is -1
but Android put it center vertically.
To change the horizontal positions of child views in a horizontal linear container, one can use layout_weight
, margin and padding of the child view.
Similarly, for vertical View Group container, the vertical gravity of its child view is top-aligned one below another and cannot be changed. The default horizontal gravity is center (or center_horizontal
) and can be changed to left or right.
Actually, a child view such as a button also has android:gravity
XML attribute and the setGravity()
method to control its child views -- the text in it. The Button.setGravity(int)
is linked to this developer.android.com entry.
Seems I don't have enough rep to post a comment, so another answer will have to do.
When you unlink a node using removeChild() or by setting the innerHTML property on the parent, you also need to make sure that there is nothing else referencing it otherwise it won't actually be destroyed and will lead to a memory leak. There are lots of ways in which you could have taken a reference to the node before calling removeChild() and you have to make sure those references that have not gone out of scope are explicitly removed.
Doug Crockford writes here that event handlers are known a cause of circular references in IE and suggests removing them explicitly as follows before calling removeChild()
function purge(d) {
var a = d.attributes, i, l, n;
if (a) {
for (i = a.length - 1; i >= 0; i -= 1) {
n = a[i].name;
if (typeof d[n] === 'function') {
d[n] = null;
}
}
}
a = d.childNodes;
if (a) {
l = a.length;
for (i = 0; i < l; i += 1) {
purge(d.childNodes[i]);
}
}
}
And even if you take a lot of precautions you can still get memory leaks in IE as described by Jens-Ingo Farley here.
And finally, don't fall into the trap of thinking that Javascript delete is the answer. It seems to be suggested by many, but won't do the job. Here is a great reference on understanding delete by Kangax.
Working on Motorola cell phones operating system, we hijacked memory allocation library to observe all memory allocations. It helped to find a lot of problems with memory allocations. Since prevention is better then curing, I would recommend to use static analysis tool like Klockwork or PC-Lint
Here is my complete solution for dynamic String values with case check.
/**
* Makes a portion of String formatted in BOLD.
*
* @param completeString String from which a portion needs to be extracted and formatted.<br> eg. I am BOLD.
* @param targetStringToFormat Target String value to format. <br>eg. BOLD
* @param matchCase Match by target character case or not. If true, BOLD != bold
* @return A string with a portion formatted in BOLD. <br> I am <b>BOLD</b>.
*/
public static SpannableStringBuilder formatAStringPortionInBold(String completeString, String targetStringToFormat, boolean matchCase) {
//Null complete string return empty
if (TextUtils.isEmpty(completeString)) {
return new SpannableStringBuilder("");
}
SpannableStringBuilder str = new SpannableStringBuilder(completeString);
int start_index = 0;
//if matchCase is true, match exact string
if (matchCase) {
if (TextUtils.isEmpty(targetStringToFormat) || !completeString.contains(targetStringToFormat)) {
return str;
}
start_index = str.toString().indexOf(targetStringToFormat);
} else {
//else find in lower cases
if (TextUtils.isEmpty(targetStringToFormat) || !completeString.toLowerCase().contains(targetStringToFormat.toLowerCase())) {
return str;
}
start_index = str.toString().toLowerCase().indexOf(targetStringToFormat.toLowerCase());
}
int end_index = start_index + targetStringToFormat.length();
str.setSpan(new StyleSpan(BOLD), start_index, end_index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return str;
}
Eg. completeString = "I am BOLD"
CASE I
if *targetStringToFormat* = "bold"
and *matchCase* = true
returns "I am BOLD" (since bold != BOLD)
CASE II
if *targetStringToFormat* = "bold"
and *matchCase* = false
returns "I am BOLD"
To Apply:
myTextView.setText(formatAStringPortionInBold("I am BOLD", "bold", false))
Hope that helps!
I have a really stupid use case for why I got this error. Originally I was printing my data > file.txt
Then I changed my mind, and decided to use open("file.txt", "w") instead. But when I called python, I left > file.txt .....
You can use the centos-sclo-rh-testing repo to install GCC v7 without having to compile it forever, also enable V7 by default and let you switch between different versions if required.
sudo yum install -y yum-utils centos-release-scl;
sudo yum -y --enablerepo=centos-sclo-rh-testing install devtoolset-7-gcc;
echo "source /opt/rh/devtoolset-7/enable" | sudo tee -a /etc/profile;
source /opt/rh/devtoolset-7/enable;
gcc --version;
For Scalar Function Syntax is
Select dbo.Function_Name(parameter_name)
Select dbo.Department_Employee_Count('HR')
There's a few problems in your code, first your json must look like :
var json = [{
"id" : "1",
"msg" : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": "[email protected]"
},
{
"id" : "2",
"msg" : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "[email protected]"
}];
Next, you can iterate like this :
for (var key in json) {
if (json.hasOwnProperty(key)) {
alert(json[key].id);
alert(json[key].msg);
}
}
And it gives perfect result.
See the fiddle here : http://jsfiddle.net/zrSmp/
If you want to also support array-like objects, use Array.from (ES2015):
Array.from(arrayLike, x => x.foo);
The advantage it has over Array.prototype.map() method is the input can also be a Set:
let arrayLike = new Set([{foo: 1}, {foo: 2}, {foo: 3}]);
How you deal with this at the moment depends on what model you are using Linq to SQL or EntityFramework?
In L2S you can add
public partial class NWDataContext
{
partial void InsertCategory(Category instance)
{
if(Instance.Date == null)
Instance.Data = DateTime.Now;
ExecuteDynamicInsert(instance);
}
}
EF is a little more complicated see http://msdn.microsoft.com/en-us/library/cc716714.aspx for more info on EF buisiness logic.
Use Java script to change action url dynamically Works for me well
function chgAction( action_name )
{
{% for data in sidebar_menu_data %}
if( action_name== "ABC"){ document.forms.action = "/ABC/";
}
else if( action_name== "XYZ"){ document.forms.action = "/XYZ/";
}
}
<form name="forms" method="post" action="<put default url>" onSubmit="return checkForm(this);">{% csrf_token %}
Does this help you:
<script type="text/javascript">
window.onerror = function() {
alert("Error caught");
};
xxx();
</script>
I'm not sure how it handles Flash errors though...
Update: it doesn't work in Opera, but I'm hacking Dragonfly right now to see what it gets. Suggestion about hacking Dragonfly came from this question:
Here is worked for me:
Subject: SomeSubject
From:Company B (me)
Reply-to:Company A
To:Company A's customers
I had a similar problem. npm install --only=dev
didn't work, and neither did npm rebuild
. Ultimately, I had to delete node_modules
and package-lock.json
and run npm install
again. That fixed it for me.
in javascript, object properties can be accessed with . operator or with associative array indexing using []. ie. object.property
is equivalent to object["property"]
this should do the trick
var smth = mydata.list[0]["points.bean.pointsBase"][0].time;
@xtrem's answer is good, but I think the toFixed
and the makePercentage
are common use. Define two functions, and we can use that at everywhere.
const R = require('ramda')
const RA = require('ramda-adjunct')
const fix = R.invoker(1, 'toFixed')(2)
const makePercentage = R.when(
RA.isNotNil,
R.compose(R.flip(R.concat)('%'), fix, R.multiply(100)),
)
let a = 0.9988
let b = null
makePercentage(b) // -> null
makePercentage(a) // -> ?????99.88%?????