Since version 1.6 we have new annotation JsonSerialize (in version 1.9.9 for example).
Example:
@JsonSerialize(include=Inclusion.NON_NULL)
public class Test{
...
}
Default value is ALWAYS.
In old versions you can use JsonWriteNullProperties, which is deprecated in new versions. Example:
@JsonWriteNullProperties(false)
public class Test{
...
}
All of the previous answers are great. If it is a simple, one line sql command you wish to run, you could also use the -e option.
mysql -h <host> -u<user> -p<password> database -e \
"SELECT * FROM blah WHERE foo='bar';"
Here is a solution. Create a function that returns the random number and place it outside the main function to make it global. Hope this helps
#include <iostream>
#include <cstdlib>
#include <ctime>
int rollDie();
using std::cout;
int main (){
srand((unsigned)time(0));
int die1;
int die2;
for (int n=10; n>0; n--){
die1 = rollDie();
die2 = rollDie();
cout << die1 << " + " << die2 << " = " << die1 + die2 << "\n";
}
system("pause");
return 0;
}
int rollDie(){
return (rand()%6)+1;
}
PHP is run server-side. JavaScript is run client-side in the browser of the user requesting the page. By the time the JavaScript is executed, there is no access to PHP on the server whatsoever. Please read this article with details about client-side vs server-side coding.
What happens in a nutshell is this:
In your case, PHP will write the JS code into the page, so it can be executed when the page is rendered in your browser. By that time, the PHP part in your JS snippet does no longer exist. It was executed on the server already. It created a variable $result
that contained a SQL query string. You didn't use it, so when the page is send back to your browser, it's gone. Have a look at the sourcecode when the page is rendered in your browser. You will see that there is nothing at the position you put the PHP code.
The only way to do what you are looking to do is either:
with the values you want to be insert into the database.
Another one:
"-exec rm -rf {} \;" can be replaced by "-delete"
find -type d -name __pycache__ -delete # GNU find
find . -type d -name __pycache__ -delete # POSIX find (e.g. Mac OS X)
Here is my code, it might be sloppy but it seems to work for me anyway.
# a is the number you want the inverse for
# b is the modulus
def mod_inverse(a, b):
r = -1
B = b
A = a
eq_set = []
full_set = []
mod_set = []
#euclid's algorithm
while r!=1 and r!=0:
r = b%a
q = b//a
eq_set = [r, b, a, q*-1]
b = a
a = r
full_set.append(eq_set)
for i in range(0, 4):
mod_set.append(full_set[-1][i])
mod_set.insert(2, 1)
counter = 0
#extended euclid's algorithm
for i in range(1, len(full_set)):
if counter%2 == 0:
mod_set[2] = full_set[-1*(i+1)][3]*mod_set[4]+mod_set[2]
mod_set[3] = full_set[-1*(i+1)][1]
elif counter%2 != 0:
mod_set[4] = full_set[-1*(i+1)][3]*mod_set[2]+mod_set[4]
mod_set[1] = full_set[-1*(i+1)][1]
counter += 1
if mod_set[3] == B:
return mod_set[2]%B
return mod_set[4]%B
With that level of accuracy, it would be better to reason in CPU tick rather than in system call like clock(). And do not forget that if it takes more than one nanosecond to execute an instruction... having a nanosecond accuracy is pretty much impossible.
Still, something like that is a start:
Here's the actual code to retrieve number of 80x86 CPU clock ticks passed since the CPU was last started. It will work on Pentium and above (386/486 not supported). This code is actually MS Visual C++ specific, but can be probably very easy ported to whatever else, as long as it supports inline assembly.
inline __int64 GetCpuClocks()
{
// Counter
struct { int32 low, high; } counter;
// Use RDTSC instruction to get clocks count
__asm push EAX
__asm push EDX
__asm __emit 0fh __asm __emit 031h // RDTSC
__asm mov counter.low, EAX
__asm mov counter.high, EDX
__asm pop EDX
__asm pop EAX
// Return result
return *(__int64 *)(&counter);
}
This function has also the advantage of being extremely fast - it usually takes no more than 50 cpu cycles to execute.
Using the Timing Figures:
If you need to translate the clock counts into true elapsed time, divide the results by your chip's clock speed. Remember that the "rated" GHz is likely to be slightly different from the actual speed of your chip. To check your chip's true speed, you can use several very good utilities or the Win32 call, QueryPerformanceFrequency().
you can use isEmpty()
or isBlank()
methods regarding what you need.
Returns true if, and only if, length() is 0.
this.name.getText().isEmpty();
Returns true if the string is empty or contains only white space codepoints, otherwise false
this.name.getText().isBlank();
A simple solution of error is that you first need to change the folder directory in command prompt. By default in command prompt or in terminal(Inside Android studio in the bottom)tab the path is set to C:\Users#Name of your PC that you selected\AndroidStudioProjects#app name\flutter_app> Change accordingly:- C:\Users#Name of your PC that you selected\AndroidStudioProjects#app name\flutter_app>cd\
document.getElementById("whatever").className += "classToKeep";
With the plus sign ('+') appending the class as opposed to overwriting any existing classes
You cannot redeclare any functions in PHP. You can, however, override them. Check out overriding functions as well as renaming functions in order to save the function you're overriding if you want.
So, keep in mind that when you override a function, you lose it. You may want to consider keeping it, but in a different name. Just saying.
Also, if these are functions in classes that you're wanting to override, you would just need to create a subclass and redeclare the function in your class without having to do rename_function and override_function.
Example:
rename_function('mysql_connect', 'original_mysql_connect' );
override_function('mysql_connect', '$a,$b', 'echo "DOING MY FUNCTION INSTEAD"; return $a * $b;');
stream = activity.getContentResolver().openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
bitmap = BitmapFactory.decodeStream(stream, null, options);
int Height = bitmap.getHeight();
int Width = bitmap.getWidth();
enter code here
int newHeight = 1000;
float scaleFactor = ((float) newHeight) / Height;
float newWidth = Width * scaleFactor;
float scaleWidth = scaleFactor;
float scaleHeight = scaleFactor;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
resizedBitmap= Bitmap.createBitmap(bitmap, 0, 0,Width, Height, matrix, true);
bitmap.recycle();
Then in Appliaction tag, add largeheapsize="true
I prefer to use something like this:
window.callbackClass['newFunctionName'] = function(data) { console.log(data) };
...
window.callbackClass['newFunctionName'](data);
You use the ajaxStop to execute code when the ajax are completed:
$(document).ajaxStop(function(){
setTimeout("window.location = 'otherpage.html'",100);
});
In JDK7, "more NIO features" should have methods to apply the visitor pattern over a file tree or just the immediate contents of a directory - no need to find all the files in a potentially huge directory before iterating over them.
Use the re.escape()
function for this:
escape(string)
Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.
A simplistic example, search any occurence of the provided string optionally followed by 's', and return the match object.
def simplistic_plural(word, text):
word_or_plural = re.escape(word) + 's?'
return re.match(word_or_plural, text)
I believe that you are looking for the java.lang.BigDecimal class.
__main__.py
is used for python programs in zip files. The __main__.py
file will be executed when the zip file in run. For example, if the zip file was as such:
test.zip
__main__.py
and the contents of __main__.py
was
import sys
print "hello %s" % sys.argv[1]
Then if we were to run python test.zip world
we would get hello world
out.
So the __main__.py
file run when python is called on a zip file.
After reading @MLProgrammer-CiM's answer, here is my code:
class NormalViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
@Bind(R.id.card_item_normal)
CardView cardView;
public NormalViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
cardView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v instanceof CardView) {
// use getAdapterPosition() instead of getLayoutPosition()
int itemPosition = getAdapterPosition();
removeItem(itemPosition);
}
}
}
The problem was that my connection string url contained database name instead of SID. Replacing database name with oracle database connection SID solved this problem.
To know your oracle SID's you can browse tnsnames.ora
file.
XE
was the actual SID, so this is how my tomcat connection string looks like now:
<Resource
name="jdbc/my_db_conn"
auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@//127.0.0.1:1521/XE"
username="test_user"
password="test" />
My server version was "Oracle 11.2 Express", but solution should work on other versions too.
CREATE TABLE newTable LIKE oldTable;
Then, to copy the data over
INSERT INTO newTable SELECT * FROM oldTable;
It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:
When location matches the last part of the directive’s value: it is better to use the root directive instead:
which would yield:
server {
listen 8080;
server_name www.mysite.com mysite.com;
error_log /home/www-data/logs/nginx_www.error.log;
error_page 404 /404.html;
location /public/doc/ {
autoindex on;
root /home/www-data/mysite;
}
location = /404.html {
root /home/www-data/mysite/static/html;
}
}
AB.reserve( A.size() + B.size() ); // preallocate memory
AB.insert( AB.end(), A.begin(), A.end() );
AB.insert( AB.end(), B.begin(), B.end() );
This webpage have an explanation and a solution.
The solution is:
To fix this problem the behavior of the kernel has to be changed, so it will no longer overcommit the memory for application requests. Finally I have included those mentioned values into the /etc/sysctl.conf file, so they get automatically applied on start-up:
vm.overcommit_memory = 2
vm.overcommit_ratio = 80
Use the keyword and
, not &
because &
is a bit operator.
Be careful with this... just so you know, in Java and C++, the &
operator is ALSO a bit operator. The correct way to do a boolean comparison in those languages is &&
. Similarly |
is a bit operator, and ||
is a boolean operator. In Python and
and or
are used for boolean comparisons.
I would start with upgrade of CMAKE version.
You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries
INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)
note that lib1
is expanded to liblib1.so
(on Linux), so use ln to create appropriate links in case you do not have them
Just run composer install
- it will make your vendor
directory reflect dependencies in composer.lock
file.
In other words - it will delete any vendor which is missing in composer.lock
.
Please update the composer itself before running this.
While the answer given by Paul H shows the essential part, it is not a complete example. On the other hand the matplotlib example seems rather complicated and does not show how to use days.
So for everyone in need here is a full working example:
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
myDates = [datetime(2012,1,i+3) for i in range(10)]
myValues = [5,6,4,3,7,8,1,2,5,4]
fig, ax = plt.subplots()
ax.plot(myDates,myValues)
myFmt = DateFormatter("%d")
ax.xaxis.set_major_formatter(myFmt)
## Rotate date labels automatically
fig.autofmt_xdate()
plt.show()
You typically have to do this in a single syscall, or else you will get a race condition.
This will open for reading and writing, creating the file if necessary.
FILE *fp = fopen("scores.dat", "ab+");
If you want to read it and then write a new version from scratch, then do it as two steps.
FILE *fp = fopen("scores.dat", "rb");
if (fp) {
read_scores(fp);
}
// Later...
// truncates the file
FILE *fp = fopen("scores.dat", "wb");
if (!fp)
error();
write_scores(fp);
in my case I did
function myFunc() {
console.log('myFunc', $(this));
}
$("selector").on("click", "selector", function(e) {
e.preventDefault();
myFunc.call(this);
});
properly calls myFunc with the correct this
.
which(df==my.val, arr.ind=TRUE)
Use WinSCP for file transfer over SSH, putty is only for SSH commands.
One hackish way to define an exit
method in context:
class Bar; def exit; end; end
This works because exit
in the initializer will be resolved as self.exit
1. In addition, this approach allows using the object after it has been created, as in: b = B.new
.
But really, one shouldn't be doing this: don't have exit
(or even puts
) there to begin with.
(And why is there an "infinite" loop and/or user input in an intiailizer? This entire problem is primarily the result of poorly structured code.)
1 Remember Kernel#exit is only a method. Since Kernel is included in every Object, then it's merely the case that exit
normally resolves to Object#exit
. However, this can be changed by introducing an overridden method as shown - nothing fancy.
For me it was rather frustrating, but I've found solution for my case at least:
If your TestMethod is async, it cannot be void. It MUST return Task.
Hope it helps someone :)
Reading this rather entertaining discussion, I remembered that I had a real-world, time-sensitive function that tested for odd and even numbers inside the main loop. It's an integer power function, posted elsewhere on StackOverflow, as follows. The benchmarks were quite surprising. At least in this real-world function, modulo is slower, and significantly so. The winner, by a wide margin, requiring 67% of modulo's time, is an or ( | ) approach, and is nowhere to be found elsewhere on this page.
static dbl IntPow(dbl st0, int x) {
UINT OrMask = UINT_MAX -1;
dbl st1=1.0;
if(0==x) return (dbl)1.0;
while(1 != x) {
if (UINT_MAX == (x|OrMask)) { // if LSB is 1...
//if(x & 1) {
//if(x % 2) {
st1 *= st0;
}
x = x >> 1; // shift x right 1 bit...
st0 *= st0;
}
return st1 * st0;
}
For 300 million loops, the benchmark timings are as follows.
3.962 the | and mask approach
4.851 the & approach
5.850 the % approach
For people who think theory, or an assembly language listing, settles arguments like these, this should be a cautionary tale. There are more things in heaven and earth, Horatio, than are dreamt of in your philosophy.
You could fire an event into the quit() slot of your application even without connect(). This way, the event-loop does at least one turn and should process the events within your main()-logic:
#include <QCoreApplication>
#include <QTimer>
int main(int argc, char *argv[])
{
QCoreApplication app( argc, argv );
// do your thing, once
QTimer::singleShot( 0, &app, &QCoreApplication::quit );
return app.exec();
}
Don't forget to place CONFIG += console
in your .pro-file, or set consoleApplication: true
in your .qbs Project.CppApplication.
I have a Droid 3 (Verizon). I went to Motorola here and found the driver for the device 'Motorola ADB Interface' which was showing in device manager. It's kind of a big download for just the driver, but during installation it found it and installed correctly.
if(str.matches(".*\\d.*")){
// contains a number
} else{
// does not contain a number
}
Previous suggested solution, which does not work, but brought back because of @Eng.Fouad's request/suggestion.
String strWithNumber = "This string has a 1 number";
String strWithoutNumber = "This string does not have a number";
System.out.println(strWithNumber.contains("\d"));
System.out.println(strWithoutNumber.contains("\d"));
String strWithNumber = "This string has a 1 number";
if(strWithNumber.matches(".*\\d.*")){
System.out.println("'"+strWithNumber+"' contains digit");
} else{
System.out.println("'"+strWithNumber+"' does not contain a digit");
}
String strWithoutNumber = "This string does not have a number";
if(strWithoutNumber.matches(".*\\d.*")){
System.out.println("'"+strWithoutNumber+"' contains digit");
} else{
System.out.println("'"+strWithoutNumber+"' does not contain a digit");
}
Output
'This string has a 1 number' contains digit
'This string does not have a number' does not contain a digit
The question is: how-to-access-data-data-folder-in-android-device?
If android-device is Bluestacks * Root Browser APK shows data/data/..
Try to download Root Browser from https://apkpure.com/root-browser/com.jrummy.root.browserfree
If the file is a text file you need to click on "Open as", "Text file", "Open as", "RB Text Editor"
There isn't a single answer to this question as there are too many variables, but SHA2 is not yet really cracked (see: Lifetimes of cryptographic hash functions) so it is still a good algorithm to use to store passwords in. The use of salt is good because it prevents attack from dictionary attacks or rainbow tables. Importance of a salt is that it should be unique for each password. You can use a format like [128-bit salt][512-bit password hash] when storing the hashed passwords.
The only viable way to attack is to actually calculate hashes for different possibilities of password and eventually find the right one by matching the hashes.
To give an idea about how many hashes can be done in a second, I think Bitcoin is a decent example. Bitcoin uses SHA256 and to cut it short, the more hashes you generate, the more bitcoins you get (which you can trade for real money) and as such people are motivated to use GPUs for this purpose. You can see in the hardware overview that an average graphic card that costs only $150 can calculate more than 200 million hashes/s. The longer and more complex your password is, the longer time it will take. Calculating at 200M/s, to try all possibilities for an 8 character alphanumberic (capital, lower, numbers) will take around 300 hours. The real time will most likely less if the password is something eligible or a common english word.
As such with anything security you need to look at in context. What is the attacker's motivation? What is the kind of application? Having a hash with random salt for each gives pretty good protection against cases where something like thousands of passwords are compromised.
One thing you can do is also add additional brute force protection by slowing down the hashing procedure. As you only hash passwords once, and the attacker has to do it many times, this works in your favor. The typical way to do is to take a value, hash it, take the output, hash it again and so forth for a fixed amount of iterations. You can try something like 1,000 or 10,000 iterations for example. This will make it that many times times slower for the attacker to find each password.
String.format("%03d", 1) // => "001"
// ¦¦¦ +-- print the number one
// ¦¦+------ ... as a decimal integer
// ¦+------- ... minimum of 3 characters wide
// +-------- ... pad with zeroes instead of spaces
See java.util.Formatter
for more information.
This is my example.
https://github.com/luisnicg/jQuery-Sortable-and-PHP
You need to catch the order in the update event
$( "#sortable" ).sortable({
placeholder: "ui-state-highlight",
update: function( event, ui ) {
var sorted = $( "#sortable" ).sortable( "serialize", { key: "sort" } );
$.post( "form/order.php",{ 'choices[]': sorted});
}
});
package com.infy.test;
import java.util.Scanner ;
import java.lang.String ;
public class Test1 {
public static void main (String[]args)
{
String a =null;
Scanner scan = new Scanner(System.in);
System.out.println("*********White Space Remover Program************\n");
System.out.println("Enter your string\n");
a = scan.nextLine();
System.out.println("Input String is :\n"+a);
String b= a.replaceAll("\\s+","");
System.out.println("\nOutput String is :\n"+b);
}
}
I would like to share a useful example of overloaded-like approach.
function Clear(control)
{
var o = typeof control !== "undefined" ? control : document.body;
var children = o.childNodes;
while (o.childNodes.length > 0)
o.removeChild(o.firstChild);
}
Usage: Clear(); // Clears all the document
Clear(myDiv); // Clears panel referenced by myDiv
You may try to use Trove http://trove.starlight-systems.com/
TIntObjectHashMap is probably what you are looking for.
var data = {_x000D_
"items": [{_x000D_
"id": 1,_x000D_
"category": "cat1"_x000D_
}, {_x000D_
"id": 2,_x000D_
"category": "cat2"_x000D_
}, {_x000D_
"id": 3,_x000D_
"category": "cat1"_x000D_
}, {_x000D_
"id": 4,_x000D_
"category": "cat2"_x000D_
}, {_x000D_
"id": 5,_x000D_
"category": "cat1"_x000D_
}]_x000D_
};_x000D_
//Filters an array of numbers to include only numbers bigger then zero._x000D_
//Exact Data you want..._x000D_
var returnedData = $.grep(data.items, function(element) {_x000D_
return element.category === "cat1" && element.id === 3;_x000D_
}, false);_x000D_
console.log(returnedData);_x000D_
$('#id').text('Id is:-' + returnedData[0].id)_x000D_
$('#category').text('Category is:-' + returnedData[0].category)_x000D_
//Filter an array of numbers to include numbers that are not bigger than zero._x000D_
//Exact Data you don't want..._x000D_
var returnedOppositeData = $.grep(data.items, function(element) {_x000D_
return element.category === "cat1";_x000D_
}, true);_x000D_
console.log(returnedOppositeData);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<p id='id'></p>_x000D_
<p id='category'></p>
_x000D_
The $.grep()
method eliminates items from an array as necessary so that only remaining items carry a given search. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.
No there isn't. You can only read information associated with the current domain.
Try:
InputStream inputStream= // Your InputStream from your database.
Reader reader = new InputStreamReader(inputStream,"UTF-8");
InputSource is = new InputSource(reader);
is.setEncoding("UTF-8");
saxParser.parse(is, handler);
If it's anything else than UTF-8, just change the encoding part for the good one.
You need to run Set-ExecutionPolicy
:
Set-ExecutionPolicy Unrestricted <-- Will allow unsigned PowerShell scripts to run.
Set-ExecutionPolicy Restricted <-- Will not allow unsigned PowerShell scripts to run.
Set-ExecutionPolicy RemoteSigned <-- Will allow only remotely signed PowerShell scripts to run.
you need to execute two queries:
One - to add the default value to the column required
ALTER TABLE 'Table_Name` ADD DEFAULT 'value' FOR 'Column_Name'
i want add default value to Column IsDeleted as below:
Example: ALTER TABLE [dbo].[Employees] ADD Default 0 for IsDeleted
Two - to alter the column value nullable to not null
ALTER TABLE 'table_name' ALTER COLUMN 'column_name' 'data_type' NOT NULL
i want to make the column IsDeleted as not null
ALTER TABLE [dbo].[Employees] Alter Column IsDeleted BIT NOT NULL
The ftp
command isn't designed for scripts, so controlling it is awkward, and getting its exit status is even more awkward.
Curl is made to be scriptable, and also has the merit that you can easily switch to other protocols later by just modifying the URL. If you put your FTP credentials in your .netrc, you can simply do:
# Download file
curl --netrc --remote-name ftp://ftp.example.com/file.bin
# Upload file
curl --netrc --upload-file file.bin ftp://ftp.example.com/
If you must, you can specify username and password directly on the command line using --user username:password
instead of --netrc
.
>>> import datetime
>>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d')
>>> d.strftime('%b %d,%Y')
'Jun 09,2011'
In pre-2.5 Python, you can replace datetime.strptime
with time.strptime
, like so (untested): datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))
Since Mockito 2.0 there's also possibility to use static method Matchers.argThat(ArgumentMatcher). With the help of Java 8 it is now much cleaner and more readable to write:
verify(mockBar).doSth(argThat((arg) -> arg.getSurname().equals("OneSurname")));
verify(mockBar).doSth(argThat((arg) -> arg.getSurname().equals("AnotherSurname")));
If you're tied to lower Java version there's also not-that-bad:
verify(mockBar).doSth(argThat(new ArgumentMatcher<Employee>() {
@Override
public boolean matches(Object emp) {
return ((Employee) emp).getSurname().equals("SomeSurname");
}
}));
Of course none of those can verify order of calls - for which you should use InOrder :
InOrder inOrder = inOrder(mockBar);
inOrder.verify(mockBar).doSth(argThat((arg) -> arg.getSurname().equals("FirstSurname")));
inOrder.verify(mockBar).doSth(argThat((arg) -> arg.getSurname().equals("SecondSurname")));
Please take a look at mockito-java8 project which makes possible to make calls such as:
verify(mockBar).doSth(assertArg(arg -> assertThat(arg.getSurname()).isEqualTo("Surname")));
UPDATE: https://requests.readthedocs.io/en/master/user/advanced/#timeouts
In new version of requests
:
If you specify a single value for the timeout, like this:
r = requests.get('https://github.com', timeout=5)
The timeout value will be applied to both the connect
and the read
timeouts. Specify a tuple if you would like to set the values separately:
r = requests.get('https://github.com', timeout=(3.05, 27))
If the remote server is very slow, you can tell Requests to wait forever for a response, by passing None as a timeout value and then retrieving a cup of coffee.
r = requests.get('https://github.com', timeout=None)
My old (probably outdated) answer (which was posted long time ago):
There are other ways to overcome this problem:
1. Use the TimeoutSauce
internal class
From: https://github.com/kennethreitz/requests/issues/1928#issuecomment-35811896
import requests from requests.adapters import TimeoutSauce class MyTimeout(TimeoutSauce): def __init__(self, *args, **kwargs): connect = kwargs.get('connect', 5) read = kwargs.get('read', connect) super(MyTimeout, self).__init__(connect=connect, read=read) requests.adapters.TimeoutSauce = MyTimeout
This code should cause us to set the read timeout as equal to the connect timeout, which is the timeout value you pass on your Session.get() call. (Note that I haven't actually tested this code, so it may need some quick debugging, I just wrote it straight into the GitHub window.)
2. Use a fork of requests from kevinburke: https://github.com/kevinburke/requests/tree/connect-timeout
From its documentation: https://github.com/kevinburke/requests/blob/connect-timeout/docs/user/advanced.rst
If you specify a single value for the timeout, like this:
r = requests.get('https://github.com', timeout=5)
The timeout value will be applied to both the connect and the read timeouts. Specify a tuple if you would like to set the values separately:
r = requests.get('https://github.com', timeout=(3.05, 27))
kevinburke has requested it to be merged into the main requests project, but it hasn't been accepted yet.
From the docs on angular.element
:
find()
- Limited to lookups by tag name
So if you're not using jQuery with Angular, but relying upon its jqlite implementation, you can't do elm.find('#someid')
.
You do have access to children()
, contents()
, and data()
implementations, so you can usually find a way around it.
Follow the Instructions from the Ruby Installer Developer Kit Wiki:
cd C:\Ruby193\DevKit
ruby dk.rb init
ruby dk.rb review
ruby dk.rb install
To return to the problem at hand, you should be able to install JSON (or otherwise test that your DevKit successfully installed) by running the following commands which will perform an install of the JSON gem and then use it:
gem install json --platform=ruby
ruby -rubygems -e "require 'json'; puts JSON.load('[42]').inspect"
in bootstrap 3.0 :
Set heights using classes like .input-lg, and set widths using grid column classes like .col-lg-*.
Example:
<div class="row">
<div class="col-xs-2">
<input type="text" class="form-control" placeholder=".col-xs-2">
</div>
<div class="col-xs-3">
<input type="text" class="form-control" placeholder=".col-xs-3">
</div>
<div class="col-xs-4">
<input type="text" class="form-control" placeholder=".col-xs-4">
</div>
</div>
I know this is an old question and the correct answer, use _blank
, has been mentioned several times, but using <a target="somesite.com" target="_blank">Link</a>
is a security risk.
It is recommended (performance benefits) to use:
<a href="somesite.com" target="_blank" rel="noopener noreferrer">Link</a>
below formula worked form me in MS EXEL
=TEXT(CELL_VALUE/24/60/60/1000 + 25569,"YYYY-MM-DD HH:MM")
CELL_VALUE is timestamp in milliseconds
here is explanation for text function.
it's because you are trying to launch your app from an activity that is not launcher activity. try run it from launcher activity or change your current activity category to launcher in android Manifest.
I have modified the extension found here: Github Gist, for Swift 3
which I have tested in the context of an extension for UIImage.
func tint(with color: UIColor) -> UIImage
{
UIGraphicsBeginImageContext(self.size)
guard let context = UIGraphicsGetCurrentContext() else { return self }
// flip the image
context.scaleBy(x: 1.0, y: -1.0)
context.translateBy(x: 0.0, y: -self.size.height)
// multiply blend mode
context.setBlendMode(.multiply)
let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
context.clip(to: rect, mask: self.cgImage!)
color.setFill()
context.fill(rect)
// create UIImage
guard let newImage = UIGraphicsGetImageFromCurrentImageContext() else { return self }
UIGraphicsEndImageContext()
return newImage
}
def query(id):
for line in file:
table = line.split(";")
if id == int(table[0]):
yield table
id = int(input("Enter the ID of the user: "))
for id_, name, city in query(id):
print("ID: " + id_)
print("Name: " + name)
print("City: " + city)
file.close()
Using yield..
Run this command in your project console:
mvn idea:idea
Done. Had this issue many times. Tried 'Invalidate Cache & Restart' and all other solutions. Running that command works perfect to me. I'm currently using IntelliJ 2019.2, but this also happened in previous versions and solution worked as well.
Are you sure the curl module honors ini_set('user_agent',...)? There is an option CURLOPT_USERAGENT described at http://docs.php.net/function.curl-setopt.
Could there also be a cookie tested by the server? That you can handle by using CURLOPT_COOKIE, CURLOPT_COOKIEFILE and/or CURLOPT_COOKIEJAR.
edit: Since the request uses https there might also be error in verifying the certificate, see CURLOPT_SSL_VERIFYPEER.
$url="https://new.aol.com/productsweb/subflows/ScreenNameFlow/AjaxSNAction.do?s=username&f=firstname&l=lastname";
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
var_dump($result);
Use System.Diagnostics.Process.Start()
method.
Check out this article on how to use it.
Process.Start("notepad", "readme.txt");
string winpath = Environment.GetEnvironmentVariable("windir");
string path = System.IO.Path.GetDirectoryName(
System.Windows.Forms.Application.ExecutablePath);
Process.Start(winpath + @"\Microsoft.NET\Framework\v1.0.3705\Installutil.exe",
path + "\\MyService.exe");
Go to the Config button (up right) and select the Autostart for Apache.
Firefox? I don't think you can. IE is another story though..
This did the trick for me. It captures all the stdout output from the subprocess(For python 3.8):
from subprocess import check_output, STDOUT
cmd = "Your Command goes here"
try:
cmd_stdout = check_output(cmd, stderr=STDOUT, shell=True).decode()
except Exception as e:
print(e.output.decode()) # print out the stdout messages up to the exception
print(e) # To print out the exception message
This answers a different question:
If trying to figure out if an OBJECT (not class) has a property,
OBJECT.GetType().GetProperty("PROPERTY") != null
returns true if (but not only if) the property exists.
In my case, I was in an ASP.NET MVC Partial View and wanted to render something if either the property did not exist, or the property (boolean) was true.
@if ((Model.GetType().GetProperty("AddTimeoffBlackouts") == null) ||
Model.AddTimeoffBlackouts)
helped me here.
Edit: Nowadays, it's probably smart to use the nameof
operator instead of the stringified property name.
You may set $PATH
permanently in 2 ways.
To set path for particular user :
You may need to make the entry in .bash_profile
in home directory in the user.
e.g in my case I will set java path in tomcat user profile
[tomcat]$ echo "export PATH=$PATH:/path/to/dir" >> /home/tomcat/.bash_profile
To set common path for ALL system users, you may need to set path like this :
[root~]# echo "export PATH=$PATH:/path/to/dir" >> /etc/profile
I rather often find it useful to on-the-fly define some key mapping just like one would define a macro. The twist here is, that the mapping is recursive and is executed until it fails.
Example:
enum ProcStats
{
ps_pid,
ps_comm,
ps_state,
ps_ppid,
ps_pgrp,
:map X /ps_<CR>3xixy<Esc>X
Gives:
enum ProcStats
{
xypid,
xycomm,
xystate,
xyppid,
xypgrp,
Just an silly example :).
I am completely aware of all the downsides - it just so happens that I found it rather useful in some occasions. Also it can be interesting to watch it at work ;).
To force LF line endings for all text files, you can create .gitattributes
file in top-level of your repository with the following lines (change as desired):
# Ensure all C and PHP files use LF.
*.c eol=lf
*.php eol=lf
which ensures that all files that Git considers to be text files have normalized (LF
) line endings in the repository (normally core.eol
configuration controls which one do you have by default).
Based on the new attribute settings, any text files containing CRLFs should be normalized by Git. If this won't happen automatically, you can refresh a repository manually after changing line endings, so you can re-scan and commit the working directory by the following steps (given clean working directory):
$ echo "* text=auto" >> .gitattributes
$ rm .git/index # Remove the index to force Git to
$ git reset # re-scan the working directory
$ git status # Show files that will be normalized
$ git add -u
$ git add .gitattributes
$ git commit -m "Introduce end-of-line normalization"
or as per GitHub docs:
git add . -u
git commit -m "Saving files before refreshing line endings"
git rm --cached -r . # Remove every file from Git's index.
git reset --hard # Rewrite the Git index to pick up all the new line endings.
git add . # Add all your changed files back, and prepare them for a commit.
git commit -m "Normalize all the line endings" # Commit the changes to your repository.
See also: @Charles Bailey post.
In addition, if you would like to exclude any files to not being treated as a text, unset their text attribute, e.g.
manual.pdf -text
Or mark it explicitly as binary:
# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary
To see some more advanced git normalization file, check .gitattributes
at Drupal core:
# Drupal git normalization
# @see https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html
# @see https://www.drupal.org/node/1542048
# Normally these settings would be done with macro attributes for improved
# readability and easier maintenance. However macros can only be defined at the
# repository root directory. Drupal avoids making any assumptions about where it
# is installed.
# Define text file attributes.
# - Treat them as text.
# - Ensure no CRLF line-endings, neither on checkout nor on checkin.
# - Detect whitespace errors.
# - Exposed by default in `git diff --color` on the CLI.
# - Validate with `git diff --check`.
# - Deny applying with `git apply --whitespace=error-all`.
# - Fix automatically with `git apply --whitespace=fix`.
*.config text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.css text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.dist text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.engine text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.html text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=html
*.inc text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.install text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.js text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.json text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.lock text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.map text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.md text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.module text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.php text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.po text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.profile text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.script text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.sh text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.sql text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.svg text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.theme text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.twig text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.txt text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.xml text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.yml text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
# Define binary file attributes.
# - Do not treat them as text.
# - Include binary diff in patches instead of "binary files differ."
*.eot -text diff
*.exe -text diff
*.gif -text diff
*.gz -text diff
*.ico -text diff
*.jpeg -text diff
*.jpg -text diff
*.otf -text diff
*.phar -text diff
*.png -text diff
*.svgz -text diff
*.ttf -text diff
*.woff -text diff
*.woff2 -text diff
See also:
Add this below code(<handler>
) on your web.config within <system.webServer>
:
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
You have to properly understand what is a "stdafx.h", aka precompiled header. Other questions or Wikipedia will answer that. In many cases a precompiled header can be avoided, especially if your project is small and with few dependencies. In your case, as you probably started from a template project, it was used to include Windows.h
only for the _TCHAR
macro.
Then, precompiled header is usually a per-project file in Visual Studio world, so:
#include <stdafx.h>
to #include "stdafx.h"
. It is supposed to be a project local file, not to be resolved in include directories.Secondly: it's inadvisable to include the precompiled header in your own headers, to not clutter namespace of other source that can use your code as a library, so completely remove its inclusion in vector.h
.
I solved this issue to update .htaccess
file inside your workspace (like C:\xampp\htdocs\Nayan\.htaccess
in my case).
Just update or add this
php_value max_execution_time 300
line before# END WordPress
. Then save the file and try to install again.
If the error occurs again, you can maximize the value from 300
to 600
.
This looks cool.
-moz-box-shadow: 0 0 5px #999;
-webkit-box-shadow: 0 0 5px #999;
box-shadow: 0 0 5px #999;
For ListBox / DropDown in MVC5 - i've found this to work for me sofar:
in Model:
[Required(ErrorMessage = "- Select item -")]
public List<string> SelectedItem { get; set; }
public List<SelectListItem> AvailableItemsList { get; set; }
in View:
@Html.ListBoxFor(model => model.SelectedItem, Model.AvailableItemsList)
@Html.ValidationMessageFor(model => model.SelectedItem, "", new { @class = "text-danger" })
In case anyone wanted more of a visual reference:
Decimal approximations reference table:
+----------------------------------------------------------------------------+
¦ aspect ratio ¦ decimal approx. ¦ decimal approx. ¦
¦ [long edge x short edge] ¦ [short edge/long edge] ¦ [long edge/short edge] ¦
¦--------------------------+------------------------+------------------------¦
¦ 19.5 x 9 ¦ 0.462... ¦ 2.167... ¦
¦--------------------------+------------------------+------------------------¦
¦ 19 x 9 ¦ 0.474... ¦ 2.11... ¦
¦--------------------------+------------------------+------------------------¦
¦ ~18.7 x 9 ¦ 0.482... ¦ 2.074... ¦
¦--------------------------+------------------------+------------------------¦
¦ 18.5 x 9 ¦ 0.486... ¦ 2.056... ¦
¦--------------------------+------------------------+------------------------¦
¦ 18 x 9 ¦ 0.5 ¦ 2 ¦
¦--------------------------+------------------------+------------------------¦
¦ 19 x 10 ¦ 0.526... ¦ 1.9 ¦
¦--------------------------+------------------------+------------------------¦
¦ 16 x 9 ¦ 0.5625 ¦ 1.778... ¦
¦--------------------------+------------------------+------------------------¦
¦ 5 x 3 ¦ 0.6 ¦ 1.667... ¦
¦--------------------------+------------------------+------------------------¦
¦ 16 x 10 ¦ 0.625 ¦ 1.6 ¦
¦--------------------------+------------------------+------------------------¦
¦ 3 x 2 ¦ 0.667... ¦ 1.5 ¦
¦--------------------------+------------------------+------------------------¦
¦ 4 x 3 ¦ 0.75 ¦ 1.333... ¦
+----------------------------------------------------------------------------+
Changelog:
56x27 === ~18.7x9
(Huawei P20), 19x9
(Nokia X6 2018) and 19.5x9
(LG G7 ThinQ)19x10
(Essential Phone)18.5x9
(Samsung Galaxy S8) and 18x9
(LG G6)To verify only first letter is number or character -- For number Character.isDigit(str.charAt(0)) --return true
For character Character.isLetter(str.charAt(0)) --return true
For dynamic arrays (malloc or C++ new) you need to store the size of the array as mentioned by others or perhaps build an array manager structure which handles add, remove, count, etc. Unfortunately C doesn't do this nearly as well as C++ since you basically have to build it for each different array type you are storing which is cumbersome if you have multiple types of arrays that you need to manage.
For static arrays, such as the one in your example, there is a common macro used to get the size, but it is not recommended as it does not check if the parameter is really a static array. The macro is used in real code though, e.g. in the Linux kernel headers although it may be slightly different than the one below:
#if !defined(ARRAY_SIZE)
#define ARRAY_SIZE(x) (sizeof((x)) / sizeof((x)[0]))
#endif
int main()
{
int days[] = {1,2,3,4,5};
int *ptr = days;
printf("%u\n", ARRAY_SIZE(days));
printf("%u\n", sizeof(ptr));
return 0;
}
You can google for reasons to be wary of macros like this. Be careful.
If possible, the C++ stdlib such as vector which is much safer and easier to use.
Here is the tutorial to install GBD.
Usually GNU Debugger might not be in your computer, so you would install it first. The installation steps are basic "configure", "make", and "make install".
Once installed, try which gdb
in terminal, to find the executable path of GDB.
set this :
#inner-right {
height: 100%;
max-height: 96%;//change here
overflow: auto;
background: ivory;
}
this will solve your problem.
Python
if x is not None
orif not x is None
?
TLDR: The bytecode compiler parses them both to x is not None
- so for readability's sake, use if x is not None
.
We use Python because we value things like human readability, useability, and correctness of various paradigms of programming over performance.
Python optimizes for readability, especially in this context.
The not
binds more weakly than is
, so there is no logical difference here. See the documentation:
The operators
is
andis not
test for object identity:x is y
is true if and only if x and y are the same object.x is not y
yields the inverse truth value.
The is not
is specifically provided for in the Python grammar as a readability improvement for the language:
comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
And so it is a unitary element of the grammar as well.
Of course, it is not parsed the same:
>>> import ast
>>> ast.dump(ast.parse('x is not None').body[0].value)
"Compare(left=Name(id='x', ctx=Load()), ops=[IsNot()], comparators=[Name(id='None', ctx=Load())])"
>>> ast.dump(ast.parse('not x is None').body[0].value)
"UnaryOp(op=Not(), operand=Compare(left=Name(id='x', ctx=Load()), ops=[Is()], comparators=[Name(id='None', ctx=Load())]))"
But then the byte compiler will actually translate the not ... is
to is not
:
>>> import dis
>>> dis.dis(lambda x, y: x is not y)
1 0 LOAD_FAST 0 (x)
3 LOAD_FAST 1 (y)
6 COMPARE_OP 9 (is not)
9 RETURN_VALUE
>>> dis.dis(lambda x, y: not x is y)
1 0 LOAD_FAST 0 (x)
3 LOAD_FAST 1 (y)
6 COMPARE_OP 9 (is not)
9 RETURN_VALUE
So for the sake of readability and using the language as it was intended, please use is not
.
To not use it is not wise.
Here is all the information you need in order to format clickable hyperlinks in LaTeX:
http://en.wikibooks.org/wiki/LaTeX/Hyperlinks
Essentially, you use the hyperref
package and use the \url
or \href
tag depending on what you're trying to achieve.
After going mad trying to remove the border in IE7, I found that the frameBorder attribute is case sensitive.
You have to set the frameBorder attribute with a capital B.
<iframe frameBorder="0"></iframe>
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar
ojdbc14.jar(it's jar file)
public static boolean areAllTrue(boolean[] array)
{
for(boolean b : array) if(!b) return false;
return true;
}
You can do this without a JOIN
:
SELECT *
FROM (SELECT *,COUNT(*) OVER(PARTITION BY phone_number) as Phone_CT
FROM YourTable
)sub
WHERE Phone_CT > 1
ORDER BY phone_number, employee_ids
Demo: SQL Fiddle
npm install http-server -g
http-server . -o
As of Java 7, java.util.logging.SimpleFormatter supports getting its format from a system property, so adding something like this to the JVM command line will cause it to print on one line:
-Djava.util.logging.SimpleFormatter.format='%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n'
Alternatively, you can also add this to your logger.properties
:
java.util.logging.SimpleFormatter.format='%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n'
FIRST UPDATE: Before you try this ever in a production environment (not advised), read this first: http://www.javaspecialists.eu/archive/Issue237.html Starting from Java 9, the solution as described won't work anymore, because now Java will store strings as byte[] by default.
SECOND UPDATE: As of 2016-10-25, on my AMDx64 8core and source 1.8, there is no difference between using 'charAt' and field access. It appears that the jvm is sufficiently optimized to inline and streamline any 'string.charAt(n)' calls.
THIRD UPDATE: As of 2020-09-07, on my Ryzen 1950-X 16 core and source 1.14, 'charAt1' is 9 times slower than field access and 'charAt2' is 4 times slower than field access. Field access is back as the clear winner. Note than the program will need to use byte[] access for Java 9+ version jvms.
It all depends on the length of the String
being inspected. If, as the question says, it is for long strings, the fastest way to inspect the string is to use reflection to access the backing char[]
of the string.
A fully randomized benchmark with JDK 8 (win32 and win64) on an 64 AMD Phenom II 4 core 955 @ 3.2 GHZ (in both client mode and server mode) with 9 different techniques (see below!) shows that using String.charAt(n)
is the fastest for small strings and that using reflection
to access the String backing array is almost twice as fast for large strings.
9 different optimization techniques are tried.
All string contents are randomized
The test are done for string sizes in multiples of two starting with 0,1,2,4,8,16 etc.
The tests are done 1,000 times per string size
The tests are shuffled into random order each time. In other words, the tests are done in random order every time they are done, over 1000 times over.
The entire test suite is done forwards, and backwards, to show the effect of JVM warmup on optimization and times.
The entire suite is done twice, once in -client
mode and the other in -server
mode.
For strings 1 to 256 characters in length, calling string.charAt(i)
wins with an average processing of 13.4 million to 588 million characters per second.
Also, it is overall 5.5% faster (client) and 13.9% (server) like this:
for (int i = 0; i < data.length(); i++) {
if (data.charAt(i) <= ' ') {
doThrow();
}
}
than like this with a local final length variable:
final int len = data.length();
for (int i = 0; i < len; i++) {
if (data.charAt(i) <= ' ') {
doThrow();
}
}
For long strings, 512 to 256K characters length, using reflection to access the String's backing array is fastest. This technique is almost twice as fast as String.charAt(i) (178% faster). The average speed over this range was 1.111 billion characters per second.
The Field must be obtained ahead of time and then it can be re-used in the library on different strings. Interestingly, unlike the code above, with Field access, it is 9% faster to have a local final length variable than to use 'chars.length' in the loop check. Here is how Field access can be setup as fastest:
final Field field = String.class.getDeclaredField("value");
field.setAccessible(true);
try {
final char[] chars = (char[]) field.get(data);
final int len = chars.length;
for (int i = 0; i < len; i++) {
if (chars[i] <= ' ') {
doThrow();
}
}
return len;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
Field access starting winning after 32 character length strings in server mode on a 64 bit Java machine on my AMD 64 machine. That was not seen until 512 characters length in client mode.
Also worth noting I think, when I was running JDK 8 (32 bit build) in server mode, the overall performance was 7% slower for both large and small strings. This was with build 121 Dec 2013 of JDK 8 early release. So, for now, it seems that 32 bit server mode is slower than 32 bit client mode.
That being said ... it seems the only server mode that is worth invoking is on a 64 bit machine. Otherwise it actually hampers performance.
For 32 bit build running in -server mode
on an AMD64, I can say this:
Also worth saying, String.chars() (Stream and the parallel version) are a bust. Way slower than any other way. The Streams
API is a rather slow way to perform general string operations.
Java String could have predicate accepting optimized methods such as contains(predicate), forEach(consumer), forEachWithIndex(consumer). Thus, without the need for the user to know the length or repeat calls to String methods, these could help parsing libraries beep-beep beep
speedup.
Keep dreaming :)
Happy Strings!
~SH
"charAt1" -- CHECK THE STRING CONTENTS THE USUAL WAY:
int charAtMethod1(final String data) {
final int len = data.length();
for (int i = 0; i < len; i++) {
if (data.charAt(i) <= ' ') {
doThrow();
}
}
return len;
}
"charAt2" -- SAME AS ABOVE BUT USE String.length() INSTEAD OF MAKING A FINAL LOCAL int FOR THE LENGTh
int charAtMethod2(final String data) {
for (int i = 0; i < data.length(); i++) {
if (data.charAt(i) <= ' ') {
doThrow();
}
}
return data.length();
}
"stream" -- USE THE NEW JAVA-8 String's IntStream AND PASS IT A PREDICATE TO DO THE CHECKING
int streamMethod(final String data, final IntPredicate predicate) {
if (data.chars().anyMatch(predicate)) {
doThrow();
}
return data.length();
}
"streamPara" -- SAME AS ABOVE, BUT OH-LA-LA - GO PARALLEL!!!
// avoid this at all costs
int streamParallelMethod(final String data, IntPredicate predicate) {
if (data.chars().parallel().anyMatch(predicate)) {
doThrow();
}
return data.length();
}
"reuse" -- REFILL A REUSABLE char[] WITH THE STRINGS CONTENTS
int reuseBuffMethod(final char[] reusable, final String data) {
final int len = data.length();
data.getChars(0, len, reusable, 0);
for (int i = 0; i < len; i++) {
if (reusable[i] <= ' ') {
doThrow();
}
}
return len;
}
"new1" -- OBTAIN A NEW COPY OF THE char[] FROM THE STRING
int newMethod1(final String data) {
final int len = data.length();
final char[] copy = data.toCharArray();
for (int i = 0; i < len; i++) {
if (copy[i] <= ' ') {
doThrow();
}
}
return len;
}
"new2" -- SAME AS ABOVE, BUT USE "FOR-EACH"
int newMethod2(final String data) {
for (final char c : data.toCharArray()) {
if (c <= ' ') {
doThrow();
}
}
return data.length();
}
"field1" -- FANCY!! OBTAIN FIELD FOR ACCESS TO THE STRING'S INTERNAL char[]
int fieldMethod1(final Field field, final String data) {
try {
final char[] chars = (char[]) field.get(data);
final int len = chars.length;
for (int i = 0; i < len; i++) {
if (chars[i] <= ' ') {
doThrow();
}
}
return len;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
"field2" -- SAME AS ABOVE, BUT USE "FOR-EACH"
int fieldMethod2(final Field field, final String data) {
final char[] chars;
try {
chars = (char[]) field.get(data);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
for (final char c : chars) {
if (c <= ' ') {
doThrow();
}
}
return chars.length;
}
-client
MODE (forwards and backwards tests combined)Note: that the -client mode with Java 32 bit and -server mode with Java 64 bit are the same as below on my AMD64 machine.
Size WINNER charAt1 charAt2 stream streamPar reuse new1 new2 field1 field2
1 charAt 77.0 72.0 462.0 584.0 127.5 89.5 86.0 159.5 165.0
2 charAt 38.0 36.5 284.0 32712.5 57.5 48.3 50.3 89.0 91.5
4 charAt 19.5 18.5 458.6 3169.0 33.0 26.8 27.5 54.1 52.6
8 charAt 9.8 9.9 100.5 1370.9 17.3 14.4 15.0 26.9 26.4
16 charAt 6.1 6.5 73.4 857.0 8.4 8.2 8.3 13.6 13.5
32 charAt 3.9 3.7 54.8 428.9 5.0 4.9 4.7 7.0 7.2
64 charAt 2.7 2.6 48.2 232.9 3.0 3.2 3.3 3.9 4.0
128 charAt 2.1 1.9 43.7 138.8 2.1 2.6 2.6 2.4 2.6
256 charAt 1.9 1.6 42.4 90.6 1.7 2.1 2.1 1.7 1.8
512 field1 1.7 1.4 40.6 60.5 1.4 1.9 1.9 1.3 1.4
1,024 field1 1.6 1.4 40.0 45.6 1.2 1.9 2.1 1.0 1.2
2,048 field1 1.6 1.3 40.0 36.2 1.2 1.8 1.7 0.9 1.1
4,096 field1 1.6 1.3 39.7 32.6 1.2 1.8 1.7 0.9 1.0
8,192 field1 1.6 1.3 39.6 30.5 1.2 1.8 1.7 0.9 1.0
16,384 field1 1.6 1.3 39.8 28.4 1.2 1.8 1.7 0.8 1.0
32,768 field1 1.6 1.3 40.0 26.7 1.3 1.8 1.7 0.8 1.0
65,536 field1 1.6 1.3 39.8 26.3 1.3 1.8 1.7 0.8 1.0
131,072 field1 1.6 1.3 40.1 25.4 1.4 1.9 1.8 0.8 1.0
262,144 field1 1.6 1.3 39.6 25.2 1.5 1.9 1.9 0.8 1.0
-server
MODE (forwards and backwards tests combined)Note: this is the test for Java 32 bit running in server mode on an AMD64. The server mode for Java 64 bit was the same as Java 32 bit in client mode except that Field access starting winning after 32 characters size.
Size WINNER charAt1 charAt2 stream streamPar reuse new1 new2 field1 field2
1 charAt 74.5 95.5 524.5 783.0 90.5 102.5 90.5 135.0 151.5
2 charAt 48.5 53.0 305.0 30851.3 59.3 57.5 52.0 88.5 91.8
4 charAt 28.8 32.1 132.8 2465.1 37.6 33.9 32.3 49.0 47.0
8 new2 18.0 18.6 63.4 1541.3 18.5 17.9 17.6 25.4 25.8
16 new2 14.0 14.7 129.4 1034.7 12.5 16.2 12.0 16.0 16.6
32 new2 7.8 9.1 19.3 431.5 8.1 7.0 6.7 7.9 8.7
64 reuse 6.1 7.5 11.7 204.7 3.5 3.9 4.3 4.2 4.1
128 reuse 6.8 6.8 9.0 101.0 2.6 3.0 3.0 2.6 2.7
256 field2 6.2 6.5 6.9 57.2 2.4 2.7 2.9 2.3 2.3
512 reuse 4.3 4.9 5.8 28.2 2.0 2.6 2.6 2.1 2.1
1,024 charAt 2.0 1.8 5.3 17.6 2.1 2.5 3.5 2.0 2.0
2,048 charAt 1.9 1.7 5.2 11.9 2.2 3.0 2.6 2.0 2.0
4,096 charAt 1.9 1.7 5.1 8.7 2.1 2.6 2.6 1.9 1.9
8,192 charAt 1.9 1.7 5.1 7.6 2.2 2.5 2.6 1.9 1.9
16,384 charAt 1.9 1.7 5.1 6.9 2.2 2.5 2.5 1.9 1.9
32,768 charAt 1.9 1.7 5.1 6.1 2.2 2.5 2.5 1.9 1.9
65,536 charAt 1.9 1.7 5.1 5.5 2.2 2.4 2.4 1.9 1.9
131,072 charAt 1.9 1.7 5.1 5.4 2.3 2.5 2.5 1.9 1.9
262,144 charAt 1.9 1.7 5.1 5.1 2.3 2.5 2.5 1.9 1.9
(to test on Java 7 and earlier, remove the two streams tests)
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.function.IntPredicate;
/**
* @author Saint Hill <http://stackoverflow.com/users/1584255/saint-hill>
*/
public final class TestStrings {
// we will not test strings longer than 512KM
final int MAX_STRING_SIZE = 1024 * 256;
// for each string size, we will do all the tests
// this many times
final int TRIES_PER_STRING_SIZE = 1000;
public static void main(String[] args) throws Exception {
new TestStrings().run();
}
void run() throws Exception {
// double the length of the data until it reaches MAX chars long
// 0,1,2,4,8,16,32,64,128,256 ...
final List<Integer> sizes = new ArrayList<>();
for (int n = 0; n <= MAX_STRING_SIZE; n = (n == 0 ? 1 : n * 2)) {
sizes.add(n);
}
// CREATE RANDOM (FOR SHUFFLING ORDER OF TESTS)
final Random random = new Random();
System.out.println("Rate in nanoseconds per character inspected.");
System.out.printf("==== FORWARDS (tries per size: %s) ==== \n", TRIES_PER_STRING_SIZE);
printHeadings(TRIES_PER_STRING_SIZE, random);
for (int size : sizes) {
reportResults(size, test(size, TRIES_PER_STRING_SIZE, random));
}
// reverse order or string sizes
Collections.reverse(sizes);
System.out.println("");
System.out.println("Rate in nanoseconds per character inspected.");
System.out.printf("==== BACKWARDS (tries per size: %s) ==== \n", TRIES_PER_STRING_SIZE);
printHeadings(TRIES_PER_STRING_SIZE, random);
for (int size : sizes) {
reportResults(size, test(size, TRIES_PER_STRING_SIZE, random));
}
}
///
///
/// METHODS OF CHECKING THE CONTENTS
/// OF A STRING. ALWAYS CHECKING FOR
/// WHITESPACE (CHAR <=' ')
///
///
// CHECK THE STRING CONTENTS
int charAtMethod1(final String data) {
final int len = data.length();
for (int i = 0; i < len; i++) {
if (data.charAt(i) <= ' ') {
doThrow();
}
}
return len;
}
// SAME AS ABOVE BUT USE String.length()
// instead of making a new final local int
int charAtMethod2(final String data) {
for (int i = 0; i < data.length(); i++) {
if (data.charAt(i) <= ' ') {
doThrow();
}
}
return data.length();
}
// USE new Java-8 String's IntStream
// pass it a PREDICATE to do the checking
int streamMethod(final String data, final IntPredicate predicate) {
if (data.chars().anyMatch(predicate)) {
doThrow();
}
return data.length();
}
// OH LA LA - GO PARALLEL!!!
int streamParallelMethod(final String data, IntPredicate predicate) {
if (data.chars().parallel().anyMatch(predicate)) {
doThrow();
}
return data.length();
}
// Re-fill a resuable char[] with the contents
// of the String's char[]
int reuseBuffMethod(final char[] reusable, final String data) {
final int len = data.length();
data.getChars(0, len, reusable, 0);
for (int i = 0; i < len; i++) {
if (reusable[i] <= ' ') {
doThrow();
}
}
return len;
}
// Obtain a new copy of char[] from String
int newMethod1(final String data) {
final int len = data.length();
final char[] copy = data.toCharArray();
for (int i = 0; i < len; i++) {
if (copy[i] <= ' ') {
doThrow();
}
}
return len;
}
// Obtain a new copy of char[] from String
// but use FOR-EACH
int newMethod2(final String data) {
for (final char c : data.toCharArray()) {
if (c <= ' ') {
doThrow();
}
}
return data.length();
}
// FANCY!
// OBTAIN FIELD FOR ACCESS TO THE STRING'S
// INTERNAL CHAR[]
int fieldMethod1(final Field field, final String data) {
try {
final char[] chars = (char[]) field.get(data);
final int len = chars.length;
for (int i = 0; i < len; i++) {
if (chars[i] <= ' ') {
doThrow();
}
}
return len;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
// same as above but use FOR-EACH
int fieldMethod2(final Field field, final String data) {
final char[] chars;
try {
chars = (char[]) field.get(data);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
for (final char c : chars) {
if (c <= ' ') {
doThrow();
}
}
return chars.length;
}
/**
*
* Make a list of tests. We will shuffle a copy of this list repeatedly
* while we repeat this test.
*
* @param data
* @return
*/
List<Jobber> makeTests(String data) throws Exception {
// make a list of tests
final List<Jobber> tests = new ArrayList<Jobber>();
tests.add(new Jobber("charAt1") {
int check() {
return charAtMethod1(data);
}
});
tests.add(new Jobber("charAt2") {
int check() {
return charAtMethod2(data);
}
});
tests.add(new Jobber("stream") {
final IntPredicate predicate = new IntPredicate() {
public boolean test(int value) {
return value <= ' ';
}
};
int check() {
return streamMethod(data, predicate);
}
});
tests.add(new Jobber("streamPar") {
final IntPredicate predicate = new IntPredicate() {
public boolean test(int value) {
return value <= ' ';
}
};
int check() {
return streamParallelMethod(data, predicate);
}
});
// Reusable char[] method
tests.add(new Jobber("reuse") {
final char[] cbuff = new char[MAX_STRING_SIZE];
int check() {
return reuseBuffMethod(cbuff, data);
}
});
// New char[] from String
tests.add(new Jobber("new1") {
int check() {
return newMethod1(data);
}
});
// New char[] from String
tests.add(new Jobber("new2") {
int check() {
return newMethod2(data);
}
});
// Use reflection for field access
tests.add(new Jobber("field1") {
final Field field;
{
field = String.class.getDeclaredField("value");
field.setAccessible(true);
}
int check() {
return fieldMethod1(field, data);
}
});
// Use reflection for field access
tests.add(new Jobber("field2") {
final Field field;
{
field = String.class.getDeclaredField("value");
field.setAccessible(true);
}
int check() {
return fieldMethod2(field, data);
}
});
return tests;
}
/**
* We use this class to keep track of test results
*/
abstract class Jobber {
final String name;
long nanos;
long chars;
long runs;
Jobber(String name) {
this.name = name;
}
abstract int check();
final double nanosPerChar() {
double charsPerRun = chars / runs;
long nanosPerRun = nanos / runs;
return charsPerRun == 0 ? nanosPerRun : nanosPerRun / charsPerRun;
}
final void run() {
runs++;
long time = System.nanoTime();
chars += check();
nanos += System.nanoTime() - time;
}
}
// MAKE A TEST STRING OF RANDOM CHARACTERS A-Z
private String makeTestString(int testSize, char start, char end) {
Random r = new Random();
char[] data = new char[testSize];
for (int i = 0; i < data.length; i++) {
data[i] = (char) (start + r.nextInt(end));
}
return new String(data);
}
// WE DO THIS IF WE FIND AN ILLEGAL CHARACTER IN THE STRING
public void doThrow() {
throw new RuntimeException("Bzzzt -- Illegal Character!!");
}
/**
* 1. get random string of correct length 2. get tests (List<Jobber>) 3.
* perform tests repeatedly, shuffling each time
*/
List<Jobber> test(int size, int tries, Random random) throws Exception {
String data = makeTestString(size, 'A', 'Z');
List<Jobber> tests = makeTests(data);
List<Jobber> copy = new ArrayList<>(tests);
while (tries-- > 0) {
Collections.shuffle(copy, random);
for (Jobber ti : copy) {
ti.run();
}
}
// check to make sure all char counts the same
long runs = tests.get(0).runs;
long count = tests.get(0).chars;
for (Jobber ti : tests) {
if (ti.runs != runs && ti.chars != count) {
throw new Exception("Char counts should match if all correct algorithms");
}
}
return tests;
}
private void printHeadings(final int TRIES_PER_STRING_SIZE, final Random random) throws Exception {
System.out.print(" Size");
for (Jobber ti : test(0, TRIES_PER_STRING_SIZE, random)) {
System.out.printf("%9s", ti.name);
}
System.out.println("");
}
private void reportResults(int size, List<Jobber> tests) {
System.out.printf("%6d", size);
for (Jobber ti : tests) {
System.out.printf("%,9.2f", ti.nanosPerChar());
}
System.out.println("");
}
}
If you have successfully deleted from workspace tab but still it is showing in drop down menu. Then also you can successfully remove that by following these steps:
user_name will be your username of your computer
There will be two tag
varName = "RecentlyUsedWorkspaces" remove the deleted workspace tag
A propertyList tag will be there with varName=deleted_workspace_name delete that tag.
from drop down menu workspace name will be deleted
The reason you separate the login and non-login shell is because the .bashrc
file is reloaded every time you start a new copy of Bash. The .profile
file is loaded only when you either log in or use the appropriate flag to tell Bash to act as a login shell.
Personally,
PATH
setup into a .profile
file (because I sometimes use other shells);.bashrc
file;I put this
#!/bin/bash
#
# CRM .bash_profile Time-stamp: "2008-12-07 19:42"
#
# echo "Loading ${HOME}/.bash_profile"
source ~/.profile # get my PATH setup
source ~/.bashrc # get my Bash aliases
in my .bash_profile
file.
Oh, and the reason you need to type bash
again to get the new alias is that Bash loads your .bashrc
file when it starts but it doesn't reload it unless you tell it to. You can reload the .bashrc
file (and not need a second shell) by typing
source ~/.bashrc
which loads the .bashrc
file as if you had typed the commands directly to Bash.
So probably not the best solution, but seems to work OK.
<IFRAME ID=myframe SRC=.... ></IFRAME>
<SCRIPT>
window.onload = function(){document.getElementById('myframe').contentWindow.document.body.style = 'zoom:50%;';};
</SCRIPT>
Obviously not trying to fix the parent, just adding the "zoom:50%" style to the body of the child with a bit of javascript.
Maybe could set the style of the "HTML" element, but didn't try that.
Here are 535 ways to reload a page using javascript, very cool:
Here are the first 20:
location = location
location = location.href
location = window.location
location = self.location
location = window.location.href
location = self.location.href
location = location['href']
location = window['location']
location = window['location'].href
location = window['location']['href']
location = window.location['href']
location = self['location']
location = self['location'].href
location = self['location']['href']
location = self.location['href']
location.assign(location)
location.replace(location)
window.location.assign(location)
window.location.replace(location)
self.location.assign(location)
and the last 10:
self['location']['replace'](self.location['href'])
location.reload()
location['reload']()
window.location.reload()
window['location'].reload()
window.location['reload']()
window['location']['reload']()
self.location.reload()
self['location'].reload()
self.location['reload']()
self['location']['reload']()
Here's your method:
public static Calendar toCalendar(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
}
Everything else you are doing is both wrong and unnecessary.
BTW, Java Naming conventions suggest that method names start with a lower case letter, so it should be: dateToCalendar
or toCalendar
(as shown).
OK, let's milk your code, shall we?
DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
date = (Date)formatter.parse(date.toString());
DateFormat
is used to convert Strings to Dates (parse()
) or Dates to Strings (format()
). You are using it to parse the String representation of a Date back to a Date. This can't be right, can it?
The second way is a tad more efficient, but a much better way is to execute them in batches:
public void executeBatch(List<Entity> entities) throws SQLException {
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL);
) {
for (Entity entity : entities) {
statement.setObject(1, entity.getSomeProperty());
// ...
statement.addBatch();
}
statement.executeBatch();
}
}
You're however dependent on the JDBC driver implementation how many batches you could execute at once. You may for example want to execute them every 1000 batches:
public void executeBatch(List<Entity> entities) throws SQLException {
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL);
) {
int i = 0;
for (Entity entity : entities) {
statement.setObject(1, entity.getSomeProperty());
// ...
statement.addBatch();
i++;
if (i % 1000 == 0 || i == entities.size()) {
statement.executeBatch(); // Execute every 1000 items.
}
}
}
}
As to the multithreaded environments, you don't need to worry about this if you acquire and close the connection and the statement in the shortest possible scope inside the same method block according the normal JDBC idiom using try-with-resources statement as shown in above snippets.
If those batches are transactional, then you'd like to turn off autocommit of the connection and only commit the transaction when all batches are finished. Otherwise it may result in a dirty database when the first bunch of batches succeeded and the later not.
public void executeBatch(List<Entity> entities) throws SQLException {
try (Connection connection = dataSource.getConnection()) {
connection.setAutoCommit(false);
try (PreparedStatement statement = connection.prepareStatement(SQL)) {
// ...
try {
connection.commit();
} catch (SQLException e) {
connection.rollback();
throw e;
}
}
}
}
Please note that --tests
option may not work if you have different build types/flavors
(fails with Unknown command-line option '--tests'
). In this case, it's necessary to specify the particular test task (e.g. testProdReleaseUnitTest
instead of just test
)
foo.instance_of? String
or
foo.kind_of? String
if you you only care if it is derrived from String
somewhere up its inheritance chain
My jQuery ajax settings:
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: url,
dataType: "json",
type: "post",
data: params,
success: function (resp){
....
},
error: responseFunc
});
And now i am able to get the request via $request->all()
in Laravel
dataType: "json"
is the important part in the ajax request to handle the response as an json object and not string.
I had this same error but only on my staging server not my production environment. nodejs was already installed on both environments.
By typing:
which node
I found out that the node command was located in: /usr/bin/node on production but: /usr/local/bin/node in staging.
After creating a symlink on staging i.e. :
sudo ln -s /usr/local/bin/node /usr/bin/node
the application then worked in staging.
No muss no fuss.
You can use pydoc
.
Open your terminal and type python -m pydoc list.append
The advantage of pydoc
over help()
is that you do not have to import a module to look at its help text.
For instance python -m pydoc random.randint
.
Also you can start an HTTP server to interactively browse documentation by typing python -m pydoc -b
(python 3)
For more information python -m pydoc
I amended the code from stej (which was great, just what i needed!) to use larger buffer, [long] for larger files and used System.Diagnostics.Stopwatch class to track elapsed time and estimate time remaining.
Also added reporting of transfer rate during transfer and outputting overall elapsed time and overall transfer rate.
Using 4MB (4096*1024 bytes) buffer to get better than Win7 native throughput copying from NAS to USB stick on laptop over wifi.
On To-Do list:
Feel free to use/improve :-)
function Copy-File {
param( [string]$from, [string]$to)
$ffile = [io.file]::OpenRead($from)
$tofile = [io.file]::OpenWrite($to)
Write-Progress `
-Activity "Copying file" `
-status ($from.Split("\")|select -last 1) `
-PercentComplete 0
try {
$sw = [System.Diagnostics.Stopwatch]::StartNew();
[byte[]]$buff = new-object byte[] (4096*1024)
[long]$total = [long]$count = 0
do {
$count = $ffile.Read($buff, 0, $buff.Length)
$tofile.Write($buff, 0, $count)
$total += $count
[int]$pctcomp = ([int]($total/$ffile.Length* 100));
[int]$secselapsed = [int]($sw.elapsedmilliseconds.ToString())/1000;
if ( $secselapsed -ne 0 ) {
[single]$xferrate = (($total/$secselapsed)/1mb);
} else {
[single]$xferrate = 0.0
}
if ($total % 1mb -eq 0) {
if($pctcomp -gt 0)`
{[int]$secsleft = ((($secselapsed/$pctcomp)* 100)-$secselapsed);
} else {
[int]$secsleft = 0};
Write-Progress `
-Activity ($pctcomp.ToString() + "% Copying file @ " + "{0:n2}" -f $xferrate + " MB/s")`
-status ($from.Split("\")|select -last 1) `
-PercentComplete $pctcomp `
-SecondsRemaining $secsleft;
}
} while ($count -gt 0)
$sw.Stop();
$sw.Reset();
}
finally {
write-host (($from.Split("\")|select -last 1) + `
" copied in " + $secselapsed + " seconds at " + `
"{0:n2}" -f [int](($ffile.length/$secselapsed)/1mb) + " MB/s.");
$ffile.Close();
$tofile.Close();
}
}
Anyone using composer dependencies, you might want to consider this library: https://github.com/ramsey/uuid
It doesn't get any easier than this:
Uuid::uuid4();
Is this what you are trying? I have commented the code so that you will not have any problem understanding it.
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long, lCol As Long
Dim rng As Range
'~~> Set this to the relevant worksheet
Set ws = [Sheet1]
With ws
'~~> Get the last row and last column
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
'~~> Set the range
Set rng = .Range(.Cells(lRow, 1), .Cells(lRow, lCol))
With rng
Debug.Print .Address
'
'~~> What ever you want to do with the address
'
End With
End With
End Sub
BTW I am assuming that LastRow
is the same for all rows and same goes for the columns. If that is not the case then you will have use .Find
to find the Last Row and the Last Column. You might want to see THIS
This is a broad question and there are multiple ways you can achieve this. In my experience, I've seen a lot of single page applications having an entry point file such as index.js
. This file would be responsible for 'bootstrapping' the application and will be your entry point for webpack.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Application from './components/Application';
const root = document.getElementById('someElementIdHere');
ReactDOM.render(
<Application />,
root,
);
Your <Application />
component would contain the next pieces of your app. You've stated you want different pages and that leads me to believe you're using some sort of routing. That could be included into this component along with any libraries that need to be invoked on application start. react-router
, redux
, redux-saga
, react-devtools
come to mind. This way, you'll only need to add a single entry point into your webpack configuration and everything will trickle down in a sense.
When you've setup a router, you'll have options to set a component to a specific matched route. If you had a URL of /about
, you should create the route in whatever routing package you're using and create a component of About.js
with whatever information you need.
Make sure that you have the correct layout, and that the RecyclerView id is inside the layout. Otherwise, you will be getting this error. I had the same problem, then I noticed the layout was wrong.
public class ColorsFragment extends Fragment {
public ColorsFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
==> make sure you are getting the correct layout here. R.layout...
View rootView = inflater.inflate(R.layout.fragment_colors, container, false);
I didn't realise from your original question that you were opening a file on the local machine, I thought you were sending a file from the web server to the client.
Based on your screenshot, try formatting your link like so:
<a href="file:///C:/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">Klik hier</a>
(without knowing the contents of each of your recordset variables I can't give you the exact ASP code)
I created the following function to generate an html table from an arbitrary JSON object:
function toTable(json, colKeyClassMap, rowKeyClassMap){
let tab;
if(typeof colKeyClassMap === 'undefined'){
colKeyClassMap = {};
}
if(typeof rowKeyClassMap === 'undefined'){
rowKeyClassMap = {};
}
const newTable = '<table class="table table-bordered table-condensed table-striped" />';
if($.isArray(json)){
if(json.length === 0){
return '[]'
} else {
const first = json[0];
if($.isPlainObject(first)){
tab = $(newTable);
const row = $('<tr />');
tab.append(row);
$.each( first, function( key, value ) {
row.append($('<th />').addClass(colKeyClassMap[key]).text(key))
});
$.each( json, function( key, value ) {
const row = $('<tr />');
$.each( value, function( key, value ) {
row.append($('<td />').addClass(colKeyClassMap[key]).html(toTable(value, colKeyClassMap, rowKeyClassMap)))
});
tab.append(row);
});
return tab;
} else if ($.isArray(first)) {
tab = $(newTable);
$.each( json, function( key, value ) {
const tr = $('<tr />');
const td = $('<td />');
tr.append(td);
$.each( value, function( key, value ) {
td.append(toTable(value, colKeyClassMap, rowKeyClassMap));
});
tab.append(tr);
});
return tab;
} else {
return json.join(", ");
}
}
} else if($.isPlainObject(json)){
tab = $(newTable);
$.each( json, function( key, value ) {
tab.append(
$('<tr />')
.append($('<th style="width: 20%;"/>').addClass(rowKeyClassMap[key]).text(key))
.append($('<td />').addClass(rowKeyClassMap[key]).html(toTable(value, colKeyClassMap, rowKeyClassMap))));
});
return tab;
} else if (typeof json === 'string') {
if(json.slice(0, 4) === 'http'){
return '<a target="_blank" href="'+json+'">'+json+'</a>';
}
return json;
} else {
return ''+json;
}
};
So you can simply call:
$('#mydiv').html(toTable([{"city":"AMBALA","cStatus":"Y"},{"city":"ASANKHURD","cStatus":"Y"},{"city":"ASSANDH","cStatus":"Y"}]));
According to IE 9 – What’s Changed? on the HttpWatch blog, IE9 still has a 2 connection limit when over VPN.
Using a VPN Still Clobbers IE 9 Performance
We previously reported about the scaling back of the maximum number of concurrent connections in IE 8 when your PC uses a VPN connection. This happened even if the browser traffic didn’t go over that connection.
Unfortunately, IE 9 is affected by VPN connections in the same way:
I use this: if you declare var x = 0; before the functions declarations, the variable works for all the code files, but the variable will be declare every time that you edit a cell in the spreadsheet
I had the same problem. The answers got me on the right track. So the problem is that functions marked with async don't return a task of the function itself as expected (but another continuation task of the function).
So its the "await"and "async" keywords that screws thing up. The simplest solution then is simply to remove them. Then it works as expected. As in:
static void Main(string[] args)
{
Console.WriteLine("Foo called");
var result = Foo(5);
while (result.Status != TaskStatus.RanToCompletion)
{
Console.WriteLine("Thread ID: {0}, Status: {1}", Thread.CurrentThread.ManagedThreadId, result.Status);
Task.Delay(100).Wait();
}
Console.WriteLine("Result: {0}", result.Result);
Console.WriteLine("Finished.");
Console.ReadKey(true);
}
private static Task<string> Foo(int seconds)
{
return Task.Run(() =>
{
for (int i = 0; i < seconds; i++)
{
Console.WriteLine("Thread ID: {0}, second {1}.", Thread.CurrentThread.ManagedThreadId, i);
Task.Delay(TimeSpan.FromSeconds(1)).Wait();
}
return "Foo Completed.";
});
}
Which outputs:
Foo called
Thread ID: 1, Status: WaitingToRun
Thread ID: 3, second 0.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 3, second 1.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 3, second 2.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 3, second 3.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 3, second 4.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Result: Foo Completed.
Finished.
If you want firebug for Safari, you just have to go to the apple extensions and search for Firebug
I found that I also had to set the Access Modifier in the Resources tab to 'Public' - by default it was set to Internal and my icon only appeared in design mode but not when I ran the application.
None of those worked for me. I was trying to clone a directory from a private git server and entered my credentials false and then it wouldn't let me try different credentials on subsequent tries, it just errored out immediately with an authentication error.
What did work was specifying the user name (mike-wise
)in the url like this:
git clone https://[email protected]/someuser/somerepo.git
I guess setting the position property of the #inner div to relative may also help achieve the effect. But anyways I tried the original code pasted in the Question on IE9 and latest Google Chrome and they already give the desirable effect without any modifications.
var lst = new List<int>() { 1, 2, 3 };
var ans = lst.Where( i => i > 3 );
(ans == null).Dump(); // False
(ans.Count() == 0 ).Dump(); // True
(Dump is from LinqPad)
Actually, the problem is that either /sys/kernel/debug
is not mounted, or that the running kernel has no ftrace tracers compiled in so that /sys/kernel/debug/tracing
is unavailable. This is the code throwing the error (platform_frameworks_native/libs/utils/Trace.cpp
):
void Tracer::init() {
Mutex::Autolock lock(sMutex);
if (!sIsReady) {
add_sysprop_change_callback(changeCallback, 0);
const char* const traceFileName =
"/sys/kernel/debug/tracing/trace_marker";
sTraceFD = open(traceFileName, O_WRONLY);
if (sTraceFD == -1) {
ALOGE("error opening trace file: %s (%d)", strerror(errno), errno);
sEnabledTags = 0; // no tracing can occur
} else {
loadSystemProperty();
}
android_atomic_release_store(1, &sIsReady);
}
}
The log message could definitely be a bit more informative.
You can't initialize your testArray
field this way, because the application resources still aren't ready.
Just change the code to:
package com.xtensivearts.episode.seven;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class Episode7 extends ListActivity {
String[] mTestArray;
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create an ArrayAdapter that will contain all list items
ArrayAdapter<String> adapter;
mTestArray = getResources().getStringArray(R.array.testArray);
/* Assign the name array to that adapter and
also choose a simple layout for the list items */
adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
mTestArray);
// Assign the adapter to this ListActivity
setListAdapter(adapter);
}
}
I think what BrandonS wants is not the position of the mouse relative to the root element, but rather the position of some descendant element.
For that, there is the TransformToAncestor method:
Point relativePoint = myVisual.TransformToAncestor(rootVisual)
.Transform(new Point(0, 0));
Where myVisual
is the element that was just double-clicked, and rootVisual
is Application.Current.MainWindow or whatever you want the position relative to.
I will leave the way I do to submit the form without using the name
tag inside the form:
<button type="submit" onClick="placeOrder(this.form)">Place Order</button>
function placeOrder(form){
form.submit();
}
The shortcut key is ctrl+] to indentation and ctrl +[ to unindent
Further modification from JC_VA, take what he has, and replace the MyModelConverter with...
public class MyModelConverter : JsonConverter
{
//objectType is the type as specified for List<myModel> (i.e. myModel)
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.Load(reader); //json from myModelList > model
var list = Activator.CreateInstance(objectType) as System.Collections.IList; // new list to return
var itemType = objectType.GenericTypeArguments[0]; // type of the list (myModel)
if (token.Type.ToString() == "Object") //Object
{
var child = token.Children();
var newObject = Activator.CreateInstance(itemType);
serializer.Populate(token.CreateReader(), newObject);
list.Add(newObject);
}
else //Array
{
foreach (var child in token.Children())
{
var newObject = Activator.CreateInstance(itemType);
serializer.Populate(child.CreateReader(), newObject);
list.Add(newObject);
}
}
return list;
}
public override bool CanConvert(Type objectType)
{
return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
}
This should work for json that is either
myModelList{
model: [{ ... object ... }]
}
or
myModelList{
model: { ... object ... }
}
they will both end up being parsed as if they were
myModelList{
model: [{ ... object ... }]
}
Let me add a little to Sebastian Roth's answer.
Your project can be compiled by using ndk-build
in the command line after adding the code Sebastian had posted. But as for me, there were syntax errors in Eclipse, and I didn't have code completion.
Note that your project must be converted to a C/C++ project.
How to convert a C/C++ project
To fix this issue right-click on your project, click Properties
Choose C/C++ General -> Paths and Symbols and include the ${ANDROID_NDK}/sources/cxx-stl/stlport/stlport
to Include directories
Click Yes when a dialog shows up.
Before
After
Update #1
GNU C. Add directories, rebuild. There won't be any errors in C source files
GNU C++. Add directories, rebuild. There won't be any errors in CPP source files.
I use combination of several plugins - for the basic assignment of roles and permission I use Role Strategy Plugin.
When I need to split some role depending on parameters (e.g. everybody with job-runner is able to run jobs, but user only user UUU is allowed to run the deployment job to deploy on machine MMM), I use Python Plugin and define a python script as first build step and end with sys.exit(-1) when the job is forbidden to be run with the given combination of parameters.
Build User Vars Plugin provides me the information about the user executing the job as environment variables.
E.g:
import os
import sys
print os.environ["BUILD_USER"], "deploying to", os.environ["target_host"]
# only some users are allowed to deploy to servers "MMM"
mmm_users = ["UUU"]
if os.environ["target_host"] != "MMM" or os.environ["BUILD_USER"] in mmm_users:
print "access granted"
else:
print "access denied"
sys.exit(-1)
Just proof of concept Controler.UpdateModel
won't work correctly.
Full class here:
const string PK = "Id";
protected Models.Entities con;
protected System.Data.Entity.DbSet<T> model;
private void TestUpdate(object item)
{
var props = item.GetType().GetProperties();
foreach (var prop in props)
{
object value = prop.GetValue(item);
if (prop.PropertyType.IsInterface && value != null)
{
foreach (var iItem in (System.Collections.IEnumerable)value)
{
TestUpdate(iItem);
}
}
}
int id = (int)item.GetType().GetProperty(PK).GetValue(item);
if (id == 0)
{
con.Entry(item).State = System.Data.Entity.EntityState.Added;
}
else
{
con.Entry(item).State = System.Data.Entity.EntityState.Modified;
}
}
keep using the id
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserVerification extends Model
{
protected $table = 'user_verification';
protected $fillable = [
'id',
'email',
'verification_token'
];
//$timestamps = false;
protected $primaryKey = 'verification_token';
}
and get the email :
$usr = User::find($id);
$token = $usr->verification_token;
$email = UserVerification::find($token);
Above solutions is also correct, but some time if location is null then it crash the app or not working properly. The best way to get Latitude and Longitude of android is:
Geocoder geocoder;
String bestProvider;
List<Address> user = null;
double lat;
double lng;
LocationManager lm = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
bestProvider = lm.getBestProvider(criteria, false);
Location location = lm.getLastKnownLocation(bestProvider);
if (location == null){
Toast.makeText(activity,"Location Not found",Toast.LENGTH_LONG).show();
}else{
geocoder = new Geocoder(activity);
try {
user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
lat=(double)user.get(0).getLatitude();
lng=(double)user.get(0).getLongitude();
System.out.println(" DDD lat: " +lat+", longitude: "+lng);
}catch (Exception e) {
e.printStackTrace();
}
}
If there is a Relation R(ABC)
-----------
|A | B | C |
-----------
|a | 1 | x |
|b | 1 | x |
|c | 1 | x |
|d | 2 | y |
|e | 2 | y |
|f | 3 | z |
|g | 3 | z |
----------
Given,
F1: A --> B
F2: B --> C
The Primary Key and Candidate Key is: A
As the closure of A+ = {ABC} or R --- So only attribute A is sufficient to find Relation R.
DEF-1: From Some Definitions (unknown source) - A partial dependency is a dependency when prime attribute (i.e., an attribute that is a part(or proper subset) of Candidate Key) determines non-prime attribute (i.e., an attribute that is not the part (or subset) of Candidate Key).
Hence, A is a prime(P) attribute and B, C are non-prime(NP) attributes.
So, from the above DEF-1,
CONSIDERATION-1:: F1: A --> B (P determines NP) --- It must be Partial Dependency.
CONSIDERATION-2:: F2: B --> C (NP determines NP) --- Transitive Dependency.
What I understood from @philipxy answer (https://stackoverflow.com/a/25827210/6009502) is...
CONSIDERATION-1:: F1: A --> B; Should be fully functional dependency because B is completely dependent on A and If we Remove A then there is no proper subset of (for complete clarification consider L.H.S. as X NOT BY SINGLE ATTRIBUTE) that could determine B.
For Example: If I consider F1: X --> Y where X = {A} and Y = {B} then if we remove A from X; i.e., X - {A} = {}; and an empty set is not considered generally (or not at all) to define functional dependency. So, there is no proper subset of X that could hold the dependency F1: X --> Y; Hence, it is fully functional dependency.
F1: A --> B If we remove A then there is no attribute that could hold functional dependency F1. Hence, F1 is fully functional dependency not partial dependency.
If F1 were, F1: AC --> B;
and F2 were, F2: C --> B;
then on the removal of A;
C --> B that means B is still dependent on C;
we can say F1 is partial dependecy.
So, @philipxy answer contradicts DEF-1 and CONSIDERATION-1 that is true and crystal clear.
Hence, F1: A --> B is Fully Functional Dependency not partial dependency.
I have considered X to show left hand side of functional dependency because single attribute couldn't have a proper subset of attributes. Here, I am considering X as a set of attributes and in current scenario X is {A}
-- For the source of DEF-1, please search on google you may be able to hit similar definitions. (Consider that DEF-1 is incorrect or do not work in the above-mentioned example).
I guess you can do this in 5 minute without any further IP/port forwarding, for presenting your local websites temporary.
All you need to do it, go to http://ngrok.com Download small tool extract and run that tool as administrator
Enter command
ngrok http 80
You will see it will connect to server and will create a temporary URL for you which you can share to your friend and let him browse localhost or any of its folder.
You can see detailed process here.
How do I access/share xampp or localhost website from another computer
Yes, it is a non-type parameter. You can have several kinds of template parameters
What you have there is of the last kind. It's a compile time constant (so-called constant expression) and is of type integer or enumeration. After looking it up in the standard, i had to move class templates up into the types section - even though templates are not types. But they are called type-parameters for the purpose of describing those kinds nonetheless. You can have pointers (and also member pointers) and references to objects/functions that have external linkage (those that can be linked to from other object files and whose address is unique in the entire program). Examples:
Template type parameter:
template<typename T>
struct Container {
T t;
};
// pass type "long" as argument.
Container<long> test;
Template integer parameter:
template<unsigned int S>
struct Vector {
unsigned char bytes[S];
};
// pass 3 as argument.
Vector<3> test;
Template pointer parameter (passing a pointer to a function)
template<void (*F)()>
struct FunctionWrapper {
static void call_it() { F(); }
};
// pass address of function do_it as argument.
void do_it() { }
FunctionWrapper<&do_it> test;
Template reference parameter (passing an integer)
template<int &A>
struct SillyExample {
static void do_it() { A = 10; }
};
// pass flag as argument
int flag;
SillyExample<flag> test;
Template template parameter.
template<template<typename T> class AllocatePolicy>
struct Pool {
void allocate(size_t n) {
int *p = AllocatePolicy<int>::allocate(n);
}
};
// pass the template "allocator" as argument.
template<typename T>
struct allocator { static T * allocate(size_t n) { return 0; } };
Pool<allocator> test;
A template without any parameters is not possible. But a template without any explicit argument is possible - it has default arguments:
template<unsigned int SIZE = 3>
struct Vector {
unsigned char buffer[SIZE];
};
Vector<> test;
Syntactically, template<>
is reserved to mark an explicit template specialization, instead of a template without parameters:
template<>
struct Vector<3> {
// alternative definition for SIZE == 3
};
openssl rsa -in privkey.pem -out private.key
does the job.
As for "Why not use int or unsigned int?", simply because it's semantically more meaningful not to. There's the practical reason that it can be, say, typedef
d as an int
and then upgraded to a long
later, without anyone having to change their code, of course, but more fundamentally than that a type is supposed to be meaningful. To vastly simplify, a variable of type size_t
is suitable for, and used for, containing the sizes of things, just like time_t
is suitable for containing time values. How these are actually implemented should quite properly be the implementation's job. Compared to just calling everything int
, using meaningful typenames like this helps clarify the meaning and intent of your program, just like any rich set of types does.
If I am not mistaken, it will be onunload event.
"Occurs when the application is about to be unloaded." - MSDN
If you need to have control over the format of the date (in other words not just the yyyy-mm-dd format is acceptable), another solution could be adding a helper property that is of type string and add a date validator to that property, and bind to this property on UI.
[Display(Name = "Due date")]
[Required]
[AllowHtml]
[DateValidation]
public string DueDateString { get; set; }
public DateTime? DueDate
{
get
{
return string.IsNullOrEmpty(DueDateString) ? (DateTime?)null : DateTime.Parse(DueDateString);
}
set
{
DueDateString = value == null ? null : value.Value.ToString("d");
}
}
And here is a date validator:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class DateValidationAttribute : ValidationAttribute
{
public DateValidationAttribute()
{
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
DateTime date;
if (value is string)
{
if (!DateTime.TryParse((string)value, out date))
{
return new ValidationResult(validationContext.DisplayName + " must be a valid date.");
}
}
else
date = (DateTime)value;
if (date < new DateTime(1900, 1, 1) || date > new DateTime(3000, 12, 31))
{
return new ValidationResult(validationContext.DisplayName + " must be a valid date.");
}
}
return null;
}
}
You cannot mock a final class with Mockito, as you can't do it by yourself.
What I do, is to create a non-final class to wrap the final class and use as delegate. An example of this is TwitterFactory
class, and this is my mockable class:
public class TwitterFactory {
private final twitter4j.TwitterFactory factory;
public TwitterFactory() {
factory = new twitter4j.TwitterFactory();
}
public Twitter getInstance(User user) {
return factory.getInstance(accessToken(user));
}
private AccessToken accessToken(User user) {
return new AccessToken(user.getAccessToken(), user.getAccessTokenSecret());
}
public Twitter getInstance() {
return factory.getInstance();
}
}
The disadvantage is that there is a lot of boilerplate code; the advantage is that you can add some methods that may relate to your application business (like the getInstance that is taking a user instead of an accessToken, in the above case).
In your case I would create a non-final RainOnTrees
class that delegate to the final class. Or, if you can make it non-final, it would be better.
The question is for linux but I had the same issue with git bash on my Windows machine.
My pqsql is installed here:
C:\Program Files\PostgreSQL\10\bin\psql.exe
You can add the location of psql.exe
to your Path environment variable as shown in this screenshot:
After changing the above, please close all cmd
and/or bash
windows, and re-open them (as mentioned in the comments @Ayush Shankar)
You might need to change default logging user using below command.
psql -U postgres
Here postgres
is the username. Without -U
, it will pick the windows loggedin user.
List<T>.Add
adds a single element. Instead, use List<T>.AddRange
to add multiple values.
Additionally, List<T>.AddRange
takes an IEnumerable<T>
, so you don't need to convert tripDetails
into a List<TripDetails>
, you can pass it directly, e.g.:
tripDetailsCollection.AddRange(tripDetails);
Looking into this, it seems like the LibMan approach works best for my needs with adding Bootstrap. I like it because it is now built into Visual Studio 2017(15.8 or later) and has its own dialog boxes.
Update 6/11/2020: bootstrap 4.1.3 is now added by default with VS-2019.5 (Thanks to Harald S. Hanssen for noticing.)
The default method VS adds to projects uses Bower but it looks like it is on the way out. In the header of Microsofts bower page they write:
Following a couple links lead to Use LibMan with ASP.NET Core in Visual Studio where it shows how libs can be added using a built-in Dialog:
In Solution Explorer, right-click the project folder in which the files should be added. Choose Add > Client-Side Library. The Add Client-Side Library dialog appears: [source: Scott Addie 2018]
Then for bootstrap just (1) select the unpkg, (2) type in "bootstrap@.." (3) Install. After this, you would just want to verify all the includes in the _Layout.cshtml or other places are correct. They should be something like href="~/lib/bootstrap/dist/js/bootstrap...")
You can use a span with 50% border radius.
.mydot{_x000D_
background: rgb(66, 183, 42);_x000D_
border-radius: 50%;_x000D_
display: inline-block;_x000D_
height: 20px;_x000D_
margin-left: 4px;_x000D_
margin-right: 4px;_x000D_
width: 20px;_x000D_
}
_x000D_
<span class="mydot"></span>
_x000D_
Mocking is generating pseudo-objects that simulate real objects behaviour for tests
Primary key mainly prevent duplication and shows the uniqueness of columns Foreign key mainly shows relationship on two tables
If you are using SQL server 2016 or higher and if your table is having partitions created based on column you are trying to delete(for example Timestamp column), then you could use this new command to delete data by partitions.
TRUNCATE TABLE WITH ( PARTITIONS ( { | } [ , ...n ] ) )
This will delete the data in selected partition(s) only and should be the most efficient way to delete data from part of table since it will not create transaction logs and will be done just as fast as regular truncate but without having all the data deleted from the table.
Drawback is if your table is not setup with partition, then you need to go old school and delete the data with regular approach and then recreate the table with partitions so that you can do this in future, which is what I did. I added the partition creation and deletion into insertion procedure itself. I had table with 500 million rows so this was the only option to reduce deletion time.
For more details refer to below links: https://docs.microsoft.com/en-us/sql/t-sql/statements/truncate-table-transact-sql?view=sql-server-2017
SQL server 2016 Truncate table with partitions
Below is what I did first to delete the data before I could recreate the table with partitions with required data in it. This query will run for days during specified time window until the data is deleted.
:connect <<ServerName>>
use <<DatabaseName>>
SET NOCOUNT ON;
DECLARE @Deleted_Rows INT;
DECLARE @loopnum INT;
DECLARE @msg varchar(100);
DECLARE @FlagDate datetime;
SET @FlagDate = getdate() - 31;
SET @Deleted_Rows = 1;
SET @loopnum = 1;
/*while (getdate() < convert(datetime,'2018-11-08 14:00:00.000',120))
BEGIN
RAISERROR( 'WAIT for START' ,0,1) WITH NOWAIT
WAITFOR DELAY '00:10:00'
END*/
RAISERROR( 'STARTING PURGE' ,0,1) WITH NOWAIT
WHILE (1=1)
BEGIN
WHILE (@Deleted_Rows > 0 AND (datepart(hh, getdate() ) >= 12 AND datepart(hh, getdate() ) <= 20)) -- (getdate() < convert(datetime,'2018-11-08 19:00:00.000',120) )
BEGIN
-- Delete some small number of rows at a time
DELETE TOP (500000) dbo.<<table_name>>
WHERE timestamp_column < convert(datetime, @FlagDate,102)
SET @Deleted_Rows = @@ROWCOUNT;
WAITFOR DELAY '00:00:01'
select @msg = 'ROWCOUNT' + convert(varchar,@Deleted_Rows);
set @loopnum = @loopnum + 1
if @loopnum > 1000
begin
begin try
DBCC SHRINKFILE (N'<<databasename>>_log' , 0, TRUNCATEONLY)
RAISERROR( @msg ,0,1) WITH NOWAIT
end try
begin catch
RAISERROR( 'DBCC SHRINK' ,0,1) WITH NOWAIT
end catch
set @loopnum = 1
end
END
WAITFOR DELAY '00:10:00'
END
select getdate()
Here is the Swift 5
version of Mobile Dan's answer:
public extension NSAttributedString {
convenience init?(_ html: String) {
guard let data = html.data(using: .unicode) else {
return nil
}
try? self.init(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
}
}
Within Databricks you can visualize the dataframe in a tabular format. With the command:
display(results)
It will look like
If you have a need to copy the exact same timestamp data, change the data type in the destination table from timestamp to binary(8) -- i used varbinary(8) and it worked fine.
This obviously breaks any timestamp functionality in the destination table, so make sure you're ok with that first.
Thread thread = new Thread(Work);
thread.Start(Parameter);
private void Work(object param)
{
string Parameter = (string)param;
}
The parameter type must be an object.
EDIT:
While this answer isn't incorrect I do recommend against this approach. Using a lambda expression is much easier to read and doesn't require type casting. See here: https://stackoverflow.com/a/1195915/52551
Not exactly making the cell a link, but the table itself. I use this as a button in e-mails, giving me div-like controls.
<a href="https://www.foo.bar" target="_blank" style="color: white; font-weight: bolder; text-decoration: none;">
<table style="margin-left: auto; margin-right: auto;" align="center">
<tr>
<td style="padding: 20px; height: 60px;" bgcolor="#00b389">Go to Foo Bar</td>
</tr>
</table>
</a>
_x000D_
Edited: optimized code.
public static Bitmap RotateBitmap(Bitmap source, float angle)
{
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
To get Bitmap from resources:
Bitmap source = BitmapFactory.decodeResource(this.getResources(), R.drawable.your_img);
For future reference:
yyyy => 4 digit year
MM => 2 digit month (you must type MM in ALL CAPS)
dd => 2 digit "day of the month"
HH => 2-digit "hour in day" (0 to 23)
mm => 2-digit minute (you must type mm in lowercase)
ss => 2-digit seconds
SSS => milliseconds
So "yyyy-MM-dd HH:mm:ss" returns "2018-01-05 09:49:32"
But "MMM dd, yyyy hh:mm a" returns "Jan 05, 2018 09:49 am"
The so-called examples at https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html show only output. They do not tell you what formats to use!
SET collation_connection = 'utf8_general_ci';
then for your databases
ALTER DATABASE your_database_name CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE your_table_name CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
MySQL sneaks swedish in there sometimes for no sensible reason.
$('').bind('input propertychange', function() {....});
This will work for mouse paste event.
Alternatively, while in your screen session all you have to do is type exit
This will kill the shell session initiated by the screen, which effectively terminates the screen session you are on.
No need to bother with screen session id, etc.
I will just repeat what @Ivo Bosticky said which can be overlooked. Put these lines at the VERY start of the py file.
import matplotlib
matplotlib.use('Agg')
Or one would get error
*/usr/lib/pymodules/python2.7/matplotlib/__init__.py:923: UserWarning: This call to matplotlib.use() has no effect because the the backend has already been chosen; matplotlib.use() must be called *before* pylab, matplotlib.pyplot,*
This will resolve all Display issue
There's many useful things in Python's unicodedata
library. One of them is the .normalize()
function.
Try:
new_str = unicodedata.normalize("NFKD", unicode_str)
Replacing NFKD with any of the other methods listed in the link above if you don't get the results you're after.
Output size of sha1 is 160 bits. Which is 160/8 == 20 chars (if you use 8-bit chars) or 160/16 = 10 (if you use 16-bit chars).
Java 8
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int arr[] = Arrays.stream(in.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
here is linked a bitter article by Joel Spolsky, but contains a good distinction between toolboxes, libraries, frameworks and such
You cannot rely on CSS for form elements. The results vary wildly across all the browsers. I don't think Safari lets you customize any form elements at all.
Your best bet is to use a plugin like jqTransform (uses jQuery).
EDIT: that page doesn't seem to be working at the moment. There is also Custom Form Elements which supports MooTools and may support jQuery in the future.
'So from this discussion i am thinking this should be the code then.
Sub Button1_Click()
Dim excel As excel.Application
Dim wb As excel.Workbook
Dim sht As excel.Worksheet
Dim f As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = False
f.Show
Set excel = CreateObject("excel.Application")
Set wb = excel.Workbooks.Open(f.SelectedItems(1))
Set sht = wb.Worksheets("Data")
sht.Activate
sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
wb.Close
End Sub
'Let me know if this is correct or a step was missed. Thx.
You could make an array the same size as the ArrayList
and then make an iterated for loop to index the items and insert them into the array.
You have two typing errors in your code:
struct timeval,
should be
struct timeval
and after the printf()
parenthesis you need a semicolon.
Also, depending on the compiler, so simple a cycle might just be optimized out, giving you a time of 0 microseconds whatever you do.
Finally, the time calculation is wrong. You only take into accounts the seconds, ignoring the microseconds. You need to get the difference between seconds, multiply by one million, then add "after" tv_usec
and subtract "before" tv_usec
. You gain nothing by casting an integer number of seconds to a float.
I'd suggest checking out the man page for struct timeval
.
This is the code:
#include <stdio.h>
#include <sys/time.h>
int main (int argc, char** argv) {
struct timeval tvalBefore, tvalAfter; // removed comma
gettimeofday (&tvalBefore, NULL);
int i =0;
while ( i < 10000) {
i ++;
}
gettimeofday (&tvalAfter, NULL);
// Changed format to long int (%ld), changed time calculation
printf("Time in microseconds: %ld microseconds\n",
((tvalAfter.tv_sec - tvalBefore.tv_sec)*1000000L
+tvalAfter.tv_usec) - tvalBefore.tv_usec
); // Added semicolon
return 0;
}
Add a unique id to all your instances, i.e.
public interface Idable {
int id();
}
public class IdGenerator {
private static int id = 0;
public static synchronized int generate() { return id++; }
}
public abstract class AbstractSomething implements Idable {
private int id;
public AbstractSomething () {
this.id = IdGenerator.generate();
}
public int id() { return id; }
}
Extend from AbstractSomething and query this property. Will be safe inside a single vm (assuming no game playing with classloaders to get around statics).
For anyone coming here in 2018:
You have to include the expression for your calculated column:
SELECT
ColumnA,
ColumnB,
ColumnA + ColumnB AS calccolumn1
(ColumnA + ColumnB) / ColumnC AS calccolumn2
You are testing if the values of the variables error
and Already
are present in RepoOutput[RepoName.index(repo)]
. If these variables don't exist then an undefined object is used.
Both of your if
and elif
tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].
I think you wanted to test if certain strings are in the value instead:
{% if "error" in RepoOutput[RepoName.index(repo)] %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
<td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>
Other corrections I made:
{% elif ... %}
instead of {$ elif ... %}
.</tr>
tag out of the if
conditional structure, it needs to be there always.id
attributeNote that most likely you want to use a class
attribute instead here, not an id
, the latter must have a value that must be unique across your HTML document.
Personally, I'd set the class value here and reduce the duplication a little:
{% if "Already" in RepoOutput[RepoName.index(repo)] %}
{% set row_class = "good" %}
{% else %}
{% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>
If you are writing in C++ -- it is a way better to use data structures from standard library such as vector.
C-style arrays are very error-prone, and should be avoided whenever possible.
You can use:
mse = ((A - B)**2).mean(axis=ax)
Or
mse = (np.square(A - B)).mean(axis=ax)
ax=0
the average is performed along the row, for each column, returning an arrayax=1
the average is performed along the column, for each row, returning an arrayax=None
the average is performed element-wise along the array, returning a scalar valueThe non-greedy regex modifiers are like their greedy counter-parts but with a ?
immediately following them:
* - zero or more
*? - zero or more (non-greedy)
+ - one or more
+? - one or more (non-greedy)
? - zero or one
?? - zero or one (non-greedy)
Follow these step:
File -> Project Structure -> Project SDK(Select the SDK Path in the Android SDK) -> OK
Make sure your device is connected to the PC.
Open GitBash and type: flutter devices. Then run your flutter app.It will work.
Personally I prefer this method. This will overwrite the file on the destination, removes the source file and also prevent removing the source file when the copy fails.
string source = @"c:\test\SomeFile.txt";
string destination = @"c:\test\test\SomeFile.txt";
try
{
File.Copy(source, destination, true);
File.Delete(source);
}
catch
{
//some error handling
}
I have encountered this problem as well. Here is my solution:
Below is the error while running a small Spring Application:-
*HTTP Status 500 -
--------------------------------------------------------------------------------
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/employe.jsp at line 12
9: <form:form method="POST" commandName="command" action="/SpringWeb/addEmploye">
10: <table>
11: <tr>
12: <td><form:label path="name">Name</form:label></td>
13: <td><form:input path="name" /></td>
14: </tr>
15: <tr>
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:465)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194)
org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:129)
org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:119)
org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:89)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79)
org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspx_meth_form_005flabel_005f0(employe_jsp.java:185)
org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspx_meth_form_005fform_005f0(employe_jsp.java:120)
org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspService(employe_jsp.java:80)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.26 logs.*
In order to resolve this issue you need to do the following in the controller class:-
import org.springframework.web.portlet.ModelAndView;
"
to "import org.springframework.web.servlet.ModelAndView;
"...Open notepad and paste the code below into it. Change "YourApp" into your app's name. Save it to YourApp.reg and execute it by clicking on it in explorer. That's it! Cheers! Erwin Haantjes
REGEDIT4
[HKEY_CLASSES_ROOT\YourApp]
@="URL:YourApp Protocol"
"URL Protocol"=""
[HKEY_CLASSES_ROOT\YourApp\DefaultIcon]
@="\"C:\\Program Files\\YourApp\\YourApp.exe\""
[HKEY_CLASSES_ROOT\YourApp\shell]
[HKEY_CLASSES_ROOT\YourApp\shell\open]
[HKEY_CLASSES_ROOT\YourApp\shell\open\command]
@="\"C:\\Program Files\\YourApp\\YourApp.exe\" \"%1\" \"%2\" \"%3\" \"%4\" \"%5\" \"%6\" \"%7\" \"%8\" \"%9\""
I would suggest doing this in a more functional style :P
function CreateMessageboard(BoardMessages) {
var htmlMessageboardString = BoardMessages
.map(function(BoardMessage) {
return MessageToHTMLString(BoardMessage);
})
.join('');
}
Try this
CSV stands for comma separated values. CSV is like a text file and can be created simply by adding the .CSV extension
for example write this code:
f = open('example.csv','w')
f.write("display,variable x")
f.close()
you can open this file with excel.
In IE9, it is possible with purely a hack as advised by @Spudley. Since you've customized height and width of the div and select, you need to change div:before
css to match yours.
In case if it is IE10 then using below css3 it is possible
select::-ms-expand {
display: none;
}
However if you're interested in jQuery plugin, try Chosen.js
or you can create your own in js.
Starting from Framework v4.5 you can use Activator.CreateInstanceFrom() to easily instantiate classes within assemblies. The following example shows how to use it and how to call a method passing parameters and getting return value.
// Assuming moduleFileName contains full or valid relative path to assembly
var moduleInstance = Activator.CreateInstanceFrom(moduleFileName, "MyNamespace.MyClass");
MethodInfo mi = moduleInstance.Unwrap().GetType().GetMethod("MyMethod");
// Assuming the method returns a boolean and accepts a single string parameter
bool rc = Convert.ToBoolean(mi.Invoke(moduleInstance.Unwrap(), new object[] { "MyParamValue" } ));
I had a similar issue when deploying from OSx on my local to my Linux live site.
It ran fine on OSx, but on Linux I was getting:
An Error Was Encountered
Unable to load the requested class: Ckeditor
The problem was that Linux paths are apparently case-sensitive so I had to rename my library files from "ckeditor.php" to "CKEditor.php".
I also changed my load call to match the capitalization:
$this->load->library('CKEditor');
To solve your other problem, where you need to set scrolled
if the user scrolls manually, you'd have to attach a handler to the window scroll event. Generally this is a bad idea as the handler will fire a lot, a common technique is to set a timeout, like so:
var timer = 0;
$(window).scroll(function() {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function() {
scrolled = $(window).scrollTop();
}, 250);
});
Application.Sum often does not work well in my experience (or at least the VBA developer environment does not like it for whatever reason).
The function that works best for me is Excel.WorksheetFunction.Sum()
Example:
Dim Report As Worksheet 'Set up your new worksheet variable.
Set Report = Excel.ActiveSheet 'Assign the active sheet to the variable.
Report.Cells(11, 1).Value = Excel.WorksheetFunction.Sum(Report.Range("A1:A10")) 'Add the function result.
The other method which you were looking for I think is to place the function directly into the cell. This can be done by inputting the function string into the cell value. Here is an example that provides the same result as above, except the cell value is given the function and not the result of the function:
Dim Report As Worksheet 'Set up your new worksheet variable.
Set Report = Excel.ActiveSheet 'Assign the active sheet to the variable.
Report.Cells(11, 1).Value = "=Sum(A1:A10)" 'Add the function.
EntityManager.persist()
makes an entity persistent whereas EntityManager.flush()
actually runs the query on your database.
So, when you call EntityManager.flush()
, queries for inserting/updating/deleting associated entities are executed in the database. Any constraint failures (column width, data types, foreign key) will be known at this time.
The concrete behaviour depends on whether flush-mode is AUTO or COMMIT.
Just in case you forgot or avoided to copy through PHPMYADMIN export feature..
Procedure: You can manually copy: Procedure For MAC OS, for latest versions of XAMPP
Location : Find the database folders here /Users/XXXXUSER/XAMPP/xamppfiles/var/mysql..
Solution: Copy the entire folder with database names into your new xampp in similar folder.
Hope it helps, happy coding.
I'm not sure what you want, but i'll use lattice.
x = rep(x,2)
y = c(y1,y2)
fac.data = as.factor(rep(1:2,each=5))
df = data.frame(x=x,y=y,z=fac.data)
# this create a data frame where I have a factor variable, z, that tells me which data I have (y1 or y2)
Then, just plot
xyplot(y ~x|z, df)
# or maybe
xyplot(x ~y|z, df)
tl;dr
"Foo" and "bar" as metasyntactic variables were popularised by MIT and DEC, the first references are in work on LISP and PDP-1 and Project MAC from 1964 onwards.
Many of these people were in MIT's Tech Model Railroad Club, where we find the first documented use of "foo" in tech circles in 1959 (and a variant in 1958).
Both "foo" and "bar" (and even "baz") were well known in popular culture, especially from Smokey Stover and Pogo comics, which will have been read by many TMRC members.
Also, it seems likely the military FUBAR contributed to their popularity.
The use of lone "foo" as a nonsense word is pretty well documented in popular culture in the early 20th century, as is the military FUBAR. (Some background reading: FOLDOC FOLDOC Jargon File Jargon File Wikipedia RFC3092)
OK, so let's find some references.
STOP PRESS! After posting this answer, I discovered this perfect article about "foo" in the Friday 14th January 1938 edition of The Tech ("MIT's oldest and largest newspaper & the first newspaper published on the web"), Volume LVII. No. 57, Price Three Cents:
On Foo-ism
The Lounger thinks that this business of Foo-ism has been carried too far by its misguided proponents, and does hereby and forthwith take his stand against its abuse. It may be that there's no foo like an old foo, and we're it, but anyway, a foo and his money are some party. (Voice from the bleachers- "Don't be foo-lish!")
As an expletive, of course, "foo!" has a definite and probably irreplaceable position in our language, although we fear that the excessive use to which it is currently subjected may well result in its falling into an early (and, alas, a dark) oblivion. We say alas because proper use of the word may result in such happy incidents as the following.
It was an 8.50 Thermodynamics lecture by Professor Slater in Room 6-120. The professor, having covered the front side of the blackboard, set the handle that operates the lift mechanism, turning meanwhile to the class to continue his discussion. The front board slowly, majestically, lifted itself, revealing the board behind it, and on that board, writ large, the symbols that spelled "FOO"!
The Tech newspaper, a year earlier, the Letter to the Editor, September 1937:
By the time the train has reached the station the neophytes are so filled with the stories of the glory of Phi Omicron Omicron, usually referred to as Foo, that they are easy prey.
...
It is not that I mind having lost my first four sons to the Grand and Universal Brotherhood of Phi Omicron Omicron, but I do wish that my fifth son, my baby, should at least be warned in advance.
Hopefully yours,
Indignant Mother of Five.
And The Tech in December 1938:
General trend of thought might be best interpreted from the remarks made at the end of the ballots. One vote said, '"I don't think what I do is any of Pulver's business," while another merely added a curt "Foo."
The first documented "foo" in tech circles is probably 1959's Dictionary of the TMRC Language:
FOO: the sacred syllable (FOO MANI PADME HUM); to be spoken only when under inspiration to commune with the Deity. Our first obligation is to keep the Foo Counters turning.
These are explained at FOLDOC. The dictionary's compiler Pete Samson said in 2005:
Use of this word at TMRC antedates my coming there. A foo counter could simply have randomly flashing lights, or could be a real counter with an obscure input.
And from 1996's Jargon File 4.0.0:
Earlier versions of this lexicon derived 'baz' as a Stanford corruption of bar. However, Pete Samson (compiler of the TMRC lexicon) reports it was already current when he joined TMRC in 1958. He says "It came from "Pogo". Albert the Alligator, when vexed or outraged, would shout 'Bazz Fazz!' or 'Rowrbazzle!' The club layout was said to model the (mythical) New England counties of Rowrfolk and Bassex (Rowrbazzle mingled with (Norfolk/Suffolk/Middlesex/Essex)."
A year before the TMRC dictionary, 1958's MIT Voo Doo Gazette ("Humor suplement of the MIT Deans' office") (PDF) mentions Foocom, in "The Laws of Murphy and Finagle" by John Banzhaf (an electrical engineering student):
Further research under a joint Foocom and Anarcom grant expanded the law to be all embracing and universally applicable: If anything can go wrong, it will!
Also 1964's MIT Voo Doo (PDF) references the TMRC usage:
Yes! I want to be an instant success and snow customers. Send me a degree in: ...
Foo Counters
Foo Jung
Let's find "foo", "bar" and "foobar" published in code examples.
So, Jargon File 4.4.7 says of "foobar":
Probably originally propagated through DECsystem manuals by Digital Equipment Corporation (DEC) in 1960s and early 1970s; confirmed sightings there go back to 1972.
The first published reference I can find is from February 1964, but written in June 1963, The Programming Language LISP: its Operation and Applications by Information International, Inc., with many authors, but including Timothy P. Hart and Michael Levin:
Thus, since "FOO" is a name for itself, "COMITRIN" will treat both "FOO" and "(FOO)" in exactly the same way.
Also includes other metasyntactic variables such as: FOO CROCK GLITCH / POOT TOOR / ON YOU / SNAP CRACKLE POP / X Y Z
I expect this is much the same as this next reference of "foo" from MIT's Project MAC in January 1964's AIM-064, or LISP Exercises by Timothy P. Hart and Michael Levin:
car[((FOO . CROCK) . GLITCH)]
It shares many other metasyntactic variables like: CHI / BOSTON NEW YORK / SPINACH BUTTER STEAK / FOO CROCK GLITCH / POOT TOOP / TOOT TOOT / ISTHISATRIVIALEXCERCISE / PLOOP FLOT TOP / SNAP CRACKLE POP / ONE TWO THREE / PLANE SUB THRESHER
For both "foo" and "bar" together, the earliest reference I could find is from MIT's Project MAC in June 1966's AIM-098, or PDP-6 LISP by none other than Peter Samson:
EXPLODE, like PRIN1, inserts slashes, so (EXPLODE (QUOTE FOO/ BAR)) PRIN1's as (F O O // / B A R) or PRINC's as (F O O / B A R).
Some more recallations.
@Walter Mitty recalled on this site in 2008:
I second the jargon file regarding Foo Bar. I can trace it back at least to 1963, and PDP-1 serial number 2, which was on the second floor of Building 26 at MIT. Foo and Foo Bar were used there, and after 1964 at the PDP-6 room at project MAC.
John V. Everett recalls in 1996:
When I joined DEC in 1966, foobar was already being commonly used as a throw-away file name. I believe fubar became foobar because the PDP-6 supported six character names, although I always assumed the term migrated to DEC from MIT. There were many MIT types at DEC in those days, some of whom had worked with the 7090/7094 CTSS. Since the 709x was also a 36 bit machine, foobar may have been used as a common file name there.
Foo and bar were also commonly used as file extensions. Since the text editors of the day operated on an input file and produced an output file, it was common to edit from a .foo file to a .bar file, and back again.
It was also common to use foo to fill a buffer when editing with TECO. The text string to exactly fill one disk block was IFOO$HXA127GA$$. Almost all of the PDP-6/10 programmers I worked with used this same command string.
Daniel P. B. Smith in 1998:
Dick Gruen had a device in his dorm room, the usual assemblage of B-battery, resistors, capacitors, and NE-2 neon tubes, which he called a "foo counter." This would have been circa 1964 or so.
Robert Schuldenfrei in 1996:
The use of FOO and BAR as example variable names goes back at least to 1964 and the IBM 7070. This too may be older, but that is where I first saw it. This was in Assembler. What would be the FORTRAN integer equivalent? IFOO and IBAR?
Paul M. Wexelblat in 1992:
The earliest PDP-1 Assembler used two characters for symbols (18 bit machine) programmers always left a few words as patch space to fix problems. (Jump to patch space, do new code, jump back) That space conventionally was named FU: which stood for Fxxx Up, the place where you fixed Fxxx Ups. When spoken, it was known as FU space. Later Assemblers ( e.g. MIDAS allowed three char tags so FU became FOO, and as ALL PDP-1 programmers will tell you that was FOO space.
Bruce B. Reynolds in 1996:
On the IBM side of FOO(FU)BAR is the use of the BAR side as Base Address Register; in the middle 1970's CICS programmers had to worry out the various xxxBARs...I think one of those was FRACTBAR...
Here's a straight IBM "BAR" from 1955.
Other early references:
1973 foo bar International Joint Council on Artificial Intelligence
1975 foo bar International Joint Council on Artificial Intelligence
I haven't been able to find any references to foo bar as "inverted foo signal" as suggested in RFC3092 and elsewhere.
Here are a some of even earlier F00s but I think they're coincidences/false positives:
The other way to tackle it is to use this code snippet:
JSON.parse(JSON.stringify(response)).data
This feels so wrong but it works
Editted:
In order to flex only the center text, a different approach can be taken - Unflex the other views.
alignItems : 'center'
from containeralignSelf:'center'
to the textviews that you don't want to flexYou can wrap the Text component in a View component and give the View a flex of 1.
The flex will give :
100% width if the flexDirection:'row'
in styles.container
100% height if the flexDirection:'column'
in styles.container
It is interesting to note that strconv.Itoa
is shorthand for
func FormatInt(i int64, base int) string
with base 10
For Example:
strconv.Itoa(123)
is equivalent to
strconv.FormatInt(int64(123), 10)
For multiple headers do as follow:
import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('param1', '212212')
req.add_header('param2', '12345678')
req.add_header('other_param1', 'sample')
req.add_header('other_param2', 'sample1111')
req.add_header('and_any_other_parame', 'testttt')
resp = urllib2.urlopen(req)
content = resp.read()
I've had exactly the same problem as you for a while now, and after looking at some of the suggestions above, I finally solved the problem.
It turns out (at least for me anyway), I needed to supply a key (a prop called 'key') to the component I am returning from my renderSeparator method. Adding a key to my renderRow or renderSectionHeader didn't do anything, but adding it to renderSeparator made the warning go away.
Hope that helps.
A simple js can solve this:
document.getElementById("idName").style.background = "blue";
You need the get the values from the query string (since you dont have a method set, your using GET by default)
use the following tutorial.
http://papermashup.com/read-url-get-variables-withjavascript/
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
You can use pip install scikit-image
.
Also see the recommended procedure.
I did it like this
echo "NEO4J_ULIMIT_NOFILE=50000" >> neo4j
mv neo4j /etc/default/
PARTITION BY
segregate sets, this enables you to be able to work(ROW_NUMBER(),COUNT(),SUM(),etc) on related set independently.
In your query, the related set comprised of rows with similar cdt.country_code, cdt.account, cdt.currency. When you partition on those columns and you apply ROW_NUMBER on them. Those other columns on those combination/set will receive sequential number from ROW_NUMBER
But that query is funny, if your partition by some unique data and you put a row_number on it, it will just produce same number. It's like you do an ORDER BY on a partition that is guaranteed to be unique. Example, think of GUID as unique combination of cdt.country_code, cdt.account, cdt.currency
newid()
produces GUID, so what shall you expect by this expression?
select
hi,ho,
row_number() over(partition by newid() order by hi,ho)
from tbl;
...Right, all the partitioned(none was partitioned, every row is partitioned in their own row) rows' row_numbers are all set to 1
Basically, you should partition on non-unique columns. ORDER BY on OVER needed the PARTITION BY to have a non-unique combination, otherwise all row_numbers will become 1
An example, this is your data:
create table tbl(hi varchar, ho varchar);
insert into tbl values
('A','X'),
('A','Y'),
('A','Z'),
('B','W'),
('B','W'),
('C','L'),
('C','L');
Then this is analogous to your query:
select
hi,ho,
row_number() over(partition by hi,ho order by hi,ho)
from tbl;
What will be the output of that?
HI HO COLUMN_2
A X 1
A Y 1
A Z 1
B W 1
B W 2
C L 1
C L 2
You see thee combination of HI HO? The first three rows has unique combination, hence they are set to 1, the B rows has same W, hence different ROW_NUMBERS, likewise with HI C rows.
Now, why is the ORDER BY
needed there? If the previous developer merely want to put a row_number on similar data (e.g. HI B, all data are B-W, B-W), he can just do this:
select
hi,ho,
row_number() over(partition by hi,ho)
from tbl;
But alas, Oracle(and Sql Server too) doesn't allow partition with no ORDER BY
; whereas in Postgresql, ORDER BY
on PARTITION is optional: http://www.sqlfiddle.com/#!1/27821/1
select
hi,ho,
row_number() over(partition by hi,ho)
from tbl;
Your ORDER BY
on your partition look a bit redundant, not because of the previous developer's fault, some database just don't allow PARTITION
with no ORDER BY
, he might not able find a good candidate column to sort on. If both PARTITION BY columns and ORDER BY columns are the same just remove the ORDER BY, but since some database don't allow it, you can just do this:
SELECT cdt.*,
ROW_NUMBER ()
OVER (PARTITION BY cdt.country_code, cdt.account, cdt.currency
ORDER BY newid())
seq_no
FROM CUSTOMER_DETAILS cdt
You cannot find a good column to use for sorting similar data? You might as well sort on random, the partitioned data have the same values anyway. You can use GUID for example(you use newid()
for SQL Server). So that has the same output made by previous developer, it's unfortunate that some database doesn't allow PARTITION
with no ORDER BY
Though really, it eludes me and I cannot find a good reason to put a number on the same combinations (B-W, B-W in example above). It's giving the impression of database having redundant data. Somehow reminded me of this: How to get one unique record from the same list of records from table? No Unique constraint in the table
It really looks arcane seeing a PARTITION BY with same combination of columns with ORDER BY, can not easily infer the code's intent.
Live test: http://www.sqlfiddle.com/#!3/27821/6
But as dbaseman have noticed also, it's useless to partition and order on same columns.
You have a set of data like this:
create table tbl(hi varchar, ho varchar);
insert into tbl values
('A','X'),
('A','X'),
('A','X'),
('B','Y'),
('B','Y'),
('C','Z'),
('C','Z');
Then you PARTITION BY hi,ho; and then you ORDER BY hi,ho. There's no sense numbering similar data :-) http://www.sqlfiddle.com/#!3/29ab8/3
select
hi,ho,
row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;
Output:
HI HO ROW_QUERY_A
A X 1
A X 2
A X 3
B Y 1
B Y 2
C Z 1
C Z 2
See? Why need to put row numbers on same combination? What you will analyze on triple A,X, on double B,Y, on double C,Z? :-)
You just need to use PARTITION on non-unique column, then you sort on non-unique column(s)'s unique-ing column. Example will make it more clear:
create table tbl(hi varchar, ho varchar);
insert into tbl values
('A','D'),
('A','E'),
('A','F'),
('B','F'),
('B','E'),
('C','E'),
('C','D');
select
hi,ho,
row_number() over(partition by hi order by ho) as nr
from tbl;
PARTITION BY hi
operates on non unique column, then on each partitioned column, you order on its unique column(ho), ORDER BY ho
Output:
HI HO NR
A D 1
A E 2
A F 3
B E 1
B F 2
C D 1
C E 2
That data set makes more sense
Live test: http://www.sqlfiddle.com/#!3/d0b44/1
And this is similar to your query with same columns on both PARTITION BY and ORDER BY:
select
hi,ho,
row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;
And this is the ouput:
HI HO NR
A D 1
A E 1
A F 1
B E 1
B F 1
C D 1
C E 1
See? no sense?
Live test: http://www.sqlfiddle.com/#!3/d0b44/3
Finally this might be the right query:
SELECT cdt.*,
ROW_NUMBER ()
OVER (PARTITION BY cdt.country_code, cdt.account -- removed: cdt.currency
ORDER BY
-- removed: cdt.country_code, cdt.account,
cdt.currency) -- keep
seq_no
FROM CUSTOMER_DETAILS cdt
Even if the question is old, a more accurate answer about Management Studio would be required.
You can create the column manually or with Management Studio. But Management Studio will require to recreate the table and will result in a time out if you have too much data in it already, avoid unless the table is light.
To change the order of the columns you simply need to move them around in Management Studio. This should not require (Exceptions most likely exists) that Management Studio to recreate the table since it most likely change the ordination of the columns in the table definitions.
I've done it this way on numerous occasion with tables that I could not add columns with the GUI because of the data in them. Then moved the columns around with the GUI of Management Studio and simply saved them.
You will go from an assured time out to a few seconds of waiting.
With git 2.10+ (Q3 2016: released Sept. 2d, 2016), you have the possibility to set a config for GIT_SSH_COMMAND
(and not just an environment variable as described in Rober Jack Will's answer)
See commit 3c8ede3 (26 Jun 2016) by Nguy?n Thái Ng?c Duy (pclouds
).
(Merged by Junio C Hamano -- gitster
-- in commit dc21164, 19 Jul 2016)
A new configuration variable
core.sshCommand
has been added to specify what value forGIT_SSH_COMMAND
to use per repository.
core.sshCommand:
If this variable is set,
git fetch
andgit push
will use the specified command instead ofssh
when they need to connect to a remote system.
The command is in the same form as theGIT_SSH_COMMAND
environment variable and is overridden when the environment variable is set.
It means the git pull
can be:
cd /path/to/my/repo/already/cloned
git config core.sshCommand 'ssh -i private_key_file'
# later on
git pull
You can even set it for just one command like git clone
:
git -c core.sshCommand="ssh -i private_key_file" clone host:repo.git
This is easier than setting a GIT_SSH_COMMAND
environment variable, which, on Windows, as noted by Mátyás Kuti-Kreszács, would be
set "GIT_SSH_COMMAND=ssh -i private_key_file"
The simpler and current approach for adding header to a single request is:
// Step 1
const yourHeader: HttpHeaders = new HttpHeaders({
Authorization: 'Bearer JWT-token'
});
// POST request
this.http.post(url, body, { headers: yourHeader });
// GET request
this.http.get(url, { headers: yourHeader });
Perl solution:
perl -lane 'splice @F,0,2; print join " ",@F' file
These command-line options are used:
-n
loop around every line of the input file, do not automatically print every line
-l
removes newlines before processing, and adds them back in afterwards
-a
autosplit mode – split input lines into the @F array. Defaults to splitting on whitespace
-e
execute the perl code
splice @F,0,2
cleanly removes columns 0 and 1 from the @F array
join " ",@F
joins the elements of the @F array, using a space in-between each element
If your input file is comma-delimited, rather than space-delimited, use -F, -lane
Python solution:
python -c "import sys;[sys.stdout.write(' '.join(line.split()[2:]) + '\n') for line in sys.stdin]" < file