With 2018.3 it appears to automatically detect that I'm using pytest, which is nice, but it still doesn't allow running from the top level of the project. I had to run pytest
for each tests
directory individually.
However, I found that I could choose one of the configurations and manually edit it to run at the root of the project and that this worked. I have to manually choose it in the Configurations drop-down - can't right click on the root folder in the Project pane. But at least it allows me to run all tests at once.
I had a similar issue. pytest
did not recognize a module installed in the environment I was working in.
I resolved it by also installing pytest
into the same environment.
Use the -s
option:
pytest -s
From the docs:
During test execution any output sent to stdout and stderr is captured. If a test or a setup method fails its according captured output will usually be shown along with the failure traceback.
pytest
has the option --capture=method
in which method
is per-test capturing method, and could be one of the following: fd
, sys
or no
. pytest
also has the option -s
which is a shortcut for --capture=no
, and this is the option that will allow you to see your print statements in the console.
pytest --capture=no # show print statements in console
pytest -s # equivalent to previous command
There are two ways in which pytest
can perform capturing:
file descriptor (FD) level capturing (default): All writes going to the operating system file descriptors 1 and 2 will be captured.
sys level capturing: Only writes to Python files sys.stdout and sys.stderr will be captured. No capturing of writes to filedescriptors is performed.
pytest -s # disable all capturing
pytest --capture=sys # replace sys.stdout/stderr with in-mem files
pytest --capture=fd # also point filedescriptors 1 and 2 to temp file
If you want to test for a specific error type, use a combination of try, catch and raise:
#-- test for TypeError
try:
myList.append_number("a")
assert False
except TypeError: pass
except: assert False
Try pytest -s -v test_login.py
for more info in console.
-v
it's a short --verbose
-s
means 'disable all capturing'
Maybe using pytest_collect_file()
hook you can parse the content of a .txt
o .yaml
file where the tests are specify as you want, and return them to the pytest core.
A nice example is shown in the pytest documentation. I think what you are looking for.
This might help http://docs.pytest.org/en/latest/xunit_setup.html
In my test suite, I group my test cases into classes. For the setup and teardown I need for all the test cases in that class, I use the setup_class(cls)
and teardown_class(cls)
classmethods.
And for the setup and teardown I need for each of the test case, I use the setup_method(method)
and teardown_method(methods)
Example:
lh = <got log handler from logger module>
class TestClass:
@classmethod
def setup_class(cls):
lh.info("starting class: {} execution".format(cls.__name__))
@classmethod
def teardown_class(cls):
lh.info("starting class: {} execution".format(cls.__name__))
def setup_method(self, method):
lh.info("starting execution of tc: {}".format(method.__name__))
def teardown_method(self, method):
lh.info("starting execution of tc: {}".format(method.__name__))
def test_tc1(self):
<tc_content>
assert
def test_tc2(self):
<tc_content>
assert
Now when I run my tests, when the TestClass execution is starting, it logs the details for when it is beginning execution, when it is ending execution and same for the methods..
You can add up other setup and teardown steps you might have in the respective locations.
Hope it helps!
I disagree with the posts saying that you must remove any __init__.py
files. What you must instead do is alter the sys.path
.
Run an experiment where you print sys.path
when running the code normally.
Then print sys.path
while running the code via pytest. I think you will find that there is a difference between these two paths, hence why pytest breaks.
To fix this, insert the path from the first experiment at the 0th index of the second.
Let '/usr/exampleUser/Documents/foo'
be the first element of print(sys.path)
for experiment 1.
Below is code that should fix your issue:
import sys
sys.path[0] = '/usr/exampleUser/Documents/foo'
Put this at the top of your file, before your actual import statement.
Source: I was dealing with this myself and the above process solved it.
You're right MacOSX has Objective-C in the core.
Windows C++
Linux C
About the scripting languages, no, they pretty much high level.
In order to create a backup using pg_dump
that is compatible with pg_restore
you must use the --format=custom
/ -Fc
when creating your dump.
From the docs:
Output a custom-format archive suitable for input into pg_restore.
So your pg_dump
command might look like:
pg_dump --file /tmp/db.dump --format=custom --host localhost --dbname my-source-database --username my-username --password
And your pg_restore
command:
pg_restore --verbose --clean --no-acl --no-owner --host localhost --dbname my-destination-database /tmp/db.dump
Not a complete answer, but a useful link:
"I frequently do calculations against decimal values. In some cases casting decimal values to float ASAP, prior to any calculations, yields better accuracy. "
You need to use get_serving_url
from the Images API. As that page explains, you need to call create_gs_key()
first to get the key to pass to the Images API.
When compiling for x64, the difference between int and long is somewhere between 0 and 4 bytes, depending on what compiler you use.
GCC uses the LP64 model, which means that ints are 32-bits but longs are 64-bits under 64-bit mode.
MSVC for example uses the LLP64 model, which means both ints and longs are 32-bits even in 64-bit mode.
You can get it with .outerHeight()
.
Sometimes, it will return 0
. For the best results, you can call it in your div
's ready event.
To be safe, you should not set the height of the div
to x
. You can keep its height auto
to get content populated properly with the correct height.
$('#x').ready( function(){
// alerts the height in pixels
alert($('#x').outerHeight());
})
You can find a detailed post here.
The most likely possibility is that it was the most idiomatic choice. Not only is it easy to speak, but rather intuitive to understand. Some could argue, even more so than var
.
But I reckon there's a little more history to this.
From Wikipedia:
Dana Scott's LCF language was a stage in the evolution of lambda calculus into modern functional languages. This language introduced the let expression, which has appeared in most functional languages since that time.
State-full imperative languages such as ALGOL and Pascal essentially implement a let expression, to implement restricted scope of functions, in block structures.
I would like to believe this was an inspiration too, for the let
in Javascript.
This response doesn't pertain to your stated question, but to an implicit question I see in the code you posted, ie, "how to check if something is an integer?"
The first answer you'll generally get to that question is "Don't!" And it's true that in Python, typechecking is usually not the right thing to do.
For those rare exceptions, though, instead of looking for a decimal point in the string representation of the number, the thing to do is use the isinstance function:
>>> isinstance(5,int)
True
>>> isinstance(5.0,int)
False
Of course this applies to the variable rather than a value. If I wanted to determine whether the value was an integer, I'd do this:
>>> x=5.0
>>> round(x) == x
True
But as everyone else has covered in detail, there are floating-point issues to be considered in most non-toy examples of this kind of thing.
AWS users using the EC2 External Inventory Script can simply filter by instance id:
ansible-playbook sample-playbook.yml --limit i-c98d5a71 --list-hosts
This works because the inventory script creates default groups.
I have run through this. My case was more involved. The project was packaged fine from maven command line.
Couple of things I made. 1. One class has many imports that confused eclipse. Cleaning them fixed part of the problem 2. One case was about a Setter, pressing F3 navigating to that Setter although eclipse complained it is not there. So I simply retyped it and it worked fine (even for all other Setters)
I am still struggling with Implicit super constructor Item() is undefined for default constructor. Must define an explicit constructor"
Often, for init default values of form i use fixtures. Of cause this way is not easiest, but very comfortable.
Example:
class LoadSurgeonPlanData implements FixtureInterface
{
public function load(ObjectManager $manager)
{
$surgeonPlan = new SurgeonPlan();
$surgeonPlan->setName('Free trial');
$surgeonPlan->setPrice(0);
$surgeonPlan->setDelayWorkHours(0);
$surgeonPlan->setSlug('free');
$manager->persist($surgeonPlan);
$manager->flush();
}
}
Yet, symfony type field have the option data.
Example
$builder->add('token', 'hidden', array(
'data' => 'abcdef',
));
The python manual provides the following:
import termios, fcntl, sys, os
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
try:
while 1:
try:
c = sys.stdin.read(1)
print "Got character", repr(c)
except IOError: pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
which can be rolled into your use case.
In MySQL, certain words like SELECT
, INSERT
, DELETE
etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.
As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):
Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.
...
If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.
...
The identifier quote character is the backtick ("
`
"):
A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.
You have two options.
The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.
Doing this has a couple of advantages:
It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.
The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.
Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.
If renaming the table or column isn't possible, wrap the offending identifier in backticks (`
) as described in the earlier quote from 10.2 Schema Object Names.
An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):
mysql> CREATE TABLE interval (begin INT, end INT); ERROR 1064 (42000): You have an error in your SQL syntax. near 'interval (begin INT, end INT)'
mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)
Similarly, the query from the question can be fixed by wrapping the keyword key
in backticks, as shown below:
INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)"; ^ ^
Use the following to evaluate an expression (constant 0 evaluates to false).
#if 0
...
#endif
while True:
b1=input('Type a number:')
try:
a1=int(b1)
except ValueError:
print ('"%(a1)s" is not a number. Try again.' %{'a1':b1})
else:
print ('You typed "{}".'.format(a1))
break
This makes a loop to check whether input is an integer or not, result would look like below:
>>> %Run 1.1.py
Type a number:d
"d" is not a number. Try again.
Type a number:
>>> %Run 1.1.py
Type a number:4
You typed 4.
>>>
Try below code:
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));// set transparent in window background
View _v = inflater.inflate(R.layout.some_you_layout, container, false);
//load animation
//Animation transition_in_view = AnimationUtils.loadAnimation(getContext(), android.R.anim.fade_in);// system animation appearance
Animation transition_in_view = AnimationUtils.loadAnimation(getContext(), R.anim.customer_anim);//customer animation appearance
_v.setAnimation( transition_in_view );
_v.startAnimation( transition_in_view );
//really beautiful
return _v;
}
Create the custom Anim.: res/anim/customer_anim.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="500"
android:fromYDelta="100%"
android:toYDelta="-7%"/>
<translate
android:duration="300"
android:startOffset="500"
android:toYDelta="7%" />
<translate
android:duration="200"
android:startOffset="800"
android:toYDelta="0%" />
</set>
Change Below line
if (str == null | str.length() == 0) {
into
if (str == null || str.isEmpty()) {
now your code will run corectlly. Make sure str.isEmpty()
comes after str == null
because calling isEmpty()
on null will cause NullPointerException
. Because of Java uses Short-circuit evaluation when str == null
is true it will not evaluate str.isEmpty()
You need quotes around the string you're trying to pass off as a date, and you can also use BETWEEN here:
SELECT *
FROM TABLENAME
WHERE DateTime BETWEEN '04/12/2011 12:00:00 AM' AND '05/25/2011 3:53:04 AM'
See answer to the following question for examples on how to explicitly convert strings to dates while specifying the format:
This worked for me:
var message = new HttpRequestMessage(method, url);
message.Headers.TryAddWithoutValidation("user-agent", "<user agent header value>");
var client = new HttpClient();
var response = await client.SendAsync(message);
Here you can find the documentation for TryAddWithoutValidation
The solution involved putting the gtest source directory as a subdirectory of your project. I've included the working CMakeLists.txt below if it is helpful to anyone.
cmake_minimum_required(VERSION 2.6)
project(basic_test)
################################
# GTest
################################
ADD_SUBDIRECTORY (gtest-1.6.0)
enable_testing()
include_directories(${gtest_SOURCE_DIR}/include ${gtest_SOURCE_DIR})
################################
# Unit Tests
################################
# Add test cpp file
add_executable( runUnitTests testgtest.cpp )
# Link test executable against gtest & gtest_main
target_link_libraries(runUnitTests gtest gtest_main)
add_test( runUnitTests runUnitTests )
mkdirs()
will create the specified directory path in its entirety where mkdir()
will only create the bottom most directory, failing if it can't find the parent directory of the directory it is trying to create.
In other words mkdir()
is like mkdir
and mkdirs()
is like mkdir -p
.
For example, imagine we have an empty /tmp
directory. The following code
new File("/tmp/one/two/three").mkdirs();
would create the following directories:
/tmp/one
/tmp/one/two
/tmp/one/two/three
Where this code:
new File("/tmp/one/two/three").mkdir();
would not create any directories - as it wouldn't find /tmp/one/two
- and would return false
.
Escape the | character using a backtick
get-content c:\new\temp_*.txt | select-string -pattern 'H`|159' -notmatch | Out-File c:\new\newfile.txt
Had the same ssl-problem on my developer machine (php 7, xampp on windows) with a self signed certificate trying to fopen a "https://localhost/..."-file. Obviously the root-certificate-assembly (cacert.pem) didn't work. I just copied manually the code from the apache server.crt-File in the downloaded cacert.pem and did the openssl.cafile=path/to/cacert.pem entry in php.ini
To make it more specific Create a tracking branch, which means you are now tracking a remote branch.
git branch --track branch remote-branch
git branch --track exp remotes/origin/experimental
After which you can
git branch # to see the remote tracking branch "exp" created .
Then to work on that branch do
git checkout branchname
git checkout exp
After you have made changes to the branch. You can git fetch and git merge with your remote tracking branch to merge your changes and push to the remote branch as below.
git fetch origin
git merge origin/experimental
git push origin/experimental
Hope it helps and gives you an idea, how this works.
This is what resolved the problem for me:
In your HTML tr tag, add this:
style="border-collapse: collapse; border: none;"
That removed all the borders that were showing on the table row.
I know it's not XAML, but I did the same thing with SizeChanged event of the textbox:
private void TextBlock_SizeChanged(object sender, SizeChangedEventArgs e)
{
TextBlock textBlock = sender as TextBlock;
FrameworkElement element = textBlock.Parent as FrameworkElement;
textBlock.Margin = new Thickness(0, 0, (element.ActualWidth / 100) * 20, 0);
}
The textbox appears to be 80% size of its parent (well right side margin is 20%) and stretches when needed.
Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
Everytime I install node.js it needs a reboot and then the path is recognized.
As mentioned above, there are issues with using the top-most scope in your script file. Here is another issue: The script file might be run from a context that is not the global context in some run-time environment.
It has been proposed to assign the global to window
directly. But that is also run-time dependent and does not work in Node etc. It goes to show that portable global variable management needs some careful consideration and extra effort. Maybe they will fix it in future ECMS versions!
For now, I would recommend something like this to support proper global management for all run-time environments:
/**
* Exports the given object into the global context.
*/
var exportGlobal = function(name, object) {
if (typeof(global) !== "undefined") {
// Node.js
global[name] = object;
}
else if (typeof(window) !== "undefined") {
// JS with GUI (usually browser)
window[name] = object;
}
else {
throw new Error("Unkown run-time environment. Currently only browsers and Node.js are supported.");
}
};
// export exportGlobal itself
exportGlobal("exportGlobal", exportGlobal);
// create a new global namespace
exportGlobal("someothernamespace", {});
It's a bit more typing, but it makes your global variable management future-proof.
Disclaimer: Part of this idea came to me when looking at previous versions of stacktrace.js.
I reckon, one can also use Webpack or other tools to get more reliable and less hackish detection of the run-time environment.
May be this will help you.
SELECT SUBSTRING(myColumn, 1, CASE CHARINDEX('/', myColumn)
WHEN 0
THEN LEN(myColumn)
ELSE CHARINDEX('/', myColumn) - 1
END) AS FirstName
,SUBSTRING(myColumn, CASE CHARINDEX('/', myColumn)
WHEN 0
THEN LEN(myColumn) + 1
ELSE CHARINDEX('/', myColumn) + 1
END, 1000) AS LastName
FROM MyTable
This function uses the current millisecond time to subtract the current week, and then subtracts one more week if the current date is on a monday (javascript counts from sunday).
function getMonday(fromDate) {
// length of one day i milliseconds
var dayLength = 24 * 60 * 60 * 1000;
// Get the current date (without time)
var currentDate = new Date(fromDate.getFullYear(), fromDate.getMonth(), fromDate.getDate());
// Get the current date's millisecond for this week
var currentWeekDayMillisecond = ((currentDate.getDay()) * dayLength);
// subtract the current date with the current date's millisecond for this week
var monday = new Date(currentDate.getTime() - currentWeekDayMillisecond + dayLength);
if (monday > currentDate) {
// It is sunday, so we need to go back further
monday = new Date(monday.getTime() - (dayLength * 7));
}
return monday;
}
I have tested it when week spans over from one month to another (and also years), and it seems to work properly.
With me the problem was solved by removing the type
attribute:
<embed name="myMusic" loop="true" hidden="true" src="Music.mp3"></embed>
Cerntainly not the cleanest way.
If you're using HTML5: MP3 isn't supported by Firefox. Wav and Ogg are though. Here you can find an overview of which browser support which type of audio: http://www.w3schools.com/html/html5_audio.asp
almost there, just change outerWidth: 100%;
to width: auto;
(outerWidth is not a CSS property)
alternatively, apply the following styles to bar:
width: auto;
display: block;
Anyone interested in doing this should read the documentation of the Django Sessions framework. It stores a session ID in the user's cookies, but maps all the cookies-like data to your database. This is an improvement on the typical cookies-based workflow for HTTP requests.
Here is an example with a Django view ...
def homepage(request):
request.session.setdefault('how_many_visits', 0)
request.session['how_many_visits'] += 1
print(request.session['how_many_visits'])
return render(request, 'home.html', {})
If you keep visiting the page over and over, you'll see the value start incrementing up from 1 until you clear your cookies, visit on a new browser, go incognito, or do anything else that sidesteps Django's Session ID cookie.
This is a bit of an ugly solution but you could just do this
var tab = ' ';
And then use the tab variable in your strings.
I agree with @Vishnu's answer. I would like to add that if you want to use the application user in your trigger you can use "context_info" to pass the info to the trigger.
I found following very helpful in doing that: http://jasondentler.com/blog/2010/01/exploiting-context_info-for-fun-and-audit
If you are using it with Hibernate, you'll have to explicitly define the annotation CascadeType.DELETE_ORPHAN
, which can be used in conjunction with JPA CascadeType.ALL
.
If you don't plan to use Hibernate, you'll have to explicitly first delete the child elements and then delete the main record to avoid any orphan records.
execution sequence
With JPA 2.0, you can now use the option orphanRemoval = true
@OneToMany(mappedBy="foo", orphanRemoval=true)
var obj = [
{"name": "Afghanistan", "code": "AF"},
{"name": "Åland Islands", "code": "AX"},
{"name": "Albania", "code": "AL"},
{"name": "Algeria", "code": "DZ"}
];
// the code you're looking for
var needle = 'AL';
// iterate over each element in the array
for (var i = 0; i < obj.length; i++){
// look for the entry with a matching `code` value
if (obj[i].code == needle){
// we found it
// obj[i].name is the matched result
}
}
What you really want to do is to remove any string that starts with either http://
or https://
plus any combination of non white space characters. Here is how I would solve it. My solution is very similar to that of @tolgayilmaz
#Define the text from which you want to replace the url with "".
text ='''The link to this post is https://stackoverflow.com/questions/11331982/how-to-remove-any-url-within-a-string-in-python'''
import re
#Either use:
re.sub('http://\S+|https://\S+', '', text)
#OR
re.sub('http[s]?://\S+', '', text)
And the result of running either code above is
>>> 'The link to this post is '
I prefer the second one because it is more readable.
If you need to set the credentials on the fly, have a look at this source:
http://spc3.codeplex.com/SourceControl/changeset/view/57957#1015709
private ICredentials BuildCredentials(string siteurl, string username, string password, string authtype) {
NetworkCredential cred;
if (username.Contains(@"\")) {
string domain = username.Substring(0, username.IndexOf(@"\"));
username = username.Substring(username.IndexOf(@"\") + 1);
cred = new System.Net.NetworkCredential(username, password, domain);
} else {
cred = new System.Net.NetworkCredential(username, password);
}
CredentialCache cache = new CredentialCache();
if (authtype.Contains(":")) {
authtype = authtype.Substring(authtype.IndexOf(":") + 1); //remove the TMG: prefix
}
cache.Add(new Uri(siteurl), authtype, cred);
return cache;
}
Java date libraries are notoriously broken. I would advise to use Joda Time. It will take care of leap year, time zone and so on for you.
Minimal working example:
import java.util.Scanner;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class DateTestCase {
public static void main(String[] args) {
System.out.print("Insert first date: ");
Scanner s = new Scanner(System.in);
String firstdate = s.nextLine();
System.out.print("Insert second date: ");
String seconddate = s.nextLine();
// Formatter
DateTimeFormatter dateStringFormat = DateTimeFormat
.forPattern("dd MM yyyy");
DateTime firstTime = dateStringFormat.parseDateTime(firstdate);
DateTime secondTime = dateStringFormat.parseDateTime(seconddate);
int days = Days.daysBetween(new LocalDate(firstTime),
new LocalDate(secondTime)).getDays();
System.out.println("Days between the two dates " + days);
}
}
elaborating on the above answers for server deployment.
$hostname = gethostname();
if($hostname=="mydevpc")
{
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
should do the trick for development environment without compromising the server when deployed.
For example, if this is a number :
ouloulou={
1:US,
2:BR,
3:FR
}
ouloulou[1]()
It's work perfectly, but if you use for example :
ouloulou[input("select 1 2 or 3"]()
it's doesn't work, because your input return string '1'. So you need to use int()
ouloulou[int(input("select 1 2 or 3"))]()
Try downgrading your java version, this will happen when your systems java version isn't compatible with the one from android. Once you changed you the java version just run flutter doctor
it will automatically accepts the licenses.
This is not an error, it is a warning from your Microsoft compiler.
Select your project and click "Properties" in the context menu.
In the dialog, chose Configuration Properties
-> C/C++
-> Preprocessor
In the field PreprocessorDefinitions add ;_CRT_SECURE_NO_WARNINGS
to turn those warnings off.
None of the other answers worked for me. I fixed my error by changing the web project's output path. I had had it set to bin\debug but the web project doesn't work unless the output path is set to simply "bin"
If you’re using a multi-byte character encoding and do not just want to remove the first four bytes like substr
does, use the multi-byte counterpart mb_substr
. This does of course will also work with single-byte strings.
You could replace something in there by getting the index along with the item.
>>> foo = ['a', 'b', 'c', 'A', 'B', 'C']
>>> for index, item in enumerate(foo):
... print(index, item)
...
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'A')
(4, 'B')
(5, 'C')
>>> for index, item in enumerate(foo):
... if item in ('a', 'A'):
... foo[index] = 'replaced!'
...
>>> foo
['replaced!', 'b', 'c', 'replaced!', 'B', 'C']
Note that if you want to remove something from the list you have to iterate over a copy of the list, else you will get errors since you're trying to change the size of something you are iterating over. This can be done quite easily with slices.
Wrong:
>>> foo = ['a', 'b', 'c', 1, 2, 3]
>>> for item in foo:
... if isinstance(item, int):
... foo.remove(item)
...
>>> foo
['a', 'b', 'c', 2]
The 2 is still in there because we modified the size of the list as we iterated over it. The correct way would be:
>>> foo = ['a', 'b', 'c', 1, 2, 3]
>>> for item in foo[:]:
... if isinstance(item, int):
... foo.remove(item)
...
>>> foo
['a', 'b', 'c']
left(currentdb.Name,instr(1,currentdb.Name,dir(currentdb.Name))-1)
The Dir function will return only the file portion of the full path. Currentdb.Name is used here, but it could be any full path string.
You want $_SERVER['REQUEST_URI']
. From the docs:
'REQUEST_URI'
The URI which was given in order to access this page; for instance,
'/index.html'
.
I recommend using .htaccess
. You only need to add:
DirectoryIndex home.php
or whatever page name you want to have for it.
EDIT: basic htaccess tutorial.
1) Create .htaccess
file in the directory where you want to change the index file.
.
in front, to ensure it is a "hidden" fileEnter the line above in there. There will likely be many, many other things you will add to this (AddTypes for webfonts / media files, caching for headers, gzip declaration for compression, etc.), but that one line declares your new "home" page.
2) Set server to allow reading of .htaccess
files (may only be needed on your localhost, if your hosting servce defaults to allow it as most do)
Assuming you have access, go to your server's enabled site location. I run a Debian server for development, and the default site setup is at /etc/apache2/sites-available/default
for Debian / Ubuntu. Not sure what server you run, but just search for "sites-available" and go into the "default" document. In there you will see an entry for Directory. Modify it to look like this:
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
Then restart your apache server. Again, not sure about your server, but the command on Debian / Ubuntu is:
sudo service apache2 restart
Technically you only need to reload, but I restart just because I feel safer with a full refresh like that.
Once that is done, your site should be reading from your .htaccess file, and you should have a new default home page! A side note, if you have a sub-directory that runs a site (like an admin section or something) and you want to have a different "home page" for that directory, you can just plop another .htaccess
file in that sub-site's root and it will overwrite the declaration in the parent.
2018 Solution, still other answers are valid but you dont need to use any dependency:
First you have to create a new migration:
php artisan make:migration change_appointment_time_column_type
Then in that migration file up()
, try:
Schema::table('appointments', function ($table) {
$table->string('time')->change();
});
If you donot change the size default will be varchar(191)
but If you want to change size of the field:
Schema::table('appointments', function ($table) {
$table->string('time', 40)->change();
});
Then migrate the file by:
php artisan migrate
To expand on another answer, here is a fairly complete example which can cleanup the tmpdir even on exceptions:
import contextlib
import os
import shutil
import tempfile
@contextlib.contextmanager
def cd(newdir, cleanup=lambda: True):
prevdir = os.getcwd()
os.chdir(os.path.expanduser(newdir))
try:
yield
finally:
os.chdir(prevdir)
cleanup()
@contextlib.contextmanager
def tempdir():
dirpath = tempfile.mkdtemp()
def cleanup():
shutil.rmtree(dirpath)
with cd(dirpath, cleanup):
yield dirpath
def main():
with tempdir() as dirpath:
pass # do something here
For this error:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
There are problems with your import or package name.
You can delete the package name or fix import errors
use this function derived from link provided by IJas
function openFbPopUp() {
var fburl = '';
var fbimgurl = 'http://';
var fbtitle = 'Your title';
var fbsummary = "your description";
var sharerURL = "http://www.facebook.com/sharer/sharer.php?s=100&p[url]=" + encodeURI(fburl) + "&p[images][0]=" + encodeURI(fbimgurl) + "&p[title]=" + encodeURI(fbtitle) + "&p[summary]=" + encodeURI(fbsummary);
window.open(
sharerURL,
'facebook-share-dialog',
'width=626,height=436');
return false;
}
Or you can also use the latest FB.ui Function if using FB JavaScript SDK for more controlled callback function.
refer: FB.ui
function openFbPopUp() {
FB.ui(
{
method: 'feed',
name: 'Facebook Dialogs',
link: 'https://developers.facebook.com/docs/dialogs/',
picture: 'http://fbrell.com/f8.jpg',
caption: 'Reference Documentation',
description: 'Dialogs provide a simple, consistent interface for applications to interface with users.'
},
function(response) {
if (response && response.post_id) {
alert('Post was published.');
} else {
alert('Post was not published.');
}
}
);
}
I don't like adding new package into my project just to handle this simple task.
And also, I try my best to avoid RECURSIVE algorithm.... since, for most cases it is slower compared to non Recursive one.
So I made a function to get all the folder content (and its sub folder).... NON-Recursively
var getDirectoryContent = function(dirPath) {
/*
get list of files and directories from given dirPath and all it's sub directories
NON RECURSIVE ALGORITHM
By. Dreamsavior
*/
var RESULT = {'files':[], 'dirs':[]};
var fs = fs||require('fs');
if (Boolean(dirPath) == false) {
return RESULT;
}
if (fs.existsSync(dirPath) == false) {
console.warn("Path does not exist : ", dirPath);
return RESULT;
}
var directoryList = []
var DIRECTORY_SEPARATOR = "\\";
if (dirPath[dirPath.length -1] !== DIRECTORY_SEPARATOR) dirPath = dirPath+DIRECTORY_SEPARATOR;
directoryList.push(dirPath); // initial
while (directoryList.length > 0) {
var thisDir = directoryList.shift();
if (Boolean(fs.existsSync(thisDir) && fs.lstatSync(thisDir).isDirectory()) == false) continue;
var thisDirContent = fs.readdirSync(thisDir);
while (thisDirContent.length > 0) {
var thisFile = thisDirContent.shift();
var objPath = thisDir+thisFile
if (fs.existsSync(objPath) == false) continue;
if (fs.lstatSync(objPath).isDirectory()) { // is a directory
let thisDirPath = objPath+DIRECTORY_SEPARATOR;
directoryList.push(thisDirPath);
RESULT['dirs'].push(thisDirPath);
} else { // is a file
RESULT['files'].push(objPath);
}
}
}
return RESULT;
}
the only drawback of this function is that this is Synchronous function... You have been warned ;)
I use LuaSocket to get more precision.
require "socket"
print("Milliseconds: " .. socket.gettime()*1000)
This adds a dependency of course, but works fine for personal use (in benchmarking scripts for example).
Why wouldn't the user just hit the home button? Then they can exit your app from any of your activities, not just a specific one.
If you are worried about your application continuing to do something in the background. Make sure to stop it in the relevant onPause and onStop commands (which will get triggered when the user presses Home).
If your issue is that you want the next time the user clicks on your app for it to start back at the beginning, I recommend putting some kind of menu item or UI button on the screen that takes the user back to the starting activity of your app. Like the twitter bird in the official twitter app, etc.
__all__
is very good - it helps guide import statements without automatically importing modules
http://docs.python.org/tutorial/modules.html#importing-from-a-package
using __all__
and import *
is redundant, only __all__
is needed
I think one of the most powerful reasons to use import *
in an __init__.py
to import packages is to be able to refactor a script that has grown into multiple scripts without breaking an existing application. But if you're designing a package from the start. I think it's best to leave __init__.py
files empty.
for example:
foo.py - contains classes related to foo such as fooFactory, tallFoo, shortFoo
then the app grows and now it's a whole folder
foo/
__init__.py
foofactories.py
tallFoos.py
shortfoos.py
mediumfoos.py
santaslittlehelperfoo.py
superawsomefoo.py
anotherfoo.py
then the init script can say
__all__ = ['foofactories', 'tallFoos', 'shortfoos', 'medumfoos',
'santaslittlehelperfoo', 'superawsomefoo', 'anotherfoo']
# deprecated to keep older scripts who import this from breaking
from foo.foofactories import fooFactory
from foo.tallfoos import tallFoo
from foo.shortfoos import shortFoo
so that a script written to do the following does not break during the change:
from foo import fooFactory, tallFoo, shortFoo
http://phpjs.org/functions/isset:454
phpjs project is a trusted source. Lots of js equivalent php functions available there. I have been using since a long time and found no issues so far.
Go with this
body {
padding:0px;
margin:0px;
}
To find an ancestor of a given type from code, you can use:
[CanBeNull]
public static T FindAncestor<T>(DependencyObject d) where T : DependencyObject
{
while (true)
{
d = VisualTreeHelper.GetParent(d);
if (d == null)
return null;
var t = d as T;
if (t != null)
return t;
}
}
This implementation uses iteration instead of recursion which can be slightly faster.
If you're using C# 7, this can be made slightly shorter:
[CanBeNull]
public static T FindAncestor<T>(DependencyObject d) where T : DependencyObject
{
while (true)
{
d = VisualTreeHelper.GetParent(d);
if (d == null)
return null;
if (d is T t)
return t;
}
}
Launch the Chrome Android app.
Open any offline website or webpage that you need to hard refresh.
Change the onclick from
onclick="javascript:SubmitFrm()"
to
onclick="SubmitFrm()"
Go to "Control Panel" -> "Administrative Tools" and open "Datasources (ODBC)". By default, the tab "User-DSN" will be opened, click "Add" and a dialogue will pop up:
You can also install the required packages with Help -> Install new software...
See http://www.eclipse.org/downloads/compare.php for the packages you need to install to have eclipse IDE for java EE developers
You can use %
:
SELECT * FROM datetable WHERE datecol LIKE '2012-12-25%'
There is a simple hack to this:
Insert a hidden input field in the form with an entity which only occur in the character set the server your posting (or doing a GET) to accepts.
Example: If the form is located on a server serving ISO-8859-1 and the form will post to a server expecting UTF-8 insert something like this in the form:
<input name="iehack" type="hidden" value="☠" />
IE will then "detect" that the form contains a UTF-8 character and use UTF-8 when you POST or GET. Strange, but it does work.
Use #include <windows.h>
instead of #include <windef.h>
.
From the windows.h
wikipedia page:
There are a number of child header files that are automatically included with
windows.h
. Many of these files cannot simply be included by themselves (they are not self-contained), because of dependencies.
windef.h
is one of the files automatically included with windows.h
.
Local variables are non existent in the memory after the function termination.
However static
variables remain allocated in the memory throughout the life of the program irrespective of whatever function.
Additionally from your question, static
variables can be declared locally in class
or function scope and globally in namespace
or file scope. They are allocated the memory from beginning to end, it's just the initialization which happens sooner or later.
In case, you would like to collect bitstamp trade data form their websocket in higher resolution over longer time period you could use script log_bitstamp_trades.py below.
The script uses python websocket-client and pusher_client_python libraries, so install them.
#!/usr/bin/python
import pusherclient
import time
import logging
import sys
import datetime
import signal
import os
logging.basicConfig()
log_file_fd = None
def sigint_and_sigterm_handler(signal, frame):
global log_file_fd
log_file_fd.close()
sys.exit(0)
class BitstampLogger:
def __init__(self, log_file_path, log_file_reload_path, pusher_key, channel, event):
self.channel = channel
self.event = event
self.log_file_fd = open(log_file_path, "a")
self.log_file_reload_path = log_file_reload_path
self.pusher = pusherclient.Pusher(pusher_key)
self.pusher.connection.logger.setLevel(logging.WARNING)
self.pusher.connection.bind('pusher:connection_established', self.connect_handler)
self.pusher.connect()
def callback(self, data):
utc_timestamp = time.mktime(datetime.datetime.utcnow().timetuple())
line = str(utc_timestamp) + " " + data + "\n"
if os.path.exists(self.log_file_reload_path):
os.remove(self.log_file_reload_path)
self.log_file_fd.close()
self.log_file_fd = open(log_file_path, "a")
self.log_file_fd.write(line)
def connect_handler(self, data):
channel = self.pusher.subscribe(self.channel)
channel.bind(self.event, self.callback)
def main(log_file_path, log_file_reload_path):
global log_file_fd
bitstamp_logger = BitstampLogger(
log_file_path,
log_file_reload_path,
"de504dc5763aeef9ff52",
"live_trades",
"trade")
log_file_fd = bitstamp_logger.log_file_fd
signal.signal(signal.SIGINT, sigint_and_sigterm_handler)
signal.signal(signal.SIGTERM, sigint_and_sigterm_handler)
while True:
time.sleep(1)
if __name__ == '__main__':
log_file_path = sys.argv[1]
log_file_reload_path = sys.argv[2]
main(log_file_path, log_file_reload_path
and logrotate file config
/mnt/data/bitstamp_logs/bitstamp-trade.log
{
rotate 10000000000
minsize 10M
copytruncate
missingok
compress
postrotate
touch /mnt/data/bitstamp_logs/reload_log > /dev/null
endscript
}
then you can run it on background
nohup ./log_bitstamp_trades.py /mnt/data/bitstamp_logs/bitstamp-trade.log /mnt/data/bitstamp_logs/reload_log &
127.0.0.1 restricts access on every interface on port 8000 except development computer. change it to 0.0.0.0:8000 this will allow connection from curl.
I like this for clarity and a DRY syntax.
varName = "larry";
switch (true)
{
case ["afshin", "saeed", "larry"].includes(varName) :
alert('Hey');
break;
default:
alert('Default case');
}
It looks like a JSON string. You can use one of many JSON libraries and it's as simple as doing:
JSON.parse(string)
Both of these work,
jQuery(this).attr("id");
and
alert(this.id);
If you want to use a function form a package or module in python you have to import and reference them. For example normally you do the following to draw 5 points( [1,5],[2,4],[3,3],[4,2],[5,1]) in the space:
import matplotlib.pyplot
matplotlib.pyplot.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
matplotlib.pyplot.show()
In your solution
from matplotlib import*
This imports the package matplotlib and "plot is not defined" means there is no plot function in matplotlib you can access directly, but instead if you import as
from matplotlib.pyplot import *
plot([1,2,3,4,5],[5,4,3,2,1],"bx")
show()
Now you can use any function in matplotlib.pyplot without referencing them with matplotlib.pyplot.
I would recommend you to name imports you have, in this case you can prevent disambiguation and future problems with the same function names. The last and clean version of above example looks like:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
plt.show()
Use:
Create a batch file
Copy the below text into the batch file
set folder="C:\test"
cd /d %folder%
for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
It will delete all files and folders.
You can bind the 'input' event to the textbox. This would fire every time the input changes, so when you paste something (even with right click), delete and type anything.
$('#myTextbox').on('input', function() {
// do something
});
If you use the change
handler, this will only fire after the user deselects the input box, which may not be what you want.
There is an example of both here: http://jsfiddle.net/6bSX6/
You can use the IAsyncResult and Action class/interface to achieve this.
public void TimeoutExample()
{
IAsyncResult result;
Action action = () =>
{
// Your code here
};
result = action.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(10000))
Console.WriteLine("Method successful.");
else
Console.WriteLine("Method timed out.");
}
I use getActionCommand() to hear buttons. I apply the setActionCommand() to each button so that I can hear whenever an event is execute with event.getActionCommand("The setActionCommand() value of the button").
I use getSource() for JRadioButtons for example. I write methods that returns each JRadioButton so in my Listener Class I can specify an action each time a new JRadioButton is pressed. So for example:
public class SeleccionListener implements ActionListener, FocusListener {}
So with this I can hear button events and radioButtons events. The following are examples of how I listen each one:
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals(GUISeleccion.BOTON_ACEPTAR)) {
System.out.println("Aceptar pressed");
}
In this case GUISeleccion.BOTON_ACEPTAR is a "public static final String" which is used in JButtonAceptar.setActionCommand(BOTON_ACEPTAR).
public void focusGained(FocusEvent focusEvent) {
if (focusEvent.getSource().equals(guiSeleccion.getJrbDat())){
System.out.println("Data radio button");
}
In this one, I get the source of any JRadioButton that is focused when the user hits it. guiSeleccion.getJrbDat() returns the reference to the JRadioButton that is in the class GUISeleccion (this is a Frame)
A cleaner way instead of the
textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
method is to use
textView.getPaint().setUnderlineText(true);
And if you need to later turn off underlining for that view, such as in a reused view in a RecyclerView, textView.getPaint().setUnderlineText(false);
I landed here once because I was working with git itself. When I built it the default makefile installed the binary in ~/bin/git. Since my PATH had ~/bin first when I ran 'git pull --rebase' it used the one in ~/bin and consequently could not locate the helpers.
I worked around the issue by running '/usr/bin/git ...' with a full path (alternatively I could have adjusted my PATH).
just add using System.Linq
and see the magic happening when you try to access the available methods in the IEnumerable
. Adding this will give you access to method named Count()
as simple as that. just remember to check for null value
before calling count()
:)
re
(as in regular expressions) allows splitting on multiple characters at once:
$ string = "blah, lots , of , spaces, here "
$ re.split(', ',string)
['blah', 'lots ', ' of ', ' spaces', 'here ']
This doesn't work well for your example string, but works nicely for a comma-space separated list. For your example string, you can combine the re.split power to split on regex patterns to get a "split-on-this-or-that" effect.
$ re.split('[, ]',string)
['blah',
'',
'lots',
'',
'',
'',
'',
'of',
'',
'',
'',
'spaces',
'',
'here',
'']
Unfortunately, that's ugly, but a filter
will do the trick:
$ filter(None, re.split('[, ]',string))
['blah', 'lots', 'of', 'spaces', 'here']
Voila!
Try: Controls("Check Box 1") = True
Use below css to align Label with Checkbox
.chkbox label
{
position: relative;
top: -2px;
}
<div class="chkbox">
<asp:CheckBox ID="Ckbox" runat="server" Text="Check Box Alignment"/>
</div>
I have faced the problem by placing a <div>
inside <td>
.
I was unable to identify the div using document.getElementById()
if i place that inside td. But outside, it was working fine.
The scope <scope>provided</scope>
gives you an opportunity to tell that the jar would be available at runtime, so do not bundle it. It does not mean that you do not need it at compile time, hence maven would try to download that.
Now I think, the below maven artifact do not exist at all. I tries searching google, but not able to find. Hence you are getting this issue.
Change groupId
to <groupId>net.sourceforge.ant4x</groupId>
to get the latest jar.
<dependency>
<groupId>net.sourceforge.ant4x</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
Another solution for this problem is:
Where http://localhost/repo is your local repo URL:
<repositories>
<repository>
<id>wmc-central</id>
<url>http://localhost/repo</url>
</repository>
<-- Other repository config ... -->
</repositories>
You should not use the viewport meta tag at all if your design is not responsive. Misusing this tag may lead to broken layouts. You may read this article for documentation about why you should'n use this tag unless you know what you're doing. http://blog.javierusobiaga.com/stop-using-the-viewport-tag-until-you-know-ho
"user-scalable=no" also helps to prevent the zoom-in effect on iOS input boxes.
Here's my solution:
@arr = ['<p>Hello World</p>', '<p>This is a test</p>']
@arr.reduce(:+)
=> <p>Hello World</p><p>This is a test</p>
In my case the same error happen because I was trying to use mysql by just typing "mysql" instead of "mysql -u root -p"
The simplest and most reliable solution is inserting flex items at the right places. If they are wide enough (width: 100%
), they will force a line break.
.container {_x000D_
background: tomato;_x000D_
display: flex;_x000D_
flex-flow: row wrap;_x000D_
align-content: space-between;_x000D_
justify-content: space-between;_x000D_
}_x000D_
.item {_x000D_
width: 100px;_x000D_
background: gold;_x000D_
height: 100px;_x000D_
border: 1px solid black;_x000D_
font-size: 30px;_x000D_
line-height: 100px;_x000D_
text-align: center;_x000D_
margin: 10px_x000D_
}_x000D_
.item:nth-child(4n - 1) {_x000D_
background: silver;_x000D_
}_x000D_
.line-break {_x000D_
width: 100%;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="item">1</div>_x000D_
<div class="item">2</div>_x000D_
<div class="item">3</div>_x000D_
<div class="line-break"></div>_x000D_
<div class="item">4</div>_x000D_
<div class="item">5</div>_x000D_
<div class="item">6</div>_x000D_
<div class="line-break"></div>_x000D_
<div class="item">7</div>_x000D_
<div class="item">8</div>_x000D_
<div class="item">9</div>_x000D_
<div class="line-break"></div>_x000D_
<div class="item">10</div>_x000D_
</div>
_x000D_
But that's ugly and not semantic. Instead, we could generate pseudo-elements inside the flex container, and use order
to move them to the right places.
.container {_x000D_
background: tomato;_x000D_
display: flex;_x000D_
flex-flow: row wrap;_x000D_
align-content: space-between;_x000D_
justify-content: space-between;_x000D_
}_x000D_
.item {_x000D_
width: 100px;_x000D_
background: gold;_x000D_
height: 100px;_x000D_
border: 1px solid black;_x000D_
font-size: 30px;_x000D_
line-height: 100px;_x000D_
text-align: center;_x000D_
margin: 10px_x000D_
}_x000D_
.item:nth-child(3n) {_x000D_
background: silver;_x000D_
}_x000D_
.container::before, .container::after {_x000D_
content: '';_x000D_
width: 100%;_x000D_
order: 1;_x000D_
}_x000D_
.item:nth-child(n + 4) {_x000D_
order: 1;_x000D_
}_x000D_
.item:nth-child(n + 7) {_x000D_
order: 2;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="item">1</div>_x000D_
<div class="item">2</div>_x000D_
<div class="item">3</div>_x000D_
<div class="item">4</div>_x000D_
<div class="item">5</div>_x000D_
<div class="item">6</div>_x000D_
<div class="item">7</div>_x000D_
<div class="item">8</div>_x000D_
<div class="item">9</div>_x000D_
</div>
_x000D_
But there is a limitation: the flex container can only have a ::before
and a ::after
pseudo-element. That means you can only force 2 line breaks.
To solve that, you can generate the pseudo-elements inside the flex items instead of in the flex container. This way you won't be limited to 2. But those pseudo-elements won't be flex items, so they won't be able to force line breaks.
But luckily, CSS Display L3 has introduced display: contents
(currently only supported by Firefox 37):
The element itself does not generate any boxes, but its children and pseudo-elements still generate boxes as normal. For the purposes of box generation and layout, the element must be treated as if it had been replaced with its children and pseudo-elements in the document tree.
So you can apply display: contents
to the children of the flex container, and wrap the contents of each one inside an additional wrapper. Then, the flex items will be those additional wrappers and the pseudo-elements of the children.
.container {_x000D_
background: tomato;_x000D_
display: flex;_x000D_
flex-flow: row wrap;_x000D_
align-content: space-between;_x000D_
justify-content: space-between;_x000D_
}_x000D_
.item {_x000D_
display: contents;_x000D_
}_x000D_
.item > div {_x000D_
width: 100px;_x000D_
background: gold;_x000D_
height: 100px;_x000D_
border: 1px solid black;_x000D_
font-size: 30px;_x000D_
line-height: 100px;_x000D_
text-align: center;_x000D_
margin: 10px;_x000D_
}_x000D_
.item:nth-child(3n) > div {_x000D_
background: silver;_x000D_
}_x000D_
.item:nth-child(3n)::after {_x000D_
content: '';_x000D_
width: 100%;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="item"><div>1</div></div>_x000D_
<div class="item"><div>2</div></div>_x000D_
<div class="item"><div>3</div></div>_x000D_
<div class="item"><div>4</div></div>_x000D_
<div class="item"><div>5</div></div>_x000D_
<div class="item"><div>6</div></div>_x000D_
<div class="item"><div>7</div></div>_x000D_
<div class="item"><div>8</div></div>_x000D_
<div class="item"><div>9</div></div>_x000D_
<div class="item"><div>10</div></div>_x000D_
</div>
_x000D_
Alternatively, according to Fragmenting Flex Layout and CSS Fragmentation, Flexbox allows forced breaks by using break-before
, break-after
or their CSS 2.1 aliases:
.item:nth-child(3n) {
page-break-after: always; /* CSS 2.1 syntax */
break-after: always; /* New syntax */
}
.container {_x000D_
background: tomato;_x000D_
display: flex;_x000D_
flex-flow: row wrap;_x000D_
align-content: space-between;_x000D_
justify-content: space-between;_x000D_
}_x000D_
.item {_x000D_
width: 100px;_x000D_
background: gold;_x000D_
height: 100px;_x000D_
border: 1px solid black;_x000D_
font-size: 30px;_x000D_
line-height: 100px;_x000D_
text-align: center;_x000D_
margin: 10px_x000D_
}_x000D_
.item:nth-child(3n) {_x000D_
page-break-after: always;_x000D_
background: silver;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="item">1</div>_x000D_
<div class="item">2</div>_x000D_
<div class="item">3</div>_x000D_
<div class="item">4</div>_x000D_
<div class="item">5</div>_x000D_
<div class="item">6</div>_x000D_
<div class="item">7</div>_x000D_
<div class="item">8</div>_x000D_
<div class="item">9</div>_x000D_
<div class="item">10</div>_x000D_
</div>
_x000D_
Forced line breaks in flexbox are not widely supported yet, but it works on Firefox.
As already stated: closures, out of the box, cannot be serialized.
However, using the __sleep()
, __wakeup()
magic methods and reflection u CAN manually make closures serializable. For more details see extending-php-5-3-closures-with-serialization-and-reflection
This makes use of reflection and the php function eval. Do note this opens up the possibility of CODE injection, so please take notice of WHAT you are serializing.
Clear improperly cached compile errors.
All Projects Locations in Eclipse
workspace\.metadata\.plugins\org.eclipse.core.resources\.projects\<project>\
First things first, hover the mouse over the grey area below. Not part of the answer, but absolutely has to be said:
If you have a shell script that does "checkout, build, deploy" all by itself, then why are you using Jenkins? You are foregoing all the features of Jenkins that make it what it is. You might as well have a cron or an SVN post-commit hook call the script directly. Jenkins performing the SVN checkout itself is crucial. It allows the builds to be triggered only when there are changes (or on timer, or manual, if you prefer). It keeps track of changes between builds. It shows those changes, so you can see which build was for which set of changes. It emails committers when their changes caused successful or failed build (again, as configured as you prefer). It will email committers when their fixes fixed the failing build. And more and more. Jenkins archiving the artifacts also makes them available, per build, straight off Jenkins. While not as crucial as the SVN checkout, this is once again an integral part of what makes it Jenkins. Same with deploying. Unless you have a single environment, deployment usually happens to multiple environments. Jenkins can keep track of which environment a specific build (with specific set of SVN changes) is deployed it, through the use of Promotions. You are foregoing all of this. It sounds like you are told "you have to use Jenkins" but you don't really want to, and you are doing it just to get your bosses off your back, just to put a checkmark "yes, I've used Jenkins"
The short answer is: the exit code of last command of the Jenkin's Execute Shell build step is what determines the success/failure of the Build Step. 0
- success, anything else
- failure.
Note, this is determining the success/failure of the build step, not the whole job run. The success/failure of the whole job run can further be affected by multiple build steps, and post-build actions and plugins.
You've mentioned Build step 'Execute shell' marked build as failure
, so we will focus just on a single build step. If your Execute shell build step only has a single line that calls your shell script, then the exit code of your shell script will determine the success/failure of the build step. If you have more lines, after your shell script execution, then carefully review them, as they are the ones that could be causing failure.
Finally, have a read here Jenkins Build Script exits after Google Test execution. It is not directly related to your question, but note that part about Jenkins launching the Execute Shell build step, as a shell script with /bin/sh -xe
The -e
means that the shell script will exit with failure, even if just 1 command fails, even if you do error checking for that command (because the script exits before it gets to your error checking). This is contrary to normal execution of shell scripts, which usually print the error message for the failed command (or redirect it to null and handle it by other means), and continue.
To circumvent this, add set +e
to the top of your shell script.
Since you say your script does all it is supposed to do, chances are the failing command is somewhere at the end of the script. Maybe a final echo? Or copy of artifacts somewhere? Without seeing the full console output, we are just guessing.
Please post the job run's console output, and preferably the shell script itself too, and then we could tell you exactly which line is failing.
If you have a array of objects you can do like this:
myArrayObjects = myArrayObjects.sort(function(a, b) {
return a.name.localeCompare(b.name, undefined, {
numeric: true,
sensitivity: 'base'
});
});
var myArrayObjects = [{_x000D_
"id": 1,_x000D_
"name": "1 example"_x000D_
},_x000D_
{_x000D_
"id": 2,_x000D_
"name": "100 example"_x000D_
},_x000D_
{_x000D_
"id": 3,_x000D_
"name": "12 example"_x000D_
},_x000D_
{_x000D_
"id": 4,_x000D_
"name": "5 example"_x000D_
},_x000D_
_x000D_
]_x000D_
_x000D_
myArrayObjects = myArrayObjects.sort(function(a, b) {_x000D_
return a.name.localeCompare(b.name, undefined, {_x000D_
numeric: true,_x000D_
sensitivity: 'base'_x000D_
});_x000D_
});_x000D_
console.log(myArrayObjects);
_x000D_
The ASP.NET Core way is now here:
[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
// full path to file in temp location
var filePath = Path.GetTempFileName();
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
using (var stream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
}
}
}
// process uploaded files
// Don't rely on or trust the FileName property without validation.
return Ok(new { count = files.Count, size, filePath});
}
is it possible to export without looping through all records
For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application
object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data
Option Explicit
Sub AccImport()
Dim acc As New Access.Application
acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
acc.DoCmd.TransferSpreadsheet _
TransferType:=acImport, _
SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
TableName:="tblExcelImport", _
Filename:=Application.ActiveWorkbook.FullName, _
HasFieldNames:=True, _
Range:="Folio_Data_original$A1:B10"
acc.CloseCurrentDatabase
acc.Quit
Set acc = Nothing
End Sub
Seconds since epoch to datetime
to strftime
:
>>> ts_epoch = 1362301382
>>> ts = datetime.datetime.fromtimestamp(ts_epoch).strftime('%Y-%m-%d %H:%M:%S')
>>> ts
'2013-03-03 01:03:02'
I would put decimal.MaxValue.ToString()
since this is the effective ceiling for the decmial type it is equivalent to not having an upper bound.
Change the order you're including your scripts (jQuery first):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="./javascript.js"></script>
<script
src="http://maps.googleapis.com/maps/api/js?key=YOUR_APIKEY&sensor=false">
</script>
Use
text-align: right
The text-align CSS property describes how inline content like text is aligned in its parent block element. text-align does not control the alignment of block elements itself, only their inline content.
See
<td class='alnright'>text to be aligned to right</td>
<style>
.alnright { text-align: right; }
</style>
function FastScrollUp()
{
window.scroll(0,0)
};
function FastScrollDown()
{
$i = document.documentElement.scrollHeight ;
window.scroll(0,$i)
};
var step = 20;
var h,t;
var y = 0;
function SmoothScrollUp()
{
h = document.documentElement.scrollHeight;
y += step;
window.scrollBy(0, -step)
if(y >= h )
{clearTimeout(t); y = 0; return;}
t = setTimeout(function(){SmoothScrollUp()},20);
};
function SmoothScrollDown()
{
h = document.documentElement.scrollHeight;
y += step;
window.scrollBy(0, step)
if(y >= h )
{clearTimeout(t); y = 0; return;}
t = setTimeout(function(){SmoothScrollDown()},20);
}
$myObj = new stdClass();
// OR
$myObj = (object) [
"foo" => "Foo value",
"bar" => "Bar value"
];
I love how easy is to create objects of anonymous type in JavaScript:
//JavaScript
var myObj = {
foo: "Foo value",
bar: "Bar value"
};
console.log(myObj.foo); //Output: Foo value
So I always try to write this kind of objects in PHP like javascript does:
//PHP >= 5.4
$myObj = (object) [
"foo" => "Foo value",
"bar" => "Bar value"
];
//PHP < 5.4
$myObj = (object) array(
"foo" => "Foo value",
"bar" => "Bar value"
);
echo $myObj->foo; //Output: Foo value
But as this is basically an array you can't do things like assign anonymous functions to a property like js does:
//JavaScript
var myObj = {
foo: "Foo value",
bar: function(greeting) {
return greeting + " bar";
}
};
console.log(myObj.bar("Hello")); //Output: Hello bar
//PHP >= 5.4
$myObj = (object) [
"foo" => "Foo value",
"bar" => function($greeting) {
return $greeting . " bar";
}
];
var_dump($myObj->bar("Hello")); //Throw 'undefined function' error
var_dump($myObj->bar); //Output: "object(Closure)"
Well, you can do it, but IMO isn't practical / clean:
$barFunc = $myObj->bar;
echo $barFunc("Hello"); //Output: Hello bar
Also, using this synthax you can find some funny surprises, but works fine for most cases.
You can use itertools.cycle
:
>>> from itertools import cycle
>>> lis = [[10,13,17],[3,5,1],[13,11,12]]
>>> cyc = cycle((-1, 1))
>>> 50 + sum(x*next(cyc) for x in lis[0]) # lis[0] is [10,13,17]
36
Here the generator expression inside sum
would return something like this:
>>> cyc = cycle((-1, 1))
>>> [x*next(cyc) for x in lis[0]]
[-10, 13, -17]
You can also use zip
here:
>>> cyc = cycle((-1, 1))
>>> [x*y for x, y in zip(lis[0], cyc)]
[-10, 13, -17]
You could use flatMap. It can filter and map in one.
$scope.appIds = $scope.applicationsHere.flatMap(obj => obj.selected ? obj.id : [])
UITableView
has a property separatorInset
. You can use that to set the insets of the table view separators to zero to let them span the full width of the screen.
[tableView setSeparatorInset:UIEdgeInsetsZero];
Note: If your app is also targeting other iOS versions, you should check for the availability of this property before calling it by doing something like this:
if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
[tableView setSeparatorInset:UIEdgeInsetsZero];
}
\r
move the cursor to the begin of the line.
Line breaks are managed differently on different systems. Some only use \n
(line feed, e.g. Unix), some use (\r
e.g. MacOS before OS X afaik) and some use \r\n
(e.g. Windows afaik).
public changeAttr(int id)
{
list.Find(p => p.IdItem == id).FieldToModify = newValueForTheFIeld;
}
With:
IdItem is the id of the element you want to modify
FieldToModify is the Field of the item that you want to update.
NewValueForTheField is exactly that, the new value.
(It works perfect for me, tested and implemented)
As the html5 way (my previous answer) is not available in all browsers, heres another slightly hack way.
This solution requires you are serving the intended file from same domain, OR has CORS permission.
application/octet-stream
.
Result should look likedata:application/octet-stream;base64,SGVsbG8sIFdvcmxkIQ%3D%3D
Now set location.href = data
. This will cause the browser to download the file. Unfortunately you can't set file name or extension this way. Fiddling with the media-type could yield something.
See details: https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs
I was having the same problem but when I created a test project, to my surprise, datepicker worked perfectly using Bootstrap v2.0.2 and Jquery UI 1.8.11. Here are the scripts i'm including:
<link href="@Url.Content("~/Content/bootstrap.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/bootstrap-responsive.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/themes/base/jquery.ui.all.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
You can pass the event as argument to the function and then prevent the default behaviour.
var OnSubmitTest = React.createClass({
render: function() {
doSomething = function(event){
event.preventDefault();
alert('it works!');
}
return <form onSubmit={this.doSomething}>
<button>Click me</button>
</form>;
}
});
It specifies an "Anchor", or a position on the page, and allows you to "jump" or "scroll" to that position on the page.
Please see this page for more details.
Here's a collection of scripts: http://webtecker.com/2008/03/26/collection-of-password-strength-scripts/
I think both of them rate the password and don't use jQuery... but I don't know if they have native support for disabling the form?
As a workaround you could add a handler to the ServicePointManager
's ServerCertificateValidationCallback
on the client side:
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
(se, cert, chain, sslerror) =>
{
return true;
};
but be aware that this is not a good practice as it completely ignores the server certificate and tells the service point manager that whatever certificate is fine which can seriously compromise client security. You could refine this and do some custom checking (for certificate name, hash etc). at least you can circumvent problems during development when using test certificates.
showInventory(player);
is passing a type as parameter. That's illegal, you need to pass an object.
For example, something like:
player p;
showInventory(p);
I'm guessing you have something like this:
int main()
{
player player;
toDo();
}
which is awful. First, don't name the object the same as your type. Second, in order for the object to be visible inside the function, you'll need to pass it as parameter:
int main()
{
player p;
toDo(p);
}
and
std::string toDo(player& p)
{
//....
showInventory(p);
//....
}
Use dir
or type
on the 'string' to find out what it is. I suspect that it's one of BeautifulSoup's tag objects, that prints like a string, but really isn't one. Otherwise, its inside a list and you need to convert each string separately.
In any case, why are you objecting to using Unicode? Any specific reason?
Yes this will be accesible from other machines if you bind on any external IP address. For example binding to http://*:80
. Note that binding to http://localhost:80
will only bind on 127.0.0.1 interface and therefore will not be accesible from other machines.
Visual Studio is overriding your port. You can change VS port editing this file Properties\launchSettings.json
or else set it by code:
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseUrls("http://*:80") // <-----
.Build();
host.Run();
A step by step guide using an external config file is available here.
With Bootstrap >4.1 it's just a case of using the flexbox utility classes. Just have a flexbox container inside your column, and then give all the elements within it the "flex-fill" class. As with inline forms you'll need to set the margins/padding on the elements yourself.
.prop-label {_x000D_
margin: .25rem 0 !important;_x000D_
}_x000D_
_x000D_
.prop-field {_x000D_
margin-left: 1rem;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="row">_x000D_
<div class="col-12">_x000D_
<div class="d-flex">_x000D_
<label class="flex-fill prop-label">Label:</label>_x000D_
<input type="text" class="flex-fill form-control prop-field">_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Looking at your example, I think this is what you want:
var dict = TableObj.ToDictionary(t => t.Key, t=> t.TimeStamp);
You can solve this in two ways:
First way: If you wish to keep using REST you have to you a ModelAndView
object to render a HTML page. An example is being posted by Happy Nguyen and I am posting it once more here:
@RequestMapping("/")
public ModelAndView index () {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
return modelAndView;
}
Second Way: If it is not important weather you keep using REST or not, so you can just change the @RestController
to @Controller
and make sure that you have already added Thymeleaf template engine.
what about simply this:
byte[] args2 = getByteArry();
String byteStr = new String(args2);
Looks like your problem is that you are trying to run python test.py
from within the Python interpreter, which is why you're seeing that traceback.
Make sure you're out of the interpreter, then run the python test.py
command from bash or command prompt or whatever.
We can also do the same using java 8.
public static<T> List<T> reverseList(List<T> list) {
List<T> reverse = new ArrayList<>(list.size());
list.stream()
.collect(Collectors.toCollection(LinkedList::new))
.descendingIterator()
.forEachRemaining(reverse::add);
return reverse;
}
Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction()
function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!
Go to the metadata directory as below
your workspace>projectname>.metadata
inside this metada directory, there will be a lock file. Delete this lock file.
Restart eclipse and rebuild project. It worked for me !
This is an issue relating JRE.In my case (eclipse Luna with Maven plugin, JDK 7) I solved this by making following change in pom.xml and then Maven Update Project.
from:
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
to:
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
Screenshot showing problem in JRE:
Looks like you should loop over the values of myUri.Query
and parse it from there.
string desiredValue;
foreach(string item in myUri.Query.Split('&'))
{
string[] parts = item.Replace("?", "").Split('=');
if(parts[0] == "desiredKey")
{
desiredValue = parts[1];
break;
}
}
I wouldn't use this code without testing it on a bunch of malformed URLs however. It might break on some/all of these:
hello.html?
hello.html?valuelesskey
hello.html?key=value=hi
hello.html?hi=value?&b=c
Just in case you are lazy like me, here's a solution amalgamated from this and other answers on SO.
set @orig_lat=37.46;
set @orig_long=-122.25;
set @bounding_distance=1;
SELECT
*
,((ACOS(SIN(@orig_lat * PI() / 180) * SIN(`lat` * PI() / 180) + COS(@orig_lat * PI() / 180) * COS(`lat` * PI() / 180) * COS((@orig_long - `long`) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS `distance`
FROM `cities`
WHERE
(
`lat` BETWEEN (@orig_lat - @bounding_distance) AND (@orig_lat + @bounding_distance)
AND `long` BETWEEN (@orig_long - @bounding_distance) AND (@orig_long + @bounding_distance)
)
ORDER BY `distance` ASC
limit 25;
If you don't have C++17 yet and look for a platform agnostic solution, use ghc::filesystem. The header-ony code is compatible to C++17 (in fact a backport) and easy to migrate later on.
You can also use:
your_dataframe.insert(loc=0, value=np.nan, column="")
where loc
is your empty row index.
From official documentation, FailedPreconditionError
This exception is most commonly raised when running an operation that reads a tf.Variable before it has been initialized.
In your case the error even explains what variable was not initialized: Attempting to use uninitialized value Variable_1
. One of the TF tutorials explains a lot about variables, their creation/initialization/saving/loading
Basically to initialize the variable you have 3 options:
tf.global_variables_initializer()
tf.variables_initializer(list_of_vars)
. Notice that you can use this function to mimic global_variable_initializer: tf.variable_initializers(tf.global_variables())
var_name.initializer
I almost always use the first approach. Remember you should put it inside a session run. So you will get something like this:
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
If your are curious about more information about variables, read this documentation to know how to report_uninitialized_variables
and check is_variable_initialized
.
Follow this method if problem comes when working with angular2+ projects
I was looking for a solution when i got this error, and it got me here. But this question seems to be specific but the error is not, its a generic error. This is a common error for angular developers dealing with Internet Explorer.
I had the same issue while working with angular 2+, and it got resolved just by few simple steps.
In Angular latest versions, there are come commented codes in the polyfills.ts shows all the polyfills required for the smooth running in Internet Explorer versions IE09,IE10 and IE11
/** IE9, IE10 and IE11 requires all of the following polyfills. **/
//import 'core-js/es6/symbol';
//import 'core-js/es6/object';
//import 'core-js/es6/function';
//import 'core-js/es6/parse-int';
//import 'core-js/es6/parse-float';
//import 'core-js/es6/number';
//import 'core-js/es6/math';
//import 'core-js/es6/string';
//import 'core-js/es6/date';
//import 'core-js/es6/array';
//import 'core-js/es6/regexp';
//import 'core-js/es6/map';
//import 'core-js/es6/weak-map';
//import 'core-js/es6/set';
Uncomment the codes and it would work perfectly in IE browsers
/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';
But you might see a performance drop in IE browsers compared to others :(
Another option is to create a free Kiln account -- kiln round trips between git and hg with 100% metadata retention, so you can use it for a one time convert or use it to access a repository using whichever client you prefer.
From MySQL documentation:
The effective maximum length of a VARCHAR in MySQL 5.0.3 and later is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used. For example, utf8 characters can require up to three bytes per character, so a VARCHAR column that uses the utf8 character set can be declared to be a maximum of 21,844 characters.
Limits for the VARCHAR varies depending on charset used. Using ASCII would use 1 byte per character. Meaning you could store 65,535 characters. Using utf8 will use 3 bytes per character resulting in character limit of 21,844. BUT if you are using the modern multibyte charset utf8mb4 which you should use! It supports emojis and other special characters. It will be using 4 bytes per character. This will limit the number of characters per table to 16,383. Note that other fields such as INT will also be counted to these limits.
Conclusion:
utf8 maximum of 21,844 characters
utf8mb4 maximum of 16,383 characters
This will help in adjusting the emulator according to the webpage:
WebView wb;
//CALL THIS METHOD
wb.setInitialScale(50);
You can set the intial scale in percentage as shown above.
Go via POSIXct
and you want to set a TZ
there -- here you see my (Chicago) default:
R> val <- 1352068320
R> as.POSIXct(val, origin="1970-01-01")
[1] "2012-11-04 22:32:00 CST"
R> as.Date(as.POSIXct(val, origin="1970-01-01"))
[1] "2012-11-05"
R>
Edit: A few years later, we can now use the anytime package:
R> library(anytime)
R> anytime(1352068320)
[1] "2012-11-04 16:32:00 CST"
R> anydate(1352068320)
[1] "2012-11-04"
R>
Note how all this works without any format or origin arguments.
If you say that it works with accessing directly manageproducts.do?option=1
in the browser then it should work with:
$.get('manageproducts.do', { option: '1' }, function(data) {
...
});
as it would send the same GET request.
Try setting the style to display=none:
<img src="a.gif" style="display:none">
You need to put it in the join
clause, not the where
:
SELECT *
FROM categories
LEFT JOIN user_category_subscriptions ON
user_category_subscriptions.category_id = categories.category_id
and user_category_subscriptions.user_id =1
See, with an inner join
, putting a clause in the join
or the where
is equivalent. However, with an outer join
, they are vastly different.
As a join
condition, you specify the rowset that you will be joining to the table. This means that it evaluates user_id = 1
first, and takes the subset of user_category_subscriptions
with a user_id
of 1
to join to all of the rows in categories
. This will give you all of the rows in categories
, while only the categories
that this particular user has subscribed to will have any information in the user_category_subscriptions
columns. Of course, all other categories
will be populated with null
in the user_category_subscriptions
columns.
Conversely, a where
clause does the join, and then reduces the rowset. So, this does all of the joins and then eliminates all rows where user_id
doesn't equal 1
. You're left with an inefficient way to get an inner join
.
Hopefully this helps!
You can
Best practice would be #4 if you are using non-modal forms.
I solved by setting async
to false and restructure my ajax call :
I set global function called sendRequest(type, url, data)
with three parameters to be called every time everywhere
function sendRequest(type, url, data) {
let returnValue = null;
$.ajax({
url: url,
type: type,
async: false,
data: data,
dataType: 'json',
success: function (resp) {
returnValue = resp;
}
});
return returnValue;
}
Now call function
let password = $("#password").val();
let email = $("#email").val();
let data = {
email: email,
password: password,
};
let resp = sendRequest('POST', 'http://localhost/signin')}}", data);
console.log(resp);
Important Note in code is :
async: false
The C++ way would be to use a std::stringstream
object as:
std::stringstream fmt;
fmt << a << " " << b << " > " << c;
The C way would be to use sprintf
.
The C way is difficult to get right since:
Of course, you may want to fall back on the C way if performance is an issue (imagine you are creating fixed-size million little stringstream
objects and then throwing them away).
Leaving aside the technical issues with the code you posted, you asked this:
To use this Dictionary Items in a Table View i have to transfer it to a NSArray, am i right?
The answer to which is: not necessarily. There's nothing intrinsic to the machinery of UITableView
, UITableViewDataSource
, or UITableViewDelegate
that means that your data has to be in an array. You will need to implement various methods to tell the system how many rows are in your table, and what data appears in each row. Many people find it much more natural and efficient to answer those questions with an ordered data structure like an array. But there's no requirement that you do so. If you can write the code to implement those methods with the dictionary you started with, feel free!
You can use 'th:if' together with 'th:text'
<span th:if="${someObject.someProperty != null}" th:text="${someObject.someProperty}">someValue</span>
First, make sure you're logged into heroku:
heroku login
Enter your credentials.
It's common to get this error when using a cloned git repo onto a new machine. Even if your heroku credentials are already on the machine, there is no link between the cloned repo and heroku locally yet. To do this, cd into the root dir of the cloned repo and run
heroku git:remote -a yourapp
This will probably not make me a lot of new friends, but it should be added that the C# people have a different guideline: The enum instances are "Pascal case" (upper/lower case mixed). See stackoverflow discussion and MSDN Enumeration Type Naming Guidelines.
As we are exchanging data with a C# system, I am tempted to copy their enums exactly, ignoring Java's "constants have uppercase names" convention. Thinking about it, I don't see much value in being restricted to uppercase for enum instances. For some purposes .name() is a handy shortcut to get a readable representation of an enum constant and a mixed case name would look nicer.
So, yes, I dare question the value of the Java enum naming convention. The fact that "the other half of the programming world" does indeed use a different style makes me think it is legitimate to doubt our own religion.
FWIW, you probably want to look at F# instead of C# in the context of technical computing because F# is specifically designed for that purpose. However, I developed my own commercial plotting library because I was not satisfied with anything freely available on .NET.
The function you need is CInt
.
ie CInt(PrinterLabel)
See Type Conversion Functions (Visual Basic) on MSDN
Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!
You can start IPython
from within ipdb
.
Induce the ipdb
debugger1:
import idpb; ipdb.set_trace()
Enter IPython from within in the ipdb>
console2:
from IPython import embed; embed()
Return to the ipdb>
console from within IPython
:
exit
If you're lucky enough to be using Emacs, things can be made even more convenient.
This requires using M-x shell
. Using yasnippet
and bm, define the following snippet. This will replace the text ipdb
in the editor with the set-trace
line. After inserting the snippet, the line will be highlighted so that it is easily noticeable and navigable. Use M-x bm-next
to navigate.
# -*- mode: snippet -*-
# name: ipdb
# key: ipdb
# expand-env: ((yas-after-exit-snippet-hook #'bm-toggle))
# --
import ipdb; ipdb.set_trace()
1 All on one line for easy deletion. Since imports
only happen once, this form ensures ipdb
will be imported when you need it with no extra overhead.
2 You can save yourself some typing by importing IPython
within your .pdbrc
file:
try:
from IPython import embed
except:
pass
This allows you to simply call embed()
from within ipdb
(of course, only when IPython is installed).
Shelving is like your changes have been stored in the source control without affecting the existing changes. Means if you check in a file in source control it will modify the existing file but shelving is like storing your changes in source control but without modifying the actual changes.
first off, to be a bit of a henpeck, its best NOT to use just the <background>
tag. rather, use the proper, more specific, <background-image>
tag.
the only way that i'm aware of to do such a thing is to build the padding into the image by extending the matte. since the empty pixels aren't stripped, you have your padding right there. so if you need a 10px border, create 10px of empty pixels all around your image. this is mui simple in Photoshop, Fireworks, GIMP, &c.
i'd also recommend trying out the PNG8 format instead of the dying GIF... much better.
there may be an alternate solution to your problem if we knew a bit more of how you're using it. :) it LOOKS like you're trying to add an accordion button. this would be best placed in the HTML because then you can target it with JavaScript/PHP; something you cannot do if it's in the background (at least not simply). in such a case, you can style the heck out of the image you currently have in CSS by using the following:
#hello img { padding: 10px; }
WR!
<<
is the left-shift operator, as it is in many other languages.
Here RAM_DEPTH
will be 1
left-shifted by 8 bits
, which is equivalent to 2^8
, or 256
.
If you use the ||
and &&
forms, rather than the |
and &
forms of these operators, Java will not bother to evaluate the right-hand operand alone.
It's a matter of if you want to short-circuit the evaluation or not -- most of the time you want to.
A good way to illustrate the benefits of short-circuiting would be to consider the following example.
Boolean b = true;
if(b || foo.timeConsumingCall())
{
//we entered without calling timeConsumingCall()
}
Another benefit, as Jeremy and Peter mentioned, for short-circuiting is the null reference check:
if(string != null && string.isEmpty())
{
//we check for string being null before calling isEmpty()
}
Here is the YUI counterpart to the jQuery posts above.
<script>
YAHOO.util.Event.onDOMReady(function() {
document.getElementById("foo").onclick = function (){alert('foo');};
});
</script>
The answer is given but think that for some situation this will be also interesting way to get string from NSInteger
NSInteger value = 12;
NSString * string = [NSString stringWithFormat:@"%0.0f", (float)value];
How to convert string to lowercase in Python?
Is there any way to convert an entire user inputted string from uppercase, or even part uppercase to lowercase?
E.g. Kilometers --> kilometers
The canonical Pythonic way of doing this is
>>> 'Kilometers'.lower()
'kilometers'
However, if the purpose is to do case insensitive matching, you should use case-folding:
>>> 'Kilometers'.casefold()
'kilometers'
Here's why:
>>> "Maße".casefold()
'masse'
>>> "Maße".lower()
'maße'
>>> "MASSE" == "Maße"
False
>>> "MASSE".lower() == "Maße".lower()
False
>>> "MASSE".casefold() == "Maße".casefold()
True
This is a str method in Python 3, but in Python 2, you'll want to look at the PyICU or py2casefold - several answers address this here.
Python 3 handles plain string literals as unicode:
>>> string = '????????'
>>> string
'????????'
>>> string.lower()
'????????'
In Python 2, the below, pasted into a shell, encodes the literal as a string of bytes, using utf-8
.
And lower
doesn't map any changes that bytes would be aware of, so we get the same string.
>>> string = '????????'
>>> string
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> string.lower()
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> print string.lower()
????????
In scripts, Python will object to non-ascii (as of Python 2.5, and warning in Python 2.4) bytes being in a string with no encoding given, since the intended coding would be ambiguous. For more on that, see the Unicode how-to in the docs and PEP 263
str
literalsSo we need a unicode
string to handle this conversion, accomplished easily with a unicode string literal, which disambiguates with a u
prefix (and note the u
prefix also works in Python 3):
>>> unicode_literal = u'????????'
>>> print(unicode_literal.lower())
????????
Note that the bytes are completely different from the str
bytes - the escape character is '\u'
followed by the 2-byte width, or 16 bit representation of these unicode
letters:
>>> unicode_literal
u'\u041a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> unicode_literal.lower()
u'\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
Now if we only have it in the form of a str
, we need to convert it to unicode
. Python's Unicode type is a universal encoding format that has many advantages relative to most other encodings. We can either use the unicode
constructor or str.decode
method with the codec to convert the str
to unicode
:
>>> unicode_from_string = unicode(string, 'utf-8') # "encoding" unicode from string
>>> print(unicode_from_string.lower())
????????
>>> string_to_unicode = string.decode('utf-8')
>>> print(string_to_unicode.lower())
????????
>>> unicode_from_string == string_to_unicode == unicode_literal
True
Both methods convert to the unicode type - and same as the unicode_literal.
It is recommended that you always work with text in Unicode.
Software should only work with Unicode strings internally, converting to a particular encoding on output.
However, to get the lowercase back in type str
, encode the python string to utf-8
again:
>>> print string
????????
>>> string
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> string.decode('utf-8')
u'\u041a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> string.decode('utf-8').lower()
u'\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> string.decode('utf-8').lower().encode('utf-8')
'\xd0\xba\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> print string.decode('utf-8').lower().encode('utf-8')
????????
So in Python 2, Unicode can encode into Python strings, and Python strings can decode into the Unicode type.
Add the template and give date pipe, you need to use escape characters for the format of the date. You can give any format as you want like 'MM-yyyy-dd' etc.
template: '{{ current_date | date: \'yyyy-MM-dd\' }}',
Check this out : http://codepen.io/Rowno/pen/Afykb
.carousel-fade {
.carousel-inner {
.item {
opacity: 0;
transition-property: opacity;
}
.active {
opacity: 1;
}
.active.left,
.active.right {
left: 0;
opacity: 0;
z-index: 1;
}
.next.left,
.prev.right {
opacity: 1;
}
}
Works marvellously, I hope it works
If it's a new project, I'd just drop the database, and create a new one with a proper charset:
CREATE DATABASE <dbname> CHARACTER SET utf8;
I hope you guys already got a solution reading all those. But I found my solution as follows. I am expecting that you already have a cell with UITextField
. So on preparing just keep the row index into the text field's tag.
cell.textField.tag = IndexPath.row;
Create an activeTextField
, instance of UITextField
with global scope as below:
@interface EditViewController (){
UITextField *activeTextField;
}
So, now you just copy paste my code at the end. And also don't forget to add UITextFieldDelegate
#pragma mark - TextField Delegation
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
activeTextField = textField;
return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
activeTextField = nil;
}
Registers keyboard notifications
#pragma mark - Keyboard Activity
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
Handles Keyboard Notifications
:
Called when the UIKeyboardDidShowNotification
is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
[self.tableView setContentInset:contentInsets];
[self.tableView setScrollIndicatorInsets:contentInsets];
NSIndexPath *currentRowIndex = [NSIndexPath indexPathForRow:activeTextField.tag inSection:0];
[self.tableView scrollToRowAtIndexPath:currentRowIndex atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
Called when the UIKeyboardWillHideNotification
is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
[self.tableView setContentInset:contentInsets];
[self.tableView setScrollIndicatorInsets:contentInsets];
}
Now one thing is left, Call the registerForKeyboardNotifications
method in to ViewDidLoad
method as follows:
- (void)viewDidLoad {
[super viewDidLoad];
// Registering keyboard notification
[self registerForKeyboardNotifications];
// Your codes here...
}
You are done, hope your textFields
will no longer hidden by the keyboard.
Manoj Govindan's answer is correct but I saw that comment:
Run it from the terminal.
And got to thinking about why this is so not obvious to windows users and realized it's because CMD.EXE is such a poor excuse for a shell that it should start with:
Windows command interpreter copyright 1999 Microsoft
Mein Gott!! Whatever you do, don't use this!!
C:>
Which leads me to point at https://stackoverflow.com/questions/913912/bash-shell-for-windows
Pitfall:
<my-directive></my-directive>
wont work on IE8 without workaround (https://docs.angularjs.org/guide/ie)<div data-my-directive="ValueOfTheFirstParameter"></div>
Instead of this:
<my-directive my-param="ValueOfTheFirstParameter"></my-directive>
We dont use custom html elements, because if this 2 facts.
Every directive by third party framework can be written in two ways:
<my-directive></my-directive>
or
<div data-my-directive></div>
does the same.
The answer here is Oracle only. Here's a bit more sophisticated answer in all SQL:
Who has the best overall homework result (maximum sum of homework points)?
SELECT FIRST, LAST, SUM(POINTS) AS TOTAL
FROM STUDENTS S, RESULTS R
WHERE S.SID = R.SID AND R.CAT = 'H'
GROUP BY S.SID, FIRST, LAST
HAVING SUM(POINTS) >= ALL (SELECT SUM (POINTS)
FROM RESULTS
WHERE CAT = 'H'
GROUP BY SID)
And a more difficult example, which need some explanation, for which I don't have time atm:
Give the book (ISBN and title) that is most popular in 2008, i.e., which is borrowed most often in 2008.
SELECT X.ISBN, X.title, X.loans
FROM (SELECT Book.ISBN, Book.title, count(Loan.dateTimeOut) AS loans
FROM CatalogEntry Book
LEFT JOIN BookOnShelf Copy
ON Book.bookId = Copy.bookId
LEFT JOIN (SELECT * FROM Loan WHERE YEAR(Loan.dateTimeOut) = 2008) Loan
ON Copy.copyId = Loan.copyId
GROUP BY Book.title) X
HAVING loans >= ALL (SELECT count(Loan.dateTimeOut) AS loans
FROM CatalogEntry Book
LEFT JOIN BookOnShelf Copy
ON Book.bookId = Copy.bookId
LEFT JOIN (SELECT * FROM Loan WHERE YEAR(Loan.dateTimeOut) = 2008) Loan
ON Copy.copyId = Loan.copyId
GROUP BY Book.title);
Hope this helps (anyone).. :)
Regards, Guus
This is a way I did it pretty simply:
YourWindow.xaml.cs
//In your constructor
public YourWindow()
{
InitializeComponent();
DataContext = new YourWindowViewModel(this);
}
YourWindowViewModel.cs
private YourWindow window;//so we can kill the window
//In your constructor
public YourWindowViewModel(YourWindow window)
{
this.window = window;
}
//to close the window
public void CloseWindow()
{
window.Close();
}
I don't see anything wrong with the answer you chose, I just thought this might be a more simple way to do it!
changing:
.ui-menu .ui-menu-item {
margin: 0;
padding: 0;
zoom: 1;
width: 100%;
}
to:
.ui-menu .ui-menu-item {
margin: 0;
padding: 0;
zoom: 1;
width: auto;
float:left;
}
should start you off.
Keystore only has one password. You can change it using keytool:
keytool -storepasswd -keystore my.keystore
To change the key's password:
keytool -keypasswd -alias <key_name> -keystore my.keystore
This could be complicated way of doing
String newString = new String(oldString);
This shortens the String is the underlying char[] used is much longer.
However more specifically it will be checking that every character can be UTF-8 encoded.
There are some "characters" you can have in a String which cannot be encoded and these would be turned into ?
Any character between \uD800 and \uDFFF cannot be encoded and will be turned into '?'
String oldString = "\uD800";
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8");
System.out.println(newString.equals(oldString));
prints
false
Using Bash Parameter Expansion:
orig="AxxBCyyyDEFzzLMN"
mod=${orig//[xyz]/_}
Try:
cl /v
Actually, any time I give cl an argument, it prints out the version number on the first line.
You could just feed it a garbage argument and then parse the first line of the output, which contains the verison number.
There are many answers here that suggest a variety of techniques. But when presenting numbers in the UI, you invariably want to use a NumberFormatter
so that the results are properly formatted, rounded, and localized:
let value = 10000.5
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
guard let string = formatter.string(for: value) else { return }
print(string) // 10,000.5
If you want fixed number of decimal places, e.g. for currency values
let value = 10000.5
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
guard let string = formatter.string(for: value) else { return }
print(string) // 10,000.50
But the beauty of this approach, is that it will be properly localized, resulting in 10,000.50
in the US but 10.000,50
in Germany. Different locales have different preferred formats for numbers, and we should let NumberFormatter
use the format preferred by the end user when presenting numeric values within the UI.
Needless to say, while NumberFormatter
is essential when preparing string representations within the UI, it should not be used if writing numeric values as strings for persistent storage, interface with web services, etc.
You can set a default style for the entire workbook (all worksheets):
$objPHPExcel->getDefaultStyle()
->getBorders()
->getTop()
->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
->getBorders()
->getBottom()
->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
->getBorders()
->getLeft()
->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
->getBorders()
->getRight()
->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
or
$styleArray = array(
'borders' => array(
'allborders' => array(
'style' => PHPExcel_Style_Border::BORDER_THIN
)
)
);
$objPHPExcel->getDefaultStyle()->applyFromArray($styleArray);
And this can be used for all style properties, not just borders.
But column autosizing is structural
rather than stylistic
, and has to be set for each column on each worksheet individually.
EDIT
Note that default workbook style only applies to Excel5 Writer
If you're just quickly looking to keep a cmd instance open instead of exiting immediately, simply doing the following is enough
set /p asd="Hit enter to continue"
at the end of your script and it'll keep the window open.
Note that this'll set asd
as an environment variable, and can be replaced with anything else.
You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :
BEGIN TRANSACTION
update A
set A.ORG_NAME = @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
COMMIT
Here's a simplest example from ASP.NET Community, this gave me a clear understanding on the concept....
what difference does this make?
For an example of this, here is a way to put focus on a text box on a page when the page is loaded into the browser—with Visual Basic using the RegisterStartupScript
method:
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)
This works well because the textbox on the page is generated and placed on the page by the time the browser gets down to the bottom of the page and gets to this little bit of JavaScript.
But, if instead it was written like this (using the RegisterClientScriptBlock
method):
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)
Focus will not get to the textbox control and a JavaScript error will be generated on the page
The reason for this is that the browser will encounter the JavaScript before the text box is on the page. Therefore, the JavaScript will not be able to find a TextBox1.
<script type="text/javascript">
$(document).ready(function() {
$("#Button1").click(function() {
alert("hello");
});
}
);
</script>
Dirty and quick hack:
SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1 INNER JOIN Table2 ON Table1.Col1 = Table2.Col1
AND ((Table1.Col2 = Table2.Col2) OR (Table1.Col2 IS NULL AND Table2.Col2 IS NULL))
Could this be a typo? (two Ps in ppasscode, intended?)
$_POST['ppasscode'];
I would make sure and do:
print_r($_POST);
and make sure the data is accurate there, and then echo out what it should look like:
echo hash('sha256', $_POST['ppasscode']);
Compare this output to what you have in the database (manually). By doing this you're exploring your possible points of failure:
Sometimes this can be fixed by provisioning the box on vagrant up
vagrant up --provision
dtype('O')
inside dataframe this means Pandas string.What is dtype
?
Something that belongs to pandas
or numpy
, or both, or something else? If we examine pandas code:
df = pd.DataFrame({'float': [1.0],
'int': [1],
'datetime': [pd.Timestamp('20180310')],
'string': ['foo']})
print(df)
print(df['float'].dtype,df['int'].dtype,df['datetime'].dtype,df['string'].dtype)
df['string'].dtype
It will output like this:
float int datetime string
0 1.0 1 2018-03-10 foo
---
float64 int64 datetime64[ns] object
---
dtype('O')
You can interpret the last as Pandas dtype('O')
or Pandas object which is Python type string, and this corresponds to Numpy string_
, or unicode_
types.
Pandas dtype Python type NumPy type Usage
object str string_, unicode_ Text
Like Don Quixote is on ass, Pandas is on Numpy and Numpy understand the underlying architecture of your system and uses the class numpy.dtype
for that.
Data type object is an instance of numpy.dtype
class that understand the data type more precise including:
In the context of this question dtype
belongs to both pands and numpy and in particular dtype('O')
means we expect the string.
Here is some code for testing with explanation: If we have the dataset as dictionary
import pandas as pd
import numpy as np
from pandas import Timestamp
data={'id': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}, 'date': {0: Timestamp('2018-12-12 00:00:00'), 1: Timestamp('2018-12-12 00:00:00'), 2: Timestamp('2018-12-12 00:00:00'), 3: Timestamp('2018-12-12 00:00:00'), 4: Timestamp('2018-12-12 00:00:00')}, 'role': {0: 'Support', 1: 'Marketing', 2: 'Business Development', 3: 'Sales', 4: 'Engineering'}, 'num': {0: 123, 1: 234, 2: 345, 3: 456, 4: 567}, 'fnum': {0: 3.14, 1: 2.14, 2: -0.14, 3: 41.3, 4: 3.14}}
df = pd.DataFrame.from_dict(data) #now we have a dataframe
print(df)
print(df.dtypes)
The last lines will examine the dataframe and note the output:
id date role num fnum
0 1 2018-12-12 Support 123 3.14
1 2 2018-12-12 Marketing 234 2.14
2 3 2018-12-12 Business Development 345 -0.14
3 4 2018-12-12 Sales 456 41.30
4 5 2018-12-12 Engineering 567 3.14
id int64
date datetime64[ns]
role object
num int64
fnum float64
dtype: object
All kind of different dtypes
df.iloc[1,:] = np.nan
df.iloc[2,:] = None
But if we try to set np.nan
or None
this will not affect the original column dtype. The output will be like this:
print(df)
print(df.dtypes)
id date role num fnum
0 1.0 2018-12-12 Support 123.0 3.14
1 NaN NaT NaN NaN NaN
2 NaN NaT None NaN NaN
3 4.0 2018-12-12 Sales 456.0 41.30
4 5.0 2018-12-12 Engineering 567.0 3.14
id float64
date datetime64[ns]
role object
num float64
fnum float64
dtype: object
So np.nan
or None
will not change the columns dtype
, unless we set the all column rows to np.nan
or None
. In that case column will become float64
or object
respectively.
You may try also setting single rows:
df.iloc[3,:] = 0 # will convert datetime to object only
df.iloc[4,:] = '' # will convert all columns to object
And to note here, if we set string inside a non string column it will become string or object dtype
.
I had this problem,when you install the git,you have to choose the right path,i mean,it should be the same path that you write git(code)in the Git Bash...for example,if your path is c:\Users\username , you must install the git in same path(c:\Users\username)..these 2 paths should not be different
you'll want to use && to see that it is not equal to "AM" AND not equal to "PM"
if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) {
System.out.println("Sorry, incorrect input.");
System.exit(1);
}
to be clear you can also do
if(!(TimeOfDayStringQ.equals("AM") || TimeOfDayStringQ.equals("PM"))){
System.out.println("Sorry, incorrect input.");
System.exit(1);
}
to have the not (one or the other)
phrase in the code (remember the (silent) brackets)
I don't really see the need, as a module with functions (and not a class) would serve well as a singleton. All its variables would be bound to the module, which could not be instantiated repeatedly anyway.
If you do wish to use a class, there is no way of creating private classes or private constructors in Python, so you can't protect against multiple instantiations, other than just via convention in use of your API. I would still just put methods in a module, and consider the module as the singleton.
You should be able to use the "ours" merge strategy to overwrite master with seotweaks like this:
git checkout seotweaks
git merge -s ours master
git checkout master
git merge seotweaks
The result should be your master is now essentially seotweaks.
(-s ours
is short for --strategy=ours
)
From the docs about the 'ours' strategy:
This resolves any number of heads, but the resulting tree of the merge is always that of the current branch head, effectively ignoring all changes from all other branches. It is meant to be used to supersede old development history of side branches. Note that this is different from the -Xours option to the recursive merge strategy.
Update from comments: If you get fatal: refusing to merge unrelated histories
, then change the second line to this: git merge --allow-unrelated-histories -s ours master
Pure Java:
urlToInputStream(url,httpHeaders);
With some success I use this method. It handles redirects and one can pass a variable number of HTTP headers asMap<String,String>
. It also allows redirects from HTTP to HTTPS.
private InputStream urlToInputStream(URL url, Map<String, String> args) {
HttpURLConnection con = null;
InputStream inputStream = null;
try {
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(15000);
con.setReadTimeout(15000);
if (args != null) {
for (Entry<String, String> e : args.entrySet()) {
con.setRequestProperty(e.getKey(), e.getValue());
}
}
con.connect();
int responseCode = con.getResponseCode();
/* By default the connection will follow redirects. The following
* block is only entered if the implementation of HttpURLConnection
* does not perform the redirect. The exact behavior depends to
* the actual implementation (e.g. sun.net).
* !!! Attention: This block allows the connection to
* switch protocols (e.g. HTTP to HTTPS), which is <b>not</b>
* default behavior. See: https://stackoverflow.com/questions/1884230
* for more info!!!
*/
if (responseCode < 400 && responseCode > 299) {
String redirectUrl = con.getHeaderField("Location");
try {
URL newUrl = new URL(redirectUrl);
return urlToInputStream(newUrl, args);
} catch (MalformedURLException e) {
URL newUrl = new URL(url.getProtocol() + "://" + url.getHost() + redirectUrl);
return urlToInputStream(newUrl, args);
}
}
/*!!!!!*/
inputStream = con.getInputStream();
return inputStream;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Full example call
private InputStream getInputStreamFromUrl(URL url, String user, String passwd) throws IOException {
String encoded = Base64.getEncoder().encodeToString((user + ":" + passwd).getBytes(StandardCharsets.UTF_8));
Map<String,String> httpHeaders=new Map<>();
httpHeaders.put("Accept", "application/json");
httpHeaders.put("User-Agent", "myApplication");
httpHeaders.put("Authorization", "Basic " + encoded);
return urlToInputStream(url,httpHeaders);
}
The problem is RecyclerView.Adatper
does not provide any methods that return the index of element
public abstract static class Adapter<VH extends ViewHolder> {
/**
* returns index of the given element in adapter, return -1 if not exist
*/
public int indexOf(Object elem);
}
My workaround is to create a map instance for (element, position)s
public class FriendAdapter extends RecyclerView.Adapter<MyViewHolder> {
private Map<Friend, Integer> posMap ;
private List<Friend> friends;
public FriendAdapter(List<Friend> friends ) {
this.friends = new ArrayList<>(friends);
this.posMap = new HashMap<>();
for(int i = 0; i < this.friends.size(); i++) {
posMap.put(this.friends.get(i), i);
}
}
public int indexOf(Friend friend) {
Integer position = this.posMap.get(elem);
return position == null ? -1 : position;
}
// skip other methods in class Adapter
}
Friend
) should implements hashCode()
and equals()
because it is key in hashmap.when an element changed,
void someMethod() {
Friend friend = ...;
friend.setPhoneNumber('xxxxx');
int position = friendAdapter.indexOf(friend);
friendAdapter.notifyItemChanged(position);
}
It is good to define an helper method
public class FriendAdapter extends extends RecyclerView.Adapter<MyViewHolder> {
public void friendUpdated(Friend friend) {
int position = this.indexOf(friend);
this.notifyItemChanged(position);
}
}
Map instance(Map<Friend, Integer> posMap
) is not necessarily required.
If map is not used, looping throughout list can find the position of an element.
I had the same problem, and it was solved by using App Cache Cleaner.
case isnull(B.[stat],0)
when 0 then dateadd(dd,10,(c.[Eventdate]))
end
you can add in else statement if you want to add 30 days to the same .
Difficult task. I would normally suggest to grab a debugger/memory profiler like Valgrind and run the programs one after one in it. Soon or later you will find the program that leaks and can tell it the devloper or fix it yourself.
Another workaround would be to initiate a modal window containing its own form
Use <a>
with href instead of a <button>
solves my problem.
<ion-nav-buttons side="secondary">
<a class="button icon-right ion-plus-round" href="#/app/gosomewhere"></a>
</ion-nav-buttons>
All previously proposed approaches didn't satisfy my requirements for getting a complete URL (complete as in qualified) e.g. to be used in an email send from controller action. I need the scheme and hostname as well then, and thus stumbled over the following approach:
<?php echo Router::url( array( $id ), true ) ?>
Due to providing router array current controller and action is kept, however id isn't and thus has to be provided here again. Second argument true
is actually requesting to prepend hostname etc. for getting full URL.
Using Router::url() is available in every situation and thus can be used in view files as well.
mv file.txt file.tmp && sed 's/foo/bar/g' < file.tmp > file.txt
Should preserve all hardlinks, since output is directed back to overwrite the contents of the original file, and avoids any need for a special version of sed.
Ok, I know that it's an old issue but I post my answer anyway.
I like this solution. I only have to specify the identity column(s).
SELECT * INTO TempTable FROM MyTable_T WHERE id = 1;
ALTER TABLE TempTable DROP COLUMN id;
INSERT INTO MyTable_T SELECT * FROM TempTable;
DROP TABLE TempTable;
The "id"-column is the identity column and that's the only column I have to specify. It's better than the other way around anyway. :-)
I use SQL Server. You may want to use "CREATE TABLE
" and "UPDATE TABLE
" at row 1 and 2.
Hmm, I saw that I did not really give the answer that he wanted. He wanted to copy the id to another column also. But this solution is nice for making a copy with a new auto-id.
I edit my solution with the idéas from Michael Dibbets.
use MyDatabase;
SELECT * INTO #TempTable FROM [MyTable] WHERE [IndexField] = :id;
ALTER TABLE #TempTable DROP COLUMN [IndexField];
INSERT INTO [MyTable] SELECT * FROM #TempTable;
DROP TABLE #TempTable;
You can drop more than one column by separating them with a ",". The :id should be replaced with the id of the row you want to copy. MyDatabase, MyTable and IndexField should be replaced with your names (of course).
It is possible to do everything you want. Aaron's answer was not quite complete.
His approach is correct, up to creating the temporary table in the inner query. Then, you need to insert the results into a table in the outer query.
The following code snippet grabs the first line of a file and inserts it into the table @Lines:
declare @fieldsep char(1) = ',';
declare @recordsep char(1) = char(10);
declare @Lines table (
line varchar(8000)
);
declare @sql varchar(8000) = '
create table #tmp (
line varchar(8000)
);
bulk insert #tmp
from '''+@filename+'''
with (FirstRow = 1, FieldTerminator = '''+@fieldsep+''', RowTerminator = '''+@recordsep+''');
select * from #tmp';
insert into @Lines
exec(@sql);
select * from @lines
Nobody noticed the html attibute "accesskey" which is available since a while.
This is a no javascript way to keyboard shortcuts stuffs.
The accesskey attributes shortcuts on MDN
Intented to be used like this. The html attribute itself is enough, howewer we can change the placeholder or other indicator depending of the browser and os. The script is a untested scratch approach to give an idea. You may want to use a browser library detector like the tiny bowser
let client = navigator.userAgent.toLowerCase(),_x000D_
isLinux = client.indexOf("linux") > -1,_x000D_
isWin = client.indexOf("windows") > -1,_x000D_
isMac = client.indexOf("apple") > -1,_x000D_
isFirefox = client.indexOf("firefox") > -1,_x000D_
isWebkit = client.indexOf("webkit") > -1,_x000D_
isOpera = client.indexOf("opera") > -1,_x000D_
input = document.getElementById('guestInput');_x000D_
_x000D_
if(isFirefox) {_x000D_
input.setAttribute("placeholder", "ALT+SHIFT+Z");_x000D_
} else if (isWin) {_x000D_
input.setAttribute("placeholder", "ALT+Z");_x000D_
} else if (isMac) {_x000D_
input.setAttribute("placeholder", "CTRL+ALT+Z");_x000D_
} else if (isOpera) {_x000D_
input.setAttribute("placeholder", "SHIFT+ESCAPE->Z");_x000D_
} else {'Point me to operate...'}
_x000D_
<input type="text" id="guestInput" accesskey="z" placeholder="Acces shortcut:"></input>
_x000D_
This is the result from
library(scales)
show_col(hue_pal()(4))
show_col(hue_pal()(3))
While the above answers describe the situation well, while troubleshooting the issue check also that browser really gets the format DataTables expects. There maybe other reasons not to get the data
. For example, if the user does not have access to the data URL and gets some HTML instead. Or the remote system has some unfortunate "fix-ups" in place. Network tab in the browser's Debug tools helps.
expanding on the answer above the 'each' function will return you the table-cell html object. wrapping that in $() will then allow you to perform jquery actions on it.
$(this).find('td').each (function( column, td) {
$(td).blah
});