As answer no. 2 by fnieto - Fernando Nieto clearly and correctly describes that this warning is given because somewhere in your code you are doing (not in the code you posted) something like:
void foo(char* str);
foo("hello");
However, if you want to keep your code warning-free as well then just make respective change in your code:
void foo(char* str);
foo((char *)"hello");
That is, simply cast the string
constant to (char *)
.
Explicit conversion constructors (C++ only)
The explicit function specifier controls unwanted implicit type conversions. It can only be used in declarations of constructors within a class declaration. For example, except for the default constructor, the constructors in the following class are conversion constructors.
class A
{
public:
A();
A(int);
A(const char*, int = 0);
};
The following declarations are legal:
A c = 1;
A d = "Venditti";
The first declaration is equivalent to A c = A( 1 );
.
If you declare the constructor of the class as explicit
, the previous declarations would be illegal.
For example, if you declare the class as:
class A
{
public:
explicit A();
explicit A(int);
explicit A(const char*, int = 0);
};
You can only assign values that match the values of the class type.
For example, the following statements are legal:
A a1;
A a2 = A(1);
A a3(1);
A a4 = A("Venditti");
A* p = new A(1);
A a5 = (A)1;
A a6 = static_cast<A>(1);
From the menu bar: Project -> Properties -> Java Compiler
Enable project specific settings (checked) Uncheck "use Compliance from execution environment '.... Select the desired "compiler compliance level"
That will allow you to compile "1.5" code using a "1.6" JDK.
If you want to acutally use a 1.5 JDK to produce "1.5" compliant code, then install a suitable 1.5 JDK and tell eclipse where it is installed via:
Window -> preferences -> Installed JREs
And then go back to your project
Project -> properties -> Java Build Path -> libraries
remove the 1.6 system libaries, and: add library... -> JRE System LIbrary -> Alternate JRE -> The JRE you want.
Verify that the correct JRE is on the project's build path, save everything, and enjoy!
Suppose gamma1 and gamma2 are two such columns for which df.isnull().any() gives True value , the following code can be used to print the rows.
bool1 = pd.isnull(df['gamma1'])
bool2 = pd.isnull(df['gamma2'])
df[bool1]
df[bool2]
An sql sum of column_name's unique values and sorted by the frequency:
SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name ORDER BY 2 DESC;
There is no need of doing such hectic stuffs. Find in your system where there is "SDK Manager".(incase of windows). Suppose your sdk manager is in E:\Android-9. Go to that path double click the SDK manager ;it will automatically start to download from https://dl-ssl.google.com/../..
Initially you will se it is failing. On the window that appears there will be 'settings' menu. Click on that set the proxy and port. and it will start downloading.
The solution in one sentence is "Don't use eclipse for the download;directly use Android sdk manager and your problem is resolved". Let me know if you have any futhur queries on this issue.
Use jQuery's IsNumeric method.
http://api.jquery.com/jQuery.isNumeric/
if ($.isNumeric(id)) {
//it's numeric
}
CORRECTION: that would not ensure an integer. This would:
if ( (id+"").match(/^\d+$/) ) {
//it's all digits
}
That, of course, doesn't use jQuery, but I assume jQuery isn't actually mandatory as long as the solution works
I could use the GetBody
from Request package.
Look this comment in source code from request.go in net/http:
GetBody defines an optional func to return a new copy of Body. It is used for client requests when a redirect requires reading the body more than once. Use of GetBody still requires setting Body. For server requests it is unused."
GetBody func() (io.ReadCloser, error)
This way you can get the body request without make it empty.
Sample:
getBody := request.GetBody
copyBody, err := getBody()
if err != nil {
// Do something return err
}
http.DefaultClient.Do(request)
I couldn't find an answer that would solve this:
[{name:"Vehicle.Make", value: "Honda"}, {name:"Vehicle.VIN", value: "123"}]
This calls for this object:
{Vehicle: {Make: "Honda", "VIN": "123"}}
So I had to write a serializer of my own that would solve this:
function(formArray){
var obj = {};
$.each(formArray, function(i, pair){
var cObj = obj, pObj, cpName;
$.each(pair.name.split("."), function(i, pName){
pObj = cObj;
cpName = pName;
cObj = cObj[pName] ? cObj[pName] : (cObj[pName] = {});
});
pObj[cpName] = pair.value;
});
return obj;
}
Maybe it will help somebody.
Works like a charm!
.imageClass {
-webkit-filter: drop-shadow(12px 12px 7px rgba(0,0,0,0.5));
}
Voila! That's it! Obviously this won't work in ie, but who cares...
I also ran into the error (that's why I am landed here), but none of the suggestions worked for me. This was my very first time I try to deploy local Git to azure. When I got this error, I reset my credentials (by clicking the link in Azure) after a few tries. The problem is that at this point it tells me my user name is already taken, so I also changed my user name to another one. In the end, I manually deleted the .git folder on my local drive, and redeployed it without problem.
It's really easy to do from the command line. I had a gist of a script for doing this. It has now been incorporated into the ipa_sign script in https://github.com/RichardBronosky/ota-tools which I use daily. If you have any questions about using these tools, don't hesitate to ask.
The heart of it is this:
CODESIGN_ALLOCATE=`xcrun --find codesign_allocate`; export CODESIGN_ALLOCATE
IPA="/path/to/file.ipa"
PROVISION="/path/to/file.mobileprovision"
CERTIFICATE="Name of certificate: To sign with" # must be in keychain
# unzip the ipa
unzip -q "$IPA"
# remove the signature
rm -rf Payload/*.app/_CodeSignature
# replace the provision
cp "$PROVISION" Payload/*.app/embedded.mobileprovision
# sign with the new certificate (--resource-rules has been deprecated OS X Yosemite (10.10), it can safely be removed)
/usr/bin/codesign -f -s "$CERTIFICATE" Payload/*.app
# zip it back up
zip -qr resigned.ipa Payload
Your new signed app is called resigned.ipa
Select * from employee where salary = (Select max(salary) from employee where salary not in(Select max(salary)from employee))
Explanation :
Query 1 : Select max(salary) from employee where salary not in(Select max(salary) from employee) - This query will retrieve second highest salary
Query 2 : Select * from employee where salary=(Query 1) - This query will retrieve all the records having second highest salary(Second highest salary may have multiple records)
If you want system back color in white then you can use this code
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:elevation="0dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar_notification"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
app:contentInsetStartWithNavigation="0dp">
<include layout="@layout/action_bar_notification" />
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
Note:- android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
is key
The paste is in your activity where you want to show back button on action bar
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_notification);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(false);
For those of you using Spring, you can simply reference any classpath-resource using the classpath-protocol. So in case of the wsdlLocation, this becomes:
<wsdlLocation>classpath:META-INF/webservice.wsdl</wsdlLocation>
Note that is not standard Java behavior. See also: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/resources.html
It depends what is a use of those tables, but you might consider putting trigger on original table on insert and update. When insert or update is done, update the second table based on only one item from the original table. It will be quicker.
A Java list is a collection of objects ... the elements of a list. The size of the list is the number of elements in that list. If you want that size to be fixed, that means that you cannot either add or remove elements, because adding or removing elements would violate your "fixed size" constraint.
The simplest way to implement a "fixed sized" list (if that is really what you want!) is to put the elements into an array and then Arrays.asList(array)
to create the list wrapper. The wrapper will allow you to do operations like get
and set
, but the add
and remove
operations will throw exceptions.
And if you want to create a fixed-sized wrapper for an existing list, then you could use the Apache commons FixedSizeList
class. But note that this wrapper can't stop something else changing the size of the original list, and if that happens the wrapped list will presumably reflect those changes.
On the other hand, if you really want a list type with a fixed limit (or limits) on its size, then you'll need to create your own List class to implement this. For example, you could create a wrapper class that implements the relevant checks in the various add
/ addAll
and remove
/ removeAll
/ retainAll
operations. (And in the iterator remove
methods if they are supported.)
So why doesn't the Java Collections framework implement these? Here's why I think so:
Collections.sort
.Is the recommendation to include CSS before JavaScript invalid?
Not if you treat it as simply a recommendation. But if your treat it as a hard and fast rule?, yes, it is invalid.
From https://developer.mozilla.org/en-US/docs/Web/Reference/Events/DOMContentLoaded
Stylesheet loads block script execution, so if you have a
<script>
after a<link rel="stylesheet" ...>
the page will not finish parsing - and DOMContentLoaded will not fire - until the stylesheet is loaded.
It appears that you need to know what each script relies on and make sure that execution of the script is delayed until after the right completion event. If the script relies only on the DOM, it can resume in ondomready/domcontentloaded, if it relies on images to be loaded or stylesheets to be applied, then if I read the above reference correctly, that code must be deferred until the onload event.
I don't think that one sock size fits all, even though that is the way they are sold and I know that one shoe size does not fit all. I don't think that there is a definitive answer to which to load first, styles or script. It is more a case by case decision of what must be loaded in what order and what can be deferred until later as not being on the "critical path".
To speak to the observer that commented that it is better to delay the users ability to interact until the sheet is pretty. There are many of you out there and you annoy your counterparts that feel the opposite. They came to a site to accomplish a purpose and delays to their ability to interact with a site while waiting for things that don't matter to finish loading are very frustrating. I am not saying that you are wrong, only that you should be aware that there is another faction that exists that does not share your priority.
This question particularly applies to all of the ads being placed on web sites. I would love it if site authors rendered just placeholder divs for the ad content and made sure that their site was loaded and interactive before injecting the ads in an onload event. Even then I would like to see the ads loaded serially instead of all at once because they impact my ability to even scroll the site content while the bloated ads are loading. But that is just one persons point of view.
Regular Expression that can be used:
Find: \w.+
Replace: able:"$&"
As, $&
will give you the string you search for.
Refer: regexr
On Mac brew install postgres
THEN bundle install
var str = "123, 124, 234,252";
var arr = str.split(",");
for(var i=0;i<arr.length;i++) {
arr[i] = ++arr[i];
}
To avoid nesting and ngSwitch, there is also this possibility, which leverages the way logical operators work in Javascript:
<ng-container *ngIf="foo === 1; then first; else (foo === 2 && second) || (foo === 3 && third)"></ng-container>
<ng-template #first>First</ng-template>
<ng-template #second>Second</ng-template>
<ng-template #third>Third</ng-template>
There are many possibilities to solve this task.
The easiest solution is running the batch file with full path.
"F:\- Big Packets -\kitterengine\Common\Template.bat"
Once end of batch file Template.bat
is reached, there is no return to previous script in case of the command line above is within a *.bat or *.cmd file.
The current directory for the batch file Template.bat
is the current directory of the current process. In case of Template.bat
requires that the directory of this batch file is the current directory, the batch file Template.bat
should contain after @echo off
as second line the following command line:
cd /D "%~dp0"
Run in a command prompt window cd /?
for getting displayed the help of this command explaining parameter /D
... change to specified directory also on a different drive.
Run in a command prompt window call /?
for getting displayed the help of this command used also in 2., 4. and 5. solution and explaining also %~dp0
... drive and path of argument 0 which is the name of the batch file.
Another solution is calling the batch file with full path.
call "F:\- Big Packets -\kitterengine\Common\Template.bat"
The difference to first solution is that after end of batch file Template.bat
is reached the batch processing continues in batch script containing this command line.
For the current directory read above.
There are 3 operators for running multiple commands on one command line: &
, &&
and ||
.
For details see answer on Single line with multiple commands using Windows batch file
I suggest for this task the &&
operator.
cd /D "F:\- Big Packets -\kitterengine\Common" && Template.bat
As on first solution there is no return to current script if this is a *.bat or *.cmd file and changing the directory and continuation of batch processing on Template.bat
is successful.
This command line changes the directory and on success calls the batch file.
cd /D "F:\- Big Packets -\kitterengine\Common" && call Template.bat
The difference to third solution is the return to current batch script on exiting processing of Template.bat
.
The four solutions above change the current directory and it is unknown what Template.bat
does regarding
In case of it is important to keep the environment of current *.bat or *.cmd script unmodified by whatever Template.bat
changes on environment for itself, it is advisable to use setlocal
and endlocal
.
Run in a command prompt window setlocal /?
and endlocal /?
for getting displayed the help of these two commands. And read answer on change directory command cd ..not working in batch file after npm install explaining more detailed what these two commands do.
setlocal & cd /D "F:\- Big Packets -\kitterengine\Common" & call Template.bat & endlocal
Now there is only &
instead of &&
used as it is important here that after setlocal
is executed the command endlocal
is finally also executed.
ONE MORE NOTE
If batch file Template.bat
contains the command exit
without parameter /B
and this command is really executed, the command process is always exited independent on calling hierarchy. So make sure Template.bat
contains exit /B
or goto :EOF
instead of just exit
if there is exit
used at all in this batch file.
It's frowned upon because it's a platform-specific hack that has nothing to do with actually learning programming, but instead to get around a feature of the IDE/OS - the console window launched from Visual Studio closes when the program has finished execution, and so the new user doesn't get to see the output of his new program.
Bodging in System("pause") runs the Windows command-line "pause" program and waits for that to terminate before it continues execution of the program - the console window stays open so you can read the output.
A better idea would be to put a breakpoint at the end and debug it, but that again has problems.
In your own (base) class, willSet
and didSet
are quite reduntant , as you could instead define a calculated property (i.e get- and set- methods) that access a _propertyVariable
and does the desired pre- and post- prosessing.
If, however, you override a class where the property is already defined, then the willSet
and didSet
are useful and not redundant!
I was not actually able to render an image without borders or axis data based on any of the code snippets here (even the one accepted at the answer). After digging through some API documentation, I landed on this code to render my image
plt.axis('off')
plt.tick_params(axis='both', left='off', top='off', right='off', bottom='off', labelleft='off', labeltop='off', labelright='off', labelbottom='off')
plt.savefig('foo.png', dpi=100, bbox_inches='tight', pad_inches=0.0)
I used the tick_params
call to basically shut down any extra information that might be rendered and I have a perfect graph in my output file.
Try This one
<TouchableOpacity onPress={() => this._onPressAppoimentButton()} style={styles.Btn}>
<Button title="Order Online" style={styles.Btn} > </Button>
</TouchableOpacity>
The actual reason is that, in a new repo (git init), there is no branch (no master
, no branch at all, zero branches)
So when you are pushing for the first time to an empty upstream repo (generally a bare one), that upstream repo has no branch of the same name.
And:
matching
' (push all the branches of the same name, creating them if they don't exist), simple
' (push only the current branch, and only if it has a similarly named remote tracking branch on upstream, since git 1.7.11)In both cases, since the upstream empty repo has no branch:
That means your local first push has no idea:
So you need at least to do a:
git push origin master
But if you do only that, you:
master
branch on the upstream (now non-empty repo): good.master
' needs to be pushed to upstream (origin
) 'master
' (upstream branch): bad.That is why it is recommended, for the first push, to do a:
git push -u origin master
That will record origin/master
as a remote tracking branch, and will enable the next push to automatically push master
to origin/master
.
git checkout master
git push
And that will work too with push policies 'current
' or 'upstream
'.
In each case, after the initial git push -u origin master
, a simple git push will be enough to continue pushing master to the right upstream branch.
I have an answer that doesn't require a UDF, XML Because IN accepts a select statement e.g. SELECT * FROM Test where Data IN (SELECT Value FROM TABLE)
You really only need a way to convert the string into a table.
This can be done with a recursive CTE, or a query with a number table (or Master..spt_value)
Here's the CTE version.
DECLARE @InputString varchar(8000) = 'ruby,rails,scruffy,rubyonrails'
SELECT @InputString = @InputString + ','
;WITH RecursiveCSV(x,y)
AS
(
SELECT
x = SUBSTRING(@InputString,0,CHARINDEX(',',@InputString,0)),
y = SUBSTRING(@InputString,CHARINDEX(',',@InputString,0)+1,LEN(@InputString))
UNION ALL
SELECT
x = SUBSTRING(y,0,CHARINDEX(',',y,0)),
y = SUBSTRING(y,CHARINDEX(',',y,0)+1,LEN(y))
FROM
RecursiveCSV
WHERE
SUBSTRING(y,CHARINDEX(',',y,0)+1,LEN(y)) <> '' OR
SUBSTRING(y,0,CHARINDEX(',',y,0)) <> ''
)
SELECT
*
FROM
Tags
WHERE
Name IN (select x FROM RecursiveCSV)
OPTION (MAXRECURSION 32767);
From here - Remember:
<input v-model="something">
is essentially the same as:
<input
v-bind:value="something"
v-on:input="something = $event.target.value"
>
or (shorthand syntax):
<input
:value="something"
@input="something = $event.target.value"
>
So v-model
is a two-way binding for form inputs. It combines v-bind
, which brings a js value into the markup, and v-on:input
to update the js value.
Use v-model
when you can. Use v-bind
/v-on
when you must :-) I hope your answer was accepted.
v-model
works with all the basic HTML input types (text, textarea, number, radio, checkbox, select). You can use v-model
with input type=date
if your model stores dates as ISO strings (yyyy-mm-dd). If you want to use date objects in your model (a good idea as soon as you're going to manipulate or format them), do this.
v-model
has some extra smarts that it's good to be aware of. If you're using an IME ( lots of mobile keyboards, or Chinese/Japanese/Korean ), v-model will not update until a word is complete (a space is entered or the user leaves the field). v-input
will fire much more frequently.
v-model
also has modifiers .lazy
, .trim
, .number
, covered in the doc.
If you don't want to use float, the easiest and cleanest way to do it is by using an auto width column:
<div class="row">
<div class="col">
<h3 class="one">Text</h3>
</div>
<div class="col-auto">
<button class="btn btn-secondary pull-right">Button</button>
</div>
</div>
Note that rstrip doesn't act exactly like Perl's chomp() because it doesn't modify the string. That is, in Perl:
$x="a\n";
chomp $x
results in $x
being "a"
.
but in Python:
x="a\n"
x.rstrip()
will mean that the value of x
is still "a\n"
. Even x=x.rstrip()
doesn't always give the same result, as it strips all whitespace from the end of the string, not just one newline at most.
I propose a simple TLDR:; example for the un-initiated.
Create a bash script called helloworld.sh
#!/bin/bash
while getopts "n:" arg; do
case $arg in
n) Name=$OPTARG;;
esac
done
echo "Hello $Name!"
You can then pass an optional parameter -n
when executing the script.
Execute the script as such:
$ bash helloworld.sh -n 'World'
Output
$ Hello World!
Notes
If you'd like to use multiple parameters:
while getops "n:" arg: do
with more paramaters such as
while getops "n:o:p:" arg: do
o) Option=$OPTARG
and p) Parameter=$OPTARG
To delete a normal stash created with git stash
, you want git stash drop
or git stash drop stash@{n}
. See below for more details.
You don't need to delete a stash created with git stash create
. From the docs:
Create a stash entry (which is a regular commit object) and return its object name, without storing it anywhere in the ref namespace. This is intended to be useful for scripts. It is probably not the command you want to use; see "save" above.
Since nothing references the stash commit, it will get garbage collected eventually.
A stash created with git stash
or git stash save
is saved to refs/stash
, and can be deleted with git stash drop
. As with all Git objects, the actual stash contents aren't deleted from your computer until a gc
prunes those objects after they expire (default is 2 weeks later).
Older stashes are saved in the refs/stash
reflog (try cat .git/logs/refs/stash
), and can be deleted with git stash drop stash@{n}
, where n
is the number shown by git stash list
.
In the right hand column under your solution explorer, you can see next to the reference to "Science" its marked as a warning. Either that means it cant find it, or its objecting to it for some other reason. While this is the case and your code requires it (and its not just in the references list) it wont compile.
Please post the warning message, we can try help you further.
Why don't you examine System.getProperty("os.arch")
value in your code?
It's easier than it is thought:
my_str = "hello world"
my_str_as_bytes = str.encode(my_str)
type(my_str_as_bytes) # ensure it is byte representation
my_decoded_str = my_str_as_bytes.decode()
type(my_decoded_str) # ensure it is string representation
In windows, I use this PowerShell script to start it up.
$em = $env:USERPROFILE+"\AppData\Local\Android\sdk\tools\emulator.exe";
Start-Process $em " -avd Nexus_5X_API_24" -WindowStyle Hidden;
I found solution here: https://code.visualstudio.com/docs/customization/colorizer
Go to VS_CODE_FOLDER/resources/app/extensions/
and there update package.json
I ran some tests (on postgres 9.5) using two tables with ~2M rows each. This query below performed at least 5* better than the other queries proposed:
-- Count
SELECT count(*) FROM (
(SELECT id FROM table1) EXCEPT (SELECT id FROM table2)
) t1_not_in_t2;
-- Get full row
SELECT table1.* FROM (
(SELECT id FROM table1) EXCEPT (SELECT id FROM table2)
) t1_not_in_t2 JOIN table1 ON t1_not_in_t2.id=table1.id;
Here is how you would add query string parameters using HttpClient 4.2 and later:
URIBuilder builder = new URIBuilder("http://example.com/");
builder.setParameter("parts", "all").setParameter("action", "finish");
HttpPost post = new HttpPost(builder.build());
The resulting URI would look like:
http://example.com/?parts=all&action=finish
according to Android docs, Monitor was deprecated in Android Studio 3.1 and removed from Android Studio 3.2. To access files, there is a tab in android studio called "Device File Explorer" bottom-right side of developing window which you can access your emulator file system. Just follow
/data/data/package_name/databases
good luck.
Option #1: Use ProvidePlugin
Add the ProvidePlugin to the plugins array in both build/webpack.dev.conf.js
and build/webpack.prod.conf.js
so that jQuery becomes globally available to all your modules:
plugins: [
// ...
new webpack.ProvidePlugin({
$: 'jquery',
jquery: 'jquery',
'window.jQuery': 'jquery',
jQuery: 'jquery'
})
]
Option #2: Use Expose Loader module for webpack
As @TremendusApps suggests in his answer, add the Expose Loader package:
npm install expose-loader --save-dev
Use in your entry point main.js
like this:
import 'expose?$!expose?jQuery!jquery'
// ...
I tried a couple of codes, but end up using something as simple as (in Python 3):
from datetime import datetime
df['difference_in_datetime'] = abs(df['end_datetime'] - df['start_datetime'])
If your start_datetime and end_datetime columns are in datetime64[ns]
format, datetime understands it and return the difference in days + timestamp, which is in timedelta64[ns]
format.
If you want to see only the difference in days, you can separate only the date portion of the start_datetime and end_datetime by using (also works for the time portion):
df['start_date'] = df['start_datetime'].dt.date
df['end_date'] = df['end_datetime'].dt.date
And then run:
df['difference_in_days'] = abs(df['end_date'] - df['start_date'])
Open Terminal
cd to/the/program/location
ruby program.rb
or add #!/usr/bin/env ruby
in the first of your program (script tell that this is executed using Ruby Interpreter)
Open Terminal
cd to/the/program/location
chmod 777 program.rb
./program.rb
Date today = new Date();
Date tomorrow = new Date(today.getTime() + (1000 * 60 * 60 * 24));
Date has a constructor using the milliseconds since the UNIX-epoch. the getTime()-method gives you that value. So adding the milliseconds for a day, does the trick. If you want to do such manipulations regularly I recommend to define constants for the values.
Important hint: That is not correct in all cases. Read the WARNING comment, below.
The thing of it is there are 2 main protocol versions of WebSockets in use today. The old version which uses the [0x00][message][0xFF]
protocol, and then there's the new version using Hybi formatted packets.
The old protocol version is used by Opera and iPod/iPad/iPhones so it's actually important that backward compatibility is implemented in WebSockets servers. With these browsers using the old protocol, I discovered that refreshing the page, or navigating away from the page, or closing the browser, all result in the browser automatically closing the connection. Great!!
However with browsers using the new protocol version (eg. Firefox, Chrome and eventually IE10), only closing the browser will result in the browser automatically closing the connection. That is to say, if you refresh the page, or navigate away from the page, the browser does NOT automatically close the connection. However, what the browser does do, is send a hybi packet to the server with the first byte (the proto ident) being 0x88
(better known as the close data frame). Once the server receives this packet it can forcefully close the connection itself, if you so choose.
I too got similar error when i misplaced the code
text=(TextView)findViewById(R.id.text);// this line has to be below setcontentview
setContentView(R.layout.activity_my_otype);
//this is the correct place
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
I got it working on placing the code in right order as shown below
setContentView(R.layout.activity_my_otype);
text=(TextView)findViewById(R.id.text);
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
I use a similar technique to lazyload images, but can't help but notice that Javascript doesn't access the browser cache on first loading.
My example:
I have a rotating banner on my homepage with 4 images the slider wait 2 seconds, than the javascript loads the next image, waits 2 seconds, etc.
These images have unique urls that change whenever I modify them, so they get caching headers that will cache in the browser for a year.
max-age: 31536000, public
Now when I open Chrome Devtools and make sure de 'Disable cache' option is not active and load the page for the first time (after clearing the cache) all images get fetch and have a 200 status. After a full cycle of all images in the banner the network requests stop and the cached images are used.
Now when I do a regular refresh or go to a subpage and click back, the images that are in the cache seems to be ignored. I would expect to see a grey message "from disk cache" in the Network tab of Chrome devtools. In instead I see the requests pass by every two seconds with a Green status circle instead of gray, I see data being transferred, so it I get the impression the cache is not accessed at all from javascript. It simply fetches the image each time the page gets loaded.
So each request to the homepage triggers 4 requests regardless of the caching policy of the image.
Considering the above together and the new http2 standard most webservers and browsers now support, I think it's better to stop using lazyloading since http2 will load all images nearly simultaneously.
If this is a bug in Chrome Devtools it really surprises my nobody noticed this yet. ;)
If this is true, using lazyloading only increases bandwith usage.
Please correct me if I'm wrong. :)
i hope this code is work well,try this.
add css file.
.scrollbar {
height: auto;
max-height: 180px;
overflow-x: hidden;
}
HTML code:
<div class="col-sm-2 scrollable-menu" role="menu">
<div>
<ul>
<li><a class="active" href="#home">Tutorials</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
</div>
</div>
its working with this code
text-align: justify; text-align-last: center;
After long search I found a working solution. My database does not use the sys.foreign_key_columns and the information_schema.key_column_usage only contain primary keys.
I use SQL Server 2015
SOLUTION 1 (rarely used)
If other solutions does not work, this will work fine:
WITH CTE AS
(
SELECT
TAB.schema_id,
TAB.name,
COL.name AS COLNAME,
COl.is_identity
FROM
sys.tables TAB INNER JOIN sys.columns COL
ON TAB.object_id = COL.object_id
)
SELECT
DB_NAME() AS [Database],
SCHEMA_NAME(Child.schema_id) AS 'Schema',
Child.name AS 'ChildTable',
Child.COLNAME AS 'ChildColumn',
Parent.name AS 'ParentTable',
Parent.COLNAME AS 'ParentColumn'
FROM
cte Child INNER JOIN CTE Parent
ON
Child.COLNAME=Parent.COLNAME AND
Child.name<>Parent.name AND
Child.is_identity+1=Parent.is_identity
SOLUTION 2 (commonly used)
In most of the cases this will work just fine:
SELECT
DB_NAME() AS [Database],
SCHEMA_NAME(fk.schema_id) AS 'Schema',
fk.name 'Name',
tp.name 'ParentTable',
cp.name 'ParentColumn',
cp.column_id,
tr.name 'ChildTable',
cr.name 'ChildColumn',
cr.column_id
FROM
sys.foreign_keys fk
INNER JOIN
sys.tables tp ON fk.parent_object_id = tp.object_id
INNER JOIN
sys.tables tr ON fk.referenced_object_id = tr.object_id
INNER JOIN
sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
INNER JOIN
sys.columns cp ON fkc.parent_column_id = cp.column_id AND fkc.parent_object_id = cp.object_id
INNER JOIN
sys.columns cr ON fkc.referenced_column_id = cr.column_id AND fkc.referenced_object_id = cr.object_id
WHERE
-- CONCAT(SCHEMA_NAME(fk.schema_id), '.', tp.name, '.', cp.name) LIKE '%my_table_name%' OR
-- CONCAT(SCHEMA_NAME(fk.schema_id), '.', tr.name, '.', cr.name) LIKE '%my_table_name%'
ORDER BY
tp.name, cp.column_id
To get the number of selected rows I usually use the following:
cursor.execute(sql)
count = (len(cursor.fetchall))
Do some padding, i.e.
public static void prn(string fname, string fvalue)
{
string outstring = fname.PadRight(20) +"\t\t " + fvalue;
Console.WriteLine(outstring);
}
This worked well, at least for me.
If the submodule was accidentally added because you added, committed and pushed a folder that was already a Git repository (contained .git
), you won’t have a .gitmodules
file to edit, or anything in .git/config
. In this case all you need is :
git rm --cached subfolder
git add subfolder
git commit -m "Enter message here"
git push
FWIW, I also removed the .git
folder before doing the git add
.
I have seen the same error message after upgrading to git1.8.5.2:
Simply make a search for all msys-1.0.dll
on your C:\
drive, and make the one used by Git comes first.
For instance, in my case I simply changed the order of:
C:\prgs\Gow\Gow-0.7.0\bin\msys-1.0.dll
C:\prgs\git\PortableGit-1.8.5.2-preview20131230\bin\msys-1.0.dll
By making the Git path C:\prgs\git\PortableGit-1.8.5.2-preview20131230\bin\
come first in my %PATH%
, the error message disappeared.
No need to reboot or to even change the DOS session.
Once the %PATH%
is updated in that DOS session, the git commands just work.
Note that carmbrester and Sixto Saez both report below (in the comments) having to reboot in order to fix the issue.
Note: First, also removing any msys-1.0.dll
, like one in %LOCALAPPDATA%
TLDR : check if packaging
element inside the pom.xml file is set to jar
.
Like this - <packaging>jar</packaging>
. If it set to pom
your target folder will not be created even after you Clean and Build your project and Maven executable won't be able to find .class
files (because they don't exist), after which you get Error: Could not find or load main class your.package.name.MainClass
After creating a Maven POM project in Netbeans 8.2, the content of the default pom.xml
file are as follows -
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>myproject</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
Here packaging
element is set to pom
. Hence the target
directory is not created as we are not enabling maven to package our application as a jar
file. Change it to jar
then Clean and Build your project, you should see target directory created at root location. Now you should be able to run that java file with main method.
When no packaging is declared, Maven assumes the packaging as jar
. Other core packaging values are pom
, war
, maven-plugin
, ejb
, ear
, rar
. These define the goals that execute on each corresponsding build life-cycle phase of that package. See more here
There's one more subtlety that can help here.
I want to have links that both allow in-browser playing and display as well as one for purely downloading. The new download attribute is fine, but doesn't work all the time because the browser's compulsion to play the or display the file is still very strong.
BUT.. this is based on examining the extension on the URL's filename!You don't want to fiddle with the server's extension mapping because you want to deliver the same file two different ways. So for the download, you can fool it by softlinking the file to a name that is opaque to this extension mapping, pointing to it, and then using download's rename feature to fix the name.
<a target="_blank" download="realname.mp3" href="realname.UNKNOWN">Download it</a>_x000D_
<a target="_blank" href="realname.mp3">Play it</a>
_x000D_
I was hoping just throwing a dummy query on the end or otherwise obfuscating the extension would work, but sadly, it doesn't.
I also had similar problems when trying to link static compiled fontconfig and expat into a linux shared object:
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/fontconfig/lib/linux-x86_64/libfontconfig.a(fccfg.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/expat/lib/linux-x86_64/libexpat.a(xmlparse.o): relocation R_X86_64_PC32 against symbol `stderr@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC
[...]
This contrary to the fact that I was already passing -fPIC
flags though CFLAGS
variable, and other compilers/linkers variants (clang/lld) were perfectly working with the same build configuration. It ended up that these dependencies control position-independent code settings through despicable autoconf
scripts and need --with-pic
switch during build configuration on linux gcc/ld combination, and its lack probably overrides same the setting in CFLAGS
. Pass the switch to configure
script and the dependencies will be correctly compiled with -fPIC
.
There is no documented LEFT() function in Oracle. Find the full set here.
Probably what you have is a user-defined function. You can check that easily enough by querying the data dictionary:
select * from all_objects
where object_name = 'LEFT'
But there is the question of why the stored procedure works and the query doesn't. One possible solution is that the stored procedure is owned by another schema, which also owns the LEFT() function. They have granted rights on the procedure but not its dependencies. This works because stored procedures run with DEFINER privileges by default, so you run the stored procedure as if you were its owner.
If this is so then the data dictionary query I listed above won't help you: it will only return rows for objects you have rights on. In which case you will need to run the query as the stored procedure's owner or connect as a user with the rights to query DBA_OBJECTS instead.
From the help file about $
(See ?"$"
) you can read:
$ is only valid for recursive objects, and is only discussed in the section below on recursive objects.
Now, let's check whether x
is recursive
> is.recursive(x)
[1] FALSE
A recursive object has a list-like structure. A vector is not recursive, it is an atomic object instead, let's check
> is.atomic(x)
[1] TRUE
Therefore you get an error when applying $
to a vector (non-recursive object), use [
instead:
> x["ed"]
ed
2
You can also use getElement
> getElement(x, "ed")
[1] 2
XMLBeans will do it. Specifically the "scomp" command.
EDIT: XMLBeans has been retired, check this stackoverflow post for more info.
This will happen if you are making selection in code as;
mSpinner.setSelection(0);
Instead of above statement use
mSpinner.setSelection(0,false);//just simply do not animate it.
Edit: This method doesn't work for Mi Android Version Mi UI.
@Scripts.Render("~/favicon.ico"); Please try above code at the bottom of your Layout file in MVC
Check the settings of the browser proxy . For me it helped , traffic was directed outside.
If your python >= 3.6, F-string formatted literal is your new friend.
It's more simple, clean, and better performance.
In [1]: params=['Hello', 'adam', 42]
In [2]: %timeit "%s %s, the answer to everything is %d."%(params[0],params[1],params[2])
448 ns ± 1.48 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [3]: %timeit "{} {}, the answer to everything is {}.".format(*params)
449 ns ± 1.42 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [4]: %timeit f"{params[0]} {params[1]}, the answer to everything is {params[2]}."
12.7 ns ± 0.0129 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
That's because you created a Web Site instead of a Web Application. The cs/vb
files can only be seen in a Web Application, but in a website you can't have a separate cs/vb
file.
Edit: In the website you can add a cs file behavior like..
<%@ Application CodeFile="Global.asax.cs" Inherits="ApplicationName.MyApplication" Language="C#" %>
~/Global.asax.cs:
namespace ApplicationName
{
public partial class MyApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
}
}
}
If the input value gets populated by a script that has some latency involved (e.g. AJAX call) then you need to wait until the input has been populated. E.g.
var w = new WebDriverWait(WebBrowser, TimeSpan.FromSeconds(10));
w.Until((d) => {
// Wait until the input has a value...
var elements = d.FindElements(By.Name(name));
var ele = elements.SingleOrDefault();
if (ele != null)
{
// Found a single element
if (ele.GetAttribute("value") != "")
{
// We have a value now
return true;
}
}
return false;
});
var e = WebBrowser.Current.FindElement(By.Name(name));
if (e.GetAttribute("value") != value)
{
Assert.Fail("Result contains a field named '{0}', but its value is '{1}', not '{2}' as expected", name, e.GetAttribute("value"), value);
}
You can use git for exactly this purpose. Basically, you create a git repository in folder A
(the repo is in A/.git
), then copy A/.git
to B/.git
, then change to B
folder and compare simply by running git diff.
And the --exclude
functionality can be achieved with .gitignore
.
So, sticking to your example (but using bash shell on Linux):
# Create a Git repo in current_vss
pushd current_vss
printf ".svn\n*.vspscc\n*.scc" >> .gitignore
git init && git add . && git commit -m 'initial'
popd
# Copy the repo to current_svn and compare
cp -r current_vss/.git* current_svn/
pushd current_svn
git diff
Add the css:
html,body{
height:100%;
}
.bg-img {
background: url(image.jpg) no-repeat center top;
background-size: cover;
height:100%;
}
And html is:
<div class="bg-mg"></div>
CSS: stretching background image to 100% width and height of screen?
The Location directive system is
Like you want to forward all request which start /static
and your data present in /var/www/static
So a simple method is separated last folder from full path , that means
Full path : /var/www/static
Last Path : /static
and First path : /var/www
location <lastPath> {
root <FirstPath>;
}
So lets see what you did mistake and what is your solutions
Your Mistake :
location /static {
root /web/test.example.com/static;
}
Your Solutions :
location /static {
root /web/test.example.com;
}
This way you can Create NSArray, NSMutableArray.
NSArray keys =[NSArray arrayWithObjects:@"key1",@"key2",@"key3",nil];
NSArray objects =[NSArray arrayWithObjects:@"value1",@"value2",@"value3",nil];
Note that %in%
returns a logical vector of TRUE
and FALSE
. To negate it, you can use !
in front of the logical statement:
SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean,
!where_case_travelled_1 %in%
c('Outside Canada','Outside province/territory of residence but within Canada'))
Regarding your original approach with -c(...)
, -
is a unary operator that "performs arithmetic on numeric or complex vectors (or objects which can be coerced to them)" (from help("-")
). Since you are dealing with a character vector that cannot be coerced to numeric or complex, you cannot use -
.
Just press windows button and type %APPDATA% and type enter.
Above is the location where you can find \npm\node_modules folder. This is where global modules sit in your system.
Now , l meet a issue like this. It happens to decode picture. The process of decode takes too much time that the screen keep black. l add a time controler: when the time is too long, then pop up from the current Thread. The following is the diff:
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Bitmap> future = executor.submit(new Callable<Bitmap>() {
@Override
public Bitmap call() throws Exception {
Bitmap bitmap = decodeAndScaleBitmapFromStream(context, inputUri);// do some time consuming operation
return null;
}
});
try {
Bitmap result = future.get(1, TimeUnit.SECONDS);
} catch (TimeoutException e){
future.cancel(true);
}
executor.shutdown();
return (bitmap!= null);
You can't define a static property on an interface in TypeScript.
Say you wanted to change the Date
object, rather than trying to add to the definitions of Date
, you could wrap it, or simply create your rich date class to do the stuff that Date
doesn't do.
class RichDate {
public static MinValue = new Date();
}
Because Date is an interface in TypeScript, you can't extend it with a class using the extends
keyword, which is a bit of a shame as this would be a good solution if date was a class.
If you want to extend the Date object to provide a MinValue
property on the prototype, you can:
interface Date {
MinValue: Date;
}
Date.prototype.MinValue = new Date(0);
Called using:
var x = new Date();
console.log(x.MinValue);
And if you want to make it available without an instance, you also can... but it is a bit fussy.
interface DateStatic extends Date {
MinValue: Date;
}
Date['MinValue'] = new Date(0);
Called using:
var x: DateStatic = <any>Date; // We aren't using an instance
console.log(x.MinValue);
If you want to change your default shell to bash
for all projects on Jenkins, you can do so in the Jenkins config through the web portal:
Manage Jenkins > Configure System (Skip this clicking if you want by just going to https://{YOUR_JENKINS_URL}/configure
.)
Fill in the field marked 'Shell executable' with the value /bin/bash
and click 'Save'.
It depends on how your $('site-header') is constructed.
You can try to use $timeout with 0 delay. Something like:
return function(scope, element, attrs) {
$timeout(function(){
$('.main').height( $('.site-header').height() - $('.site-footer').height() );
});
}
Explanations how it works: one, two.
Don't forget to inject $timeout
in your directive:
.directive('sticky', function($timeout)
In my case the /var/www/html in not a directory but a symbolic link to the /var/app/current, so you should change the real directoy ie /var/app/current:
sudo chown -R ec2-user /var/app/current
sudo chmod -R 755 /var/app/current
I hope this save some of your times :)
Suppose the data is in the B column, write in the C column the formula:
=SUBSTITUTE(B1," ","")
Copy&Paste the formula in the whole C column.
edit: using commas or semicolons as parameters separator depends on your regional settings (I have to use the semicolons). This is weird I think. Thanks to @tocallaghan and @pablete for pointing this out.
If you cannot modify your php.ini configuration, you could as well use the following snippet at the beginning of your code:
date_default_timezone_set('Africa/Lagos');//or change to whatever timezone you want
The list of timezones can be found at http://www.php.net/manual/en/timezones.php.
you can use this simple way
<select onchange="location = this.value;">
<option value="/finished">Finished</option>
<option value="/break">Break</option>
<option value="/issue">Issues</option>
<option value="/downtime">Downtime</option>
</select>
will redirect to route url you can direct to .html page or direct to some link just change value
in option.
My issue was my SVN permissions.
I had the same problem "Access to '/svn/[my path]/!svn/me' forbidden" when trying to commit files to a project I had been working on daily for several months. After trying the steps above, I could not resolve the issue. I also tried pulling the project down from scratch, logging in/out of SVN, etc. Finally I contacted my company's IT department and there was a permissions issue that spontaneously emerged which changed my access from read/write to read-only access. The IT department refreshed my permissions and this solved the problem.
This is my .env mail settings
MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=hello27
MAIL_ENCRYPTION=tls
i was getting thesame error as stated in the question but by using
php artisan config:cache
Everything worked fine
Step 1 :Inject following code in class
@Autowired
private ApplicationContext _applicationContext;
Step 2 : Write Getter & Setter
Step 3: define autowire="byType" in xml file in which bean is defined
Your purpose can be solved using following query -
Select Value , Substring(FullName, 1,Charindex(',', FullName)-1) as Name,
Substring(FullName, Charindex(',', FullName)+1, LEN(FullName)) as Surname
from Table1
There is no readymade Split function in sql server, so we need to create user defined function.
CREATE FUNCTION Split (
@InputString VARCHAR(8000),
@Delimiter VARCHAR(50)
)
RETURNS @Items TABLE (
Item VARCHAR(8000)
)
AS
BEGIN
IF @Delimiter = ' '
BEGIN
SET @Delimiter = ','
SET @InputString = REPLACE(@InputString, ' ', @Delimiter)
END
IF (@Delimiter IS NULL OR @Delimiter = '')
SET @Delimiter = ','
--INSERT INTO @Items VALUES (@Delimiter) -- Diagnostic
--INSERT INTO @Items VALUES (@InputString) -- Diagnostic
DECLARE @Item VARCHAR(8000)
DECLARE @ItemList VARCHAR(8000)
DECLARE @DelimIndex INT
SET @ItemList = @InputString
SET @DelimIndex = CHARINDEX(@Delimiter, @ItemList, 0)
WHILE (@DelimIndex != 0)
BEGIN
SET @Item = SUBSTRING(@ItemList, 0, @DelimIndex)
INSERT INTO @Items VALUES (@Item)
-- Set @ItemList = @ItemList minus one less item
SET @ItemList = SUBSTRING(@ItemList, @DelimIndex+1, LEN(@ItemList)-@DelimIndex)
SET @DelimIndex = CHARINDEX(@Delimiter, @ItemList, 0)
END -- End WHILE
IF @Item IS NOT NULL -- At least one delimiter was encountered in @InputString
BEGIN
SET @Item = @ItemList
INSERT INTO @Items VALUES (@Item)
END
-- No delimiters were encountered in @InputString, so just return @InputString
ELSE INSERT INTO @Items VALUES (@InputString)
RETURN
END -- End Function
GO
---- Set Permissions
--GRANT SELECT ON Split TO UserRole1
--GRANT SELECT ON Split TO UserRole2
--GO
For any given number:
n = num;
rev = 0;
while (num > 0)
{
dig = num % 10;
rev = rev * 10 + dig;
num = num / 10;
}
If n == rev
then num
is a palindrome:
cout << "Number " << (n == rev ? "IS" : "IS NOT") << " a palindrome" << endl;
package com.test;
import java.util.Arrays;
public class Person implements Comparable {
private int age;
private Person(int age) {
super();
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Object o) {
Person other = (Person)o;
if (this == other)
return 0;
if (this.age < other.age) return 1;
else if (this.age == other.age) return 0;
else return -1;
}
public static void main(String[] args) {
Person[] arr = new Person[4];
arr[0] = new Person(50);
arr[1] = new Person(20);
arr[2] = new Person(10);
arr[3] = new Person(90);
Arrays.sort(arr);
for (int i=0; i < arr.length; i++ ) {
System.out.println(arr[i].age);
}
}
}
Here is one way of doing it.
I agree with @bortunac's solution. my.conf is mysql specific while netstat will provide you with all the listening ports.
Perhaps use both, one to confirm which is port set for mysql and the other to check that the system is listening through that port.
My client uses CentOS 6.6 and I have found the my.conf file under /etc/, so I used:
grep port /etc/my.conf
(CentOS 6.6)
Saving (w/o exception handling code):
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();
Loading (w/o exception handling code):
FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
SimpleClass simpleClass = (SimpleClass) is.readObject();
is.close();
fis.close();
As of cocoapods 1.7.2 you can use the cdn instead of github. It's blazing fast and it won't hang. :) The cdn is default from cocopods 1.8.0 onwards.
To use the CDN source in your Podfile:
If you don't have private specs:
source 'https://cdn.cocoapods.org/'
If you have private specs:
source 'https://github.com/artsy/Specs.git' - source 'https://github.com/CocoaPods/Specs.git' + source 'https://cdn.cocoapods.org/'
Doing this will break your Podfile.lock, so you are likely to need to run pod update to see the changes (be careful, this may update your Pods also).
If you have a CI setup, it is recommended to cache the new repo dir as it is very small and would save even more time. With 1.7.2 it should be located at ~/.cocoapods/repos/cocoapods- (yes, with a -), but we're looking to improve the naming in an upcoming release.
More info:
I rename the .gitconfig file as xyz.gitconfig, then git will generate a new .gitconfig file, that wokrd
Below are the steps to create a branch from trunk using TortoiseSVN in windows machine. This obviously needs TortoiseSVN client to be installed.
I would suggest adding
(?!.*pass|.*word|.*1234|.*qwer|.*asdf) exclude common passwords
I use a "do while" loop to read the output of the find command. In this example, I am matching (rather than excluding) certain patterns since there are a more limited number of pattern matches that I want than that I don't want. You could reverse the logic with a -not in front of the -iname flags:
find . -type f -iname "*.flac" -o -print0 -iname "*.mp3" -print0 -o -iname "*.wav" -print0 -o -iname "*.aac" -print0 -o -iname "*.wma" -print0 | while read -d $'\0' file; do cp -ruv "$file" "/media/wd/network_sync/music/$file"; done
I use the above to copy all music type files that are newer on my server than the files on a Western Digital TV Live Hub that I have mounted at /media/wd. I use the above because I have a lot of DVD files, mpegs, etc. that I want to exclude AND because for some reason rsync looks like it is copying, but after I look at the wd device, the files are not there despite no errors during the rsync with this command:
rsync -av --progress --exclude=*.VOB --exclude=*.avi --exclude=*.mkv --exclude=*.ts --exclude=*.mpg --exclude=*.iso --exclude=*ar --exclude=*.vob --exclude=*.BUP --exclude=*.cdi --exclude=*.ISO --exclude=*.shn --exclude=*.MPG --exclude=*.AVI --exclude=*.DAT --exclude=*.img --exclude=*.nrg --exclude=*.cdr --exclude=*.bin --exclude=*.MOV --exclude=*.goutputs* --exclude=*.flv --exclude=*.mov --exclude=*.m2ts --exclude=*.cdg --exclude=*.IFO --exclude=*.asf --exclude=*.ite /media/2TB\ Data/data/music/* /media/wd/network_sync/music/
the default encoding of a HTTP POST is ISO-8859-1.
else you have to look at the Content-Type header that will then look like
Content-Type: application/x-www-form-urlencoded ; charset=UTF-8
You can maybe declare your form with
<form enctype="application/x-www-form-urlencoded;charset=UTF-8">
or
<form accept-charset="UTF-8">
to force the encoding.
Some references :
Use NOT IN
to find where constraints are constraining:
SELECT column FROM table WHERE column NOT IN
(SELECT intended_foreign_key FROM another_table)
so, more specifically:
SELECT sourcecode_id FROM sourcecodes_tags WHERE sourcecode_id NOT IN
(SELECT id FROM sourcecodes)
EDIT: IN
and NOT IN
operators are known to be much faster than the JOIN
operators, as well as much easier to construct, and repeat.
You should use > or < and == here. So the solution would be:
list.sort(function(item1, item2) {
var val1 = item1.attr,
val2 = item2.attr;
if (val1 == val2) return 0;
if (val1 > val2) return 1;
if (val1 < val2) return -1;
});
unsorted_list.sort(key=lambda x: x[3])
As Dennis says, you can't control how the browser chooses to handle target=_blank.
If you're wondering about the inconsistent behavior, probably it's pop-up blocking. Many browsers will forbid new windows from being opened apropos of nothing, but will allow new windows to be spawned as the eventual result of a mouse-click event.
CSS Cursor:Pointer;
is a great solution. FastClick https://github.com/ftlabs/fastclick is another solution which doesn't require you to change css if you didn't want Cursor:Pointer;
on an element for some reason. I use fastclick now anyway to eliminate the 300ms delay on iOS devices.
Write down this and try to import pandas again!
import sys
!{sys.executable} -m pip install pandas
It worked for me, hope will work for you too.
Here is an example of iterating over a pd.DataFrame
grouped by the column atable
. For this sample, "create" statements for an SQL database are generated within the for
loop:
import pandas as pd
df1 = pd.DataFrame({
'atable': ['Users', 'Users', 'Domains', 'Domains', 'Locks'],
'column': ['col_1', 'col_2', 'col_a', 'col_b', 'col'],
'column_type':['varchar', 'varchar', 'int', 'varchar', 'varchar'],
'is_null': ['No', 'No', 'Yes', 'No', 'Yes'],
})
df1_grouped = df1.groupby('atable')
# iterate over each group
for group_name, df_group in df1_grouped:
print('\nCREATE TABLE {}('.format(group_name))
for row_index, row in df_group.iterrows():
col = row['column']
column_type = row['column_type']
is_null = 'NOT NULL' if row['is_null'] == 'NO' else ''
print('\t{} {} {},'.format(col, column_type, is_null))
print(");")
Here is another solution using only matplotlib.pyplot
and numpy
packages.
It works only for Gaussian fitting. It is based on maximum likelihood estimation and have already been mentioned in this topic.
Here is the corresponding code :
# Python version : 2.7.9
from __future__ import division
import numpy as np
from matplotlib import pyplot as plt
# For the explanation, I simulate the data :
N=1000
data = np.random.randn(N)
# But in reality, you would read data from file, for example with :
#data = np.loadtxt("data.txt")
# Empirical average and variance are computed
avg = np.mean(data)
var = np.var(data)
# From that, we know the shape of the fitted Gaussian.
pdf_x = np.linspace(np.min(data),np.max(data),100)
pdf_y = 1.0/np.sqrt(2*np.pi*var)*np.exp(-0.5*(pdf_x-avg)**2/var)
# Then we plot :
plt.figure()
plt.hist(data,30,normed=True)
plt.plot(pdf_x,pdf_y,'k--')
plt.legend(("Fit","Data"),"best")
plt.show()
and here is the output.
Nesting Text components is not possible now, but you can wrap your text in a View like this:
<View style={{flexDirection: 'row', flexWrap: 'wrap'}}>
<Text>
{'Hello '}
</Text>
<Text style={{fontWeight: 'bold'}}>
{'this is a bold text '}
</Text>
<Text>
and this is not
</Text>
</View>
I used the strings inside the brackets to force the space between words, but you can also achieve it with marginRight or marginLeft. Hope it helps.
Is this what you are after? Just index the element and assign a new value.
A[2,1]=150
A
Out[345]:
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 150, 11, 12],
[13, 14, 15, 16]])
This will remove all the whitespaces from your String,
VAR2="${VAR2//[[:space:]]/}"
/
replaces the first occurrence and //
all occurrences of whitespaces in the string. I.e. all white spaces get replaced by – nothing
In theory, according to RFC 4329, application/javascript
.
The reason it is supposed to be application
is not anything to do with whether the type is readable or executable. It's because there are custom charset-determination mechanisms laid down by the language/type itself, rather than just the generic charset
parameter. A subtype of text
should be capable of being transcoded by a proxy to another charset, changing the charset parameter. This is not true of JavaScript because:
a. the RFC says user-agents should be doing BOM-sniffing on the script to determine type (I'm not sure if any browsers actually do this though);
b. browsers use other information—the including page's encoding and in some browsers the script charset
attribute—to determine the charset. So any proxy that tried to transcode the resource would break its users. (Of course in reality no-one ever uses transcoding proxies anyway, but that was the intent.)
Therefore the exact bytes of the file must be preserved exactly, which makes it a binary application
type and not technically character-based text
.
For the same reason, application/xml
is officially preferred over text/xml
: XML has its own in-band charset signalling mechanisms. And everyone ignores application
for XML, too.
text/javascript
and text/xml
may not be the official Right Thing, but there are what everyone uses today for compatibility reasons, and the reasons why they're not the right thing are practically speaking completely unimportant.
Evaluation of main answers with a performance benchmark which confirms concerns that the current chosen answer makes costly regex operations under the hood
To date the provided answers come in 3 main styles (ignoring the JavaScript answer ;) ):
In terms of code size clearly the String.replace is the most terse. The simple Java implementation is slightly smaller and cleaner (IMHO) than the Lambda (don't get me wrong - I use Lambdas often where they are appropriate)
Execution speed was, in order of fastest to slowest: simple Java implementation, Lambda and then String.replace() (that invokes regex).
By far the fastest implementation was the simple Java implementation tuned so that it preallocates the StringBuilder buffer to the max possible result length and then simply appends chars to the buffer that are not in the "chars to delete" string. This avoids any reallocates that would occur for Strings > 16 chars in length (the default allocation for StringBuilder) and it avoids the "slide left" performance hit of deleting characters from a copy of the string that occurs is the Lambda implementation.
The code below runs a simple benchmark test, running each implementation 1,000,000 times and logs the elapsed time.
The exact results vary with each run but the order of performance never changes:
Start simple Java implementation
Time: 157 ms
Start Lambda implementation
Time: 253 ms
Start String.replace implementation
Time: 634 ms
The Lambda implementation (as copied from Kaplan's answer) may be slower because it performs a "shift left by one" of all characters to the right of the character being deleted. This would obviously get worse for longer strings with lots of characters requiring deletion. Also there might be some overhead in the Lambda implementation itself.
The String.replace implementation, uses regex and does a regex "compile" at each call. An optimization of this would be to use regex directly and cache the compiled pattern to avoid the cost of compiling it each time.
package com.sample;
import java.util.function.BiFunction;
import java.util.stream.IntStream;
public class Main {
static public String deleteCharsSimple(String fromString, String charsToDelete)
{
StringBuilder buf = new StringBuilder(fromString.length()); // Preallocate to max possible result length
for(int i = 0; i < fromString.length(); i++)
if (charsToDelete.indexOf(fromString.charAt(i)) < 0)
buf.append(fromString.charAt(i)); // char not in chars to delete so add it
return buf.toString();
}
static public String deleteCharsLambda(String fromString1, String charsToDelete)
{
BiFunction<String, String, String> deleteChars = (fromString, chars) -> {
StringBuilder buf = new StringBuilder(fromString);
IntStream.range(0, buf.length()).forEach(i -> {
while (i < buf.length() && chars.indexOf(buf.charAt(i)) >= 0)
buf.deleteCharAt(i);
});
return (buf.toString());
};
return deleteChars.apply(fromString1, charsToDelete);
}
static public String deleteCharsReplace(String fromString, String charsToDelete)
{
return fromString.replace(charsToDelete, "");
}
public static void main(String[] args)
{
String str = "XXXTextX XXto modifyX";
String charsToDelete = "X"; // Should only be one char as per OP's requirement
long start, end;
System.out.println("Start simple");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++)
deleteCharsSimple(str, charsToDelete);
end = System.currentTimeMillis();
System.out.println("Time: " + (end - start));
System.out.println("Start lambda");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++)
deleteCharsLambda(str, charsToDelete);
end = System.currentTimeMillis();
System.out.println("Time: " + (end - start));
System.out.println("Start replace");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++)
deleteCharsReplace(str, charsToDelete);
end = System.currentTimeMillis();
System.out.println("Time: " + (end - start));
}
}
There might be some edge case where you have a vector access inside an inline function inside an inline function, where you've gone beyond what the compiler will inline and it will force a function call. That would be so rare as to not be worth worrying about - in general I would agree with litb.
I'm surprised nobody has mentioned this yet - don't worry about performance until it has been proven to be a problem, then benchmark.
Here is the full working code to download all files (with wildcard or file extension) from the FTP site to local directory. Set the variable values.
#FTP Server Information - SET VARIABLES
$ftp = "ftp://XXX.com/"
$user = 'UserName'
$pass = 'Password'
$folder = 'FTP_Folder'
$target = "C:\Folder\Folder1\"
#SET CREDENTIALS
$credentials = new-object System.Net.NetworkCredential($user, $pass)
function Get-FtpDir ($url,$credentials) {
$request = [Net.WebRequest]::Create($url)
$request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory
if ($credentials) { $request.Credentials = $credentials }
$response = $request.GetResponse()
$reader = New-Object IO.StreamReader $response.GetResponseStream()
while(-not $reader.EndOfStream) {
$reader.ReadLine()
}
#$reader.ReadToEnd()
$reader.Close()
$response.Close()
}
#SET FOLDER PATH
$folderPath= $ftp + "/" + $folder + "/"
$files = Get-FTPDir -url $folderPath -credentials $credentials
$files
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
$counter = 0
foreach ($file in ($files | where {$_ -like "*.txt"})){
$source=$folderPath + $file
$destination = $target + $file
$webclient.DownloadFile($source, $target+$file)
#PRINT FILE NAME AND COUNTER
$counter++
$counter
$source
}
Use the Wait method:
Application.Wait Now + #0:00:01#
or (for Excel 2010 and later):
Application.Wait Now + #12:00:01 AM#
I would use the "Responsive Design View" available under Tools -> Web Developer -> Responsive Design View. It will let you test your CSS against different screen sizes.
When it says that, just open the shell and do git status
. That will give you a decent idea of what could be wrong and the state of your repo.
I can't give you a specific error for this as it happens for many reasons in Github for Windows, like say some problem in updating submodules etc.
You need to make sure if package.json file exist in app folder. i run into same problem differently but solution would be same
Run this command where "package.json" file exist. even i experience similar problem then i change the folder and got resolve it. for more explanation i run c:\selfPractice> npm start whereas my package.json resides in c:\selfPractice\frontend> then i change the folder and run c:\selfPractice\frontend> npm start and it got run
Press Ctrl+,
Then you will see a docked window under name of "Go to all"
This a picture of the "Go to all" in my IDE
This is not possible from HTML on. The closest what you can get is the accept-charset
attribute of the <form>
. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type
header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.
To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding
attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).
Update:
Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type
header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.
http://www.example.com/some/path/to/resource?param1=value1
The part before the question mark must use % encoding (so %20
for space), after the question mark you can use either %20
or +
for a space. If you need an actual +
after the question mark use %2B
.
Use the BigInteger
class that is a part of the Java library.
http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigInteger.html
You can insert script to HTML like in any other (non-PHP) page, PHP processes it like any other code:
<button id="butt">
? Click ME! ?
</button>
<script>
document.getElementById("butt").onclick = function () {
alert("Message");
}
</script>
You can use onSOMETHING
attributes:
<button onclick="alert('Message')">Button</button>
To generate message in PHP, use json_encode
function (it can convert to JavaScript everything that can be expressed in JSON — arrays, objects, strings, …):
<?php $message = "Your message variable"; ?>
<button onclick="alert(<?=htmlspecialchars(json_encode($message), ENT_QUOTES)?>)">Click me!</button>
If you generate code for <script>
tags, do NOT use htmlspecialchars
or similar function:
<?php $var = "Test string"; ?>
<button id="butt">Button</button>
<script>
document.getElementById("butt").onclick = function () {
alert(<?=json_encode($var)?>);
}
</script>
You can generate whole JavaScript files, not only JavaScript embedded into HTML. You still have to name them with .php
extension (like script.php
). Just send the correct header.
script.php
– The JavaScript file<?php header("Content-Type: application/javascript"); /* This meant the file can be used in script tag */ ?>
<?php $var = "Message"; ?>
document.getElementById("butt").onclick = function () {
alert(<?=json_encode($var)?>);
}
index.html
– Example page that uses script.php
<!doctype html>
<html lang=en>
<head>
<meta charset="utf-8">
<title>Page title</title>
</head>
<body>
<button id="butt">
BUTTON
</button>
<script src="script.js"></script>
</body>
</html>
If you are running MongoDB 3.2 or later version, you can limit the wiredTiger
cache as mentioned above.
In /etc/mongod.conf
add the wiredTiger
part
...
# Where and how to store data.
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
wiredTiger:
engineConfig:
cacheSizeGB: 1
...
This will limit the cache size to 1GB, more info in Doc
This solved the issue for me, running ubuntu 16.04
and mongoDB 3.2
PS: After changing the config, restart the mongo daemon.
$ sudo service mongod restart
# check the status
$ sudo service mongod status
i wrote a function for that below:
function getYoutubeUrlId (url) {
const urlObject = new URL(url);
let urlOrigin = urlObject.origin;
let urlPath = urlObject.pathname;
if (urlOrigin.search('youtu.be') > -1) {
return urlPath.substr(1);
}
if (urlPath.search('embed') > -1) {
// Örnegin "/embed/wCCSEol8oSc" ise "wCCSEol8oSc" return eder.
return urlPath.substr(7);
}
return urlObject.searchParams.get('v');
},
https://gist.github.com/semihkeskindev/8a4339c27203c5fabaf2824308c7868f
You should include bootstrap-datepicker.js
after bootstrap.js
and you should bind the datepicker
to your control.
$(function(){
$('.datepicker').datepicker({
format: 'mm-dd-yyyy'
});
});
Simple! Create a dummy database (say abc)
Copy all these .myd, .myi, .frm files to mysql\data\abc wherein mysql\data\ is the place where .myd, .myi, .frm for all databases are stored.
Then go to phpMyadmin, go to db abc and you find your database.
The following code worked for me:-
.nav-pills .nav-link.active, .nav-pills .show>.nav-link {
color: #fff;
background-color: rgba(0,123,255,.5);
}
Note:- This worked for me using Bootstrap 4
According to this nice FAQ there are a couple solutions.
You might also be able to escape the ampersand with the backslash character \
if you can modify the comment.
Note: You can use memset with any character.
Example:
int arr[20];
memset(arr, 'A', sizeof(arr));
Also could be partially filled
int arr[20];
memset(&arr[5], 0, 10);
But be carefull. It is not limited for the array size, you could easily cause severe damage to your program doing something like this:
int arr[20];
memset(arr, 0, 200);
It is going to work (under windows) and zero memory after your array. It might cause damage to other variables values.
1) Others (especially dirkgently) have noted that buffer needs to be allocated some memory space. For smallish values of N (say, N <= 4096), you can also allocate it on the stack:
#define BUFFER_SIZE 4096
char buffer[BUFFER_SIZE]
This saves you the worry of ensuring that you delete[]
the buffer should an exception be thrown.
But remember that stacks are finite in size (so are heaps, but stacks are finiter), so you don't want to put too much there.
2) On a -1 return code, you should not simply return immediately (throwing an exception immediately is even more sketchy.) There are certain normal conditions that you need to handle, if your code is to be anything more than a short homework assignment. For example, EAGAIN may be returned in errno if no data is currently available on a non-blocking socket. Have a look at the man page for read(2).
This workaround helped us so much at my job (Tech Support), we made a simple batch file we could run from anywhere (We didnt have the permissions to install it). This workaround will set the variable and then run OpenSSL for you. It also opens up the bin folder for you (cause this is where any files you create or modify will be saved). Also, this is only for Windows.
Copy this code to a file named StartOpenSSL.bat. Save this to a location of your choice. It can be run from anywhere.
@echo off
title OpenSSL
cd\openssl\bin
if exist "C:\openssl\share\openssl.cnf" (
set OPENSSL_CONF=c:/openssl/share/openssl.cnf
start explorer.exe c:\openssl\bin
echo Welcome to OpenSSL
openssl
) else (
echo Error: openssl.cnf was not found
echo File openssl.cnf needs to be present in c:\openssl\share
pause
)
exit
First of all you use here two strings: "" marks a string it may be ""
-empty "s"
- string of lenght 1 or "aaa"
string of lenght 3, while '' marks chars . In order to be able to do String str = "a" + "aaa" + 'a'
you must use method Character.toString(char c) as @Thomas Keene said so an example would be String str = "a" + "aaa" + Character.toString('a')
if you use EclipseLink: You should be in a JPA transaction to access the Connection
entityManager.getTransaction().begin();
java.sql.Connection connection = entityManager.unwrap(java.sql.Connection.class);
...
entityManager.getTransaction().commit();
To avoid problems of character encoding in sending emails using the class PHPMailer we can configure it to send it with UTF-8 character encoding using the "CharSet" parameter, as we can see in the following Php code:
$mail = new PHPMailer();
$mail->From = '[email protected]';
$mail->FromName = 'Mi nombre';
$mail->AddAddress('[email protected]');
$mail->Subject = 'Prueba';
$mail->Body = '';
$mail->IsHTML(true);
// Active condition utf-8
$mail->CharSet = 'UTF-8';
// Send mail
$mail->Send();
in my case this worked perfectly
<img style="border-radius: 50%;height: 50px;width: 80px;" src="<?php echo asset("storage/TeacherImages/{$studydata->teacher->profilePic}")?>">
this code is used to display image from folder
Perhaps this will work?
<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
<c:set var="myVar" value="${stat.first ? '' : myVar} ${currentItem}" />
</c:forEach>
Filenames with "jpg" and "png" extensions in "path/to/images":
import os
accepted_extensions = ["jpg", "png"]
filenames = [fn for fn in os.listdir("path/to/images") if fn.split(".")[-1] in accepted_extensions]
From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.
Usage looks like this:
using System.Linq;
// ...
public void My()
{
var myArray = new[] { "abc", "123", "zyx" };
List<string> myList = myArray.ToList();
}
PS. There's also ToArray()
method that works in other way.
Although the accepted solution is correct for iPhones, it will incorrectly declare both isiPhone
and isiPad
to be true for users visiting your site on their iPad from the Facebook app.
The conventional wisdom is that iOS devices have a user agent for Safari and a user agent for the UIWebView. This assumption is incorrect as iOS apps can and do customize their user agent. The main offender here is Facebook.
Compare these user agent strings from iOS devices:
# iOS Safari
iPad: Mozilla/5.0 (iPad; CPU OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B176 Safari/7534.48.3
iPhone: Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3
# UIWebView
iPad: Mozilla/5.0 (iPad; CPU OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/98176
iPhone: Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Mobile/8B117
# Facebook UIWebView
iPad: Mozilla/5.0 (iPad; U; CPU iPhone OS 5_1_1 like Mac OS X; en_US) AppleWebKit (KHTML, like Gecko) Mobile [FBAN/FBForIPhone;FBAV/4.1.1;FBBV/4110.0;FBDV/iPad2,1;FBMD/iPad;FBSN/iPhone OS;FBSV/5.1.1;FBSS/1; FBCR/;FBID/tablet;FBLC/en_US;FBSF/1.0]
iPhone: Mozilla/5.0 (iPhone; U; CPU iPhone OS 5_1_1 like Mac OS X; ru_RU) AppleWebKit (KHTML, like Gecko) Mobile [FBAN/FBForIPhone;FBAV/4.1;FBBV/4100.0;FBDV/iPhone3,1;FBMD/iPhone;FBSN/iPhone OS;FBSV/5.1.1;FBSS/2; tablet;FBLC/en_US]
Note that on the iPad, the Facebook UIWebView's user agent string includes 'iPhone'.
The old way to identify iPhone / iPad in JavaScript:
IS_IPAD = navigator.userAgent.match(/iPad/i) != null;
IS_IPHONE = navigator.userAgent.match(/iPhone/i) != null) || (navigator.userAgent.match(/iPod/i) != null);
If you were to go with this approach for detecting iPhone and iPad, you would end up with IS_IPHONE and IS_IPAD both being true if a user comes from Facebook on an iPad. That could create some odd behavior!
The correct way to identify iPhone / iPad in JavaScript:
IS_IPAD = navigator.userAgent.match(/iPad/i) != null;
IS_IPHONE = (navigator.userAgent.match(/iPhone/i) != null) || (navigator.userAgent.match(/iPod/i) != null);
if (IS_IPAD) {
IS_IPHONE = false;
}
We declare IS_IPHONE to be false on iPads to cover for the bizarre Facebook UIWebView iPad user agent. This is one example of how user agent sniffing is unreliable. The more iOS apps that customize their user agent, the more issues user agent sniffing will have. If you can avoid user agent sniffing (hint: CSS Media Queries), DO IT.
I had the same issue in AWS RDS. It was due to the Freeable Space (Hard Drive Storage Space) was Full. You need to increase your space, or remove some data.
I also got the following error when I run a command with PHP
, I did the solution like that:
C:\xampp\php
to your PATH Environment Variable.Very important note: restart command prompt
Use this file : "jquery.redirect.js"
$("#btn_id").click(function(){
$.redirect(http://localhost/test/test1.php,
{
user_name: "khan",
city : "Meerut",
country : "country"
});
});
});
This example will exit after 5 seconds if another instance is already running.
// unique id for global mutex - Global prefix means it is global to the machine
const string mutex_id = "Global\\{B1E7934A-F688-417f-8FCB-65C3985E9E27}";
static void Main(string[] args)
{
using (var mutex = new Mutex(false, mutex_id))
{
try
{
try
{
if (!mutex.WaitOne(TimeSpan.FromSeconds(5), false))
{
Console.WriteLine("Another instance of this program is running");
Environment.Exit(0);
}
}
catch (AbandonedMutexException)
{
// Log the fact the mutex was abandoned in another process, it will still get aquired
}
// Perform your work here.
}
finally
{
mutex.ReleaseMutex();
}
}
}
I use that construction whenever I don't want to add complexity to the problem. It's just a list, no need to say what kind of List it is, as it doesn't matter to the problem. I often use Collection for most of my solutions, as, in the end, most of the times, for the rest of the software, what really matters is the content it holds, and I don't want to add new objects to the Collection.
Futhermore, you use that construction when you think that you may want to change the implemenation of list you are using. Let's say you were using the construction with an ArrayList, and your problem wasn't thread safe. Now, you want to make it thread safe, and for part of your solution, you change to use a Vector, for example. As for the other uses of that list won't matter if it's a AraryList or a Vector, just a List, no new modifications will be needed.
"""
tcp_disconnect.py
Echo network data test program in python. This easily translates to C & Java.
A server program might want to confirm that a tcp client is still connected
before it sends a data. That is, detect if its connected without reading from socket.
This will demonstrate how to detect a TCP client disconnect without reading data.
The method to do this:
1) select on socket as poll (no wait)
2) if no recv data waiting, then client still connected
3) if recv data waiting, the read one char using PEEK flag
4) if PEEK data len=0, then client has disconnected, otherwise its connected.
Note, the peek flag will read data without removing it from tcp queue.
To see it in action: 0) run this program on one computer 1) from another computer,
connect via telnet port 12345, 2) type a line of data 3) wait to see it echo,
4) type another line, 5) disconnect quickly, 6) watch the program will detect the
disconnect and exit.
John Masinter, 17-Dec-2008
"""
import socket
import time
import select
HOST = '' # all local interfaces
PORT = 12345 # port to listen
# listen for new TCP connections
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
# accept new conneciton
conn, addr = s.accept()
print 'Connected by', addr
# loop reading/echoing, until client disconnects
try:
conn.send("Send me data, and I will echo it back after a short delay.\n")
while 1:
data = conn.recv(1024) # recv all data queued
if not data: break # client disconnected
time.sleep(3) # simulate time consuming work
# below will detect if client disconnects during sleep
r, w, e = select.select([conn], [], [], 0) # more data waiting?
print "select: r=%s w=%s e=%s" % (r,w,e) # debug output to command line
if r: # yes, data avail to read.
t = conn.recv(1024, socket.MSG_PEEK) # read without remove from queue
print "peek: len=%d, data=%s" % (len(t),t) # debug output
if len(t)==0: # length of data peeked 0?
print "Client disconnected." # client disconnected
break # quit program
conn.send("-->"+data) # echo only if still connected
finally:
conn.close()
If you're not tagetting IE6, then float the second <div>
and give it a margin equal to (or maybe a little bigger than) the first <div>
's fixed width.
HTML:
<div id="main-wrapper">
<div id="fixed-width"> lorem ipsum </div>
<div id="rest-of-space"> dolor sit amet </div>
</div>
CSS:
#main-wrapper {
100%;
background:red;
}
#fixed-width {
width:100px;
float:left
}
#rest-of-space {
margin-left:101px;
/* May have to increase depending on borders and margin of the fixd width div*/
background:blue;
}
The margin accounts for the possibility that the 'rest-of-space' <div>
may contain more content than the 'fixed-width' <div>
.
Don't give the fixed width one a background; if you need to visibly see these as different 'columns' then use the Faux Columns trick.
Multiple statements are to be separated by a new line:
If SkyIsBlue Then
StartEngines
Pollute
ElseIf SkyIsRed Then
StopAttack
Vent
ElseIf SkyIsYellow Then
If Sunset Then
Sleep
ElseIf Sunrise or IsMorning Then
Smoke
GetCoffee
Else
Error
End If
Else
Joke
Laugh
End If
Try with the fully qualified name for the resource:
private static final String FILENAME = "resources/skyscrapper";
DecimalFormat is the best ways to output, but I don't prefer it. I always do this all the time, because it return the double value. So I can use it more than just output.
Math.round(selfEvaluate*100000d.0)/100000d.0;
OR
Math.round(selfEvaluate*100000d.0)*0.00000d1;
If you need large decimal places value, you can use BigDecimal instead. Anyways .0
is important. Without it the rounding of 0.33333d5 return 0.33333 and only 9 digits are allows. The second function without .0
has problems with 0.30000 return 0.30000000000000004.
Sometimes the problem occurs if you have moved your classes around and it refers to old classes, even if they don't exist.
In this case, just do this :
mvn eclipse:clean
mvn eclipse:eclipse
This worked well for me.
You are getting NullPointerException as the "output" is null when the while loop ends. You can collect the output in some buffer and then use it, something like this-
StringBuilder buffer = new StringBuilder();
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
buffer.append(output);
}
output = buffer.toString(); // now you have the output
conn.disconnect();
From tensorflow official docs
global_step = tf.Variable(0, trainable=False)
starter_learning_rate = 0.1
learning_rate = tf.train.exponential_decay(starter_learning_rate, global_step,
100000, 0.96, staircase=True)
# Passing global_step to minimize() will increment it at each step.
learning_step = (
tf.train.GradientDescentOptimizer(learning_rate)
.minimize(...my loss..., global_step=global_step))
Simple:
if string.isalpha():
print("It's all letters")
str.isalpha()
is only true if all characters in the string are letters:
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
Demo:
>>> 'hello'.isalpha()
True
>>> '42hello'.isalpha()
False
>>> 'hel lo'.isalpha()
False
You can use stristr()
or strpos()
. Both return false if nothing is found.
You need to add uppercase L
at the end like so
long i = 12345678910L;
Same goes true for float with 3.0f
Which should answer both of your questions
You have to pass a function that accepts two parameters, compares them, and returns a number, so assuming you wanted to sort them by ID you would write...
objArray.sort(function(a,b) {
return a.id-b.id;
});
// objArray is now sorted by Id
rinohtype supports embedding PDF, PNG and JPEG images (natively) and other bitmap formats (when Pillow is installed).
(Full disclosure: I am the author of rinohtype)
Use the below code for centering the div box:
.box-content{_x000D_
margin: auto;_x000D_
top: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
position: absolute;_x000D_
width: 800px;_x000D_
height: 100px;_x000D_
background-color: green;_x000D_
}
_x000D_
<div class="box-content">_x000D_
</div>
_x000D_
Accept decimal values in text fields with single (.)dot in Swift 3
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let inverseSet = NSCharacterSet(charactersIn:"0123456789").inverted
let components = string.components(separatedBy: inverseSet)
let filtered = components.joined(separator: "")
if filtered == string {
return true
} else {
if string == "." {
let countdots = textField.text!.components(separatedBy:".").count - 1
if countdots == 0 {
return true
}else{
if countdots > 0 && string == "." {
return false
} else {
return true
}
}
}else{
return false
}
}
}
match
returns an array.
The default string representation of an array in JavaScript is the elements of the array separated by commas. In this case the desired result is in the second element of the array:
var tesst = "afskfsd33j"
var test = tesst.match(/a(.*)j/);
alert (test[1]);
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
this deletes test.blue
Have you taken a look at ExpandoObject?
From MSDN:
The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute("sampleMember").
Allowing you to do cool things like:
dynamic dynObject = new ExpandoObject();
dynObject.SomeDynamicProperty = "Hello!";
dynObject.SomeDynamicAction = (msg) =>
{
Console.WriteLine(msg);
};
dynObject.SomeDynamicAction(dynObject.SomeDynamicProperty);
Based on your actual code you may be more interested in:
public static dynamic GetDynamicObject(Dictionary<string, object> properties)
{
return new MyDynObject(properties);
}
public sealed class MyDynObject : DynamicObject
{
private readonly Dictionary<string, object> _properties;
public MyDynObject(Dictionary<string, object> properties)
{
_properties = properties;
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _properties.Keys;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (_properties.ContainsKey(binder.Name))
{
result = _properties[binder.Name];
return true;
}
else
{
result = null;
return false;
}
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (_properties.ContainsKey(binder.Name))
{
_properties[binder.Name] = value;
return true;
}
else
{
return false;
}
}
}
That way you just need:
var dyn = GetDynamicObject(new Dictionary<string, object>()
{
{"prop1", 12},
});
Console.WriteLine(dyn.prop1);
dyn.prop1 = 150;
Deriving from DynamicObject allows you to come up with your own strategy for handling these dynamic member requests, beware there be monsters here: the compiler will not be able to verify a lot of your dynamic calls and you won't get intellisense, so just keep that in mind.
I wrote a directive you can use to bind an ng-model to any expression you want. Whenever the expression changes the model is set to the new value.
module.directive('boundModel', function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ngModel) {
var boundModel$watcher = scope.$watch(attrs.boundModel, function(newValue, oldValue) {
if(newValue != oldValue) {
ngModel.$setViewValue(newValue);
ngModel.$render();
}
});
// When $destroy is fired stop watching the change.
// If you don't, and you come back on your state
// you'll have two watcher watching the same properties
scope.$on('$destroy', function() {
boundModel$watcher();
});
}
});
You can use it in your templates like this:
<li>Total<input type="text" ng-model="total" bound-model="one * two"></li>
first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
Have you tried Autodia yet? Last time I tried it it wasn't perfect, but it was good enough.
A simpler solution on recent versions of tmux (tested on 1.9) you can now do :
tmux detach -a
-a
is for all other client on this session except the current one
You can alias it in your .[bash|zsh]rc
alias takeover="tmux detach -a"
Workflow: You can connect to your session normally, and if you are bothered by another session that forced down your tmux window size you can simply call takeover
.
No. It is not possible to share the same port at a particular instant. But you can make your application such a way that it will make the port access at different instant.
Thread.interrupt() method sets internal 'interrupt status' flag. Usually that flag is checked by Thread.interrupted() method.
By convention, any method that exists via InterruptedException have to clear interrupt status flag.
Install this nuget package from Microsoft System.Net.Http.Json
. It contains extension methods.
Then add using System.Net.Http.Json
Now, you'll be able to see these methods:
So you can now do this:
await httpClient.GetFromJsonAsync<IList<WeatherForecast>>("weatherforecast");
Source: https://www.stevejgordon.co.uk/sending-and-receiving-json-using-httpclient-with-system-net-http-json
Leonid Beschastny's answer works but I also had to convert ArrayBuffer to Buffer that is used in the Node's request
module. After uploading file to the server I had it in the same format that comes from the HTML5 FileAPI (I'm using Meteor). Full code below - maybe it will be helpful for others.
function toBuffer(ab) {
var buffer = new Buffer(ab.byteLength);
var view = new Uint8Array(ab);
for (var i = 0; i < buffer.length; ++i) {
buffer[i] = view[i];
}
return buffer;
}
var req = request.post(url, function (err, resp, body) {
if (err) {
console.log('Error!');
} else {
console.log('URL: ' + body);
}
});
var form = req.form();
form.append('file', toBuffer(file.data), {
filename: file.name,
contentType: file.type
});
Delete .gradle folder(root directory) and build folder(project directory) and then invalidate caches/restart android studio, run your project again hopefully it will work. It might take some time for the background tasks. In some countries, you may need to turn on the VPN to download.
Without any additional packages:
true_Y = c(1,1,1,1,2,1,2,1,2,2)
probs = c(1,0.999,0.999,0.973,0.568,0.421,0.382,0.377,0.146,0.11)
getROC_AUC = function(probs, true_Y){
probsSort = sort(probs, decreasing = TRUE, index.return = TRUE)
val = unlist(probsSort$x)
idx = unlist(probsSort$ix)
roc_y = true_Y[idx];
stack_x = cumsum(roc_y == 2)/sum(roc_y == 2)
stack_y = cumsum(roc_y == 1)/sum(roc_y == 1)
auc = sum((stack_x[2:length(roc_y)]-stack_x[1:length(roc_y)-1])*stack_y[2:length(roc_y)])
return(list(stack_x=stack_x, stack_y=stack_y, auc=auc))
}
aList = getROC_AUC(probs, true_Y)
stack_x = unlist(aList$stack_x)
stack_y = unlist(aList$stack_y)
auc = unlist(aList$auc)
plot(stack_x, stack_y, type = "l", col = "blue", xlab = "False Positive Rate", ylab = "True Positive Rate", main = "ROC")
axis(1, seq(0.0,1.0,0.1))
axis(2, seq(0.0,1.0,0.1))
abline(h=seq(0.0,1.0,0.1), v=seq(0.0,1.0,0.1), col="gray", lty=3)
legend(0.7, 0.3, sprintf("%3.3f",auc), lty=c(1,1), lwd=c(2.5,2.5), col="blue", title = "AUC")
There is no Pair in the standard framework, but the Apache Commons Lang, which comes quite close to “standard”, has a Pair.
module Enumerable
def does_not_include?(item)
!include?(item)
end
end
Ok, but seriously, the unless works fine.
Just FYI, I had the same error and was using the correct credentials but my LDAP url was wrong :(
I got the exact same error message and code
If a
is your array:
In [11]: a[:,:2]
Out[11]:
array([[-0.57098887, -0.4274751 ],
[-0.22279713, -0.51723555],
[ 0.67492385, -0.69294472],
[ 0.41086611, 0.26374238]])
I had the same issue on Windows. I tried to update the environment variables for the path of tesseract which did not work.
What worked for me was to modify the pytesseract.py which can be found at the path C:\Program Files\Python37\Lib\site-packages\pytesseract
or usually in the C:\Users\YOUR USER\APPDATA\Python
I changed one line as per below:
#tesseract_cmd = 'tesseract'
#tesseract_cmd = 'C:\Program Files\Tesseract-OCR\\tesseract.exe'
Note I had to put an extra \
before tesseract as Python was interpreting same as \t
and you will get the below error message:
pytesseract.pytesseract.TesseractNotFoundError: C:\Program Files\Tesseract-OCR esseract.exe is not installed or it's not in your path
Note that list
and array
are different classes. You can do:
del mylist[:]
This will actually modify your existing list. David's answer creates a new list and assigns it to the same variable. Which you want depends on the situation (e.g. does any other variable have a reference to the same list?).
Try:
a = [1,2]
b = a
a = []
and
a = [1,2]
b = a
del a[:]
Print a
and b
each time to see the difference.
QT can be as simple as that of Windows. The equivalent code is
if (QMessageBox::Yes == QMessageBox(QMessageBox::Information, "title", "Question", QMessageBox::Yes|QMessageBox::No).exec())
{
}
If you are using node.js, you can use unique-random-array. It simply picks something random from an array.
The problem in your code is that you can't store the memory address of a local variable (local to a function, for example) in a globlar variable:
RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);
There, &rect
is a temporary address (stored in the function's activation registry) and will be destroyed when that function end.
The code should create a dynamic variable:
RectInvoice *rect = new RectInvoice(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(rect);
There you are using a heap address that will not be destroyed in the end of the function's execution. Tell me if it worked for you.
Cheers
<div class="col-md-3 col-sm-3">
<label>Outlet Ready</label>
<div>
<select class="form-control"
[(ngModel)]="selectedColor">
<option *ngFor="let x of colours" [ngValue]="x" >{{x.name}}</option>
</select>
</div>
</div>
Compoent.ts
import { Component, OnInit } from '@angular/core';
import {AbstractControl,FORM_DIRECTIVES } from '@angular/common';
@Component({
selector:'dropdown',
templateUrl:'app/components/dropdown/dropdown.component.html',
directives:[FORM_DIRECTIVES]
})
export class DropdownComponent implements OnInit
{
car:Car;
colours: Array<Colour>;
ngOnInit(): void {
this.colours = Array<Colour>();
this.colours.push(new Colour(-1, 'Please select'));
this.colours.push(new Colour(1, 'Green'));
this.colours.push(new Colour(2, 'Pink'));
this.car = new Car();
this.car.colour = this.colours[1];
}
}
export class Car
{
colour:Colour;
}
export class Colour
{
constructor(id:number, name:string) {
this.id=id;
this.name=name;
}
id:number;
name:string;
this is working fine...:)
I think If you are going to store large amount of data in local storage you can use sqflite library. It is very easy to setup and I have personally used for some test project and it works fine.
https://github.com/tekartik/sqflite This a tutorial - https://proandroiddev.com/flutter-bookshelf-app-part-2-personal-notes-and-database-integration-a3b47a84c57
If you want to store data in cloud you can use firebase. It is solid service provide by google.
For others landing here. This is what worked for me:
//jquery polyfill for showing place holders in IE9
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
Just add this in you script.js file. Courtesy of http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
A quick update to Michael's excellent answer above.
For Rails 4.0+ you need to put your sort in a block like this:
class Book < ActiveRecord::Base
default_scope { order('created_at DESC') }
end
Notice that the order statement is placed in a block denoted by the curly braces.
They changed it because it was too easy to pass in something dynamic (like the current time). This removes the problem because the block is evaluated at runtime. If you don't use a block you'll get this error:
Support for calling #default_scope without a block is removed. For example instead of
default_scope where(color: 'red')
, please usedefault_scope { where(color: 'red') }
. (Alternatively you can just redefine self.default_scope.)
As @Dan mentions in his comment below, you can do a more rubyish syntax like this:
class Book < ActiveRecord::Base
default_scope { order(created_at: :desc) }
end
or with multiple columns:
class Book < ActiveRecord::Base
default_scope { order({begin_date: :desc}, :name) }
end
Thanks @Dan!
Since java.sql.Date
extends java.util.Date
, you should be able to do
java.util.Date newDate = result.getDate("VALUEDATE");
It is whatever member of the enumeration represents the value 0
. Specifically, from the documentation:
The default value of an
enum E
is the value produced by the expression(E)0
.
As an example, take the following enum:
enum E
{
Foo, Bar, Baz, Quux
}
Without overriding the default values, printing default(E)
returns Foo
since it's the first-occurring element.
However, it is not always the case that 0
of an enum is represented by the first member. For example, if you do this:
enum F
{
// Give each element a custom value
Foo = 1, Bar = 2, Baz = 3, Quux = 0
}
Printing default(F)
will give you Quux
, not Foo
.
If none of the elements in an enum G
correspond to 0
:
enum G
{
Foo = 1, Bar = 2, Baz = 3, Quux = 4
}
default(G)
returns literally 0
, although its type remains as G
(as quoted by the docs above, a cast to the given enum type).
I was looking to do the same thing, but to preserve the list as a just an array of strings so I wrote a new code, which from what I've been reading may not be the most efficient but worked for what i needed to do:
combineListsAsOne <-function(list1, list2){
n <- c()
for(x in list1){
n<-c(n, x)
}
for(y in list2){
n<-c(n, y)
}
return(n)
}
It just creates a new list and adds items from two supplied lists to create one.
I know it's for a long time ago but may be helpful to any other new comers,
I decided to pass user name,password and domain while requesting SSRS reports, so I created one class which implements IReportServerCredentials.
public class ReportServerCredentials : IReportServerCredentials
{
#region Class Members
private string username;
private string password;
private string domain;
#endregion
#region Constructor
public ReportServerCredentials()
{}
public ReportServerCredentials(string username)
{
this.Username = username;
}
public ReportServerCredentials(string username, string password)
{
this.Username = username;
this.Password = password;
}
public ReportServerCredentials(string username, string password, string domain)
{
this.Username = username;
this.Password = password;
this.Domain = domain;
}
#endregion
#region Properties
public string Username
{
get { return this.username; }
set { this.username = value; }
}
public string Password
{
get { return this.password; }
set { this.password = value; }
}
public string Domain
{
get { return this.domain; }
set { this.domain = value; }
}
public WindowsIdentity ImpersonationUser
{
get { return null; }
}
public ICredentials NetworkCredentials
{
get
{
return new NetworkCredential(Username, Password, Domain);
}
}
#endregion
bool IReportServerCredentials.GetFormsCredentials(out System.Net.Cookie authCookie, out string userName, out string password, out string authority)
{
authCookie = null;
userName = password = authority = null;
return false;
}
}
while calling SSRS Reprots, put following piece of code
ReportViewer rptViewer = new ReportViewer();
string RptUserName = Convert.ToString(ConfigurationManager.AppSettings["SSRSReportUser"]);
string RptUserPassword = Convert.ToString(ConfigurationManager.AppSettings["SSRSReportUserPassword"]);
string RptUserDomain = Convert.ToString(ConfigurationManager.AppSettings["SSRSReportUserDomain"]);
string SSRSReportURL = Convert.ToString(ConfigurationManager.AppSettings["SSRSReportURL"]);
string SSRSReportFolder = Convert.ToString(ConfigurationManager.AppSettings["SSRSReportFolder"]);
IReportServerCredentials reportCredentials = new ReportServerCredentials(RptUserName, RptUserPassword, RptUserDomain);
rptViewer.ServerReport.ReportServerCredentials = reportCredentials;
rptViewer.ServerReport.ReportServerUrl = new Uri(SSRSReportURL);
SSRSReportUser,SSRSReportUserPassword,SSRSReportUserDomain,SSRSReportFolder are defined in web.config files.
but watch out for this....
Long nullLong = null;
preparedStatement.setLong( nullLong );
-thows null pointer exception-
because the protype is
setLong( long )
NOT
setLong( Long )
nice one to catch you out eh.
Go to this link
Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download
Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.
Every variable or field of a primitive value type or structure type holds a unique instance of that type, including all its fields (public and private). By contrast, variables or fields of reference types may hold null, or may refer to an object, stored elsewhere, to which any number of other references may also exist. The fields of a struct will be stored in the same place as the variable or field of that structure type, which may be either on the stack or may be part of another heap object.
Creating a variable or field of a primitive value type will create it with a default value; creating a variable or field of a structure type will create a new instance, creating all fields therein in the default manner. Creating a new instance of a reference type will start by creating all fields therein in the default manner, and then running optional additional code depending upon the type.
Copying one variable or field of a primitive type to another will copy the value. Copying one variable or field of structure type to another will copy all the fields (public and private) of the former instance to the latter instance. Copying one variable or field of reference type to another will cause the latter to refer to the same instance as the former (if any).
It's important to note that in some languages like C++, the semantic behavior of a type is independent of how it is stored, but that isn't true of .NET. If a type implements mutable value semantics, copying one variable of that type to another copies the properties of the first to another instance, referred to by the second, and using a member of the second to mutate it will cause that second instance to be changed, but not the first. If a type implements mutable reference semantics, copying one variable to another and using a member of the second to mutate the object will affect the object referred to by the first variable; types with immutable semantics do not allow mutation, so it doesn't matter semantically whether copying creates a new instance or creates another reference to the first.
In .NET, it is possible for value types to implement any of the above semantics, provided that all of their fields can do likewise. A reference type, however, can only implement mutable reference semantics or immutable semantics; value types with fields of mutable reference types are limited to either implementing mutable reference semantics or weird hybrid semantics.
Sometimes you will like to receive as argument a Parent reference and inside you probably want to do something specific of a child.
abstract class Animal{
public abstract void move();
}
class Shark extends Animal{
public void move(){
swim();
}
public void swim(){}
public void bite(){}
}
class Dog extends Animal{
public void move(){
run();
}
public void run(){}
public void bark(){}
}
...
void somethingSpecific(Animal animal){
// Here you don't know and may don't care which animal enters
animal.move(); // You can call parent methods but you can't call bark or bite.
if(animal instanceof Shark){
Shark shark = (Shark)animal;
shark.bite(); // Now you can call bite!
}
//doSomethingSharky(animal); // You cannot call this method.
}
...
In above's method you can pass either Shark or Dog, but what if you have something like this:
void doSomethingSharky(Shark shark){
//Here you cannot receive an Animal reference
}
That method can only be called by passing shark references So if you have an Animal (and it is deeply a Shark) you can call it like this:
Animal animal...
doSomethingSharky((Shark) animal)
Bottom line, you can use Parent references and it is usually better when you don't care about the implementation of the parent and use casting to use the Child as an specific object, it will be exactly the same object, but your reference know it, if you don't cast it, your reference will point to the same object but cannot be sure what kind of Animal would it be, therefore will only allow you to call known methods.
I had the same problem when setting the center of the map with map.setCenter()
. Using Number()
solved for me. Had to use parseFloat
to truncate the data.
code snippet:
var centerLat = parseFloat(data.lat).toFixed(0);
var centerLng = parseFloat(data.long).toFixed(0);
map.setCenter({
lat: Number(centerLat),
lng: Number(centerLng)
});
The children of a row-flexbox container automatically fill the container's vertical space.
Specify flex: 1;
for a child if you want it to fill the remaining horizontal space:
.wrapper {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
align-items: stretch;_x000D_
width: 100%;_x000D_
height: 5em;_x000D_
background: #ccc;_x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
background: #ccf;_x000D_
flex: 1; _x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="left">Left</div>_x000D_
<div class="right">Right</div>_x000D_
</div>
_x000D_
flex: 1;
for both children if you want them to fill equal amounts of the horizontal space: .wrapper {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
align-items: stretch;_x000D_
width: 100%;_x000D_
height: 5em;_x000D_
background: #ccc;_x000D_
}_x000D_
.wrapper > div _x000D_
{_x000D_
flex: 1; _x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
background: #ccf;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="left">Left</div>_x000D_
<div class="right">Right</div>_x000D_
</div>
_x000D_
Warning: Note that English is not restricted to just A-Z.
Try this to remove everything except a-z, A-Z and 0-9:
$result = preg_replace("/[^a-zA-Z0-9]+/", "", $s);
If your definition of alphanumeric includes letters in foreign languages and obsolete scripts then you will need to use the Unicode character classes.
Try this to leave only A-Z:
$result = preg_replace("/[^A-Z]+/", "", $s);
The reason for the warning is that words like résumé contains the letter é
that won't be matched by this. If you want to match a specific list of letters adjust the regular expression to include those letters. If you want to match all letters, use the appropriate character classes as mentioned in the comments.
SUBSTRING(str_col, PATINDEX('%[^0]%', str_col+'.'), LEN(str_col))
You can use Javascript to get the viewport width and height. Then pass the values back via a hidden form input or ajax.
var width = $(window).width();
var height = $(window).height();
Assuming you have: JQuery framework.
First, add these hidden form inputs to store the width and height until postback.
<asp:HiddenField ID="width" runat="server" />
<asp:HiddenField ID="height" runat="server" />
Next we want to get the window (viewport) width and height. JQuery has two methods for this, aptly named width() and height().
Add the following code to your .aspx file within the head element.
<script type="text/javascript">
$(document).ready(function() {
$("#width").val() = $(window).width();
$("#height").val() = $(window).height();
});
</script>
Result
This will result in the width and height of the browser window being available on postback. Just access the hidden form inputs like this:
var TheBrowserWidth = width.Value;
var TheBrowserHeight = height.Value;
This method provides the height and width upon postback, but not on the intial page load.
Note on UpdatePanels: If you are posting back via UpdatePanels, I believe the hidden inputs need to be within the UpdatePanel.
Alternatively you can post back the values via an ajax call. This is useful if you want to react to window resizing.
Update for jquery 3.1.1
I had to change the JavaScript to:
$("#width").val($(window).width());
$("#height").val($(window).height());
Just to add onto the already great answers, you might want to add multiple labels in your project so doing all of this (setting size, style etc) will be a pain. To solve this, you can create a separate UILabel class.
import UIKit
class MyLabel: UILabel {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeLabel()
}
override init(frame: CGRect) {
super.init(frame: frame)
initializeLabel()
}
func initializeLabel() {
self.textAlignment = .left
self.font = UIFont(name: "Halvetica", size: 17)
self.textColor = UIColor.white
}
}
To use it, do the following
import UIKit
class ViewController: UIViewController {
var myLabel: MyLabel()
override func viewDidLoad() {
super.viewDidLoad()
myLabel = MyLabel(frame: CGRect(x: self.view.frame.size.width / 2, y: self.view.frame.size.height / 2, width: 100, height: 20))
self.view.addSubView(myLabel)
}
}
Simply put: a recursive function is a function that calls itself.
since xcode5 organizer no longer team section exists. but the bold sentence was the answer for me. God thanks there is another mac to restore and import to problemmatic mac. now all is ok.
If you downloaded bootstrap, go to bootstrap-4.4.1-dist/css/bootstrap.min.css
find the .navbar-light .navbar-toggler-icon
or the .navbar-dark .navbar-toggler-icon
selector
select the background-image
attribute and its value. The snippet looks like this:
.navbar-light .navbar-toggler-icon {
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='30' height='30' viewBox='0 0 30 30'%3e%3cpath stroke='rgba(0, 0, 0, 0.5)' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e");
}
copy the snippet and paste it in your custom CSS
change the stroke='rgba(0, 0, 0, 0.5)'
value to your preferred rgba value
From Spring's AnnotationTransactionAspect
:
/**
* Matches the execution of any public method in a type with the Transactional
* annotation, or any subtype of a type with the Transactional annotation.
*/
private pointcut executionOfAnyPublicMethodInAtTransactionalType() :
execution(public * ((@Transactional *)+).*(..)) && within(@Transactional *);