var hello = "foo";
var my_string ="I pity the";
console.log(my_string, hello)
Actually you need to change your read
to read -r
which will make it ignore backslashes.
Also, you should escape quotes and backslashes. So
while read -r line; do
line="${line//\\/\\\\}"
line="${line//\"/\\\"}"
line="${line//\`/\\\`}"
eval echo "\"$line\""
done > destination.txt < source.txt
Still a terrible way to do expansion though.
String interpolation is going to be included with Python 3.6 as specified in PEP 498. You will be able to do this:
name = 'Spongebob Squarepants'
print(f'Who lives in a Pineapple under the sea? \n{name}')
Note that I hate Spongebob, so writing this was slightly painful. :)
While templates are probably best for the case you describe, if you have or want your data and/or arguments in iterable/array form, you can use String.raw
.
String.raw({
raw: ["I'm ", " years old!"]
}, 3);
With the data as an array, one can use the spread operator:
const args = [3, 'yesterday'];
String.raw({
raw: ["I'm ", " years old as of ", ""]
}, ...args);
w3school offered this way:
echo nl2br("One line.\n Another line.");
by use of this function you can do it..i tried other ways that said above but they wont help me..
I had this same question, and after a lot of research, it looks like it's not possible.
The answer from cgat is on the right track, but you can't actually concatenate references like that.
Here are things you can do with "variables" in YAML (which are officially called "node anchors" when you set them and "references" when you use them later):
default: &default_title This Post Has No Title
title: *default_title
{ or }
example_post: &example
title: My mom likes roosters
body: Seriously, she does. And I don't know when it started.
date: 8/18/2012
first_post: *example
second_post:
title: whatever, etc.
For more info, see this section of the wiki page about YAML: http://en.wikipedia.org/wiki/YAML#References
default: &DEFAULT
URL: stooges.com
throw_pies?: true
stooges: &stooge_list
larry: first_stooge
moe: second_stooge
curly: third_stooge
development:
<<: *DEFAULT
URL: stooges.local
stooges:
shemp: fourth_stooge
test:
<<: *DEFAULT
URL: test.stooges.qa
stooges:
<<: *stooge_list
shemp: fourth_stooge
This is taken directly from a great demo here: https://gist.github.com/bowsersenior/979804
Just use special `
var lyrics = 'Never gonna give you up';
var html = `<div>${lyrics}</div>`;
You can see more examples here.
If you're using Java 5 or higher, you can use String.format
:
urlString += String.format("u1=%s;u2=%s;u3=%s;u4=%s;", u1, u2, u3, u4);
See Formatter
for details.
Here is another way, by rotating element
with the scrollbar
for 180deg,
wrapping it's content
into another element, and rotating
that wrapper
for -180deg
.
Check the snippet below
div {_x000D_
display: inline-block;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
border: 2px solid black;_x000D_
margin: 15px;_x000D_
}_x000D_
#vertical {_x000D_
direction: rtl;_x000D_
overflow-y: scroll;_x000D_
overflow-x: hidden;_x000D_
background: gold;_x000D_
}_x000D_
#vertical p {_x000D_
direction: ltr;_x000D_
margin-bottom: 0;_x000D_
}_x000D_
#horizontal {_x000D_
direction: rtl;_x000D_
transform: rotate(180deg);_x000D_
overflow-y: hidden;_x000D_
overflow-x: scroll;_x000D_
background: tomato;_x000D_
padding-top: 30px;_x000D_
}_x000D_
#horizontal span {_x000D_
direction: ltr;_x000D_
display: inline-block;_x000D_
transform: rotate(-180deg);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id=vertical>_x000D_
<p>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content</p>_x000D_
</div>_x000D_
<div id=horizontal><span> content_content_content_content_content_content_content_content_content_content_content_content_content_content</span>_x000D_
</div>
_x000D_
From the command prompt, use the Windows "sc.exe" utility. You will run something like this:
sc delete <service-name>
CodeIgniter has some error logging functions built in.
$config['log_threshold'] = 1;
log_message('error', 'Some variable did not contain a value.');
log_exceptions()
. You can do this yourself or use this. More info on extending the core hereSee http://www.codeigniter.com/user_guide/general/errors.html
Use \x
Example from postgres manual:
postgres=# \x
postgres=# SELECT * FROM pg_stat_statements ORDER BY total_time DESC LIMIT 3;
-[ RECORD 1 ]------------------------------------------------------------
userid | 10
dbid | 63781
query | UPDATE branches SET bbalance = bbalance + $1 WHERE bid = $2;
calls | 3000
total_time | 20.716706
rows | 3000
-[ RECORD 2 ]------------------------------------------------------------
userid | 10
dbid | 63781
query | UPDATE tellers SET tbalance = tbalance + $1 WHERE tid = $2;
calls | 3000
total_time | 17.1107649999999
rows | 3000
-[ RECORD 3 ]------------------------------------------------------------
userid | 10
dbid | 63781
query | UPDATE accounts SET abalance = abalance + $1 WHERE aid = $2;
calls | 3000
total_time | 0.645601
rows | 3000
I faced this issue too. I was using jquery.poptrox.min.js
for image popping and zooming and I received an error which said:
“Uncaught TypeError: a.indexOf is not a function” error.
This is because indexOf
was not supported in 3.3.1/jquery.min.js
so a simple fix to this is to change it to an old version 2.1.0/jquery.min.js
.
This fixed it for me.
comm -23 <(ls dir1 |sort) <(ls dir2|sort)
This command will give you files those are in dir1 and not in dir2.
About <( )
sign, you can google it as 'process substitution'.
You can set default width and height for all Columns and Rows as below only with one loop.
// DataGridView Name= dgvMachineStatus
foreach (DataGridViewColumn column in dgvMachineStatus.Columns)
{
column.Width = 155;
}
foreach (DataGridViewRow row in dgvMachineStatus.Rows)
{
row.Height = 45;
}
User Endless is right,
$.browser.chrome = (typeof window.chrome === "object");
code is best to detect Chrome browser using jQuery.
If you using IE and added GoogleFrame as plugin then
var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );
code will treat as Chrome browser because GoogleFrame plugin modifying the navigator property and adding chromeframe inside it.
Short version of Franci's answer:
for(Iterator<String> iter = json.keys();iter.hasNext();) {
String key = iter.next();
...
}
http://www.kanzaki.com/docs/ical/ has a slightly more readable version of the older spec. It helps as a starting point - many things are still the same.
Also on my site, I have
.ics
over the last few years. In particular, you may find this repeating events 'cheatsheet' to be useful..ics
areas that need careful handling:
If the response is in json you could do something like (python3):
import json
import requests as reqs
# Make the HTTP request.
response = reqs.get('http://demo.ckan.org/api/3/action/group_list')
# Use the json module to load CKAN's response into a dictionary.
response_dict = json.loads(response.text)
for i in response_dict:
print("key: ", i, "val: ", response_dict[i])
To see everything in the response you can use .__dict__
:
print(response.__dict__)
string filePath = System.IO.Path.GetFullPath("settings.app.config");
var map = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
try
{
// Open App.Config of executable
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
// Add an Application Setting if not exist
config.AppSettings.Settings.Add("key1", "value1");
config.AppSettings.Settings.Add("key2", "value2");
// Save the changes in App.config file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of a changed section.
ConfigurationManager.RefreshSection("appSettings");
}
catch (ConfigurationErrorsException ex)
{
if (ex.BareMessage == "Root element is missing.")
{
File.Delete(filePath);
return;
}
MessageBox.Show(ex.Message);
}
To do this with a generic view, like CreateView...
class AddPhotoToProject(CreateView):
"""
a view where a user can associate a photo with a project
"""
model = Connection
form_class = CreateConnectionForm
def get_context_data(self, **kwargs):
context = super(AddPhotoToProject, self).get_context_data(**kwargs)
context['photo'] = self.kwargs['pk']
context['form'].fields['project'].queryset = Project.objects.for_user(self.request.user)
return context
def form_valid(self, form):
pobj = Photo.objects.get(pk=self.kwargs['pk'])
obj = form.save(commit=False)
obj.photo = pobj
obj.save()
return_json = {'success': True}
if self.request.is_ajax():
final_response = json.dumps(return_json)
return HttpResponse(final_response)
else:
messages.success(self.request, 'photo was added to project!')
return HttpResponseRedirect(reverse('MyPhotos'))
the most important part of that...
context['form'].fields['project'].queryset = Project.objects.for_user(self.request.user)
grep "subscription" | grep -v "spec"
Try quoting the argument list:
Start-Process -FilePath "C:\Program Files\MSBuild\test.exe" -ArgumentList "/genmsi/f $MySourceDirectory\src\Deployment\Installations.xml"
You can also provide the argument list as an array (comma separated args) but using a string is usually easier.
too late to answer but here is my approach since no one mentioned this here:
why note a client side solution ?
a javascript implementation to store the mac in a cookie (you can encrypt it before that)
then each request must include that cookie name, else it will be rejected.
to make this even more fun you can make a server side verification
from the mac address you get the manifacturer (there are plenty of free APIs for this)
then compare it with the user_agent value to see if there was some sort of manipulation:
a mac address of HP + a user agent of Safari = reject request.
Combining Dmitri & dcx's answers I made this:
function Confirm-WindowsServiceExists($name)
{
if (Get-Service $name -ErrorAction SilentlyContinue)
{
return $true
}
return $false
}
function Remove-WindowsServiceIfItExists($name)
{
$exists = Confirm-WindowsServiceExists $name
if ($exists)
{
sc.exe \\server delete $name
}
}
I understand what you want. You want to check every data of the array if all of it is empty or at least 1 is not empty
Empty array
Array ( [Tags] => SimpleXMLElement Object ( [0] => ) )
Not an Empty array
Array ( [Tags] => SimpleXMLElement Object ( [0] =>,[1] => "s" ) )
I hope I am right. You can use this function to check every data of an array if at least 1 of them has a value.
/*
return true if the array is not empty
return false if it is empty
*/
function is_array_empty($arr){
if(is_array($arr)){
foreach($arr $key => $value){
if(!empty($value) || $value != NULL || $value != ""){
return true;
break;//stop the process we have seen that at least 1 of the array has value so its not empty
}
}
return false;
}
}
if(is_array_empty($result['Tags'])){
//array is not empty
}else{
//array is empty
}
Hope that helps.
There is no such thing. It looks like you want something like "here documents" in Perl and the shells, but Python doesn't have that.
Using raw strings or multiline strings only means that there are fewer things to worry about. If you use a raw string then you still have to work around a terminal "\" and with any string solution you'll have to worry about the closing ", ', ''' or """ if it is included in your data.
That is, there's no way to have the string
' ''' """ " \
properly stored in any Python string literal without internal escaping of some sort.
Same thing, Just start the table name with #
or ##
:
CREATE TABLE #TemporaryTable -- Local temporary table - starts with single #
(
Col1 int,
Col2 varchar(10)
....
);
CREATE TABLE ##GlobalTemporaryTable -- Global temporary table - note it starts with ##.
(
Col1 int,
Col2 varchar(10)
....
);
Temporary table names start with #
or ##
- The first is a local temporary table and the last is a global temporary table.
Here is one of many articles describing the differences between them.
Here is another solution
Set a hidden scope variable in your html then you can use it from your controller:
<span style="display:none" >{{ formValid = myForm.$valid}}</span>
Here is the full working example:
angular.module('App', [])_x000D_
.controller('myController', function($scope) {_x000D_
$scope.userType = 'guest';_x000D_
$scope.formValid = false;_x000D_
console.info('Ctrl init, no form.');_x000D_
_x000D_
$scope.$watch('myForm', function() {_x000D_
console.info('myForm watch');_x000D_
console.log($scope.formValid);_x000D_
});_x000D_
_x000D_
$scope.isFormValid = function() {_x000D_
//test the new scope variable_x000D_
console.log('form valid?: ', $scope.formValid);_x000D_
};_x000D_
});
_x000D_
<!doctype html>_x000D_
<html ng-app="App">_x000D_
<head>_x000D_
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<form name="myForm" ng-controller="myController">_x000D_
userType: <input name="input" ng-model="userType" required>_x000D_
<span class="error" ng-show="myForm.input.$error.required">Required!</span><br>_x000D_
<tt>userType = {{userType}}</tt><br>_x000D_
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>_x000D_
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>_x000D_
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>_x000D_
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>_x000D_
_x000D_
_x000D_
/*-- Hidden Variable formValid to use in your controller --*/_x000D_
<span style="display:none" >{{ formValid = myForm.$valid}}</span>_x000D_
_x000D_
_x000D_
<br/>_x000D_
<button ng-click="isFormValid()">Check Valid</button>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
The other solutions posted here didn't work for me, because:
import *
didn't work for me, as i need a way to override them by choosing another fileSo I ended up using Configparser
and globals().update()
Test file:
#File parametertest.cfg:
[Settings]
#Comments are no Problem
test= True
bla= False #Here neither
#that neither
And that's my demo script:
import ConfigParser
cfg = ConfigParser.RawConfigParser()
cfg.read('parametertest.cfg') # Read file
#print cfg.getboolean('Settings','bla') # Manual Way to acess them
par=dict(cfg.items("Settings"))
for p in par:
par[p]=par[p].split("#",1)[0].strip() # To get rid of inline comments
globals().update(par) #Make them availible globally
print bla
It's just for a file with one section now, but that will be easy to adopt.
Hope it will be helpful for someone :)
You are missing, that \ is the escape character.
Look here: http://docs.python.org/reference/lexical_analysis.html at 2.4.1 "Escape Sequence"
Most importantly \n is a newline character. And \\ is an escaped escape character :D
>>> a = 'a\\\\nb'
>>> a
'a\\\\nb'
>>> print a
a\\nb
>>> a.replace('\\\\', '\\')
'a\\nb'
>>> print a.replace('\\\\', '\\')
a\nb
{App1(Java code)------>App1byteCode}........{(JVM+MacOS) help work with App1,App2,App3}
{App2(Java Code)----->App2byteCode}........{(JVM+LinuxOS) help work with App1,App2,App3}
{App3(Java Code)----->App3byteCode}........{(JVM+WindowsOS) help work with App1,App2,App3}
How this is happening ?
Ans: JVM have capability to read ByteCode
and Response In Accordance with the underlying OS As the JVM is in Sync with OS.
So we find, we need JVM with Sync with Platform.
But the main thing is that the programmer dont have to know specific knowledge of the Platform and program his application keeping one specific platform in mind.
This Flexibility of write Program in Java --- compile to ByteCode
and run on any Machine (Yes need to have Platform DEPENDENT JVM to execute it) makes Java Platform Independent.
Please see this link http://bugs.php.net/bug.php?id=45150 seems like they moved to native MYSQL support in PHP5.3 and it has some trouble working with IPV6. Try using "127.0.0.1" instead of "localhost"
The code below reads for any text files available in the directory which contains the script we are running. Then it opens every text file and stores the words of the text line into a list. After store the words we print each word line by line
import os, fnmatch
listOfFiles = os.listdir('.')
pattern = "*.txt"
store = []
for entry in listOfFiles:
if fnmatch.fnmatch(entry, pattern):
_fileName = open(entry,"r")
if _fileName.mode == "r":
content = _fileName.read()
contentList = content.split(" ")
for i in contentList:
if i != '\n' and i != "\r\n":
store.append(i)
for i in store:
print(i)
As of version 2.4 of the Maven Dependency Plugin, you can also define a target destination for the artifact by using the -Ddest flag. It should point to a filename (not a directory) for the destination artifact. See the parameter page for additional parameters that can be used
mvn org.apache.maven.plugins:maven-dependency-plugin:2.4:get \
-DremoteRepositories=http://download.java.net/maven/2 \
-Dartifact=robo-guice:robo-guice:0.4-SNAPSHOT \
-Ddest=c:\temp\robo-guice.jar
My guess is that your video is incompatible with Android. Try it with a different video. This one definitely works used to work with Android (but does not on newer devices, for some reason). If that video works, and yours does not, then your video is not compatible with Android.
As others have indicated, please test this on a device. Video playback on the emulator requires too much power.
UPDATE 2020-02-18: https://law.duke.edu/cspd/contest/videos/Framed-Contest_Documentaries-and-You.mp4 is an MP4 of the same content, but I have no idea if it is the same actual MP4 as I previously linked to.
--force-reinstall
doesn't appear to force reinstall using python2.7 with pip-1.5
I've had to use
--no-deps --ignore-installed
You're trying to concatenate a string and an integer, which is incorrect.
Change print(numlist.pop(2)+" has been removed")
to any of these:
Explicit int
to str
conversion:
print(str(numlist.pop(2)) + " has been removed")
Use ,
instead of +
:
print(numlist.pop(2), "has been removed")
String formatting:
print("{} has been removed".format(numlist.pop(2)))
Late to the party, so answering more for future reference.
Advances in the field + Mozilla's mindset and agenda led to these two projects towards that end:
The latter has a 12GB data-set for download. The former allows for training a model with your own audio files to my understanding
I was not able to find any solution for this type of animation using ViewPropertyAnimator.
Here's an example:
Layout:
<FrameLayout
android:id="@+id/child_view_container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/child_view"
android:gravity="center_horizontal"
android:layout_gravity="center_horizontal"
/>
</FrameLayout>
Animate - Right to left and exit view:
final childView = findViewById(R.id.child_view);
View containerView = findViewById(R.id.child_view_container);
childView.animate()
.translationXBy(-containerView.getWidth())
.setDuration(TRANSLATION_DURATION)
.setInterpolator(new AccelerateDecelerateInterpolator())
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
childView.setVisibility(View.GONE);
}
});
Animate - Right to left enter view:
final View childView = findViewById(R.id.child_view);
View containerView = findViewById(R.id.child_view_container);
childView.setTranslationX(containerView.getWidth());
childView.animate()
.translationXBy(-containerView.getWidth())
.setDuration(TRANSLATION_DURATION)
.setInterpolator(new AccelerateDecelerateInterpolator())
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
childView.setVisibility(View.VISIBLE);
}
});
I know there a lot of answers but most of these are for additional functions and additional classes. This is the one I personally use; much cleaner and much less lines of code!
if( document.body.className.match('category-page') ) {
console.log('yes');
}
In case you are using FluentValidation you could write something as simple as this:
public cass User
{
public string Email { get; set; }
}
public class UserValidator : AbstractValidator<User>
{
public UserValidator()
{
RuleFor(x => x.Email).EmailAddress().WithMessage("The text entered is not a valid email address.");
}
}
// Validates an user.
var validationResult = new UserValidator().Validate(new User { Email = "açflkdj" });
// This will return false, since the user email is not valid.
bool userIsValid = validationResult.IsValid;
for decreasing order for integer array of 2 dimension you can use
Arrays.sort(contests, (a, b) -> Integer.compare(b[0],a[0]));//decreasing order
Arrays.sort(contests, (a, b) -> Integer.compare(a[0],b[0]);//decreasing order
You forgot to put z as an bind variable.
The following EXECUTE command runs a PL/SQL statement that references a stored procedure:
SQL> EXECUTE -
> :Z := EMP_SALE.HIRE('JACK','MANAGER','JONES',2990,'SALES')
Note that the value returned by the stored procedure is being return into :Z
This has been already answered but I tried a different way to make it simpler.
The idea is using putting an ImageButton
on the right of EditText
and having negative margin to it so that the EditText
flows into the ImageButton
making it look like the Button is in the EditText
.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/editText"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Enter Pin"
android:singleLine="true"
android:textSize="25sp"
android:paddingRight="60dp"
/>
<ImageButton
android:id="@+id/pastePin"
android:layout_marginLeft="-60dp"
style="?android:buttonBarButtonStyle"
android:paddingBottom="5dp"
android:src="@drawable/ic_action_paste"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Also, as shown above, you can use a paddingRight
of similar width in the EditText
if you don't want the text in it to be flown over the ImageButton
.
I guessed margin size with the help of android-studio's layout designer and it looks similar across all screen sizes. Or else you can calculate the width of the ImageButton
and set the margin programatically.
Add this line to your Dockerfile (You can run any linux command this way)
RUN useradd -ms /bin/bash yourNewUserName
I know this is an old post but I had a lot of issues trying to solve this and I finally did so I wanted to share.
My issue was that I was adding an event listener within the ontouchstart and removing it in the ontouchend functions - something like this
function onTouchStart() {
window.addEventListener("touchmove", handleTouchMove, {
passive: false
});
}
function onTouchEnd() {
window.removeEventListener("touchmove", handleTouchMove, {
passive: true
});
}
function handleTouchMove(e) {
e.preventDefault();
}
For some reason adding it removing it like this was causing this issue of the event randomly not being cancelable. So to solve this I kept the listener active and toggled a boolean on whether or not it should prevent the event - something like this:
let stopScrolling = false;
window.addEventListener("touchmove", handleTouchMove, {
passive: false
});
function handleTouchMove(e) {
if (!stopScrolling) {
return;
}
e.preventDefault();
}
function onTouchStart() {
stopScrolling = true;
}
function onTouchEnd() {
stopScrolling = false;
}
I was actually using React so my solution involved setting state, but I've simplified it for a more generic solution. Hopefully this helps someone!
A Numpy array is immutable, meaning you technically cannot delete an item from it. However, you can construct a new array without the values you don't want, like this:
b = np.delete(a, [2,3,6])
From this looks of this MSDN article, it looks like you can now bypass the MAX_PATH restriction in Windows 10 v1607 (AKA 'anniversary update') by changing a value in the registry - or via Group Policy
Function isset()
is faster, check http://www.php.net/manual/en/function.array-key-exists.php#82867
It's simple actually you don't need any plugins, just jquery or you can do it with simple javascript.
$('#dialog').on('click', function(e){
e.stopPropagation();
});
$(document.body).on('click', function(e){
master.hide();
});
You can do it without submitting the form.
For example, if the form submit button with id "search" is in the other form . You can call click event on that submit button and call ev.preventDefault after that. For my case I validate form B from Form A submission. Like this
function validateFormB(ev){ // DOM Event object
//search is in Form A
$("#search").click();
ev.preventDefault();
//Form B validation from here on
}
I understand you asked about converting images to a gif; however, if the original format is MP4, you could use FFmpeg:
ffmpeg -i input.mp4 output.gif
str[a:b]
tl;dr: use a colon :
instead of a comma in between the two indices a
and b
in str[a:b]
When working with strings and slice notation (a common sequence operation), it can happen that a TypeError
is raised, pointing out that the indices must be integers, even if they obviously are.
>>> my_string = "hello world"
>>> my_string[0,5]
TypeError: string indices must be integers
We obviously passed two integers for the indices to the slice notation, right? So what is the problem here?
This error can be very frustrating - especially at the beginning of learning Python - because the error message is a little bit misleading.
We implicitly passed a tuple of two integers (0 and 5) to the slice notation when we called my_string[0,5]
because 0,5
(even without the parentheses) evaluates to the same tuple as (0,5)
would do.
A comma ,
is actually enough for Python to evaluate something as a tuple:
>>> my_variable = 0,
>>> type(my_variable)
<class 'tuple'>
So what we did there, this time explicitly:
>>> my_string = "hello world"
>>> my_tuple = 0, 5
>>> my_string[my_tuple]
TypeError: string indices must be integers
Now, at least, the error message makes sense.
We need to replace the comma ,
with a colon :
to separate the two integers correctly:
>>> my_string = "hello world"
>>> my_string[0:5]
'hello'
A clearer and more helpful error message could have been something like:
TypeError: string indices must be integers (not tuple)
A good error message shows the user directly what they did wrong and it would have been more obvious how to solve the problem.
[So the next time when you find yourself responsible for writing an error description message, think of this example and add the reason or other useful information to error message to let you and maybe other people understand what went wrong.]
:
to separate its indices (and step range, e.g. str[from:to:step]
),
(e.g. t = 1,
)Cheers and happy programming
winklerrr
[I know this question was already answered and this wasn't exactly the question the thread starter asked, but I came here because of the above problem which leads to the same error message. At least it took me quite some time to find that little typo.
So I hope that this will help someone else who stumbled upon the same error and saves them some time finding that tiny mistake.]
Here is my solution using AnimatorSet which seems to be a bit more reliable than AnimationSet.
// Custom animation on image
ImageView myView = (ImageView)splashDialog.findViewById(R.id.splashscreenImage);
ObjectAnimator fadeOut = ObjectAnimator.ofFloat(myView, "alpha", 1f, .3f);
fadeOut.setDuration(2000);
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(myView, "alpha", .3f, 1f);
fadeIn.setDuration(2000);
final AnimatorSet mAnimationSet = new AnimatorSet();
mAnimationSet.play(fadeIn).after(fadeOut);
mAnimationSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
mAnimationSet.start();
}
});
mAnimationSet.start();
No.The image will be loaded as usual and will still use the user’s bandwidth if you are considering the mobile phone user bandwidth saving.What u can do is to use media query and filter the devices that you want your image to be loaded.Your image must be set as a background image of a div,etc and NOT an tag since the the image tag will load the image regardless if the screen size and the media query set.
After a couple of hit and trial I use this. This works for me.
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
WARNING: As BalusC correctly mentioned, this works for JSTL 1.0.
If above solutions are not working for your TextView then this will definitely work:
1. add this style
<style name="ClickableView">
<item name="colorControlHighlight">@android:color/white</item>
<item name="android:background">?selectableItemBackground</item>
</style>
2. use it just by
android:theme="@style/ClickableView"
You can't do that, unless you take the child out of the parent and place it via positioning.
The only way I know and it actually works, is to use a translucid image (.png with transparency) for the parent's background. The only disavantage is that you can't control the opacity via CSS, other than that it works!
You can first find the position of the string in this case ":"
'position = InStr(StringToSearch, StringToFind)
position = InStr(StringToSearch, ":")
Then use Left(StringToCut, NumberOfCharacterToCut)
Result = Left(StringToSearch, position -1)
As Charles Duffey has stated, XML parsers are best parsed with a proper XML parsing tools. For one time job the following should work.
grep -oPm1 "(?<=<title>)[^<]+"
$ echo "$data"
<item>
<title>15:54:57 - George:</title>
<description>Diane DeConn? You saw Diane DeConn!</description>
</item>
<item>
<title>15:55:17 - Jerry:</title>
<description>Something huh?</description>
$ title=$(grep -oPm1 "(?<=<title>)[^<]+" <<< "$data")
$ echo "$title"
15:54:57 - George:
There are a few ways to convert String
to long
:
1)
long l = Long.parseLong("200");
String numberAsString = "1234";
long number = Long.valueOf(numberAsString).longValue();
String numberAsString = "1234";
Long longObject = new Long(numberAsString);
long number = longObject.longValue();
We can shorten to:
String numberAsString = "1234";
long number = new Long(numberAsString).longValue();
Or just
long number = new Long("1234").longValue();
String numberAsString = "1234";
DecimalFormat decimalFormat = new DecimalFormat("#");
try {
long number = decimalFormat.parse(numberAsString).longValue();
System.out.println("The number is: " + number);
} catch (ParseException e) {
System.out.println(numberAsString + " is not a valid number.");
}
Found the answer here: http://www.digitallycreated.net/Blog/59/locally-publishing-a-vs2010-asp.net-web-application-using-msbuild
Visual Studio 2010 has great new Web Application Project publishing features that allow you to easy publish your web app project with a click of a button. Behind the scenes the Web.config transformation and package building is done by a massive MSBuild script that’s imported into your project file (found at: C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets). Unfortunately, the script is hugely complicated, messy and undocumented (other then some oft-badly spelled and mostly useless comments in the file). A big flowchart of that file and some documentation about how to hook into it would be nice, but seems to be sadly lacking (or at least I can’t find it).
Unfortunately, this means performing publishing via the command line is much more opaque than it needs to be. I was surprised by the lack of documentation in this area, because these days many shops use a continuous integration server and some even do automated deployment (which the VS2010 publishing features could help a lot with), so I would have thought that enabling this (easily!) would be have been a fairly main requirement for the feature.
Anyway, after digging through the Microsoft.Web.Publishing.targets file for hours and banging my head against the trial and error wall, I’ve managed to figure out how Visual Studio seems to perform its magic one click “Publish to File System” and “Build Deployment Package” features. I’ll be getting into a bit of MSBuild scripting, so if you’re not familiar with MSBuild I suggest you check out this crash course MSDN page.
Publish to File System
The VS2010 Publish To File System Dialog Publish to File System took me a while to nut out because I expected some sensible use of MSBuild to be occurring. Instead, VS2010 does something quite weird: it calls on MSBuild to perform a sort of half-deploy that prepares the web app’s files in your project’s obj folder, then it seems to do a manual copy of those files (ie. outside of MSBuild) into your target publish folder. This is really whack behaviour because MSBuild is designed to copy files around (and other build-related things), so it’d make sense if the whole process was just one MSBuild target that VS2010 called on, not a target then a manual copy.
This means that doing this via MSBuild on the command-line isn’t as simple as invoking your project file with a particular target and setting some properties. You’ll need to do what VS2010 ought to have done: create a target yourself that performs the half-deploy then copies the results to the target folder. To edit your project file, right click on the project in VS2010 and click Unload Project, then right click again and click Edit. Scroll down until you find the Import element that imports the web application targets (Microsoft.WebApplication.targets; this file itself imports the Microsoft.Web.Publishing.targets file mentioned earlier). Underneath this line we’ll add our new target, called PublishToFileSystem:
<Target Name="PublishToFileSystem"
DependsOnTargets="PipelinePreDeployCopyAllFilesToOneFolder">
<Error Condition="'$(PublishDestination)'==''"
Text="The PublishDestination property must be set to the intended publishing destination." />
<MakeDir Condition="!Exists($(PublishDestination))"
Directories="$(PublishDestination)" />
<ItemGroup>
<PublishFiles Include="$(_PackageTempDir)\**\*.*" />
</ItemGroup>
<Copy SourceFiles="@(PublishFiles)"
DestinationFiles="@(PublishFiles->'$(PublishDestination)\%(RecursiveDir)%(Filename)%(Extension)')"
SkipUnchangedFiles="True" />
</Target>
This target depends on the PipelinePreDeployCopyAllFilesToOneFolder target, which is what VS2010 calls before it does its manual copy. Some digging around in Microsoft.Web.Publishing.targets shows that calling this target causes the project files to be placed into the directory specified by the property _PackageTempDir.
The first task we call in our target is the Error task, upon which we’ve placed a condition that ensures that the task only happens if the PublishDestination property hasn’t been set. This will catch you and error out the build in case you’ve forgotten to specify the PublishDestination property. We then call the MakeDir task to create that PublishDestination directory if it doesn’t already exist.
We then define an Item called PublishFiles that represents all the files found under the _PackageTempDir folder. The Copy task is then called which copies all those files to the Publish Destination folder. The DestinationFiles attribute on the Copy element is a bit complex; it performs a transform of the items and converts their paths to new paths rooted at the PublishDestination folder (check out Well-Known Item Metadata to see what those %()s mean).
To call this target from the command-line we can now simply perform this command (obviously changing the project file name and properties to suit you):
msbuild Website.csproj "/p:Platform=AnyCPU;Configuration=Release;PublishDestination=F:\Temp\Publish" /t:PublishToFileSystem
Create php.ini
file with your desired setting and upload it in your root folder of server. It will take effect with this new setting.
You can't edit the php.ini
file of godaddy
server, but you can upload your own copy of your php.ini
with your new setting.
This new setting will be available only to you. Other websites will not be affected with this new setting.
Previously I faced the same issue, but after doing this my problem was resolved.
If your application is 32 bit, and you want to deploy in a 64 bit machine, You need to set 'Enable 32 Bit Applications' property to 'True' in the application pool - advanced settings.
You want both worlds.
You want multiple CSS files because your sanity is a terrible thing to waste.
At the same time, it's better to have a single, large file.
The solution is to have some mechanism that combines the multiple files in to a single file.
One example is something like
<link rel="stylesheet" type="text/css" href="allcss.php?files=positions.css,buttons.css,copy.css" />
Then, the allcss.php script handles concatenating the files and delivering them.
Ideally, the script would check the mod dates on all the files, creates a new composite if any of them changes, then returns that composite, and then checks against the If-Modified HTTP headers so as to not send redundant CSS.
This gives you the best of both worlds. Works great for JS as well.
You don't have to use Javascript to do this. Using plain-old css:
div.blah {
position:absolute;
top: 0; /*[wherever you want it]*/
left:0; /*[wherever you want it]*/
}
If you feel you must use javascript, or are trying to do this dynamically Using JQuery, this affects all divs of class "blah":
var blahclass = $('.blah');
blahclass.css('position', 'absolute');
blahclass.css('top', 0); //or wherever you want it
blahclass.css('left', 0); //or wherever you want it
Alternatively, if you must use regular old-javascript you can grab by id
var domElement = document.getElementById('myElement');// don't go to to DOM every time you need it. Instead store in a variable and manipulate.
domElement.style.position = "absolute";
domElement.style.top = 0; //or whatever
domElement.style.left = 0; // or whatever
The answer is simple and I am surprised it has yet to be answered here.
Use a Header View
or/and Footer View
on the list itself.
Don't mix a ScrollView
with a ListView
or anything that can scroll. It's meant to be used with headers and footers :)
Essentially, take all the content above your ListView, put it in another .xml file as a layout and then in code inflate it and add it to the list as a header view.
i.e.
View header = getLayoutInflater().inflate(R.layout.header, null);
View footer = getLayoutInflater().inflate(R.layout.footer, null);
listView.addHeaderView(header);
listView.addFooterView(footer);
Try using Select instead of Print
DECLARE @Test AS DATETIME
SET @Test = '2011-02-15'
Select @Test
$('.clickable').hover(function(){
$('.selector').stop(true,true).fadeTo( 400 , 0.0, function() {
$('.selector').css('background-image',"url('assets/img/pic2.jpg')");
});
$('.selector').fadeTo( 400 , 1);
},
function(){
$('.selector').stop(false,true).fadeTo( 400 , 0.0, function() {
$('.selector').css('background-image',"url('assets/img/pic.jpg')");
});
$('.selector').fadeTo( 400 , 1);
}
);
The "braces" are making an object literal, i.e. they create an object. It is one argument.
Example:
function someFunc(arg) {
alert(arg.foo);
alert(arg.bar);
}
someFunc({foo: "This", bar: "works!"});
the object can be created beforehand as well:
var someObject = {
foo: "This",
bar: "works!"
};
someFunc(someObject);
I recommend to read the MDN JavaScript Guide - Working with Objects.
I stumbled across this question while hitting this road block myself. I ended up writing a piece of code real quick to handle this ReDim Preserve
on a new sized array (first or last dimension). Maybe it will help others who face the same issue.
So for the usage, lets say you have your array originally set as MyArray(3,5)
, and you want to make the dimensions (first too!) larger, lets just say to MyArray(10,20)
. You would be used to doing something like this right?
ReDim Preserve MyArray(10,20) '<-- Returns Error
But unfortunately that returns an error because you tried to change the size of the first dimension. So with my function, you would just do something like this instead:
MyArray = ReDimPreserve(MyArray,10,20)
Now the array is larger, and the data is preserved. Your ReDim Preserve
for a Multi-Dimension array is complete. :)
And last but not least, the miraculous function: ReDimPreserve()
'redim preserve both dimensions for a multidimension array *ONLY
Public Function ReDimPreserve(aArrayToPreserve,nNewFirstUBound,nNewLastUBound)
ReDimPreserve = False
'check if its in array first
If IsArray(aArrayToPreserve) Then
'create new array
ReDim aPreservedArray(nNewFirstUBound,nNewLastUBound)
'get old lBound/uBound
nOldFirstUBound = uBound(aArrayToPreserve,1)
nOldLastUBound = uBound(aArrayToPreserve,2)
'loop through first
For nFirst = lBound(aArrayToPreserve,1) to nNewFirstUBound
For nLast = lBound(aArrayToPreserve,2) to nNewLastUBound
'if its in range, then append to new array the same way
If nOldFirstUBound >= nFirst And nOldLastUBound >= nLast Then
aPreservedArray(nFirst,nLast) = aArrayToPreserve(nFirst,nLast)
End If
Next
Next
'return the array redimmed
If IsArray(aPreservedArray) Then ReDimPreserve = aPreservedArray
End If
End Function
I wrote this in like 20 minutes, so there's no guarantees. But if you would like to use or extend it, feel free. I would've thought that someone would've had some code like this up here already, well apparently not. So here ya go fellow gearheads.
Your XML is not entirely clear, but arrays XML can cause force closes if you make them numbers, and/or put white space in their definition.
Make sure they are defined like No Leading or Trailing Whitespace
Go to pom.xml
Add this Dependency :
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
using command prompt, find your folder: - mvn clean
In my case I was modifying the request to append a header (using Fiddler) to an https
request, but I did not configure it to decrypt https traffic. You can export a manually-created certificate from Fiddler, so you can trust/import the certificate by your browsers. See above link for details, some steps include:
StanleyH's answer was excellent, but it had one unfortunate bug: clicking the shaded area of the scrollbar no longer jumps to the selection you click. Instead, what you get is a very small and somewhat annoying increment in the position of the scrollbar.
Tested: 4 versions of Firefox (100% affected), 4 versions of Chrome (50% affected).
Here's my jsfiddle. You can get around this with by having an on/off (true/false) var that allows only one onScroll() event to trigger at a time:
var scrolling = false;
$(".wrapper1").scroll(function(){
if(scrolling) {
scrolling = false;
return true;
}
scrolling = true;
$(".wrapper2")
.scrollLeft($(".wrapper1").scrollLeft());
});
$(".wrapper2").scroll(function(){
if(scrolling) {
scrolling = false;
return true;
}
scrolling = true;
$(".wrapper1")
.scrollLeft($(".wrapper2").scrollLeft());
});
Problem Behavior With Accepted Answer :
Actually Desired Behavior :
So, just why does this happen? If you run through the code, you'll see that wrapper1 calls wrapper2's scrollLeft, and wrapper2 calls wrapper1's scrollLeft, and repeat this infinitely, so, we have an infinite loop problem. Or, rather: the continued scrolling of the user conflicts with wrapperx's call of the scrolling, an event conflict occurs, and the end result is no jumping in the scrollbars.
Hope this helps someone else out!
You could also try to include md5-hash-sums or similar do determine whether there are any differences at all. Then, only compare files which have different hashes...
Using msbuild
as pointed out by others worked for me but I needed to do a bit more than just that. First of all, msbuild
needs to have access to the compiler. This can be done by running:
"C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat"
Then msbuild
was not in my $PATH so I had to run it via its explicit path:
"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" myproj.sln
Lastly, my project was making use of some variables like $(VisualStudioDir)
. It seems those do not get set by msbuild
so I had to set them manually via the /property
option:
"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" /property:VisualStudioDir="C:\Users\Administrator\Documents\Visual Studio 2013" myproj.sln
That line then finally allowed me to compile my project.
Bonus: it seems that the command line tools do not require a registration after 30 days of using them like the "free" GUI-based Visual Studio Community edition does. With the Microsoft registration requirement in place, that version is hardly free. Free-as-in-facebook if anything...
this is how i did it:
String[] listAges = getResources().getStringArray(R.array.ages);
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listAges);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner_age.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.spinner_icon), PorterDuff.Mode.SRC_ATOP);
spinner_age.setAdapter(dataAdapter);
spinner_age.setSelection(0);
spinner_age.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
if(position > 0){
// get spinner value
Toast.makeText(parent.getContext(), "Age..." + item, Toast.LENGTH_SHORT).show();
}else{
// show toast select gender
Toast.makeText(parent.getContext(), "none" + item, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
I had faced he similar problem however it got resolved once i renamed the file , so i would suggest that you should
"Just rename the file"
I love this question - it's like asking "what should I learn first, snowboarding or skiing"? I think it depends if you want to snowboard or to ski. If you want to do both, you have to learn both.
In both sports, you slide down a hill on snow using devices that are sufficiently similar to provoke this question. However, they are also sufficiently different so that learning one does not help you much with the other. Same thing with C and C++. While they appear to be languages sufficiently similar in syntax, the mind set that you need for writing OO code vs procedural code is sufficiently different so that you pretty much have to start from the beginning, whatever language you learn second.
Please try with the below code snippet.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link href="http://cdn.kendostatic.com/2014.1.318/styles/kendo.common.min.css" rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2014.1.318/styles/kendo.default.min.css" rel="stylesheet" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.1.318/js/kendo.all.min.js"></script>
<script>
function onDataBound(e) {
var grid = $("#grid").data("kendoGrid");
$(grid.tbody).find('tr').removeClass('k-alt');
}
$(document).ready(function () {
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: { type: "number" },
Freight: { type: "number" },
ShipName: { type: "string" },
OrderDate: { type: "date" },
ShipCity: { type: "string" }
}
}
},
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
height: 430,
filterable: true,
dataBound: onDataBound,
sortable: true,
pageable: true,
columns: [{
field: "OrderID",
filterable: false
},
"Freight",
{
field: "OrderDate",
title: "Order Date",
width: 120,
format: "{0:MM/dd/yyyy}"
}, {
field: "ShipName",
title: "Ship Name",
width: 260
}, {
field: "ShipCity",
title: "Ship City",
width: 150
}
]
});
});
</script>
</head>
<body>
<div id="grid">
</div>
</body>
</html>
I have implemented same thing with different way.
This works too and you dont have to use join or anything:
DROP VIEW IF EXISTS yourview;
CREATE VIEW yourview AS
SELECT table1.column1,
table2.column2
FROM
table1, table2
WHERE table1.column1 = table2.column1;
What login are you connecting to SQL Server as? You need to connect with a login that has sufficient privileges to create a database. Network Service is probably not good enough, unless you go into SQL Server and add them as a login with sufficient rights.
I had the same issue and for me it had nothing to do with namespace or project naming.
But as several users hinted at it had to do with an old assembly still being referenced.
I recommend to delete all "bin"/binary folders of all projects and to re-build the whole solution. This washed out any potentially outdated assemblies and after that MEF exported all my plugins without issue.
I know this is coming a bit late, but a colleague of mine figured something out:
figure, plot ((1:10),cos(rand(1,10))-0.75,'*-')
hold on
plot ((1:10),zeros(1,10),'k+-')
text([1:10]-0.09,ones(1,10).*-0.015,[{'0' '1' '2' '3' '4' '5' '6' '7' '8' '9'}])
set(gca,'XTick',[], 'XColor',[1 1 1])
box off
getline(fin, buffer, '\n')
where fin
is opened file(ifstream object) and buffer
is of string/char
type where you want to copy line.
For example 1 and 2 you need to create static methods:
public static string InstanceMethod() {return "Hello World";}
Then for example 3 you need an instance of your object to invoke the method:
object o = new object();
string s = o.InstanceMethod();
I wrote the Text-IO library, which can deal with the problem of System.console() being null when running an application from within an IDE.
It introduces an abstraction layer similar to the one proposed by McDowell. If System.console() returns null, the library switches to a Swing-based console.
In addition, Text-IO has a series of useful features:
Usage example:
TextIO textIO = TextIoFactory.getTextIO();
String user = textIO.newStringInputReader()
.withDefaultValue("admin")
.read("Username");
String password = textIO.newStringInputReader()
.withMinLength(6)
.withInputMasking(true)
.read("Password");
int age = textIO.newIntInputReader()
.withMinVal(13)
.read("Age");
Month month = textIO.newEnumInputReader(Month.class)
.read("What month were you born in?");
textIO.getTextTerminal().println("User " + user + " is " + age + " years old, " +
"was born in " + month + " and has the password " + password + ".");
In this image you can see the above code running in a Swing-based console.
SqlConnection con = new SqlConnection("Data Source=DShp;Initial Catalog=abc;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("data", con);
da.SelectCommand.CommandType= CommandType.StoredProcedure;
DataSet ds=new DataSet();
da.Fill(ds, "data");
GridView1.DataSource = ds.Tables["data"];
GridView1.DataBind();
In PHP you can use === and !== operators to check not only if the values are equal but also if their types match. So for example: 0 == false
is true
, but 0 === false
is false
. The same goes for !=
versus !==
. Also in case you compare null
to the other two using the mentioned operators, expect similar results.
Now in PHP this quality of values is usually used when returning a value which sometimes can be 0
(zero), but sometimes it might be that the function failed. In such cases in PHP you return false
and you have to check for these cases using the identity operator ===
. For example if you are searching for a position of one string inside the other and you're using strpos()
, this function will return the numeric position which can be 0 if the string is found at the very beginning, but if the string is not found at all, then strpos()
will return false
and you have to take this into account when dealing with the result.
If you will use the same technique in your functions, anybody familiar with the standard PHP library will understand what is going on and how to check if the returned value is what is wanted or did some error occur while processing. The same actually goes for function params, you can process them differently depending on if they are arrays or strings or what not, and this technique is used throughout PHP heavily too, so everybody will get it quite easily. So I guess that's the power.
Png files can handle transparency.
So you could use this question Save plot to image file instead of displaying it using Matplotlib so as to save you graph as a png
file.
And if you want to turn all white pixel transparent, there's this other question : Using PIL to make all white pixels transparent?
If you want to turn an entire area to transparent, then there's this question: And then use the PIL library like in this question Python PIL: how to make area transparent in PNG? so as to make your graph transparent.
The PHP zip includes most of the commonly used extensions (*.dll on windows such as php_mysqli.dll) under the \ext directory, however they are not enabled by default. You might be getting this Fatal Error when trying to use MySQLi:
( ! ) Fatal error: Uncaught Error: Class 'mysqli' not found in C:\myProject\ class.Database.php on line 24
To enable extensions, open php.ini (you might need to first copy php.ini-development as php.ini), and un-comment (or add) these two lines:
extension_dir = "ext"
And any particular extensions you are getting Fatal Errors for, i.e. for mysqli:
extension=mysqli
Use ==
:
pip install django_modeltranslation==0.4.0-beta2
CharSequence
is an interface and String
implements it. You can instantiate a String
but you could not do that for CharSequence
since it is an interface. You can find other implementations in CharSequence
in the official Java website.
$data_arr = array('hello', 'developer', 'laravel' );
// We Have to remove Value "hello" from the array
// Check if the value is exists in the array
if (array_search('hello', $data_arr ) !== false) {
$key = array_search('hello', $data_arr );
unset( $data_arr[$key] );
}
# output:
// It will Return unsorted Indexed array
print( $data_arr )
// To Sort Array index use this
$data_arr = array_values( $data_arr );
// Now the array key is sorted
For bootstrap 3, the class navbar-static-top
instead of navbar-fixed-top
prevents this issue, unless you need the navbar to always be visible.
To add on to the other answers here, if you would like to create a new object of a third different type with a where clause (e.g. one that is not your Entity Framework object) you can do this:
public IEnumerable<ThirdNonEntityClass> demoMethod(IEnumerable<int> property1Values)
{
using(var entityFrameworkObjectContext = new EntityFrameworkObjectContext )
{
var result = entityFrameworkObjectContext.SomeClass
.Join(entityFrameworkObjectContext.SomeOtherClass,
sc => sc.property1,
soc => soc.property2,
(sc, soc) => new {sc, soc})
.Where(s => propertyValues.Any(pvals => pvals == es.sc.property1)
.Select(s => new ThirdNonEntityClass
{
dataValue1 = s.sc.dataValueA,
dataValue2 = s.soc.dataValueB
})
.ToList();
}
return result;
}
Pay special attention to the intermediate object that is created in the Where and Select clauses.
Note that here we also look for any joined objects that have a property1 that matches one of the ones in the input list.
I know this is a bit more complex than what the original asker was looking for, but hopefully it will help someone.
We can do this by css3 too. Try this:
.halfsize {
-moz-transform:scale(0.5);
-webkit-transform:scale(0.5);
transform:scale(0.5);
}
<img class="halfsize" src="image4.jpg">
This fiddle shows how
ul, li {
display:inline
}
Great references on lists and css here:
I thought I was bright ;-)
In CSS:
option:disabled {display:none;}
In Firefox and Chrome, a select with only the enabled options were created. Nice.
In IE, the enabled options were shown, the disabled where just blank lines, in their original location. Bad.
In Edge, the enabled options shown at top, followed by blank lines for disabled options. Acceptable.
I think the first answer is the best I wrote my own shell script developing this idea :
#!/bin/sh
if [ $# -ne 1 ]
then
echo "Sintaxis:\n\t"
echo " $0 {port to search in process }"
exit
else
MYPORT=$1
for i in `ls /proc`
do
pfiles $i | grep port | grep "port: $MYPORT" > /dev/null
if [ $? -eq 0 ]
then
echo " Port $MYPORT founded in $i proccess !!!\n\n"
echo "Details\n\t"
pfiles $i | grep port | grep "port: $MYPORT"
echo "\n\t"
echo "Process detail: \n\t"
ps -ef | grep $i | grep -v grep
fi
done
fi
Based on your requirements you can also do the following without libraries like jQuery:
Add this to your head:
window.onload = function () {
document.getElementById("frmSubmit").onsubmit = function onSubmit(form) {
var isValid = true;
//validate your elems here
isValid = false;
if (!isValid) {
alert("Please check your fields!");
return false;
}
else {
//you are good to go
return true;
}
}
}
And your form may still look something like:
<form id="frmSubmit" action="/Submit">
<input type="submit" value="Submit" />
</form>
To expand on BalusC's answer, any scenario where the sender continues to write after the peer has stopped reading and closed its socket will produce this exception, as will the peer closing while it still had unread data in its own socket receive buffer. In other words, an application protocol error. For example, if you write something to the peer that the peer doesn't understand, and then it closes its socket in protest, and you then continue to write, the peer's TCP stack will issue an RST, which results in this exception and message at the sender.
See this thread by Sun on why they deprecated Thread.stop()
. It goes into detail about why this was a bad method and what should be done to safely stop threads in general.
The way they recommend is to use a shared variable as a flag which asks the background thread to stop. This variable can then be set by a different object requesting the thread terminate.
There are two main types of margin collapse:
Using a padding or border will prevent collapse only in the latter case. Also, any value of overflow
different from its default (visible
) applied to the parent will prevent collapse. Thus, both overflow: auto
and overflow: hidden
will have the same effect. Perhaps the only difference when using hidden
is the unintended consequence of hiding content if the parent has a fixed height.
Other properties that, once applied to the parent, can help fix this behaviour are:
float: left / right
position: absolute
display: inline-block / flex
You can test all of them here: http://jsfiddle.net/XB9wX/1/.
I should add that, as usual, Internet Explorer is the exception. More specifically, in IE 7 margins do not collapse when some kind of layout is specified for the parent element, such as width
.
Sources: Sitepoint's article Collapsing Margins
Have you looked at the split command?
$ split --help
Usage: split [OPTION] [INPUT [PREFIX]]
Output fixed-size pieces of INPUT to PREFIXaa, PREFIXab, ...; default
size is 1000 lines, and default PREFIX is `x'. With no INPUT, or when INPUT
is -, read standard input.
Mandatory arguments to long options are mandatory for short options too.
-a, --suffix-length=N use suffixes of length N (default 2)
-b, --bytes=SIZE put SIZE bytes per output file
-C, --line-bytes=SIZE put at most SIZE bytes of lines per output file
-d, --numeric-suffixes use numeric suffixes instead of alphabetic
-l, --lines=NUMBER put NUMBER lines per output file
--verbose print a diagnostic to standard error just
before each output file is opened
--help display this help and exit
--version output version information and exit
You could do something like this:
split -l 200000 filename
which will create files each with 200000 lines named xaa xab xac
...
Another option, split by size of output file (still splits on line breaks):
split -C 20m --numeric-suffixes input_filename output_prefix
creates files like output_prefix01 output_prefix02 output_prefix03 ...
each of max size 20 megabytes.
For your actual form, if you were to just post the results to your same page, it should probably work out all right. Try something like:
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> method="POST>
A very simple solution, returns a list of files.
public static List<string> AllFilesInFolder(string folder)
{
var result = new List<string>();
foreach (string f in Directory.GetFiles(folder))
{
result.Add(f);
}
foreach (string d in Directory.GetDirectories(folder))
{
result.AddRange(AllFilesInFolder(d));
}
return result;
}
Recheck the package declarations in all your classes!
This behaviour has been observed in NetBeans, when the package declaration in one of the classes of the package refers to a non-existent or wrong package. NetBeans normally detects and highlights this error but has been known to fail and misleadingly report the package as free of errors when this is not the case.
You can use C function gettimeofday : http://www.opengroup.org/onlinepubs/000095399/functions/gettimeofday.html
Here C library 'ul_time', function sec_usec resides in 'time' global table and returns seconds, useconds. Copy DLL to Lua folder, open it with require 'ul_time'.
You can make a bookmark with this as the url:
javascript:
var cached_anchors = $$('a');
for (var i in cached_anchors) {
var ca = cached_anchors[i];
if(ca.href.search('sprite') < 0 && ca.href.search('.png') > -1 || ca.href.search('.gif') > -1 || ca.href.search('.jpg') > -1) {
var a = document.createElement('a');
a.href = ca.innerHTML;
a.target = '_blank';
var img = document.createElement('img');
img.src = ca.innerHTML;
img.style.maxHeight = '100px';
a.appendChild(img);
document.getElementsByTagName('body')[0].appendChild(a);
}
}
document.getElementsByTagName('body')[0].removeChild(document.getElementsByTagName('table')[0]);
void(0);
Then just go to chrome://cache and then click your bookmark and it'll show you all the images.
Without answering the question about how to create and inject Authentication objects, Spring Security 4.0 provides some welcome alternatives when it comes to testing. The @WithMockUser
annotation enables the developer to specify a mock user (with optional authorities, username, password and roles) in a neat way:
@Test
@WithMockUser(username = "admin", authorities = { "ADMIN", "USER" })
public void getMessageWithMockUserCustomAuthorities() {
String message = messageService.getMessage();
...
}
There is also the option to use @WithUserDetails
to emulate a UserDetails
returned from the UserDetailsService
, e.g.
@Test
@WithUserDetails("customUsername")
public void getMessageWithUserDetailsCustomUsername() {
String message = messageService.getMessage();
...
}
More details can be found in the @WithMockUser and the @WithUserDetails chapters in the Spring Security reference docs (from which the above examples were copied)
Although <input>
ignores the rows
attribute, you can take advantage of the fact that <textarea>
doesn't have to be inside <form>
tags, but can still be a part of a form by referencing the form's id:
<form method="get" id="testformid">
<input type="submit" />
</form>
<textarea form ="testformid" name="taname" id="taid" cols="35" wrap="soft"></textarea>
Of course, <textarea>
now appears below "submit" button, but maybe you'll find a way to reposition it.
Also note that despite errors being hidden, any custom error handler (set with set_error_handler
) will still be executed!
I found too simple hack just do this add new element in AndroidManifest
as:-
<activity android:name=".activityName"
android:label="@string/app_name"
android:noHistory="true"/>
the android:noHistory
will clear your unwanted activity from Stack.
First add the import line:
from pyspark.sql.functions import min, max
df.agg(min("age")).show()
+--------+
|min(age)|
+--------+
| 29|
+--------+
df.agg(max("age")).show()
+--------+
|max(age)|
+--------+
| 77|
+--------+
The accepted answer misses some rather significant locales. For example, the Chinese locales don't distinguish between the different scriptures (simplified han, traditional han). What's a main-land Chinese citizen who wants traditional han supposed to use - the Hong Kong setting?
I've taken this list of iOS locales, removed the strange POSIX entry, formatted it as Javascript and sorted it by value (so if you use an ordered object implementation and create a list by going through the keys and returning the value, it will show the human readable text in correct order). Also, this list both contains a main entry per language as well as all the region specific variants - this way you always have a designated fallback option, say if your interface has only defined the 'en' option - you wouldn't otherwise know on what to fall back on reliably.
var LANGUAGE_BY_LOCALE = {
af_NA: "Afrikaans (Namibia)",
af_ZA: "Afrikaans (South Africa)",
af: "Afrikaans",
ak_GH: "Akan (Ghana)",
ak: "Akan",
sq_AL: "Albanian (Albania)",
sq: "Albanian",
am_ET: "Amharic (Ethiopia)",
am: "Amharic",
ar_DZ: "Arabic (Algeria)",
ar_BH: "Arabic (Bahrain)",
ar_EG: "Arabic (Egypt)",
ar_IQ: "Arabic (Iraq)",
ar_JO: "Arabic (Jordan)",
ar_KW: "Arabic (Kuwait)",
ar_LB: "Arabic (Lebanon)",
ar_LY: "Arabic (Libya)",
ar_MA: "Arabic (Morocco)",
ar_OM: "Arabic (Oman)",
ar_QA: "Arabic (Qatar)",
ar_SA: "Arabic (Saudi Arabia)",
ar_SD: "Arabic (Sudan)",
ar_SY: "Arabic (Syria)",
ar_TN: "Arabic (Tunisia)",
ar_AE: "Arabic (United Arab Emirates)",
ar_YE: "Arabic (Yemen)",
ar: "Arabic",
hy_AM: "Armenian (Armenia)",
hy: "Armenian",
as_IN: "Assamese (India)",
as: "Assamese",
asa_TZ: "Asu (Tanzania)",
asa: "Asu",
az_Cyrl: "Azerbaijani (Cyrillic)",
az_Cyrl_AZ: "Azerbaijani (Cyrillic, Azerbaijan)",
az_Latn: "Azerbaijani (Latin)",
az_Latn_AZ: "Azerbaijani (Latin, Azerbaijan)",
az: "Azerbaijani",
bm_ML: "Bambara (Mali)",
bm: "Bambara",
eu_ES: "Basque (Spain)",
eu: "Basque",
be_BY: "Belarusian (Belarus)",
be: "Belarusian",
bem_ZM: "Bemba (Zambia)",
bem: "Bemba",
bez_TZ: "Bena (Tanzania)",
bez: "Bena",
bn_BD: "Bengali (Bangladesh)",
bn_IN: "Bengali (India)",
bn: "Bengali",
bs_BA: "Bosnian (Bosnia and Herzegovina)",
bs: "Bosnian",
bg_BG: "Bulgarian (Bulgaria)",
bg: "Bulgarian",
my_MM: "Burmese (Myanmar [Burma])",
my: "Burmese",
yue_Hant_HK: "Cantonese (Traditional, Hong Kong SAR China)",
ca_ES: "Catalan (Spain)",
ca: "Catalan",
tzm_Latn: "Central Morocco Tamazight (Latin)",
tzm_Latn_MA: "Central Morocco Tamazight (Latin, Morocco)",
tzm: "Central Morocco Tamazight",
chr_US: "Cherokee (United States)",
chr: "Cherokee",
cgg_UG: "Chiga (Uganda)",
cgg: "Chiga",
zh_Hans: "Chinese (Simplified Han)",
zh_Hans_CN: "Chinese (Simplified Han, China)",
zh_Hans_HK: "Chinese (Simplified Han, Hong Kong SAR China)",
zh_Hans_MO: "Chinese (Simplified Han, Macau SAR China)",
zh_Hans_SG: "Chinese (Simplified Han, Singapore)",
zh_Hant: "Chinese (Traditional Han)",
zh_Hant_HK: "Chinese (Traditional Han, Hong Kong SAR China)",
zh_Hant_MO: "Chinese (Traditional Han, Macau SAR China)",
zh_Hant_TW: "Chinese (Traditional Han, Taiwan)",
zh: "Chinese",
kw_GB: "Cornish (United Kingdom)",
kw: "Cornish",
hr_HR: "Croatian (Croatia)",
hr: "Croatian",
cs_CZ: "Czech (Czech Republic)",
cs: "Czech",
da_DK: "Danish (Denmark)",
da: "Danish",
nl_BE: "Dutch (Belgium)",
nl_NL: "Dutch (Netherlands)",
nl: "Dutch",
ebu_KE: "Embu (Kenya)",
ebu: "Embu",
en_AS: "English (American Samoa)",
en_AU: "English (Australia)",
en_BE: "English (Belgium)",
en_BZ: "English (Belize)",
en_BW: "English (Botswana)",
en_CA: "English (Canada)",
en_GU: "English (Guam)",
en_HK: "English (Hong Kong SAR China)",
en_IN: "English (India)",
en_IE: "English (Ireland)",
en_IL: "English (Israel)",
en_JM: "English (Jamaica)",
en_MT: "English (Malta)",
en_MH: "English (Marshall Islands)",
en_MU: "English (Mauritius)",
en_NA: "English (Namibia)",
en_NZ: "English (New Zealand)",
en_MP: "English (Northern Mariana Islands)",
en_PK: "English (Pakistan)",
en_PH: "English (Philippines)",
en_SG: "English (Singapore)",
en_ZA: "English (South Africa)",
en_TT: "English (Trinidad and Tobago)",
en_UM: "English (U.S. Minor Outlying Islands)",
en_VI: "English (U.S. Virgin Islands)",
en_GB: "English (United Kingdom)",
en_US: "English (United States)",
en_ZW: "English (Zimbabwe)",
en: "English",
eo: "Esperanto",
et_EE: "Estonian (Estonia)",
et: "Estonian",
ee_GH: "Ewe (Ghana)",
ee_TG: "Ewe (Togo)",
ee: "Ewe",
fo_FO: "Faroese (Faroe Islands)",
fo: "Faroese",
fil_PH: "Filipino (Philippines)",
fil: "Filipino",
fi_FI: "Finnish (Finland)",
fi: "Finnish",
fr_BE: "French (Belgium)",
fr_BJ: "French (Benin)",
fr_BF: "French (Burkina Faso)",
fr_BI: "French (Burundi)",
fr_CM: "French (Cameroon)",
fr_CA: "French (Canada)",
fr_CF: "French (Central African Republic)",
fr_TD: "French (Chad)",
fr_KM: "French (Comoros)",
fr_CG: "French (Congo - Brazzaville)",
fr_CD: "French (Congo - Kinshasa)",
fr_CI: "French (Côte d’Ivoire)",
fr_DJ: "French (Djibouti)",
fr_GQ: "French (Equatorial Guinea)",
fr_FR: "French (France)",
fr_GA: "French (Gabon)",
fr_GP: "French (Guadeloupe)",
fr_GN: "French (Guinea)",
fr_LU: "French (Luxembourg)",
fr_MG: "French (Madagascar)",
fr_ML: "French (Mali)",
fr_MQ: "French (Martinique)",
fr_MC: "French (Monaco)",
fr_NE: "French (Niger)",
fr_RW: "French (Rwanda)",
fr_RE: "French (Réunion)",
fr_BL: "French (Saint Barthélemy)",
fr_MF: "French (Saint Martin)",
fr_SN: "French (Senegal)",
fr_CH: "French (Switzerland)",
fr_TG: "French (Togo)",
fr: "French",
ff_SN: "Fulah (Senegal)",
ff: "Fulah",
gl_ES: "Galician (Spain)",
gl: "Galician",
lg_UG: "Ganda (Uganda)",
lg: "Ganda",
ka_GE: "Georgian (Georgia)",
ka: "Georgian",
de_AT: "German (Austria)",
de_BE: "German (Belgium)",
de_DE: "German (Germany)",
de_LI: "German (Liechtenstein)",
de_LU: "German (Luxembourg)",
de_CH: "German (Switzerland)",
de: "German",
el_CY: "Greek (Cyprus)",
el_GR: "Greek (Greece)",
el: "Greek",
gu_IN: "Gujarati (India)",
gu: "Gujarati",
guz_KE: "Gusii (Kenya)",
guz: "Gusii",
ha_Latn: "Hausa (Latin)",
ha_Latn_GH: "Hausa (Latin, Ghana)",
ha_Latn_NE: "Hausa (Latin, Niger)",
ha_Latn_NG: "Hausa (Latin, Nigeria)",
ha: "Hausa",
haw_US: "Hawaiian (United States)",
haw: "Hawaiian",
he_IL: "Hebrew (Israel)",
he: "Hebrew",
hi_IN: "Hindi (India)",
hi: "Hindi",
hu_HU: "Hungarian (Hungary)",
hu: "Hungarian",
is_IS: "Icelandic (Iceland)",
is: "Icelandic",
ig_NG: "Igbo (Nigeria)",
ig: "Igbo",
id_ID: "Indonesian (Indonesia)",
id: "Indonesian",
ga_IE: "Irish (Ireland)",
ga: "Irish",
it_IT: "Italian (Italy)",
it_CH: "Italian (Switzerland)",
it: "Italian",
ja_JP: "Japanese (Japan)",
ja: "Japanese",
kea_CV: "Kabuverdianu (Cape Verde)",
kea: "Kabuverdianu",
kab_DZ: "Kabyle (Algeria)",
kab: "Kabyle",
kl_GL: "Kalaallisut (Greenland)",
kl: "Kalaallisut",
kln_KE: "Kalenjin (Kenya)",
kln: "Kalenjin",
kam_KE: "Kamba (Kenya)",
kam: "Kamba",
kn_IN: "Kannada (India)",
kn: "Kannada",
kk_Cyrl: "Kazakh (Cyrillic)",
kk_Cyrl_KZ: "Kazakh (Cyrillic, Kazakhstan)",
kk: "Kazakh",
km_KH: "Khmer (Cambodia)",
km: "Khmer",
ki_KE: "Kikuyu (Kenya)",
ki: "Kikuyu",
rw_RW: "Kinyarwanda (Rwanda)",
rw: "Kinyarwanda",
kok_IN: "Konkani (India)",
kok: "Konkani",
ko_KR: "Korean (South Korea)",
ko: "Korean",
khq_ML: "Koyra Chiini (Mali)",
khq: "Koyra Chiini",
ses_ML: "Koyraboro Senni (Mali)",
ses: "Koyraboro Senni",
lag_TZ: "Langi (Tanzania)",
lag: "Langi",
lv_LV: "Latvian (Latvia)",
lv: "Latvian",
lt_LT: "Lithuanian (Lithuania)",
lt: "Lithuanian",
luo_KE: "Luo (Kenya)",
luo: "Luo",
luy_KE: "Luyia (Kenya)",
luy: "Luyia",
mk_MK: "Macedonian (Macedonia)",
mk: "Macedonian",
jmc_TZ: "Machame (Tanzania)",
jmc: "Machame",
kde_TZ: "Makonde (Tanzania)",
kde: "Makonde",
mg_MG: "Malagasy (Madagascar)",
mg: "Malagasy",
ms_BN: "Malay (Brunei)",
ms_MY: "Malay (Malaysia)",
ms: "Malay",
ml_IN: "Malayalam (India)",
ml: "Malayalam",
mt_MT: "Maltese (Malta)",
mt: "Maltese",
gv_GB: "Manx (United Kingdom)",
gv: "Manx",
mr_IN: "Marathi (India)",
mr: "Marathi",
mas_KE: "Masai (Kenya)",
mas_TZ: "Masai (Tanzania)",
mas: "Masai",
mer_KE: "Meru (Kenya)",
mer: "Meru",
mfe_MU: "Morisyen (Mauritius)",
mfe: "Morisyen",
naq_NA: "Nama (Namibia)",
naq: "Nama",
ne_IN: "Nepali (India)",
ne_NP: "Nepali (Nepal)",
ne: "Nepali",
nd_ZW: "North Ndebele (Zimbabwe)",
nd: "North Ndebele",
nb_NO: "Norwegian Bokmål (Norway)",
nb: "Norwegian Bokmål",
nn_NO: "Norwegian Nynorsk (Norway)",
nn: "Norwegian Nynorsk",
nyn_UG: "Nyankole (Uganda)",
nyn: "Nyankole",
or_IN: "Oriya (India)",
or: "Oriya",
om_ET: "Oromo (Ethiopia)",
om_KE: "Oromo (Kenya)",
om: "Oromo",
ps_AF: "Pashto (Afghanistan)",
ps: "Pashto",
fa_AF: "Persian (Afghanistan)",
fa_IR: "Persian (Iran)",
fa: "Persian",
pl_PL: "Polish (Poland)",
pl: "Polish",
pt_BR: "Portuguese (Brazil)",
pt_GW: "Portuguese (Guinea-Bissau)",
pt_MZ: "Portuguese (Mozambique)",
pt_PT: "Portuguese (Portugal)",
pt: "Portuguese",
pa_Arab: "Punjabi (Arabic)",
pa_Arab_PK: "Punjabi (Arabic, Pakistan)",
pa_Guru: "Punjabi (Gurmukhi)",
pa_Guru_IN: "Punjabi (Gurmukhi, India)",
pa: "Punjabi",
ro_MD: "Romanian (Moldova)",
ro_RO: "Romanian (Romania)",
ro: "Romanian",
rm_CH: "Romansh (Switzerland)",
rm: "Romansh",
rof_TZ: "Rombo (Tanzania)",
rof: "Rombo",
ru_MD: "Russian (Moldova)",
ru_RU: "Russian (Russia)",
ru_UA: "Russian (Ukraine)",
ru: "Russian",
rwk_TZ: "Rwa (Tanzania)",
rwk: "Rwa",
saq_KE: "Samburu (Kenya)",
saq: "Samburu",
sg_CF: "Sango (Central African Republic)",
sg: "Sango",
seh_MZ: "Sena (Mozambique)",
seh: "Sena",
sr_Cyrl: "Serbian (Cyrillic)",
sr_Cyrl_BA: "Serbian (Cyrillic, Bosnia and Herzegovina)",
sr_Cyrl_ME: "Serbian (Cyrillic, Montenegro)",
sr_Cyrl_RS: "Serbian (Cyrillic, Serbia)",
sr_Latn: "Serbian (Latin)",
sr_Latn_BA: "Serbian (Latin, Bosnia and Herzegovina)",
sr_Latn_ME: "Serbian (Latin, Montenegro)",
sr_Latn_RS: "Serbian (Latin, Serbia)",
sr: "Serbian",
sn_ZW: "Shona (Zimbabwe)",
sn: "Shona",
ii_CN: "Sichuan Yi (China)",
ii: "Sichuan Yi",
si_LK: "Sinhala (Sri Lanka)",
si: "Sinhala",
sk_SK: "Slovak (Slovakia)",
sk: "Slovak",
sl_SI: "Slovenian (Slovenia)",
sl: "Slovenian",
xog_UG: "Soga (Uganda)",
xog: "Soga",
so_DJ: "Somali (Djibouti)",
so_ET: "Somali (Ethiopia)",
so_KE: "Somali (Kenya)",
so_SO: "Somali (Somalia)",
so: "Somali",
es_AR: "Spanish (Argentina)",
es_BO: "Spanish (Bolivia)",
es_CL: "Spanish (Chile)",
es_CO: "Spanish (Colombia)",
es_CR: "Spanish (Costa Rica)",
es_DO: "Spanish (Dominican Republic)",
es_EC: "Spanish (Ecuador)",
es_SV: "Spanish (El Salvador)",
es_GQ: "Spanish (Equatorial Guinea)",
es_GT: "Spanish (Guatemala)",
es_HN: "Spanish (Honduras)",
es_419: "Spanish (Latin America)",
es_MX: "Spanish (Mexico)",
es_NI: "Spanish (Nicaragua)",
es_PA: "Spanish (Panama)",
es_PY: "Spanish (Paraguay)",
es_PE: "Spanish (Peru)",
es_PR: "Spanish (Puerto Rico)",
es_ES: "Spanish (Spain)",
es_US: "Spanish (United States)",
es_UY: "Spanish (Uruguay)",
es_VE: "Spanish (Venezuela)",
es: "Spanish",
sw_KE: "Swahili (Kenya)",
sw_TZ: "Swahili (Tanzania)",
sw: "Swahili",
sv_FI: "Swedish (Finland)",
sv_SE: "Swedish (Sweden)",
sv: "Swedish",
gsw_CH: "Swiss German (Switzerland)",
gsw: "Swiss German",
shi_Latn: "Tachelhit (Latin)",
shi_Latn_MA: "Tachelhit (Latin, Morocco)",
shi_Tfng: "Tachelhit (Tifinagh)",
shi_Tfng_MA: "Tachelhit (Tifinagh, Morocco)",
shi: "Tachelhit",
dav_KE: "Taita (Kenya)",
dav: "Taita",
ta_IN: "Tamil (India)",
ta_LK: "Tamil (Sri Lanka)",
ta: "Tamil",
te_IN: "Telugu (India)",
te: "Telugu",
teo_KE: "Teso (Kenya)",
teo_UG: "Teso (Uganda)",
teo: "Teso",
th_TH: "Thai (Thailand)",
th: "Thai",
bo_CN: "Tibetan (China)",
bo_IN: "Tibetan (India)",
bo: "Tibetan",
ti_ER: "Tigrinya (Eritrea)",
ti_ET: "Tigrinya (Ethiopia)",
ti: "Tigrinya",
to_TO: "Tonga (Tonga)",
to: "Tonga",
tr_TR: "Turkish (Turkey)",
tr: "Turkish",
uk_UA: "Ukrainian (Ukraine)",
uk: "Ukrainian",
ur_IN: "Urdu (India)",
ur_PK: "Urdu (Pakistan)",
ur: "Urdu",
uz_Arab: "Uzbek (Arabic)",
uz_Arab_AF: "Uzbek (Arabic, Afghanistan)",
uz_Cyrl: "Uzbek (Cyrillic)",
uz_Cyrl_UZ: "Uzbek (Cyrillic, Uzbekistan)",
uz_Latn: "Uzbek (Latin)",
uz_Latn_UZ: "Uzbek (Latin, Uzbekistan)",
uz: "Uzbek",
vi_VN: "Vietnamese (Vietnam)",
vi: "Vietnamese",
vun_TZ: "Vunjo (Tanzania)",
vun: "Vunjo",
cy_GB: "Welsh (United Kingdom)",
cy: "Welsh",
yo_NG: "Yoruba (Nigeria)",
yo: "Yoruba",
zu_ZA: "Zulu (South Africa)",
zu: "Zulu"
}
The answer from @zags is comprehensive and should suffice but the #5 method (which is the best one IMO) throws an error so I improved the helper function.
As the OP requested for converting many_to_many
fields into a list of primary keys rather than a list of objects, I enhanced the function so the return value is now JSON serializable - by converting datetime
objects into str
and many_to_many
objects to a list of id's.
import datetime
def ModelToDict(instance):
'''
Returns a dictionary object containing complete field-value pairs of the given instance
Convertion rules:
datetime.date --> str
many_to_many --> list of id's
'''
concrete_fields = instance._meta.concrete_fields
m2m_fields = instance._meta.many_to_many
data = {}
for field in concrete_fields:
key = field.name
value = field.value_from_object(instance)
if type(value) == datetime.datetime:
value = str(field.value_from_object(instance))
data[key] = value
for field in m2m_fields:
key = field.name
value = field.value_from_object(instance)
data[key] = [rel.id for rel in value]
return data
In the first code block, you're never using the str
parameter. Did you mean to say the following?
testFunc = function(str, callback) {
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: str,
success: callback
});
}
You either want to select an anonymous type:
var dataset2 = from recordset
in entities.processlists
where recordset.ProcessName == processname
select new
{
recordset.ServerName,
recordset.ProcessID,
recordset.Username
};
But you cannot cast that to another type, so I guess you want something like this:
var dataset2 = from recordset
in entities.processlists
where recordset.ProcessName == processname
// Select new concrete type
select new PInfo
{
ServerName = recordset.ServerName,
ProcessID = recordset.ProcessID,
Username = recordset.Username
};
DON'T change the interpreter path.
Change the project structure instead:
File -> Settings -> Project -> Project structure -> Add content root
PDO offers an alternative designed to replace mysql_escape_string() with the PDO::quote() method.
Here is an excerpt from the PHP website:
<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');
/* Simple string */
$string = 'Nice';
print "Unquoted string: $string\n";
print "Quoted string: " . $conn->quote($string) . "\n";
?>
The above code will output:
Unquoted string: Nice
Quoted string: 'Nice'
One question is if you also want to use git for the deploment of your projects. If so you probably would like to exclude your local sqlite file from the repository, same probably applies to file uploads (mostly in your media folder). (I'm talking about django now, since your question is also tagged with django)
In order to fully avoid floating point issues, the amount whose percent is being calculated and the percent itself need to be converted to integers. Here's how I resolved this:
function calculatePercent(amount, percent) {
const amountDecimals = getNumberOfDecimals(amount);
const percentDecimals = getNumberOfDecimals(percent);
const amountAsInteger = Math.round(amount + `e${amountDecimals}`);
const percentAsInteger = Math.round(percent + `e${percentDecimals}`);
const precisionCorrection = `e-${amountDecimals + percentDecimals + 2}`; // add 2 to scale by an additional 100 since the percentage supplied is 100x the actual multiple (e.g. 35.8% is passed as 35.8, but as a proper multiple is 0.358)
return Number((amountAsInteger * percentAsInteger) + precisionCorrection);
}
function getNumberOfDecimals(number) {
const decimals = parseFloat(number).toString().split('.')[1];
if (decimals) {
return decimals.length;
}
return 0;
}
calculatePercent(20.05, 10); // 2.005
As you can see, I:
amount
and the percent
amount
and percent
to integers using exponential notationThe usage of exponential notation was inspired by Jack Moore's blog post. I'm sure my syntax could be shorter, but I wanted to be as explicit as possible in my usage of variable names and explaining each step.
The heap is the place in memory where your dynamically allocated objects live. If you used new
then it's on the heap. That's as opposed to stack space, which is where the function stack lives. If you have a local variable then that reference is on the stack.
Java's heap is subject to garbage collection and the objects are usable directly.
EHCache's off-heap storage takes your regular object off the heap, serializes it, and stores it as bytes in a chunk of memory that EHCache manages. It's like storing it to disk but it's still in RAM. The objects are not directly usable in this state, they have to be deserialized first. Also not subject to garbage collection.
You can save it first, then import it.
from google.colab import files
src = list(files.upload().values())[0]
open('mylib.py','wb').write(src)
import mylib
Update (nov 2018): Now you can upload easily by
Update (oct 2019): If you don't want to upload every time, you can store it in S3 and mount it to Colab, as shown in this gist
Update (apr 2020): Now that you can mount your Google Drive automatically. It is easier to just copy it from Drive than upload it.
mylib.py
in your DriveFiles
viewMount Drive
then Connect to Google Drive
!cp drive/MyDrive/mylib.py .
import mylib
echoing @HYRY, see the new docs in 0.11
http://pandas.pydata.org/pandas-docs/stable/indexing.html
Here we have new operators, .iloc
to explicity support only integer indexing, and .loc
to explicity support only label indexing
e.g. imagine this scenario
In [1]: df = pd.DataFrame(np.random.rand(5,2),index=range(0,10,2),columns=list('AB'))
In [2]: df
Out[2]:
A B
0 1.068932 -0.794307
2 -0.470056 1.192211
4 -0.284561 0.756029
6 1.037563 -0.267820
8 -0.538478 -0.800654
In [5]: df.iloc[[2]]
Out[5]:
A B
4 -0.284561 0.756029
In [6]: df.loc[[2]]
Out[6]:
A B
2 -0.470056 1.192211
[]
slices the rows (by label location) only
I got a similar error and it took me a while to realize that in my case I named the array variable payInvoices and the function also payInvoices. It confused AngularJs. Once I changed the name to processPayments() it finally worked. Just wanted to share this error and solution as it took me long time to figure this out.
There are much more complicated solutions, but a very easy, simple one is just to add a random query string to your CSS include.
Such as src="/css/styles.css?v={random number/string}"
If you're using php or another server-side language, you can do this automatically with time()
. So it would be styles.css?v=<?=time();?>
This way, the query string will be new every single time. Like I said, there are much more complicated solutions that are more dynamic, but in testing purposes this method is top (IMO).
Depends on the consistency of the data - assuming a single space is the separator between what you want to appear in column one vs two:
SELECT SUBSTR(t.column_one, 1, INSTR(t.column_one, ' ')-1) AS col_one,
SUBSTR(t.column_one, INSTR(t.column_one, ' ')+1) AS col_two
FROM YOUR_TABLE t
Oracle 10g+ has regex support, allowing more flexibility depending on the situation you need to solve. It also has a regex substring method...
Reference:
I need to click the link who's href has substring "long" in it. How can I do this?
With the beauty of CSS selectors.
your statement would be...
driver.findElement(By.cssSelector("a[href*='long']")).click();
This means, in english,
Find me any 'a' elements, that have the
href
attribute, and that attributecontains
'long'
You can find a useful article about formulating your own selectors for automation effectively, as well as a list of all the other equality operators. contains
, starts with
, etc... You can find that at: http://ddavison.io/css/2014/02/18/effective-css-selectors.html
Unfortunately the xkcd comic isn't completely up to date anymore.
Since Python 3.0 you have to write:
print("Hello world!")
And someone still has to write that antigravity
library :(
You got a bunch of good answers, so I'll just throw out a suggestion. If you are going to be working on this project for more than 2 days, download eclipse or netbeans and build your project in there.
If you are not normally a java programmer, then the help it will give you will be invaluable.
It's not worth the 1/2 hour download/install if you are only spending 2 hours on it.
Both have hotkeys/menu items to "Fix imports", with this you should never have to worry about imports again.
PHPClasses have a nice class for this named PHP Working Days. You can check this class.
$(":input#single").trigger('change');
This worked for my script. I have 3 combos & bind with chainSelect event, I need to pass 3 values by url & default select all drop down. I used this
$('#machineMake').val('<?php echo $_GET['headMake']; ?>').trigger('change');
And the first event worked.
You can find all schema related information in the wisely named information_schema
table.
You might want to check the table REFERENTIAL_CONSTRAINTS
and KEY_COLUMN_USAGE
. The former tells you which tables are referenced by others; the latter will tell you how their fields are related.
Maybe you can use WebView, but as you can see in the doc WebView doesn't support javascript and other stuff like widgets by default.
http://developer.android.com/reference/android/webkit/WebView.html
I think that you can enable javascript if you need it.
Maven is not designed to work that way, but a workaround exists to achieve this goal (maybe with side effects, you will have to give a try). The trick is to tell the child project to find its parent via its relative path rather than its pure maven coordinates, and in addition to externalize the version number in a property :
<groupId>com.dummy.bla</groupId>
<artifactId>parent</artifactId>
<version>${global.version}</version>
<packaging>pom</packaging>
<properties>
<!-- Unique entry point for version number management -->
<global.version>0.1-SNAPSHOT</global.version>
</properties>
<parent>
<groupId>com.dummy.bla</groupId>
<artifactId>parent</artifactId>
<version>${global.version}</version>
<relativePath>..</relativePath>
</parent>
<groupId>com.dummy.bla.sub</groupId>
<artifactId>kid</artifactId>
I used that trick for a while for one of my project, with no specific problem, except the fact that maven logs a lot of warnings at the beginning of the build, which is not very elegant.
Seems maven 3.0.4 does not allow such a configuration anymore.
@Future-searchers: you can use aspell to do the dictionary checks, it has bindings in ruby and python. It would make your job much simpler.
jqGrid is $299 if you use a special version that has server side integration, but it really is not that difficult to use the open source free version with ASP.NET MVC, once you get your jquery configuration straight it's almost as simple to use as any other licensed grid:
http://haacked.com/archive/2009/04/14/using-jquery-grid-with-asp.net-mvc.aspx
Try this using this single code:
import javax.ws.rs.POST;
import javax.ws.rs.Path;
@Path("/serviceX")
public class MyClassRESTService {
@POST
@Path("/doSomething")
public void someMethod(String x) {
System.out.println(x);
// String x contains the body, you can process
// it, parse it using JAXB and so on ...
}
}
The url for try rest services ends .... /serviceX/doSomething
You can import a csv file to this website(https://www.tablesgenerator.com/latex_tables) and click copy to clipboard.
you can also quote string
''+document.location+''.substring(2,3);
I think you need to specify a different resolution when saving the figure to a file:
fig = matplotlib.pyplot.figure()
# generate your plot
fig.savefig("myfig.png",dpi=600)
Specifying a large dpi value should have a similar effect as maximizing the GUI window.
Use a CountDownLatch
.
It's from java.util.concurrent
and it's exactly the way to wait for several threads to complete execution before continuing.
In order to achieve the callback effect you're looking after, that does require a little additional extra work. Namely, handling this by yourself in a separate thread which uses the CountDownLatch
and does wait on it, then goes on about notifying whatever it is you need to notify. There is no native support for callback, or anything similar to that effect.
EDIT: now that I further understand your question, I think you are reaching too far, unnecessarily. If you take a regular SingleThreadExecutor
, give it all the tasks, and it will do the queueing natively.
Here's how I test javascript using PhantomJS and Django:
mobile/test_no_js_errors.js:
var page = require('webpage').create(),
system = require('system'),
url = system.args[1],
status_code;
page.onError = function (msg, trace) {
console.log(msg);
trace.forEach(function(item) {
console.log(' ', item.file, ':', item.line);
});
};
page.onResourceReceived = function(resource) {
if (resource.url == url) {
status_code = resource.status;
}
};
page.open(url, function (status) {
if (status == "fail" || status_code != 200) {
console.log("Error: " + status_code + " for url: " + url);
phantom.exit(1);
}
phantom.exit(0);
});
mobile/tests.py:
import subprocess
from django.test import LiveServerTestCase
class MobileTest(LiveServerTestCase):
def test_mobile_js(self):
args = ["phantomjs", "mobile/test_no_js_errors.js", self.live_server_url]
result = subprocess.check_output(args)
self.assertEqual(result, "") # No result means no error
Run tests:
manage.py test mobile
This might be an old qustion, but just to keep things updated, there is a forEach method in javascript that works with NodeJS. Here's the link from the docs. And an example:
count = countElements.length;
if (count > 0) {
countElements.forEach(function(countElement){
console.log(countElement);
});
}
If startDate and endDate are indeed date objects you could convert them to number of milliseconds since midnight Jan 1, 1970, like this:
var startTime = startDate.getTime(), endTime = endDate.getTime();
Then you could loop from one to another incrementing loopTime by 86400000 (1000*60*60*24) - number of milliseconds in one day:
for(loopTime = startTime; loopTime < endTime; loopTime += 86400000)
{
var loopDay=new Date(loopTime)
//use loopDay as you wish
}
This enables you to write something like:
void doSomething() {
List<String>list = new ArrayList<String>();
//do something
}
Later on, you might want to change it to:
void doSomething() {
List<String>list = new LinkedList<String>();
//do something
}
without having to change the rest of the method.
However, if you want to use a CopyOnWriteArrayList
for example, you would need to declare it as such, and not as a List if you wanted to use its extra methods (addIfAbsent for example):
void doSomething() {
CopyOnWriteArrayList<String>list = new CopyOnWriteArrayList<String>();
//do something, for example:
list.addIfAbsent("abc");
}
Check out the Programmatically Displaying the Settings Page
startActivity(context, new Intent(Settings.ACTION_SETTINGS), /*options:*/ null);
In general, you use the predefined constant Settings.ACTION__SETTINGS
. The full list can be found here
Java 9 introduces
See excellent Optional in Java 8 cheat sheet.
It provides all answers for most use cases.
Short summary below
opt.ifPresent(x -> print(x));
opt.ifPresent(this::print);
opt.filter(x -> x.contains("ab")).ifPresent(this::print);
opt.map(String::trim).filter(t -> t.length() > 1).ifPresent(this::print);
int len = opt.map(String::length).orElse(-1);
int len = opt.
map(String::length).
orElseGet(() -> slowDefault()); //orElseGet(this::slowDefault)
opt.
filter(s -> !s.isEmpty()).
map(s -> s.charAt(0)).
orElseThrow(IllegalArgumentException::new);
& and | provide the same outcome as the && and || operators. The difference is that they always evaluate both sides of the expression where as && and || stop evaluating if the first condition is enough to determine the outcome.
Return a new array of given shape and type, filled with zeros.
or
Return a new array of given shape and type, filled with ones.
or
Return a new array of given shape and type, without initializing entries.
However, the mentality in which we construct an array by appending elements to a list is not much used in numpy, because it's less efficient (numpy datatypes are much closer to the underlying C arrays). Instead, you should preallocate the array to the size that you need it to be, and then fill in the rows. You can use numpy.append
if you must, though.
Another user mentioned this in slight detail but I missed it until I came back here about 3 times over 2 days -
There is a section titled EventListener breakpoints that contains a list of other breakpoints that can be set. It happens that I accidentally enabled one of them on DOM Mutation that was letting me know whenever anything to the DOM was overridden. Unfortunately this led to me disabling a bunch of plug-ins and add-ons before I realized it was just my machine. Hope this helps someone else.
$user->data
is an array of objects. Each element in the array has a name
and value
property (as well as others).
Try putting the 2nd foreach
inside the 1st.
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
foreach($mydata->values as $values)
{
echo $values->value . "\n";
}
}
That's because you missed ELSE.
"Returns the result for the first condition that is true. If there was no matching result value, the result after ELSE is returned, or NULL if there is no ELSE part." (http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#operator_case)
use java decompiler and decompile all the .class files and save all files as project structure .
then use meld diff viewer and compare as folders ..
Try with subprocess
CurlUrl="curl 'https://www.example.com/' -H 'Connection: keep-alive' -H 'Cache-
Control: max-age=0' -H 'Origin: https://www.example.com' -H 'Accept-Encoding:
gzip, deflate, br' -H 'Cookie: SESSID=ABCDEF' --data-binary 'Pathfinder' --
compressed"
Use getstatusoutput
to store the results
status, output = subprocess.getstatusoutput(CurlUrl)
Just do:
npm install username/repo#branchName --save
e.g. (my username is betimer)
npm i betimer/rtc-attach#master --save
// this will appear in your package.json:
"rtc-attach": "github:betimer/rtc-attach#master"
One thing I also want to mention: it's not a good idea to check in the package.json for the build server auto pull the change. Instead, put the npm i (first command) into the build command, and let server just install and replace the package.
One more note, if the package.json private is set to true, may impact sometimes.
Pig-latin is data flow style, is more suitable for software engineer. While sql is more suitable for analytics person who are get used to sql. For complex task, for hive you have to manually to create temporary table to store intermediate data, but it is not necessary for pig.
Pig-latin is suitable for complicated data structure( like small graph). There's a data structure in pig called DataBag which is a collection of Tuple. Sometimes you need to calculate metrics which involve multiple tuples ( there's a hidden link between tuples, in this case I would call it graph). In this case, it is very easy to write a UDF to calculate the metrics which involve multiple tuples. Of course it could be done in hive, but it is not so convenient as it is in pig.
Writing UDF in pig much is easier than in Hive in my opinion.
Pig has no metadata support, (or it is optional, in future it may integrate hcatalog). Hive has tables' metadata stored in database.
You can debug pig script in local environment, but it would be hard for hive to do that. The reason is point 3. You need to set up hive metadata in your local environment, very time consuming.
You can use the function revalue
from the package plyr
to replace values in a factor vector.
In your example to replace the factor virginica
by setosa
:
data(iris)
library(plyr)
revalue(iris$Species, c("virginica" = "setosa")) -> iris$Species
The heredoc solutions are certainly the most common way to do this. Other common solutions are:
echo 'line 1, '"${kernel}"' line 2, line 3, '"${distro}"' line 4' > /etc/myconfig.conf
and
exec 3>&1 # Save current stdout exec > /etc/myconfig.conf echo line 1, ${kernel} echo line 2, echo line 3, ${distro} ... exec 1>&3 # Restore stdout
You are trying to add an integer into an ArrayList
that takes an array of integers Integer[]
. It should be
ArrayList<Integer> list = new ArrayList<>();
or better
List<Integer> list = new ArrayList<>();
You do cls.isFilled = True
. That overwrites the method called isFilled
and replaces it with the value True. That method is now gone and you can't call it anymore. So when you try to call it again you get an error, since it's not there anymore.
The solution is use a different name for the variable than you do for the method.
In iOS 9.1 and lower, go to Settings - General - Profiles - tap on your Profile - tap on Trust button.
In iOS 9.2+ & iOS 11+ go to: Settings - General - Profiles & Device Management - tap on your Profile - tap on Trust button.
In iOS 10+, go to: Settings - General - Device Management - tap on your Profile - tap on Trust button.
You can use IPython.display.clear_output
to clear the output of a cell.
from IPython.display import clear_output
for i in range(10):
clear_output(wait=True)
print("Hello World!")
At the end of this loop you will only see one Hello World!
.
Without a code example it's not easy to give you working code. Probably buffering the latest n events is a good strategy. Whenever the buffer changes you can clear the cell's output and print the buffer again.
Or you could do:
var myDouble = Double((mySwiftString.text as NSString).doubleValue)
You can make it like this:
$('#inputID').keypress(function () {
var maxLength = $(this).val().length;
if (maxLength >= 5) {
alert('You cannot enter more than ' + maxLength + ' chars');
return false;
}
});
Assuming you don't store things like the '+', '()', '-', spaces and what-have-yous (and why would you, they are presentational concerns which would vary based on local customs and the network distributions anyways), the ITU-T recommendation E.164 for the international telephone network (which most national networks are connected via) specifies that the entire number (including country code, but not including prefixes such as the international calling prefix necessary for dialling out, which varies from country to country, nor including suffixes, such as PBX extension numbers) be at most 15 characters.
Call prefixes depend on the caller, not the callee, and thus shouldn't (in many circumstances) be stored with a phone number. If the database stores data for a personal address book (in which case storing the international call prefix makes sense), the longest international prefixes you'd have to deal with (according to Wikipedia) are currently 5 digits, in Finland.
As for suffixes, some PBXs support up to 11 digit extensions (again, according to Wikipedia). Since PBX extension numbers are part of a different dialing plan (PBXs are separate from phone companies' exchanges), extension numbers need to be distinguishable from phone numbers, either with a separator character or by storing them in a different column.
In Python:
# as Peter van der Wal's answer
re.split(r'\r\n|\r|\n', text, flags=re.M)
or more rigorous:
# https://docs.python.org/3/library/stdtypes.html#str.splitlines
str.splitlines()
It's not too hard. Firstly, take a look at FileReader Interface.
So, when the form is submitted, catch the submission process and
var file = document.getElementById('fileBox').files[0]; //Files[0] = 1st file
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = shipOff;
//reader.onloadstart = ...
//reader.onprogress = ... <-- Allows you to update a progress bar.
//reader.onabort = ...
//reader.onerror = ...
//reader.onloadend = ...
function shipOff(event) {
var result = event.target.result;
var fileName = document.getElementById('fileBox').files[0].name; //Should be 'picture.jpg'
$.post('/myscript.php', { data: result, name: fileName }, continueSubmission);
}
Then, on the server side (i.e. myscript.php):
$data = $_POST['data'];
$fileName = $_POST['name'];
$serverFile = time().$fileName;
$fp = fopen('/uploads/'.$serverFile,'w'); //Prepends timestamp to prevent overwriting
fwrite($fp, $data);
fclose($fp);
$returnData = array( "serverFile" => $serverFile );
echo json_encode($returnData);
Or something like it. I may be mistaken (and if I am, please, correct me), but this should store the file as something like 1287916771myPicture.jpg
in /uploads/
on your server, and respond with a JSON variable (to a continueSubmission()
function) containing the fileName on the server.
Check out fwrite()
and jQuery.post()
.
On the above page it details how to use readAsBinaryString()
, readAsDataUrl()
, and readAsArrayBuffer()
for your other needs (e.g. images, videos, etc).
For example:
def anotherfunc(inputarg1, inputarg2):
pass
def myfunc(func = anotherfunc):
print func
When you call myfunc, you do this:
myfunc(anotherfunc(inputarg1, inputarg2))
This will print the return value of anotherfunc.
Hope this helps!
If you prefer a code with a pretty look, you can do a break:
for(int j = 0; ; j++){
if(j < 6
&& j < ( (int) abc[j] & 0xff)){
break;
}
// Put your code here
}
To make the answer more re-usable for things other than just the datepicker change function you can create a prototype to handle this for you.
// safety check to see if the prototype name is already defined
Function.prototype.method = function (name, func) {
if (!this.prototype[name]) {
this.prototype[name] = func;
return this;
}
};
Date.method('inPast', function () {
return this < new Date($.now());// the $.now() requires jQuery
});
// including this prototype as using in example
Date.method('addDays', function (days) {
var date = new Date(this);
date.setDate(date.getDate() + (days));
return date;
});
If you dont like the safety check you can use the conventional way to define prototypes:
Date.prototype.inPast = function(){
return this < new Date($.now());// the $.now() requires jQuery
}
Example Usage
var dt = new Date($.now());
var yesterday = dt.addDays(-1);
var tomorrow = dt.addDays(1);
console.log('Yesterday: ' + yesterday.inPast());
console.log('Tomorrow: ' + tomorrow.inPast());
Try this
function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle==$value['uid'] OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
Use this:
return this.RedirectToAction<AccountController>(m => m.LogIn());
You can only check the first character of the status. For this you use substring function.
substr(status, 1,1)
In your case past.
Here's your model (with invented CT
and TE
) using protobuf-net (yet retaining the ability to use XmlSerializer
, which can be useful - in particular for migration); I humbly submit (with lots of evidence if you need it) that this is the fastest (or certainly one of the fastest) general purpose serializer in .NET.
If you need strings, just base-64 encode the binary.
[XmlType]
public class CT {
[XmlElement(Order = 1)]
public int Foo { get; set; }
}
[XmlType]
public class TE {
[XmlElement(Order = 1)]
public int Bar { get; set; }
}
[XmlType]
public class TD {
[XmlElement(Order=1)]
public List<CT> CTs { get; set; }
[XmlElement(Order=2)]
public List<TE> TEs { get; set; }
[XmlElement(Order = 3)]
public string Code { get; set; }
[XmlElement(Order = 4)]
public string Message { get; set; }
[XmlElement(Order = 5)]
public DateTime StartDate { get; set; }
[XmlElement(Order = 6)]
public DateTime EndDate { get; set; }
public static byte[] Serialize(List<TD> tData) {
using (var ms = new MemoryStream()) {
ProtoBuf.Serializer.Serialize(ms, tData);
return ms.ToArray();
}
}
public static List<TD> Deserialize(byte[] tData) {
using (var ms = new MemoryStream(tData)) {
return ProtoBuf.Serializer.Deserialize<List<TD>>(ms);
}
}
}
The other answers seem to tell you to hard-code the width or use a browser-specific hack. I think there is a simpler way.
By calculating the width and subtracting the padding (which causes the field overlap). The 20px comes from 10px for left padding and 10px for right padding.
input[type=text],
input[type=password] {
...
width: calc(100% - 20px);
}
If you sometimes use substitution variables you might not want to turn define off. In these cases you could convert the ampersand from its numeric equivalent as in || Chr(38) ||
or append it as a single character as in || '&' ||
.
This worked for me:
I removed the single quotes.
I then used a replace ","
with "."
.
Surely this will help someone:
" & txtFinalscore.Text.Replace(",", ".") & "
with open('input.json','r') as f:
s = f.read()
s = s.replace('\'','\"')
data = json.loads(s)
This worked perfectly well for me. Thanks.
met% python -c 'import this' | grep 'only one'
There should be one-- and preferably only one --obvious way to do it.
Here is an example from my HOW TO Matlab page:
close all; clear all;
img = imread('lena.tif','tif');
imagesc(img)
img = fftshift(img(:,:,2));
F = fft2(img);
figure;
imagesc(100*log(1+abs(fftshift(F)))); colormap(gray);
title('magnitude spectrum');
figure;
imagesc(angle(F)); colormap(gray);
title('phase spectrum');
This gives the magnitude spectrum and phase spectrum of the image. I used a color image, but you can easily adjust it to use gray image as well.
ps. I just noticed that on Matlab 2012a the above image is no longer included. So, just replace the first line above with say
img = imread('ngc6543a.jpg');
and it will work. I used an older version of Matlab to make the above example and just copied it here.
On the scaling factor
When we plot the 2D Fourier transform magnitude, we need to scale the pixel values using log transform to expand the range of the dark pixels into the bright region so we can better see the transform. We use a c
value in the equation
s = c log(1+r)
There is no known way to pre detrmine this scale that I know. Just need to
try different values to get on you like. I used 100
in the above example.
First off, I think mplot3D
worked a bit differently in matplotlib
version 0.99
than it does in the current version of matplotlib
.
Which version are you using? (Try running: python -c 'import matplotlib; print matplotlib."__version__")
I'm guessing you're running version 0.99
, in which case you'll need to either use a slightly different syntax or update to a more recent version of matplotlib
.
If you're running version 0.99
, try doing this instead of using using the projection
keyword argument:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D #<-- Note the capitalization!
fig = plt.figure()
ax = Axes3D(fig) #<-- Note the difference from your original code...
X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contour(X, Y, Z, 16, extend3d=True)
ax.clabel(cset, fontsize=9, inline=1)
plt.show()
This should work in matplotlib
1.0.x
, as well, not just 0.99
.
I would imagine that it has to do with encoding. A char
is 16 bytes and some encodings will use one byte for a character whereas another will use two or even more. When Java was originally designed, they assumed that any Unicode character would fit in 2 bytes, whereas now a Unicode character can require up to 4 bytes (UTF-32). There is no way for Scanner
to represent a UTF-32 codepoint in a single char
.
You can specify an encoding to Scanner
when you construct an instance, and if not provided, it will use the platform character-set. But this still doesn't handle the issue with 3 or 4 byte Unicode characters, since they cannot be represented as a single char
primitive (since char
is only 16 bytes). So you would end up getting inconsistent results.
Code Snippet to convert SQL PreparedStaments with the list of arguments. It works for me
/**
*
* formatQuery Utility function which will convert SQL
*
* @param sql
* @param arguments
* @return
*/
public static String formatQuery(final String sql, Object... arguments) {
if (arguments != null && arguments.length <= 0) {
return sql;
}
String query = sql;
int count = 0;
while (query.matches("(.*)\\?(.*)")) {
query = query.replaceFirst("\\?", "{" + count + "}");
count++;
}
String formatedString = java.text.MessageFormat.format(query, arguments);
return formatedString;
}
Express 4.x
To get a URL parameter's value, use req.params
app.get('/p/:tagId', function(req, res) {
res.send("tagId is set to " + req.params.tagId);
});
// GET /p/5
// tagId is set to 5
If you want to get a query parameter ?tagId=5
, then use req.query
app.get('/p', function(req, res) {
res.send("tagId is set to " + req.query.tagId);
});
// GET /p?tagId=5
// tagId is set to 5
Express 3.x
URL parameter
app.get('/p/:tagId', function(req, res) {
res.send("tagId is set to " + req.param("tagId"));
});
// GET /p/5
// tagId is set to 5
Query parameter
app.get('/p', function(req, res) {
res.send("tagId is set to " + req.query("tagId"));
});
// GET /p?tagId=5
// tagId is set to 5
In case of Select2 Version 4+
it has changed syntax and you need to write like this:
// clear all option
$('#select_with_blank_data').html('').select2({data: [{id: '', text: ''}]});
// clear and add new option
$("#select_with_data").html('').select2({data: [
{id: '', text: ''},
{id: '1', text: 'Facebook'},
{id: '2', text: 'Youtube'},
{id: '3', text: 'Instagram'},
{id: '4', text: 'Pinterest'}]});
You can use:
SET PASSWORD FOR 'root' = PASSWORD('elephant7');
or, in latest versions:
SET PASSWORD FOR root = 'elephant7'
You can also use:
UPDATE user SET password=password('elephant7') WHERE user='root';
but in Mysql 5.7 the field password is no more there, and you have to use:
UPDATE user SET authentication_string=password('elephant7') WHERE user='root';
Regards
If you like python and have an option to install a package, you can use this utility that I made.
# install pythonp
python -m pip install pythonp
pythonp "5*5"
25
pythonp "1 / (1+math.exp(0.5))"
0.3775406687981454
# define a custom function and pass it to another higher-order function
pythonp "n=10;functools.reduce(lambda x,y:x*y, range(1,n+1))"
3628800
In general, if you want to use the ConcurrentHashMap
make sure you are ready to miss 'updates'
(i.e. printing contents of the HashMap does not ensure it will print the up-to-date Map) and use APIs like CyclicBarrier
to ensure consistency across your program's lifecycle.
It works like this:
h4 {
display:inline;
}
h4:after {
content:"\a";
white-space: pre;
}
Example: http://jsfiddle.net/Bb2d7/
The trick comes from here: https://stackoverflow.com/a/66000/509752 (to have more explanation)
You need to locate the element and use getText() method to extract the text.
WebElement element = driver.findElement(By.id("customSelect_3"));
System.out.println(element.getText());
New features have been added to MATLAB recently:
String arrays were introduced in R2016b (as Budo and gnovice already mentioned):
String arrays store pieces of text and provide a set of functions for working with text as data. You can index into, reshape, and concatenate strings arrays just as you can with arrays of any other type.
In addition, starting in R2017a, you can create a string using double quotes ""
.
Therefore if your MATLAB version is >= R2017a, the following will do:
for i = 1:3
Names(i) = "Sample Text";
end
Check the output:
>> Names
Names =
1×3 string array
"Sample Text" "Sample Text" "Sample Text"
No need to deal with cell arrays anymore.
Calling conventions defines how parameters are passed in the registers when calling or being called by other program. And the best source of these convention is in the form of ABI standards defined for each these hardware. For ease of compilation, the same ABI is also used by userspace and kernel program. Linux/Freebsd follow the same ABI for x86-64 and another set for 32-bit. But x86-64 ABI for Windows is different from Linux/FreeBSD. And generally ABI does not differentiate system call vs normal "functions calls". Ie, here is a particular example of x86_64 calling conventions and it is the same for both Linux userspace and kernel: http://eli.thegreenplace.net/2011/09/06/stack-frame-layout-on-x86-64/ (note the sequence a,b,c,d,e,f of parameters):
Performance is one of the reasons for these ABI (eg, passing parameters via registers instead of saving into memory stacks)
For ARM there is various ABI:
http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.subset.swdev.abi/index.html
ARM64 convention:
http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055b/IHI0055B_aapcs64.pdf
For Linux on PowerPC:
http://refspecs.freestandards.org/elf/elfspec_ppc.pdf
http://www.0x04.net/doc/elf/psABI-ppc64.pdf
And for embedded there is the PPC EABI:
http://www.freescale.com/files/32bit/doc/app_note/PPCEABI.pdf
This document is good overview of all the different conventions:
As others have mentioned, you can do this via nbextensions. I wanted to give the brief explanation of what I did, which was quick and easy:
To enable collabsible headings: In your terminal, enable/install Jupyter Notebook Extensions by first entering:
pip install jupyter_contrib_nbextensions
Then, enter:
jupyter contrib nbextension install
Re-open Jupyter Notebook. Go to "Edit" tab, and select "nbextensions config". Un-check box directly under title "Configurable nbextensions", then select "collapsible headings".
I thought I'd try code this up for fun:
graph = {
'1': ['2', '3', '4'],
'2': ['5', '6'],
'5': ['9', '10'],
'4': ['7', '8'],
'7': ['11', '12']
}
def bfs(graph, forefront, end):
# assumes no cycles
next_forefront = [(node, path + ',' + node) for i, path in forefront if i in graph for node in graph[i]]
for node,path in next_forefront:
if node==end:
return path
else:
return bfs(graph,next_forefront,end)
print bfs(graph,[('1','1')],'11')
# >>>
# 1, 4, 7, 11
If you want cycles you could add this:
for i, j in for_front: # allow cycles, add this code
if i in graph:
del graph[i]
Calling non-static methods statically generates an E_STRICT level warning.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *name = "hello";
int main(void) {
char *ext = ".txt";
int len = strlen(name) + strlen(ext) + 1;
char *n2 = malloc(len);
char *n2a = malloc(len);
if (n2 == NULL || n2a == NULL)
abort();
strlcpy(n2, name, len);
strlcat(n2, ext, len);
printf("%s\n", n2);
/* or for conforming C99 ... */
strncpy(n2a, name, len);
strncat(n2a, ext, len - strlen(n2a));
printf("%s\n", n2a);
return 0; // this exits, otherwise free n2 && n2a
}
If i want to clear all the fields except accountType..Use the following
$q(':input','#myform').not('#accountType').val('').removeAttr('checked').removeAttr('selected');
CSS:
.headercss {
width: 100%;
height: 320px;
background-color: #000000;
position: fixed;
}
Attribute position: fixed
will keep it stuck, while other content will be scrollable. Don't forget to set width:100%
to make it fill fully to the right.
Here is another example using Spark/Scala to convert a CSV to RDD. For a more detailed description see this post.
def main(args: Array[String]): Unit = {
val csv = sc.textFile("/path/to/your/file.csv")
// split / clean data
val headerAndRows = csv.map(line => line.split(",").map(_.trim))
// get header
val header = headerAndRows.first
// filter out header (eh. just check if the first val matches the first header name)
val data = headerAndRows.filter(_(0) != header(0))
// splits to map (header/value pairs)
val maps = data.map(splits => header.zip(splits).toMap)
// filter out the user "me"
val result = maps.filter(map => map("user") != "me")
// print result
result.foreach(println)
}
This is how I got it to work in Ubuntu 18.04
sudo apt install qemu-kvm
Add your user to kvm group using:
sudo adduser <Replace with username> kvm
If still showing permission denied:
sudo chown <Replace with username> /dev/kvm
Try it.