The View::make
function takes 3 arguments which according to the documentation are:
public View make(string $view, array $data = array(), array $mergeData = array())
In your case, the compact('selections')
is a 4th argument. It doesn't pass to the view and laravel throws an exception.
On the other hand, you can use with()
as many time as you like. Thus, this will work:
return View::make('gameworlds.mygame')
->with(compact('fixtures'))
->with(compact('teams'))
->with(compact('selections'));
In Mgmt Studio, when you are editing the top 200, you can view the SQL pane - either by right clicking in the grid and choosing Pane->SQL or by the button in the upper left. This will allow you to write a custom query to drill down to the row(s) you want to edit.
But ultimately mgmt studio isn't a data entry/update tool which is why this is a little cumbersome.
Refactor your second.sh
script like this:
function func1 {
fun=$1
book=$2
printf "fun=%s,book=%s\n" "${fun}" "${book}"
}
function func2 {
fun2=$1
book2=$2
printf "fun2=%s,book2=%s\n" "${fun2}" "${book2}"
}
And then call these functions from script first.sh
like this:
source ./second.sh
func1 love horror
func2 ball mystery
fun=love,book=horror
fun2=ball,book2=mystery
It is always encouraged in C++ that you have one class per header file, see this discussion in SO [1].
GManNickG answer's tells why this happen. But the best way to solve this is to put User
class in one header file (User.h
) and MyMessageBox
class in another header file (MyMessageBox.h
). Then in your User.h
you include MyMessageBox.h
and in MyMessageBox.h
you include User.h
. Do not forget "include gaurds" [2] so that your code compiles successfully.
The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.
The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.
Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.
From your feature branch (e.g configUpdate
) run:
git fetch
git rebase origin/master
Or the shorter form:
git pull --rebase
Why this works:
git merge branchname
takes new commits from the branch branchname
, and adds them to the current branch. If necessary, it automatically adds a "Merge" commit on top.
git rebase branchname
takes new commits from the branch branchname
, and inserts them "under" your changes. More precisely, it modifies the history of the current branch such that it is based on the tip of branchname
, with any changes you made on top of that.
git pull
is basically the same as git fetch; git merge origin/master
.
git pull --rebase
is basically the same as git fetch; git rebase origin/master
.
So why would you want to use git pull --rebase
rather than git pull
? Here's a simple example:
You start working on a new feature.
By the time you're ready to push your changes, several commits have been pushed by other developers.
If you git pull
(which uses merge), your changes will be buried by the new commits, in addition to an automatically-created merge commit.
If you git pull --rebase
instead, git will fast forward your master to upstream's, then apply your changes on top.
Or you can change position of specific
div
using class name
$(document).scroll(function(e){
var scrollTop = $(document).scrollTop();
if(scrollTop > 0){
//console.log(scrollTop);
$('.header').css("position","fixed");
} else {
$('.header').css("position","relative");
}
});
I know this has been answered before but I know a lot of people get tripped up on this, so I'm going to add a comment.
I had this exact same problem happen on my Nexus One. This was from the file not existing on the disk before the camera app started. Therefore, I made sure that the file existing before started the camera app. Here's some sample code that I used:
String storageState = Environment.getExternalStorageState();
if(storageState.equals(Environment.MEDIA_MOUNTED)) {
String path = Environment.getExternalStorageDirectory().getName() + File.separatorChar + "Android/data/" + MainActivity.this.getPackageName() + "/files/" + md5(upc) + ".jpg";
_photoFile = new File(path);
try {
if(_photoFile.exists() == false) {
_photoFile.getParentFile().mkdirs();
_photoFile.createNewFile();
}
} catch (IOException e) {
Log.e(TAG, "Could not create file.", e);
}
Log.i(TAG, path);
_fileUri = Uri.fromFile(_photoFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra( MediaStore.EXTRA_OUTPUT, _fileUri);
startActivityForResult(intent, TAKE_PICTURE);
} else {
new AlertDialog.Builder(MainActivity.this)
.setMessage("External Storeage (SD Card) is required.\n\nCurrent state: " + storageState)
.setCancelable(true).create().show();
}
I first create a unique (somewhat) file name using an MD5 hash and put it into the appropriate folder. I then check to see if it exists (shouldn't, but its good practice to check anyway). If it does not exist, I get the parent dir (a folder) and create the folder hierarchy up to it (therefore if the folders leading up to the location of the file don't exist, they will after this line. Then after that I create the file. Once the file is created I get the Uri and pass it to the intent and then the OK button works as expected and all is golden.
Now,when the Ok button is pressed on the camera app, the file will be present in the given location. In this example it would be /sdcard/Android/data/com.example.myapp/files/234asdioue23498ad.jpg
There is no need to copy the file in the "onActivityResult" as posted above.
If anyone looking for a solution with (.less) try below. Open your main or common less file and use like below.
@import (css) url('https://fonts.googleapis.com/css?family=Open+Sans:400,700');
body{
font-family: "Open Sans", sans-serif;
}
Follow this :)
/etc/systemd/system/tomcat.service
Can you see JAVA_HOME ? : modify it like below
Environment="JAVA_HOME=/usr/lib/jvm/java-1.11.0-openjdk-amd64"
At 1.11.0 - insert your own Jdk version
systemctl daemon-reload
sudo systemctl start tomcat
Now, in eclipse -> Add Server -> .....
Got struck at tomcat installation directory ??
Extract
the tomcat tar file you already downloaded.Point to extracted file
(done in step 1 above :)Comment if you get struck in somewhere else too )
You were very close, you can use this:
DELETE FROM table WHERE (col1,col2) IN ((1,2),(3,4),(5,6))
Please see this fiddle.
switch(i)
will throw a NullPointerException if i is null
, because it will try to unbox the Integer
into an int
. So case null
, which happens to be illegal, would never have been reached anyway.
You need to check that i is not null before the switch
statement.
$('div[id ^= "player_"]');
This worked for me..select all Div starts with "players_" keyword and display it.
//If "x" is between "a" and "b";
.....
int m = (a+b)/2;
if(Math.abs(x-m) <= (Math.abs(a-m)))
{
(operations)
}
......
//have to use floating point conversions if the summ is not even;
Simple example :
//if x is between 10 and 20
if(Math.abs(x-15)<=5)
I've just asked a similar question and here's my solution based on answer received (using boost::filesystem
library):
#include <string>
#include <iostream>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;
int main()
{
path p("D:/AnyFolder");
for (auto i = directory_iterator(p); i != directory_iterator(); i++)
{
if (!is_directory(i->path())) //we eliminate directories in a list
{
cout << i->path().filename().string() << endl;
}
else
continue;
}
}
Output is like:
file1.txt
file2.dat
At its simplest:
#include <iostream>
using namespace std;
class A {
public:
A( int x ) : n( x ){}
void print() { cout << n << endl; }
private:
int n;
};
void func( A p ) {
p.print();
}
int main () {
A a;
func ( a );
}
Of course, you should probably be using references to pass the object, but I suspect you haven't got to them yet.
I had this problem even after setting the config properly. git config
My scenario was issuing git command through supervisor (in Linux). On further debugging, supervisor was not reading the git config from home folder. Hence, I had to set the environment HOME variable in the supervisor config so that it can locate the git config correctly. It's strange that supervisor was not able to locate the git config just from the username configured in supervisor's config (/etc/supervisor/conf.d).
I think you need to define an object and then push in array
var obj = {};
obj[name] = val;
ary.push(obj);
Try this first:
git checkout master
(If you're on a different branch than master
, use the branch name there instead.)
If that doesn't work, try...
For a single file:
git checkout HEAD /path/to/file
For the entire repository working copy:
git reset --hard HEAD
And if that doesn't work, then you can look in the reflog to find your old head SHA and reset to that:
git reflog
git reset --hard <sha from reflog>
HEAD
is a name that always points to the latest commit in your current branch.
Create a Route attribute for your method.
example
[Route("api/Get")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
You can call like these http://localhost/api/Get
If you are already using Apache Commons Lang, the RandomUtils
makes this a one-liner:
byte[] randomBytes = RandomUtils.nextBytes(20);
Note: this does not produce cryptographically-secure bytes.
<div
style="-moz-user-select: none; -webkit-user-select: none; -ms-user-select:none; user-select:none;-o-user-select:none;"
unselectable="on"
onselectstart="return false;"
onmousedown="return false;">
Blabla
</div>
In OnCreate method of your activity use this code:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Now your orientation will be set to portrait and will never change.
Don't run with a space between the directory and the filename:
python /root/Desktop/1 hello.py
Use a /
instead:
python /root/Desktop/1/hello.py
Scanner's buffer full when we take a input string through scan.nextLine(); so it skips the input next time . So solution is that we can create a new object of Scanner , the name of the object can be same as previous object......
For anyone else who stumbles on this make sure you're not attempting to modify the class rather than the instance! (unless you've declared the variable as static)
eg.
MyClass.variable = 'Foo' // WRONG! - Instance member 'variable' cannot be used on type 'MyClass'
instanceOfMyClass.variable = 'Foo' // Right!
after complete the code first merge branch to master then delete that branch
git checkout master
git merge <branch-name>
git branch -d <branch-name>
use data-html="true"
and apply <br>
.
Greetings if i get you right you need a JavaScript function that doing it
function report(v) {
//To Do
switch(v) {
case "daily":
//Do something
break;
case "monthly":
//Do somthing
break;
}
}
Regards
Recursion in Python works just as recursion in an other language, with the recursive construct defined in terms of itself:
For example a recursive class could be a binary tree (or any tree):
class tree():
def __init__(self):
'''Initialise the tree'''
self.Data = None
self.Count = 0
self.LeftSubtree = None
self.RightSubtree = None
def Insert(self, data):
'''Add an item of data to the tree'''
if self.Data == None:
self.Data = data
self.Count += 1
elif data < self.Data:
if self.LeftSubtree == None:
# tree is a recurive class definition
self.LeftSubtree = tree()
# Insert is a recursive function
self.LeftSubtree.Insert(data)
elif data == self.Data:
self.Count += 1
elif data > self.Data:
if self.RightSubtree == None:
self.RightSubtree = tree()
self.RightSubtree.Insert(data)
if __name__ == '__main__':
T = tree()
# The root node
T.Insert('b')
# Will be put into the left subtree
T.Insert('a')
# Will be put into the right subtree
T.Insert('c')
As already mentioned a recursive structure must have a termination condition. In this class, it is not so obvious because it only recurses if new elements are added, and only does it a single time extra.
Also worth noting, python by default has a limit to the depth of recursion available, to avoid absorbing all of the computer's memory. On my computer this is 1000. I don't know if this changes depending on hardware, etc. To see yours :
import sys
sys.getrecursionlimit()
and to set it :
import sys #(if you haven't already)
sys.setrecursionlimit()
edit: I can't guarentee that my binary tree is the most efficient design ever. If anyone can improve it, I'd be happy to hear how
if you can code, write a console app. here is the c# equivalent of what you're after. you can do what you want with the results (split, execute etc):
SqlCommand command = null;
try
{
using (var connection = new SqlConnection("XXXX"))
{
command = new SqlCommand();
command.Connection = connection;
if (command.Connection.State == ConnectionState.Closed) command.Connection.Open();
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("C:\\test.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
command.CommandText = line;
command.ExecuteNonQuery();
Console.Write(" - DONE");
}
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
finally
{
if (command.Connection.State == ConnectionState.Open) command.Connection.Close();
}
You can also try with ng build
. I've just rebuilt the app and now it's not complying.
In my case, I reinstalled Python. It solved the problem.
brew reinstall python
A full outer join combines a left outer join and a right outer join. The result set returns rows from both tables where the conditions are met but returns null columns where there is no match.
A cross join is a Cartesian product that does not require any condition to join tables. The result set contains rows and columns that are a multiplication of both tables.
you can use this code:
$("body").css("overflow", "hidden");
The m000493
method seems to perform some kind of XOR encryption. This means that the same method can be used for both encrypting and decrypting the text. All you have to do is reverse m0001cd
:
string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));
string result = m000493(p0, "_p0lizei.");
// result == "gaia^unplugged^Ta..."
with return m0001cd(builder3.ToString());
changed to return builder3.ToString();
.
If tomcat is installed locally, type the following url in a browser window: { localhost:8080 }
This will display Tomcat home page with the following message.
If you're seeing this, you've successfully installed Tomcat. Congratulations!
If tomcat is installed on a separate server, you can type replace localhost by a valid hostname or Iess where tomcat is installed.
The above applies for a standard installation wherein tomcat uses the default port 8080
def find_offsets(haystack, needle):
"""
Find the start of all (possibly-overlapping) instances of needle in haystack
"""
offs = -1
while True:
offs = haystack.find(needle, offs+1)
if offs == -1:
break
else:
yield offs
for offs in find_offsets("ooottat", "o"):
print offs
results in
0
1
2
So there might be a few things wrong here.
First start by reading how to use XMLHttpRequest.open()
because there's a third optional parameter for specifying whether to make an asynchronous request, defaulting to true. That means you're making an asynchronous request and need to specify a callback function before you do the send()
. Here's an example from MDN:
var oXHR = new XMLHttpRequest();
oXHR.open("GET", "http://www.mozilla.org/", true);
oXHR.onreadystatechange = function (oEvent) {
if (oXHR.readyState === 4) {
if (oXHR.status === 200) {
console.log(oXHR.responseText)
} else {
console.log("Error", oXHR.statusText);
}
}
};
oXHR.send(null);
Second, since you're getting a 101 error, you might use the wrong URL. So make sure that the URL you're making the request with is correct. Also, make sure that your server is capable of serving your quiz.xml
file.
You'll probably have to debug by simplifying/narrowing down where the problem is. So I'd start by making an easy synchronous request so you don't have to worry about the callback function. So here's another example from MDN for making a synchronous request:
var request = new XMLHttpRequest();
request.open('GET', 'file:///home/user/file.json', false);
request.send(null);
if (request.status == 0)
console.log(request.responseText);
Also, if you're just starting out with Javascript, you could refer to MDN for Javascript API documentation/examples/tutorials.
Very late to the party, but A simple solution is using VBA to create a custom function.
Add the function to VBA in the WorkBook, Worksheet, or a VBA Module
Function LastSegment(S, C)
LastSegment = Right(S, Len(S) - InStrRev(S, C))
End Function
Then the cell formula
=lastsegment(B1,"/")
in a cell and the string to be searched in cell B1 will populate the cell with the text trailing the last "/" from cell B1. No length limit, no obscure formulas. Only downside I can think is the need for a macro-enabled workbook.
Any user VBA Function can be called this way to return a value to a cell formula, including as a parameter to a builtin Excel function.
If you are going to use the function heavily you'll want to check for the case when the character is not in the string, then string is blank, etc.
On Linux, I often use curl with the --head parameter. It is available for several operating systems, including Windows.
[edit] related to the answer below, gknw.net is currently down as of February 23 2012. Check curl.haxx.se for updated info.
This article helped me to make the right choices eventually since mac 10.14.6 by default came with python 2.7* and I had to upgrade to 3.7.*
brew install python3
brew update && brew upgrade python
alias python=/usr/local/bin/python3
Referred The right and wrong way to set Python 3 as default on a Mac article
I figured out a simplest way. You don't need to install package ThenInclude.EF or you don't need to use ThenInclude for all nested navigation properties. Just do like as shown below, EF will take care rest for you. example:
var thenInclude = context.One.Include(x => x.Twoes.Threes.Fours.Fives.Sixes)
.Include(x=> x.Other)
.ToList();
Your first reaction to these methods is quite interesting to me. I will use it in future arguments that both assertTrue and assertFalse are not the most friendly tools. If you would use
assertThat(thisOrThat, is(false));
it is much more readable, and it prints a better error message too.
How about using grep -E
?
echo "This is 02G05 a test string 20-Jul-2012" | grep -Eo '[0-9]+G[0-9]+'
Maybe map the share as a network drive and then do
git clone Z:\
Mostly just a guess; I always do this stuff using ssh. Following that suggstion of course will mean that you'll need to have that drive mapped every time you push/pull to/from the laptop. I'm not sure how you rig up ssh to work under windows but if you're going to be doing this a lot it might be worth investigating.
Though this question has an answer, I resolved it differently when I had the same issue. I had this issue when I copied folders with the option Create Folder references
; then the above solution of adding the folder to the build_path worked.
But when the folder was added using the Create groups for any added folder
option, the headers were picked up automatically.
The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.
The way you get your original array back is by using Convert.FromBase64String
:
byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);
To import from an SQL file use the following:
sqlite> .read <filename>
To import from a CSV file you will need to specify the file type and destination table:
sqlite> .mode csv <table>
sqlite> .import <filename> <table>
Try this:
$(document).ready( function () {
$('#example').dataTable({
"order": []
});
});
this will solve your problem.
It's just a namespace definition to avoid collision of class names. The com.domain.package.Class
is an established Java convention wherein the namespace is qualified with the company domain in reverse.
Change the following to the file
/usr/local/mysql/support-files/mysql.server
the follow lines:
basedir="/usr/local/mysql"
datadir="/usr/local/mysql/data"
and save it.
/etc/rc.common
add the follow line at end:
/usr/local/mysql/bin/mysqld_safe --user=mysql &
FINALLY Got this working after 4 hours of installing, uninstalling, updating, blah blah.
The only thing that did it was to use an older version of node v8.9.1 x64
This was a PC windows 10.
Hope this helps someone.
sunDoesNotRecommendUnderscoresBecauseJavaVariableAndFunctionNamesTendToBeLongEnoughAsItIs(); as_others_have_said_consistency_is_the_important_thing_here_so_chose_whatever_you_think_is_more_readable();
Just download it and save in your network location.
You can get it form the below.
reference: www.thedeveloperblog.com
You will be much happier using a dictionary instead:
my_data = {}
foo = "hello"
my_data[foo] = "goodbye"
assert my_data["hello"] == "goodbye"
Next to the performance issues, there is another one very important which I'd call code maintainability and extendibility.
If a T is POD and you start preferring initialization list, then if one time T will change to a non-POD type, you won't need to change anything around initialization to avoid unnecessary constructor calls because it is already optimised.
If type T does have default constructor and one or more user-defined constructors and one time you decide to remove or hide the default one, then if initialization list was used, you don't need to update code if your user-defined constructors because they are already correctly implemented.
Same with const members or reference members, let's say initially T is defined as follows:
struct T
{
T() { a = 5; }
private:
int a;
};
Next, you decide to qualify a as const, if you would use initialization list from the beginning, then this was a single line change, but having the T defined as above, it also requires to dig the constructor definition to remove assignment:
struct T
{
T() : a(5) {} // 2. that requires changes here too
private:
const int a; // 1. one line change
};
It's not a secret that maintenance is far easier and less error-prone if code was written not by a "code monkey" but by an engineer who makes decisions based on deeper consideration about what he is doing.
One option is to use str
, and then to_datetime
(or similar):
In [11]: str(dt64)
Out[11]: '2012-05-01T01:00:00.000000+0100'
In [12]: pd.to_datetime(str(dt64))
Out[12]: datetime.datetime(2012, 5, 1, 1, 0, tzinfo=tzoffset(None, 3600))
Note: it is not equal to dt
because it's become "offset-aware":
In [13]: pd.to_datetime(str(dt64)).replace(tzinfo=None)
Out[13]: datetime.datetime(2012, 5, 1, 1, 0)
This seems inelegant.
.
Update: this can deal with the "nasty example":
In [21]: dt64 = numpy.datetime64('2002-06-28T01:00:00.000000000+0100')
In [22]: pd.to_datetime(str(dt64)).replace(tzinfo=None)
Out[22]: datetime.datetime(2002, 6, 28, 1, 0)
Putting this information here for future readers' benefit.
401 (Unauthorized) response header -> Request authentication header
Here are several WWW-Authenticate
response headers. (The full list is at IANA: HTTP Authentication Schemes.)
WWW-Authenticate: Basic
-> Authorization: Basic + token - Use for basic authentication WWW-Authenticate: NTLM
-> Authorization: NTLM + token (2 challenges)WWW-Authenticate: Negotiate
-> Authorization: Negotiate + token - used for Kerberos authentication
Negotiate
: This authentication scheme violates both HTTP semantics (being connection-oriented) and syntax (use of syntax incompatible with the WWW-Authenticate and Authorization header field syntax).You can set the Authorization: Basic
header only when you also have the WWW-Authenticate: Basic
header on your 401 challenge.
But since you have WWW-Authenticate: Negotiate
this should be the case for Kerberos based authentication.
I had an issue with the same thing. ChromeOptions is very weird because it's not integrated with the desiredcapabilities like you would think. I forget the exact details, but basically ChromeOptions will reset to default certain values based on whether you did or did not pass a desired capabilities dict.
I did the following monkey-patch that allows me to specify my own dict without worrying about the complications of ChromeOptions
change the following code in /selenium/webdriver/chrome/webdriver.py:
def __init__(self, executable_path="chromedriver", port=0,
chrome_options=None, service_args=None,
desired_capabilities=None, service_log_path=None, skip_capabilities_update=False):
"""
Creates a new instance of the chrome driver.
Starts the service and then creates new instance of chrome driver.
:Args:
- executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH
- port - port you would like the service to run, if left as 0, a free port will be found.
- desired_capabilities: Dictionary object with non-browser specific
capabilities only, such as "proxy" or "loggingPref".
- chrome_options: this takes an instance of ChromeOptions
"""
if chrome_options is None:
options = Options()
else:
options = chrome_options
if skip_capabilities_update:
pass
elif desired_capabilities is not None:
desired_capabilities.update(options.to_capabilities())
else:
desired_capabilities = options.to_capabilities()
self.service = Service(executable_path, port=port,
service_args=service_args, log_path=service_log_path)
self.service.start()
try:
RemoteWebDriver.__init__(self,
command_executor=self.service.service_url,
desired_capabilities=desired_capabilities)
except:
self.quit()
raise
self._is_remote = False
all that changed was the "skip_capabilities_update" kwarg. Now I just do this to set my own dict:
capabilities = dict( DesiredCapabilities.CHROME )
if not "chromeOptions" in capabilities:
capabilities['chromeOptions'] = {
'args' : [],
'binary' : "",
'extensions' : [],
'prefs' : {}
}
capabilities['proxy'] = {
'httpProxy' : "%s:%i" %(proxy_address, proxy_port),
'ftpProxy' : "%s:%i" %(proxy_address, proxy_port),
'sslProxy' : "%s:%i" %(proxy_address, proxy_port),
'noProxy' : None,
'proxyType' : "MANUAL",
'class' : "org.openqa.selenium.Proxy",
'autodetect' : False
}
driver = webdriver.Chrome( executable_path="path_to_chrome", desired_capabilities=capabilities, skip_capabilities_update=True )
From the link Jweede posted:
exception socket.timeout:
This exception is raised when a timeout occurs on a socket which has had timeouts enabled via a prior call to settimeout(). The accompanying value is a string whose value is currently always “timed out”.
Here are the demo server and client programs for the socket module from the python docs
# Echo server program
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
And the client:
# Echo client program
import socket
HOST = 'daring.cwi.nl' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
On the docs example page I pulled these from, there are more complex examples that employ this idea, but here is the simple answer:
Assuming you're writing the client program, just put all your code that uses the socket when it is at risk of being dropped, inside a try block...
try:
s.connect((HOST, PORT))
s.send("Hello, World!")
...
except socket.timeout:
# whatever you need to do when the connection is dropped
The Expires entity-header field gives the date/time after which the response is considered stale.The Cache-control:maxage field gives the age value (in seconds) bigger than which response is consider stale.
Althought above header field give a mechanism to client to decide whether to send request to the server. In some condition, the client send a request to sever and the age value of response is bigger then the maxage value ,dose it means server needs to send the resource to client? Maybe the resource never changed.
In order to resolve this problem, HTTP1.1 gives last-modifided head. The server gives the last modified date of the response to client. When the client need this resource, it will send If-Modified-Since head field to server. If this date is before the modified date of the resouce, the server will sends the resource to client and gives 200 code.Otherwise,it will returns 304 code to client and this means client can use the resource it cached.
next in package.json file add in scripts "start": "babel-node server.js"
{
"name": "node",
"version": "1.0.0",
"description": "",
"main": "server.js",
"dependencies": {
"body-parser": "^1.18.2",
"express": "^4.16.2",
"lodash": "^4.17.4",
"mongoose": "^5.0.1"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-0": "^6.24.1"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "babel-node server.js"
},
"keywords": [],
"author": "",
"license": "ISC"
}
and create file for babel , in root ".babelrc"
{
"presets":[
"es2015",
"stage-0"
]
}
and run npm start in terminal
All of these answers miss a very important aspect!
By using .html or innerHtml or outerHtml you are not actually using the referenced element. You are using a copy of the element's html. This has some serious draw backs.
What you want to do is load the object itself into the popover.
https://jsfiddle.net/shrewmouse/ex6tuzm2/4/
HTML:
<h1> Test </h1>
<div><button id="target">click me</button></div>
<!-- This will be the contents of our popover -->
<div class='_content' id='blah'>
<h1>Extra Stuff</h1>
<input type='number' placeholder='number'/>
</div>
JQuery:
$(document).ready(function() {
// We don't want to see the popover contents until the user clicks the target.
// If you don't hide 'blah' first it will be visible outside of the popover.
//
$('#blah').hide();
// Initialize our popover
//
$('#target').popover({
content: $('#blah'), // set the content to be the 'blah' div
placement: 'bottom',
html: true
});
// The popover contents will not be set until the popover is shown. Since we don't
// want to see the popover when the page loads, we will show it then hide it.
//
$('#target').popover('show');
$('#target').popover('hide');
// Now that the popover's content is the 'blah' dive we can make it visisble again.
//
$('#blah').show();
});
var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
url: "upload.php",
type: "POST",
data : formData,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(data){
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
I was having the same issue. I tried with the compatibility option, but in Windows 10 it doesn't show the compatibility option. The following steps solved the problem for me:
taskschd.msc
as administratorSo somehow setting up the task in taskschd.msc
as a regular user wasn't working, even though my account is an admin one.
Hope this helps anyone having the same issue
use my_list.append(...) and do not use and other list to append as list are mutable.
The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.
> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }
The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.
If you need to, you can easily convert Date
objects to and from Unix timestamps1), using the getTime()
method and Date(milliseconds)
constructor, respectively.
1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.
SELECT *
FROM table_name
WHERE table_name.the_date > DATE_SUB(CURDATE(), INTERVAL 1 DAY)
If you are using mac (OSX) :
On you mac:
If you are testing your website with the address : "localhost:8888/mywebsite" (it depends on your MAMP configurations)
On your phone :
Note : you have to be connected on the same network (wifi)
From http://docs.python.org/library/csv.html#csv.writer:
If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.
In other words, when opening the file you pass 'wb' as opposed to 'w'.
You can also use a with
statement to close the file when you're done writing to it.
Tested example below:
from __future__ import with_statement # not necessary in newer versions
import csv
headers=['id', 'year', 'activity', 'lineitem', 'datum']
with open('file3.csv','wb') as fou: # note: 'wb' instead of 'w'
output = csv.DictWriter(fou,delimiter=',',fieldnames=headers)
output.writerow(dict((fn,fn) for fn in headers))
output.writerows(rows)
You can do something like this, without using any external libraries.
const fs = require("fs");
const https = require("https");
const file = fs.createWriteStream("data.txt");
https.get("https://www.w3.org/TR/PNG/iso_8859-1.txt", response => {
var stream = response.pipe(file);
stream.on("finish", function() {
console.log("done");
});
});
For apache2 server:
AddType application/octect-stream .ova
File location will depend on particular version of Apache2 -- ours is in /etc/apache2/mods-available/mime.conf
Reference:
https://askubuntu.com/questions/610645/how-to-configure-apache2-to-download-files-directly
I do not see it mentioned here, but a command that i use often and that helps me to have a bird's eye view on all groups, topics, partitions, offsets, lags, consumers, etc
kafka-consumer-groups.bat --bootstrap-server localhost:9092 --describe --all-groups
A sample would look like this:
GROUP TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG CONSUMER-ID HOST CLIENT-ID
Group Topic 2 7 7 0 <SOME-ID> XXXX <SOME-ID>
:
:
The most important column is the LAG
, where for a healthy platform, ideally it should be 0
(or nearer to 0 or a low number for high throughput) - at all times. So make sure you monitor it!!! ;-).
P.S:
An interesting article on how you can monitor the lag can be found here.
In C++20 you'll be able to do:
std::cout << std::format("{:03}", 25); // prints 025
In the meantime you can use the {fmt} library, std::format
is based on.
Disclaimer: I'm the author of {fmt} and C++20 std::format
.
Double Click the Login Button in the NETBEANS or add the Event Listener on Click Event (ActionListener)
btnLogin.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
this.setVisible(false);
new FrmMain().setVisible(true); // Main Form to show after the Login Form..
}
});
I use the following code to get the IMEI or use Secure.ANDROID_ID as an alternative, when the device doesn't have phone capabilities:
/**
* Returns the unique identifier for the device
*
* @return unique identifier for the device
*/
public String getDeviceIMEI() {
String deviceUniqueIdentifier = null;
TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
if (null != tm) {
deviceUniqueIdentifier = tm.getDeviceId();
}
if (null == deviceUniqueIdentifier || 0 == deviceUniqueIdentifier.length()) {
deviceUniqueIdentifier = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
}
return deviceUniqueIdentifier;
}
When you open a folder in VSCode, it will automatically scan the folder for typical project artifacts like project.json or solution files. From the status bar in the lower left side you can switch between solutions and projects.
By using fabric js we can solve this security error issue in IE.
function getBase64FromImageUrl(URL) {
var canvas = new fabric.Canvas('c');
var img = new Image();
img.onload = function() {
var canvas1 = document.createElement("canvas");
canvas1.width = this.width;
canvas1.height = this.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL({format: "png"});
};
img.src = URL;
}
Create,Alter,Drop of (Databases,Tables,Keys,Index,Views,Functions,Stored Procedures)
Insert ,Delete,Update,Truncate of (Tables)
SELECT * FROM (
SELECT id, name, form_id, DATE(updated_at) as date
FROM wp_frm_items
WHERE user_id = 11 && form_id=9
ORDER BY updated_at DESC
) AS TEMP
ORDER BY DATE(updated_at) DESC, name DESC
Give it a try.
If you want to show a div after scrolling a number of pixels:
$(document).scroll(function() {
var y = $(this).scrollTop();
if (y > 800) {
$('.bottomMenu').fadeIn();
} else {
$('.bottomMenu').fadeOut();
}
});
$(document).scroll(function() {
var y = $(this).scrollTop();
if (y > 800) {
$('.bottomMenu').fadeIn();
} else {
$('.bottomMenu').fadeOut();
}
});
_x000D_
body {
height: 1600px;
}
.bottomMenu {
display: none;
position: fixed;
bottom: 0;
width: 100%;
height: 60px;
border-top: 1px solid #000;
background: red;
z-index: 1;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Scroll down... </p>
<div class="bottomMenu"></div>
_x000D_
Its simple, but effective.
Documentation for .scroll()
Documentation for .scrollTop()
If you want to show a div after scrolling a number of pixels,
myID = document.getElementById("myID");
var myScrollFunc = function() {
var y = window.scrollY;
if (y >= 800) {
myID.className = "bottomMenu show"
} else {
myID.className = "bottomMenu hide"
}
};
window.addEventListener("scroll", myScrollFunc);
myID = document.getElementById("myID");
var myScrollFunc = function() {
var y = window.scrollY;
if (y >= 800) {
myID.className = "bottomMenu show"
} else {
myID.className = "bottomMenu hide"
}
};
window.addEventListener("scroll", myScrollFunc);
_x000D_
body {
height: 2000px;
}
.bottomMenu {
position: fixed;
bottom: 0;
width: 100%;
height: 60px;
border-top: 1px solid #000;
background: red;
z-index: 1;
transition: all 1s;
}
.hide {
opacity: 0;
left: -100%;
}
.show {
opacity: 1;
left: 0;
}
_x000D_
<div id="myID" class="bottomMenu hide"></div>
_x000D_
Documentation for .scrollY
Documentation for .className
Documentation for .addEventListener
If you want to show an element after scrolling to it:
$('h1').each(function () {
var y = $(document).scrollTop();
var t = $(this).parent().offset().top;
if (y > t) {
$(this).fadeIn();
} else {
$(this).fadeOut();
}
});
$(document).scroll(function() {
//Show element after user scrolls 800px
var y = $(this).scrollTop();
if (y > 800) {
$('.bottomMenu').fadeIn();
} else {
$('.bottomMenu').fadeOut();
}
// Show element after user scrolls past
// the top edge of its parent
$('h1').each(function() {
var t = $(this).parent().offset().top;
if (y > t) {
$(this).fadeIn();
} else {
$(this).fadeOut();
}
});
});
_x000D_
body {
height: 1600px;
}
.bottomMenu {
display: none;
position: fixed;
bottom: 0;
width: 100%;
height: 60px;
border-top: 1px solid #000;
background: red;
z-index: 1;
}
.scrollPast {
width: 100%;
height: 150px;
background: blue;
position: relative;
top: 50px;
margin: 20px 0;
}
h1 {
display: none;
position: absolute;
bottom: 0;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Scroll Down...</p>
<div class="scrollPast">
<h1>I fade in when you scroll to my parent</h1>
</div>
<div class="scrollPast">
<h1>I fade in when you scroll to my parent</h1>
</div>
<div class="scrollPast">
<h1>I fade in when you scroll to my parent</h1>
</div>
<div class="bottomMenu">I fade in when you scroll past 800px</div>
_x000D_
Note that you can't get the offset of elements set to display: none;
, grab the offset of the element's parent instead.
Documentation for .each()
Documentation for .parent()
Documentation for .offset()
If you want to have a nav or div stick or dock to the top of the page once you scroll to it and unstick/undock when you scroll back up:
$(document).scroll(function () {
//stick nav to top of page
var y = $(this).scrollTop();
var navWrap = $('#navWrap').offset().top;
if (y > navWrap) {
$('nav').addClass('sticky');
} else {
$('nav').removeClass('sticky');
}
});
#navWrap {
height:70px
}
nav {
height: 70px;
background:gray;
}
.sticky {
position: fixed;
top:0;
}
$(document).scroll(function () {
//stick nav to top of page
var y = $(this).scrollTop();
var navWrap = $('#navWrap').offset().top;
if (y > navWrap) {
$('nav').addClass('sticky');
} else {
$('nav').removeClass('sticky');
}
});
_x000D_
body {
height:1600px;
margin:0;
}
#navWrap {
height:70px
}
nav {
height: 70px;
background:gray;
}
.sticky {
position: fixed;
top:0;
}
h1 {
margin: 0;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas,
imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus. Zonbi tattered for solum
oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.</p>
<div id="navWrap">
<nav>
<h1>I stick to the top when you scroll down and unstick when you scroll up to my original position</h1>
</nav>
</div>
<p>Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas,
imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus. Zonbi tattered for solum
oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.</p>
_x000D_
A ListView
is basically like a ListBox
(and inherits from it), but it also has a View
property. This property allows you to specify a predefined way of displaying the items. The only predefined view in the BCL (Base Class Library) is GridView
, but you can easily create your own.
Another difference is the default selection mode: it's Single
for a ListBox
, but Extended
for a ListView
If you are using a data source, here's another way to do it without code behind.
Note the following key points:
ListItem
of Value="0"
is on the source page, not added in codeListItem
in the source will be overwritten if you don't include
AppendDataBoundItems="true"
in the DropDownList
InitialValue="0"
tells the validator that this is the value that
should fire that validator (as pointed out in other answers)Example:
<asp:DropDownList ID="ddlType" runat="server" DataSourceID="sdsType"
DataValueField="ID" DataTextField="Name" AppendDataBoundItems="true">
<asp:ListItem Value="0" Text="--Please Select--" Selected="True"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvType" runat="server" ControlToValidate="ddlType"
InitialValue="0" ErrorMessage="Type required"></asp:RequiredFieldValidator>
<asp:SqlDataSource ID="sdsType" runat="server"
ConnectionString='<%$ ConnectionStrings:TESTConnectionString %>'
SelectCommand="SELECT ID, Name FROM Type"></asp:SqlDataSource>
One possibility:
String result = str.substring(0, index) + str.substring(index+1);
Note that the result is a new String (as well as two intermediate String objects), because Strings in Java are immutable.
Nowadays (2020) you can do this with pure HTML5 and you don't need JavaScript or CSS3.
<details>
<summary>Put your summary here</summary>
<p>Put your content here!</p>
</details>
You can use this code block for JFrame background color.
JFrame frame = new JFrame("Frame BG color");
frame.setLayout(null);
frame.setSize(1000, 650);
frame.getContentPane().setBackground(new Color(5, 65, 90));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
I would like this
from subprocess import call
command = "youtube-dl https://www.youtube.com/watch?v=NG3WygJmiVs -c"
call(command.split(), shell=False)
Your program does not know what precision for decimal numbers to use so it throws:
java.lang.ArithmeticException: Non-terminating decimal expansion
MathContext precision = new MathContext(int setPrecisionYouWant); // example 2
BigDecimal a = new BigDecimal("1.6",precision);
BigDecimal b = new BigDecimal("9.2",precision);
a.divide(b) // result = 0.17
You don't say which version of the .NET framework you are using.
If you are using v2.0 or greater you could use the OnClientClick property to execute a Javascript function when the button's onclick event is raised.
All you have to do to prevent a server postback occuring is return false
from the called JavaScript function.
The user-agents on iOS devices say iPhone or iPad in them. I just filter based on those keywords.
def find_pos(chaine,x):
for i in range(len(chaine)):
if chaine[i] ==x :
return 'yes',i
return 'no'
Array initializer support for type inference were changed in Visual Basic 10 vs Visual Basic 9.
In previous version of VB it was required to put empty parens to signify an array. Also, it would define the array as object array unless otherwise was stated:
' Integer array
Dim i as Integer() = {1, 2, 3, 4}
' Object array
Dim o() = {1, 2, 3}
Check more info:
this $('#checkboxId').is(':checked')
for verify if is checked
& this $("#checkboxId").prop('checked', true)
to check
& this $("#checkboxId").prop('checked', false)
to uncheck
You can use TIMESTAMPDIFF(unit, datetime_expr1, datetime_expr2)
function:
SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age
I had the same issue, my problem was that the firewall on the server wasn't open from the current ip address.
Isn't the 'date' command much simpler? No need for awk, stat, etc.
date -r <filename>
Also, consider looking at the man page for date formatting; for example with common date and time format:
date -r <filename> "+%m-%d-%Y %H:%M:%S"
For sending emails from gmail smtp and using php mail function, First you have to setup the sendmail in your local machine, Once it is set it mean you have setup your local smtp server, you will then be able to send emails from the account you set in your sendmail smtp account, in my case I followed the instructions from https://www.developerfiles.com/how-to-send-emails-from-localhost-mac-os-x-el-capitan/ and was able to setup the account,
import os
os.system('pip install requests')
I tried above for temporary solution instead of changing docker file. Hope these might be useful to some
<style>
.class1{
height:100px;
line-height:100px;
color:white;
font-family:Bauhaus 93;
padding:25px;
background-color:#2a9fd4;
border:outset blue;
border-radius:25px;
box-shadow:10px 10px green;
font-size:45px;
}
.class2{
height:100px;
line-height:100px;
color:white;
font-family:Bauhaus 93;
padding:25px;
background-color:green;
border:outset blue;
border-radius:25px;
box-shadow:10px 10px green;
font-size:65px;
}
</style>
<script src="jquery-3.js"></script>
<script>
$(document).ready(function () {
$('#div1').addClass('class1');
var flag = true;
function blink() {
if(flag)
{
$("#div1").addClass('class2');
flag = false;
}
else
{
if ($('#div1').hasClass('class2'))
$('#div1').removeClass('class2').addClass('class1');
flag = true;
}
}
window.setInterval(blink, 1000);
});
</script>
synchronized should only be used when you want your class to be Thread safe. In fact most of the classes should not use synchronized anyways. synchronized method would only provide a lock on this object and only for the duration of its execution. if you really wanna to make your classes thread safe, you should consider making your variables volatile or synchronize the access.
one of the issues of using synchronized method is that all of the members of the class would use the same lock which will make your program slower. In your case synchronized method and block would execute no different. what I'd would recommend is to use a dedicated lock and use a synchronized block something like this.
public class AClass {
private int x;
private final Object lock = new Object(); //it must be final!
public void setX() {
synchronized(lock) {
x++;
}
}
}
This works reliably for me in my main sub.
Dim defDate1 As Date, defDate2 As Date
'** Set default date range to previous month
defDate1 = CDate(Month(Now) & "/1/" & Year(Now))
defDate1 = DateAdd("m", -1, defDate1)
defDate2 = DateAdd("d", -1, DateAdd("m", 1, defDate1))
If you installed through Homebrew, try to run
brew services start mysql
The compiler cannot guess what should be passed for the base constructor argument. You have to do it explicitly:
public class child : parent {
public child(int i) : base(i) {
Console.WriteLine("child");
}
}
Just an update.
The present TiKZ package will issue: Package tikz Warning: Snakes have been superseded by decorations. Please use the decoration libraries instead of the snakes library on input line. . .
So the pertaining part of code has to be changed to:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{decorations}
\begin{document}
\begin{tikzpicture}
%draw horizontal line
\draw (0,0) -- (2,0);
\draw[decorate,decoration={snake,pre length=5mm, post length=5mm}] (2,0) -- (4,0);
\draw (4,0) -- (5,0);
\draw[decorate,decoration={snake,pre length=5mm, post length=5mm}] (5,0) -- (7,0);
%draw vertical lines
\foreach \x in {0,1,2,4,5,7}
\draw (\x cm,3pt) -- (\x cm,-3pt);
%draw nodes
\draw (0,0) node[below=3pt] {$ 0 $} node[above=3pt] {$ $};
\draw (1,0) node[below=3pt] {$ 1 $} node[above=3pt] {$ 10 $};
\draw (2,0) node[below=3pt] {$ 2 $} node[above=3pt] {$ 20 $};
\draw (3,0) node[below=3pt] {$ $} node[above=3pt] {$ $};
\draw (4,0) node[below=3pt] {$ 5 $} node[above=3pt] {$ 50 $};
\draw (5,0) node[below=3pt] {$ 6 $} node[above=3pt] {$ 60 $};
\draw (6,0) node[below=3pt] {$ $} node[above=3pt] {$ $};
\draw (7,0) node[below=3pt] {$ n $} node[above=3pt] {$ 10n $};
\end{tikzpicture}
\end{document}
HTH
Wow, seems it got a lot easier nowadays... 3 ways you can do it:
json = { ...array };
json = Object.assign({}, array);
json = array.reduce((json, value, key) => { json[key] = value; return json; }, {});
Somehow even Webstorm made it like this import {of} from 'rxjs/observable/of';
and everything started to work
You can achieve with following way
this.projectService.create(project)
.subscribe(
result => {
console.log(result);
},
error => {
console.log(error);
this.errors = error
}
);
}
if (!this.errors) {
//route to new page
}
This situation happens because you haven't installed/start service of ASP.net.
Use below command in windows 7,8,10.
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i
SELECT column1 FROM table WHERE column1 not like '%[0-9]%'
Removing the '^' did it for me. I'm looking at a varchar field and when I included the ^ it excluded all of my non-numerics which is exactly what I didn't want. So, by removing ^ I only got non-numeric values back.
U can use something like this....
function (field,value) {
var newItemOrder= value;
// Make sure user hasnt already added this item
angular.forEach(arr, function(item) {
if (newItemOrder == item.value) {
arr.splice(arr.pop(item));
} });
submitFields.push({"field":field,"value":value});
};
Here is a little hack that we ran across while fixing some redraw issues on a large app.
Use -webkit-transform: translateZ(0);
on the parent. Of course this is specific to Chrome.
http://jsfiddle.net/senica/bCQEa/
-webkit-transform: translateZ(0);
Copy to Config File: /etc/mysql/my.cnf OR /bin/mysql/my.ini
[mysqld]
port = 3306
sql-mode=""
MySQL
restart.
Or you can also do
[mysqld]
port = 3306
SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
MySQL
restart.
public mySentences:Array<Object> = [
{id: 1, text: 'Sentence 1'},
{id: 2, text: 'Sentence 2'},
{id: 3, text: 'Sentence 3'},
{id: 4, text: 'Sentenc4 '},
];
Or rather,
export interface type{
id:number;
text:string;
}
public mySentences:type[] = [
{id: 1, text: 'Sentence 1'},
{id: 2, text: 'Sentence 2'},
{id: 3, text: 'Sentence 3'},
{id: 4, text: 'Sentenc4 '},
];
How i deal with EXC_BAD_ACCESS
Sometimes i feel that when a EXC_BAD_ACCESS error is thrown xcode will show the error in the main.m class giving no extra information of where the crash happens(Sometimes).
In those times we can set a Exceptional Breakpoint in Xcode so that when exception is caught a breakpoint will be placed and will directly intimate the user that crash has happened in that line
When you create your own key pair object, you should face a few thing.
First, you should be aware of implementing hashCode()
and equals()
. You will need to do this.
Second, when implementing hashCode()
, make sure you understand how it works. The given user example
public int hashCode() {
return this.x ^ this.y;
}
is actually one of the worst implementations you can do. The reason is simple: you have a lot of equal hashes! And the hashCode()
should return int values that tend to be rare, unique at it's best. Use something like this:
public int hashCode() {
return (X << 16) + Y;
}
This is fast and returns unique hashes for keys between -2^16 and 2^16-1 (-65536 to 65535). This fits in almost any case. Very rarely you are out of this bounds.
Third, when implementing equals()
also know what it is used for and be aware of how you create your keys, since they are objects. Often you do unnecessary if statements cause you will always have the same result.
If you create keys like this: map.put(new Key(x,y),V);
you will never compare the references of your keys. Cause everytime you want to acces the map, you will do something like map.get(new Key(x,y));
. Therefore your equals()
does not need a statement like if (this == obj)
. It will never occure.
Instead of if (getClass() != obj.getClass())
in your equals()
better use if (!(obj instanceof this))
. It will be valid even for subclasses.
So the only thing you need to compare is actually X and Y. So the best equals()
implementation in this case would be:
public boolean equals (final Object O) {
if (!(O instanceof Key)) return false;
if (((Key) O).X != X) return false;
if (((Key) O).Y != Y) return false;
return true;
}
So in the end your key class is like this:
public class Key {
public final int X;
public final int Y;
public Key(final int X, final int Y) {
this.X = X;
this.Y = Y;
}
public boolean equals (final Object O) {
if (!(O instanceof Key)) return false;
if (((Key) O).X != X) return false;
if (((Key) O).Y != Y) return false;
return true;
}
public int hashCode() {
return (X << 16) + Y;
}
}
You can give your dimension indices X
and Y
a public access level, due to the fact they are final and do not contain sensitive information. I'm not a 100% sure whether private
access level works correctly in any case when casting the Object
to a Key
.
If you wonder about the finals, I declare anything as final which value is set on instancing and never changes - and therefore is an object constant.
for (i in markersArray) {
markersArray[i].setMap(null);
}
is only working on IE.
for (var i=0; i<markersArray.length; i++) {
markersArray[i].setMap(null);
}
working on chrome, firefox, ie...
Java has Reflection (java.reflection.*), but I would suggest looking into a library like Apache Beanutils, it will make the process much less hairy than using reflection directly.
This can also be a file that contains images or charts, see this: http://kb.tableausoftware.com/articles/knowledgebase/resolving-error-external-table-is-not-in-expected-format
The recommendation is to save as Excel 2003
Unlike many other languages, R functions don't return multiple objects in the strict sense. The most general way to handle this is to return a list
object. So if you have an integer foo
and a vector of strings bar
in your function, you could create a list that combines these items:
foo <- 12
bar <- c("a", "b", "e")
newList <- list("integer" = foo, "names" = bar)
Then return
this list.
After calling your function, you can then access each of these with newList$integer
or newList$names
.
Other object types might work better for various purposes, but the list
object is a good way to get started.
For clarity, I thought that a direct example of grabbing onto a resource can be shown from the following that I think contributes to the response for this question with a quick direct example.
private MenuItem menuItem_;
@Override
public boolean onCreateOptionsMenu(Menu menuF)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_layout, menuF);
menuItem_ = menuF.findItem(R.id.menu_item_identifier);
return true;
}
In this case you hold onto a MenuItem reference at the beginning and then change the state of it (for icon state changes for example) at a later given point in time.
It is possible to upack without node installed using the following 7-Zip plugin:
http://www.tc4shell.com/en/7zip/asar/
Thanks @MayaPosch for mentioning that in this comment.
Another approach depending on how you are changing the div. If you are using JQuery to change a div's contents with its html() method, you can extend that method and call a registration function each time you put html into a div.
(function( $, oldHtmlMethod ){
// Override the core html method in the jQuery object.
$.fn.html = function(){
// Execute the original HTML method using the
// augmented arguments collection.
var results = oldHtmlMethod.apply( this, arguments );
com.invisibility.elements.findAndRegisterElements(this);
return results;
};
})( jQuery, jQuery.fn.html );
We just intercept the calls to html(), call a registration function with this, which in the context refers to the target element getting new content, then we pass on the call to the original jquery.html() function. Remember to return the results of the original html() method, because JQuery expects it for method chaining.
For more info on method overriding and extension, check out http://www.bennadel.com/blog/2009-Using-Self-Executing-Function-Arguments-To-Override-Core-jQuery-Methods.htm, which is where I cribbed the closure function. Also check out the plugins tutorial at JQuery's site.
Setting the content type and the content disposition as described above produces wildly varying results with different browsers:
IE8: SaveAs dialog as desired, and Excel as the default app. 100% good.
Firefox: SaveAs dialog does show up, but Firefox has no idea it is a spreadsheet. Suggests opening it with Visual Studio! 50% good
Chrome: the hints are fully ignored. The CSV data is shown in the browser. 0% good.
Of course in all of these cases I'm referring to the browsers as they come out of they box, with no customization of the mime/application mappings.
Try using the type
attribute selector to find buttons (maybe this'll fix it too):
input[type=button]
{
background-color: #E3E1B8;
}
input[type=button]:hover
{
background-color: #46000D
}
If you use Bootstrap 3 (or earlier)...
<dl class="dl-horizontal">
<dt>Label:</dt>
<dd>
Description of planet
</dd>
<dt>Label2:</dt>
<dd>
Description of planet
</dd>
</dl>
Use this function begining from SQL SERVER 2016
Select Count(value) From STRING_SPLIT('AAA AAA AAA',' ');
-- Output : 3
When This function used with count function it gives you how many character exists in string
Actually the problem is with the compression options. The trick is the pipe the tar result to a compressor instead of using the built-in options. Incidentally that can also give you better compression, since you can set extra compresion options.
Minimal tar:
tar --exclude=*.tar* -cf workspace.tar .
Pipe to a compressor of your choice. This example is verbose and uses xz with maximum compression:
tar --exclude=*.tar* -cv . | xz -9v >workspace.tar.xz
Solution was tested on Ubuntu 14.04 and Cygwin on Windows 7. It's a community wiki answer, so feel free to edit if you spot a mistake.
Simply add this to the head of your document:
<link rel="shortcut icon" type="image/png" href="/img/icon-192x192.png">
<link rel="shortcut icon" sizes="192x192" href="/img/icon-192x192.png">
<link rel="apple-touch-icon" href="/img/icon-192x192.png">
The last link is for Apple (home screen), the second one for Android (home screen) and the first one for the rest.
Note that this solution does not support "tiles" in Windows 8/10. It does, however, support images in shortcuts, bookmarks and browser-tabs.
The size is exactly the size the Android home screen uses. The Apple home screen icon size is 60px (3x), so 180px and will be scaled down. Other platforms use the default shortcut icon, which will be scaled down too.
As a heads up to others, I've oberserved that at least as manifested by TypeScript compiled by WebPack for Angular 2, you quietly get overWRITTEN instead of overLOADED methods.
myComponent {
method(): { console.info("no args"); },
method(arg): { console.info("with arg"); }
}
Calling:
myComponent.method()
seems to execute the method with arguments, silently ignoring the no-arg version, with output:
with arg
You need to split the line first.
import csv
with open('log.txt', 'r') as in_file:
stripped = (line.strip() for line in in_file)
lines = (line.split(",") for line in stripped if line)
with open('log.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('title', 'intro'))
writer.writerows(lines)
Here is a solution by Andreas Joseph Krogh from the PostgreSQL mailing list: http://www.postgresql.org/message-id/[email protected]
SELECT source_table::regclass, source_attr.attname AS source_column,
target_table::regclass, target_attr.attname AS target_column
FROM pg_attribute target_attr, pg_attribute source_attr,
(SELECT source_table, target_table, source_constraints[i] source_constraints, target_constraints[i] AS target_constraints
FROM
(SELECT conrelid as source_table, confrelid AS target_table, conkey AS source_constraints, confkey AS target_constraints,
generate_series(1, array_upper(conkey, 1)) AS i
FROM pg_constraint
WHERE contype = 'f'
) query1
) query2
WHERE target_attr.attnum = target_constraints AND target_attr.attrelid = target_table AND
source_attr.attnum = source_constraints AND source_attr.attrelid = source_table;
This solution handles foreign keys that reference multiple columns, and avoids duplicates (which some of the other answers fail to do). The only thing I changed were the variable names.
Here is an example that returns all employee
columns that reference the permission
table:
SELECT source_column
FROM foreign_keys
WHERE source_table = 'employee'::regclass AND target_table = 'permission'::regclass;
When I installed: ENU\x64\SQLManagementStudio_x64_ENU.exe
I had to choose the following options to get the management Tools:
When I was done I had an option "SQL Server Management Studio" within my Start Menu.
Searching for "Management" pulled it up faster within the Start Menu.
Without knowing all the information... You could bind a reset trigger to your model or controller:
this.bind("reset", this.updateView);
and when you want to reset the views, trigger a reset.
For your callback, do something like:
updateView: function() {
view.remove();
view.render();
};
Either
render partial: 'user', locals: {size: 30}
Or
render 'user', size: 30
To use locals
, you need partial
. Without the partial
argument, you can just list variables directly (not within locals
)
Definitely using the Url property is the way to go. Whether to set it in the app.config, the database, or a third location sort of depends on your configuration needs. Sometimes you don't want the app to restart when you change the web service location. You might not have a load balancer scaling the backend. You might be hot-patching a web service bug. Your implementation might have security configuration issues as well. Whether it's production db usernames and passwords or even the ws security auth info. The proper separation of duties can get you into some more involved configuration setups.
If you add a wrapper class around the proxy generated classes, you can set the Url property in some unified fashion every time you create the wrapper class to call a web method.
@JustGoscha's answer is spot on, but that's a lot to type when I want access, so I added this to the bottom of my app.js. Then all I have to type is x = getSrv('$http')
to get the http service.
// @if DEBUG
function getSrv(name, element) {
element = element || '*[ng-app]';
return angular.element(element).injector().get(name);
}
// @endif
It adds it to the global scope but only in debug mode. I put it inside the @if DEBUG
so that I don't end up with it in the production code. I use this method to remove debug code from prouduction builds.
There is no need to know where the files are, because when you launch a bat file the working directory is the directory where it was launched (the "master folder"), so if you have this structure:
.\mydocuments\folder\mybat.bat
.\mydocuments\folder\subfolder\file.txt
And the user starts the "mybat.bat", the working directory is ".\mydocuments\folder", so you only need to write the subfolder name in your script:
@Echo OFF
REM Do anything with ".\Subfolder\File1.txt"
PUSHD ".\Subfolder"
Type "File1.txt"
Pause&Exit
Anyway, the working directory is stored in the "%CD%" variable, and the directory where the bat was launched is stored on the argument 0. Then if you want to know the working directory on any computer you can do:
@Echo OFF
Echo Launch dir: "%~dp0"
Echo Current dir: "%CD%"
Pause&Exit
The following script solved my problem:
// Fake localStorage implementation.
// Mimics localStorage, including events.
// It will work just like localStorage, except for the persistant storage part.
var fakeLocalStorage = function() {
var fakeLocalStorage = {};
var storage;
// If Storage exists we modify it to write to our fakeLocalStorage object instead.
// If Storage does not exist we create an empty object.
if (window.Storage && window.localStorage) {
storage = window.Storage.prototype;
} else {
// We don't bother implementing a fake Storage object
window.localStorage = {};
storage = window.localStorage;
}
// For older IE
if (!window.location.origin) {
window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
var dispatchStorageEvent = function(key, newValue) {
var oldValue = (key == null) ? null : storage.getItem(key); // `==` to match both null and undefined
var url = location.href.substr(location.origin.length);
var storageEvent = document.createEvent('StorageEvent'); // For IE, http://stackoverflow.com/a/25514935/1214183
storageEvent.initStorageEvent('storage', false, false, key, oldValue, newValue, url, null);
window.dispatchEvent(storageEvent);
};
storage.key = function(i) {
var key = Object.keys(fakeLocalStorage)[i];
return typeof key === 'string' ? key : null;
};
storage.getItem = function(key) {
return typeof fakeLocalStorage[key] === 'string' ? fakeLocalStorage[key] : null;
};
storage.setItem = function(key, value) {
dispatchStorageEvent(key, value);
fakeLocalStorage[key] = String(value);
};
storage.removeItem = function(key) {
dispatchStorageEvent(key, null);
delete fakeLocalStorage[key];
};
storage.clear = function() {
dispatchStorageEvent(null, null);
fakeLocalStorage = {};
};
};
// Example of how to use it
if (typeof window.localStorage === 'object') {
// Safari will throw a fit if we try to use localStorage.setItem in private browsing mode.
try {
localStorage.setItem('localStorageTest', 1);
localStorage.removeItem('localStorageTest');
} catch (e) {
fakeLocalStorage();
}
} else {
// Use fake localStorage for any browser that does not support it.
fakeLocalStorage();
}
It checks if localStorage exists and can be used and in the negative case, it creates a fake local storage and uses it instead of the original localStorage. Please let me know if you need further information.
You can't actually "truncate" a Python string like you can do a dynamically allocated C string. Strings in Python are immutable. What you can do is slice a string as described in other answers, yielding a new string containing only the characters defined by the slice offsets and step. In some (non-practical) cases this can be a little annoying, such as when you choose Python as your interview language and the interviewer asks you to remove duplicate characters from a string in-place. Doh.
ndarray.tofile()
should also work
e.g. if your array is called a
:
a.tofile('yourfile.txt',sep=" ",format="%s")
Not sure how to get newline formatting though.
Edit (credit Kevin J. Black's comment here):
Since version 1.5.0,
np.tofile()
takes an optional parameternewline='\n'
to allow multi-line output. https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.savetxt.html
file = open("filename.txt", newline='')
for row in self.data:
print(row)
Save data to a variable(file
), so you need a with
.
Two ways:
<img src="..." border="1" />
or
<img style='border:1px solid #000000' src="..." />
I've been working in another solution very similar to that, but, I am using a footerView
to give the possibility to the user download more elements clicking the footerView
, I am using a "menu" which is shown above the ListView
and in the bottom of the parent view, this "menu" hides the bottom of the ListView
, so, when the listView
is scrolling the menu disappear and when scroll state is idle, the menu appear again, but when the user scrolls to the end of the listView
, I "ask" to know if the footerView
is shown in that case, the menu doesn't appear and the user can see the footerView
to load more content. Here the code:
Regards.
listView.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
if(scrollState == SCROLL_STATE_IDLE) {
if(footerView.isShown()) {
bottomView.setVisibility(LinearLayout.INVISIBLE);
} else {
bottomView.setVisibility(LinearLayout.VISIBLE);
} else {
bottomView.setVisibility(LinearLayout.INVISIBLE);
}
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
});
The most simple solution android supported now!
Use custom font in xml:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/[your font resource]"/>
look details:
https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html
public static class StringExtensions
{
public static string Repeat(this string input, int count)
{
if (!string.IsNullOrEmpty(input))
{
StringBuilder builder = new StringBuilder(input.Length * count);
for(int i = 0; i < count; i++) builder.Append(input);
return builder.ToString();
}
return string.Empty;
}
}
Edit: added information about ngMessages (>= 1.3.X) below.
Since this is one of the top results if you Google "Angular Form Validation", currently, I want to add another answer to this for anyone coming in from there.
There's a method in FormController.$setValidity but that doesn't look like a public API so I rather not use it.
It's "public", no worries. Use it. That's what it's for. If it weren't meant to be used, the Angular devs would have privatized it in a closure.
To do custom validation, if you don't want to use Angular-UI as the other answer suggested, you can simply roll your own validation directive.
app.directive('blacklist', function (){
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
var blacklist = attr.blacklist.split(',');
//For DOM -> model validation
ngModel.$parsers.unshift(function(value) {
var valid = blacklist.indexOf(value) === -1;
ngModel.$setValidity('blacklist', valid);
return valid ? value : undefined;
});
//For model -> DOM validation
ngModel.$formatters.unshift(function(value) {
ngModel.$setValidity('blacklist', blacklist.indexOf(value) === -1);
return value;
});
}
};
});
And here's some example usage:
<form name="myForm" ng-submit="doSomething()">
<input type="text" name="fruitName" ng-model="data.fruitName" blacklist="coconuts,bananas,pears" required/>
<span ng-show="myForm.fruitName.$error.blacklist">
The phrase "{{data.fruitName}}" is blacklisted</span>
<span ng-show="myForm.fruitName.$error.required">required</span>
<button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>
Note: in 1.2.X it's probably preferrable to substitute ng-if
for ng-show
above
Here is an obligatory plunker link
Also, I've written a few blog entries about just this subject that goes into a little more detail:
You can now use the ngMessages module instead of ngShow to show your error messages. It will actually work with anything, it doesn't have to be an error message, but here's the basics:
<script src="angular-messages.js"></script>
Reference ngMessages
in your module declaration:
var app = angular.module('myApp', ['ngMessages']);
Add the appropriate markup:
<form name="personForm">
<input type="email" name="email" ng-model="person.email" required/>
<div ng-messages="personForm.email.$error">
<div ng-message="required">required</div>
<div ng-message="email">invalid email</div>
</div>
</form>
In the above markup, ng-message="personForm.email.$error"
basically specifies a context for the ng-message
child directives. Then ng-message="required"
and ng-message="email"
specify properties on that context to watch. Most importantly, they also specify an order to check them in. The first one it finds in the list that is "truthy" wins, and it will show that message and none of the others.
You can make Liquinaut's answer responsive to window size changes by adding a callback that sets the height back to auto.
$("#first").animate({height: $("#first").get(0).scrollHeight}, 1000, function() {$("#first").css({height: "auto"});});
This is an old question, but if you wanted to break out of an if statement, you could do:
while 1:
if blah:
break
Sometimes I have been getting some errors when you want to pass httpBody serialized to Data
from Dictionary
, which on most cases is due to the wrong encoding or malformed data due to non NSCoding conforming objects in the Dictionary
.
Depending on your requirements one easy solution would be to create a String
instead of Dictionary
and convert it to Data
. You have the code samples below written on Objective-C
and Swift 3.0
.
// Create the URLSession on the default configuration
NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];
// Setup the request with URL
NSURL *url = [NSURL URLWithString:@"yourURL"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
// Convert POST string parameters to data using UTF8 Encoding
NSString *postParams = @"api_key=APIKEY&[email protected]&password=password";
NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];
// Convert POST string parameters to data using UTF8 Encoding
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:postData];
// Create dataTask
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// Handle your response here
}];
// Fire the request
[dataTask resume];
// Create the URLSession on the default configuration
let defaultSessionConfiguration = URLSessionConfiguration.default
let defaultSession = URLSession(configuration: defaultSessionConfiguration)
// Setup the request with URL
let url = URL(string: "yourURL")
var urlRequest = URLRequest(url: url!) // Note: This is a demo, that's why I use implicitly unwrapped optional
// Convert POST string parameters to data using UTF8 Encoding
let postParams = "api_key=APIKEY&[email protected]&password=password"
let postData = postParams.data(using: .utf8)
// Set the httpMethod and assign httpBody
urlRequest.httpMethod = "POST"
urlRequest.httpBody = postData
// Create dataTask
let dataTask = defaultSession.dataTask(with: urlRequest) { (data, response, error) in
// Handle your response here
}
// Fire the request
dataTask.resume()
Swift 4
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.barTintColor = UIColor.orange
navigationController?.navigationBar.tintColor = UIColor.white
navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
}
Here's another example of using filter
in an Angular controller:
$scope.ListOfPeople = [
{ PersonID: 10, FirstName: "John", LastName: "Smith", Sex: "Male" },
{ PersonID: 11, FirstName: "James", LastName: "Last", Sex: "Male" },
{ PersonID: 12, FirstName: "Mary", LastName: "Heart", Sex: "Female" },
{ PersonID: 13, FirstName: "Sandra", LastName: "Goldsmith", Sex: "Female" },
{ PersonID: 14, FirstName: "Shaun", LastName: "Sheep", Sex: "Male" },
{ PersonID: 15, FirstName: "Nicola", LastName: "Smith", Sex: "Male" }
];
$scope.ListOfWomen = $scope.ListOfPeople.filter(function (person) {
return (person.Sex == "Female");
});
// This will display "There are 2 women in our list."
prompt("", "There are " + $scope.ListOfWomen.length + " women in our list.");
Simple, hey ?
request.args
is a MultiDict with the parsed contents of the query string.
From the documentation of get
method:
get(key, default=None, type=None)
Return the default value if the requested data doesn’t exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible.
You have to set to element_blank()
in theme()
elements you need to remove
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
The pattern you want is something like (see it on rubular.com):
^[a-zA-Z0-9_.-]*$
Explanation:
^
is the beginning of the line anchor$
is the end of the line anchor[...]
is a character class definition*
is "zero-or-more" repetitionNote that the literal dash -
is the last character in the character class definition, otherwise it has a different meaning (i.e. range). The .
also has a different meaning outside character class definitions, but inside, it's just a literal .
Here's a snippet to show how you can use this pattern:
<?php
$arr = array(
'screen123.css',
'screen-new-file.css',
'screen_new.js',
'screen new file.css'
);
foreach ($arr as $s) {
if (preg_match('/^[\w.-]*$/', $s)) {
print "$s is a match\n";
} else {
print "$s is NO match!!!\n";
};
}
?>
The above prints (as seen on ideone.com):
screen123.css is a match
screen-new-file.css is a match
screen_new.js is a match
screen new file.css is NO match!!!
Note that the pattern is slightly different, using \w
instead. This is the character class for "word character".
This seems to follow your specification, but note that this will match things like .....
, etc, which may or may not be what you desire. If you can be more specific what pattern you want to match, the regex will be slightly more complicated.
The above regex also matches the empty string. If you need at least one character, then use +
(one-or-more) instead of *
(zero-or-more) for repetition.
In any case, you can further clarify your specification (always helps when asking regex question), but hopefully you can also learn how to write the pattern yourself given the above information.
ls | grep "^abc"
will give you all files beginning (which is what the OP specifically required) with the substringabc
.
It operates only on the current directory whereas find
operates recursively into sub folders.
To use find
for only files starting with your string try
find . -name 'abc'*
In brief, $@
expands to the positional arguments passed from the caller to either a function or a script. Its meaning is context-dependent: Inside a function, it expands to the arguments passed to such function. If used in a script (not inside the scope a function), it expands to the arguments passed to such script.
$ cat my-sh
#! /bin/sh
echo "$@"
$ ./my-sh "Hi!"
Hi!
$ put () ( echo "$@" )
$ put "Hi!"
Hi!
Now, another topic that is of paramount importance when understanding how $@
behaves in the shell is word splitting. The shell splits tokens based on the contents of the IFS
variable. Its default value is \t\n
; i.e., whitespace, tab, and newline.
Expanding "$@"
gives you a pristine copy of the arguments passed. However, expanding $@
will not always. More specifically, if the arguments contain characters from IFS
, they will split.
Most of the time what you will want to use is "$@"
, not $@
.
No. NodeJS is not available as an Apache module in the way mod-perl and mod-php are, so it's not possible to run node "on top of" Apache. As hexist pointed out, it's possible to run node as a separate process and arrange communication between the two, but this is quite different to the LAMP stack you're already using.
As a replacement for Apache, node offers performance advantages if you have many simultaneous connections. There's also a huge ecosystem of modules for almost anything you can think of.
From your question, it's not clear if you need to dynamically generate pages on every request, or just generate new content periodically for caching and serving. If its the latter, you could use separate node task to generate content to a directory that Apache would serve, but again, that's quite different to PHP or Perl.
Node isn't the best way to serve static content. Nginx and Varnish are more effective at that. They can serve static content while Node handles the dynamic data.
If you're considering using node for a web application at all, Express should be high on your list. You could implement a web application purely in Node, but Express (and similar frameworks like Flatiron, Derby and Meteor) are designed to take a lot of the pain and tedium away. Although the Express documentation can seem a bit sparse at first, check out the screen casts which are still available here: http://expressjs.com/2x/screencasts.html They'll give you a good sense of what express offers and why it is useful. The github repository for ExpressJS also contains many good examples for everything from authentication to organizing your app.
(Swift 4.2 Xcode 11) Simple to use Extension:-
extension Double {
func round(to places: Int) -> Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
}
Use:-
if let distanceDb = Double(strDistance) {
cell.lblDistance.text = "\(distanceDb.round(to:2)) km"
}
First off, you need to implement INotifyPropertyChanged
interface in your view model and raise the PropertyChanged
event in the setter of the Rule
property. Otherwise no control that binds to the SelectedRule
property will "know" when it has been changed.
Then, your XAML
<TextBlock Text="{Binding Path=SelectedRule.Name}" />
is perfectly valid if this TextBlock
is outside the ListBox
's ItemTemplate
and has the same DataContext
as the ListBox
.
First you have to define attribute in form2(child) you will update this attribute in form2 and also from form1(parent) :
public string Response { get; set; }
private void OkButton_Click(object sender, EventArgs e)
{
Response = "ok";
}
private void CancelButton_Click(object sender, EventArgs e)
{
Response = "Cancel";
}
Calling of form2(child) from form1(parent):
using (Form2 formObject= new Form2() )
{
formObject.ShowDialog();
string result = formObject.Response;
//to update response of form2 after saving in result
formObject.Response="";
// do what ever with result...
MessageBox.Show("Response from form2: "+result);
}
If you have an issue where you only want to remove trailing characters, you can try this:
WHILE EXISTS
(SELECT * FROM @ReportSet WHERE
ASCII(right(addr_3,1)) = 10
OR ASCII(right(addr_3,1)) = 13
OR ASCII(right(addr_3,1)) = 32)
BEGIN
UPDATE @ReportSet
SET addr_3 = LEFT(addr_3,LEN(addr_3)-1)
WHERE
ASCII(right(addr_3,1)) = 10
OR ASCII(right(addr_3,1)) = 13
OR ASCII(right(addr_3,1)) = 32
END
This solved a problem I had with addresses where a procedure created a field with a fixed number of lines, even if those lines were empty. To save space in my SSRS report, I cut them down.
You can do this by selecting every element of the class that is the sibling of the same class and inverting it, which will select pretty much every element on the page, so then you have to select by the class again.
eg:
<style>
:not(.bar ~ .bar).bar {
color: red;
}
<div>
<div class="foo"></div>
<div class="bar"></div> <!-- Only this will be selected -->
<div class="foo"></div>
<div class="bar"></div>
<div class="foo"></div>
<div class="bar"></div>
</div>
I just stumbled upon this great post. If you are just checking whether the data is of string type then maybe we can skip the loop and use this struct (in my humble opinion)
public static bool IsStringType(object data)
{
return (data.GetType().GetProperties().Where(x => x.PropertyType == typeof(string)).FirstOrDefault() != null);
}
You have to set the associatedEmployee on the Vehicle before persisting the Employee.
Employee newEmployee = new Employee("matt");
vehicle1.setAssociatedEmployee(newEmployee);
vehicles.add(vehicle1);
newEmployee.setVehicles(vehicles);
Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);
The following is a proposed solution for the OP's specific problem (extracting the 2nd word of a string), but it should be noted that, as mc0e's answer states, actually extracting regex matches is not supported out-of-the-box in MySQL. If you really need this, then your choices are basically to 1) do it in post-processing on the client, or 2) install a MySQL extension to support it.
BenWells has it very almost correct. Working from his code, here's a slightly adjusted version:
SUBSTRING(
sentence,
LOCATE(' ', sentence) + CHAR_LENGTH(' '),
LOCATE(' ', sentence,
( LOCATE(' ', sentence) + 1 ) - ( LOCATE(' ', sentence) + CHAR_LENGTH(' ') )
)
As a working example, I used:
SELECT SUBSTRING(
sentence,
LOCATE(' ', sentence) + CHAR_LENGTH(' '),
LOCATE(' ', sentence,
( LOCATE(' ', sentence) + 1 ) - ( LOCATE(' ', sentence) + CHAR_LENGTH(' ') )
) as string
FROM (SELECT 'THIS IS A TEST' AS sentence) temp
This successfully extracts the word IS
I had same problem and waste my 4-5 hours for solution. My problem solved with;
Hope you will find your solution.
I prefer to label buckets with a numeric formula. If the bucket size is 10 then this labels the buckets 0,1,2,...
=INT(A1/10)
If you put the bucket size 10 in a separate cell you can easily vary it.
If cell B1 contains the bucket (0,1,2,...) and column 6 contains the names Low, Medium, High then this formula converts a bucket to a name:
=INDIRECT(ADDRESS(1+B1,6))
Alternatively, this labels the buckets with the least value in the set, i.e. 0,10,20,...
=10*INT(A1/10)
or this labels them with the range 0-10,10-20,20-30,...
=10*INT(A1/10) & "-" & (10*INT(A1/10)+10)
You can use a form to do a POST to the same URL.
<form method="POST" name="refresh" id="refresh">
<input type="submit" value="Refresh" />
</form>
This gives you a button that refreshes the current page. It is a bit annoying because if the user presses the browser refresh button, they will get a do you want to resubmit the form
message.
You can call dispose()
on the current window and setVisible(true)
on the one you want to display.
we can do it with a single line of code.
user1 = pd.read_csv('dataset/1.csv', names=['TIME', 'X', 'Y', 'Z'], header=None)
Probably the simplest way is to use the InputBox
method of the Microsoft.VisualBasic.Interaction
class:
[void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
$title = 'Demographics'
$msg = 'Enter your demographics:'
$text = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title)
You can use the sp_helpindex
to view all the indexes of one table.
EXEC sys.sp_helpindex @objname = N'User' -- nvarchar(77)
And for all the indexes, you can traverse sys.objects
to get all the indexes for each table.
def lensort(list_1):
list_2=[];list_3=[]
for i in list_1:
list_2.append([i,len(i)])
list_2.sort(key = lambda x : x[1])
for i in list_2:
list_3.append(i[0])
return list_3
This works for me!
This is my implementation of (Google) JWT Validation in .NET. It is based on other implementations on Stack Overflow and GitHub gists.
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace QuapiNet.Service
{
public class JwtTokenValidation
{
public async Task<Dictionary<string, X509Certificate2>> FetchGoogleCertificates()
{
using (var http = new HttpClient())
{
var response = await http.GetAsync("https://www.googleapis.com/oauth2/v1/certs");
var dictionary = await response.Content.ReadAsAsync<Dictionary<string, string>>();
return dictionary.ToDictionary(x => x.Key, x => new X509Certificate2(Encoding.UTF8.GetBytes(x.Value)));
}
}
private string CLIENT_ID = "xxx.apps.googleusercontent.com";
public async Task<ClaimsPrincipal> ValidateToken(string idToken)
{
var certificates = await this.FetchGoogleCertificates();
TokenValidationParameters tvp = new TokenValidationParameters()
{
ValidateActor = false, // check the profile ID
ValidateAudience = true, // check the client ID
ValidAudience = CLIENT_ID,
ValidateIssuer = true, // check token came from Google
ValidIssuers = new List<string> { "accounts.google.com", "https://accounts.google.com" },
ValidateIssuerSigningKey = true,
RequireSignedTokens = true,
IssuerSigningKeys = certificates.Values.Select(x => new X509SecurityKey(x)),
IssuerSigningKeyResolver = (token, securityToken, kid, validationParameters) =>
{
return certificates
.Where(x => x.Key.ToUpper() == kid.ToUpper())
.Select(x => new X509SecurityKey(x.Value));
},
ValidateLifetime = true,
RequireExpirationTime = true,
ClockSkew = TimeSpan.FromHours(13)
};
JwtSecurityTokenHandler jsth = new JwtSecurityTokenHandler();
SecurityToken validatedToken;
ClaimsPrincipal cp = jsth.ValidateToken(idToken, tvp, out validatedToken);
return cp;
}
}
}
Note that, in order to use it, you need to add a reference to the NuGet package System.Net.Http.Formatting.Extension
. Without this, the compiler will not recognize the ReadAsAsync<>
method.
Put the text file in the assets directory. If there isnt an assets dir create one in the root of the project. Then you can use Context.getAssets().open("BlockForTest.txt");
to open a stream to this file.
I got here searching for the same error, but from Node.js native driver. The answer for me was combination of answers by campeterson and Prabhat.
The issue is that readPreference
setting defaults to primary
, which then somehow leads to the confusing slaveOk
error. My problem is that I just wan to read from my replica set from any node. I don't even connect to it as to replicaset. I just connect to any node to read from it.
Setting readPreference
to primaryPreferred
(or better to the ReadPreference.PRIMARY_PREFERRED
constant) solved it for me. Just pass it as an option to MongoClient.connect()
or to client.db()
or to any find()
, aggregate()
or other function.
const { MongoClient, ReadPreference } = require('mongodb');
const client = await MongoClient.connect(MONGODB_CONNECTIONSTRING, { readPreference: ReadPreference.PRIMARY_PREFERRED });
You don't have to define operator<
for your class, actually. You can also make a comparator function object class for it, and use that to specialize std::map
. To extend your example:
struct Class1Compare
{
bool operator() (const Class1& lhs, const Class1& rhs) const
{
return lhs.id < rhs.id;
}
};
std::map<Class1, int, Class1Compare> c2int;
It just so happens that the default for the third template parameter of std::map
is std::less
, which will delegate to operator<
defined for your class (and fail if there is none). But sometimes you want objects to be usable as map keys, but you do not actually have any meaningful comparison semantics, and so you don't want to confuse people by providing operator<
on your class just for that. If that's the case, you can use the above trick.
Yet another way to achieve the same is to specialize std::less
:
namespace std
{
template<> struct less<Class1>
{
bool operator() (const Class1& lhs, const Class1& rhs) const
{
return lhs.id < rhs.id;
}
};
}
The advantage of this is that it will be picked by std::map
"by default", and yet you do not expose operator<
to client code otherwise.
You can simply add onended="myFunction()"
to your video tag.
<video onended="myFunction()">
...
Your browser does not support the video tag.
</video>
<script type='text/javascript'>
function myFunction(){
console.log("The End.")
}
</script>
Try this query it ll change the records ends with .com
UPDATE tablename SET email = replace(email, '.com', '.org') WHERE email LIKE '%.com';
Just understand the difference between width:auto; and width:100%; Width:auto; will (AUTO)MATICALLY calculate the width in order to fit the exact given with of the wrapping div including the padding. Width 100% expands the width and adds the padding.
None of the above worked on Sublime Text 3 on Windows 10, Ctrl + Shift + ' with the Emmet Sublime Text 3 plugin works great and was the only working solution for me. Ctrl + Shift + T re-opens the last closed item and to my knowledge of Sublime, has done so since early builds of ST3 or late builds of ST2.
String.prototype.match
returns an array, we can then check the length,
I find this method to be most descriptive
var str = 'one two three four five';
str.match(/\w+/g).length;
<img src="w3schools.jpg" alt="W3Schools.com" width="104" height="142">
In above html tag we have different attributes like src
, alt
, width
and height
.
If you want to get the any attribute value from above html tag you have to pass attribute value in getAttribute()
method
Syntax:
getAttribute(attributeValue)
getAttribute(src) you get w3schools.jpg
getAttribute(height) you get 142
getAttribute(width) you get 104
I used this code to fix the issue of displaying items in the horizontal list.
new Container(
height: 20,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: array.length,
itemBuilder: (context, index){
return array[index];
},
),
],
),
);
There are several options available*:
*Disclaimer: This list may not be complete.
Using Flexbox
Nowadays, we can use flexbox. It is quite a handy alternative to the css-transform option. I would use this solution almost always. If it is just one element maybe not, but for example if I had to support an array of data e.g. rows and columns and I want them to be relatively centered in the very middle.
.flexbox {
display: flex;
height: 100px;
flex-flow: row wrap;
align-items: center;
justify-content: center;
background-color: #eaeaea;
border: 1px dotted #333;
}
.item {
/* default => flex: 0 1 auto */
background-color: #fff;
border: 1px dotted #333;
box-sizing: border-box;
}
_x000D_
<div class="flexbox">
<div class="item">I am centered in the middle.</div>
<div class="item">I am centered in the middle, too.</div>
</div>
_x000D_
Using CSS 2D-Transform
This is still a good option, was also the accepted solution back in 2015.
It is very slim and simple to apply and does not mess with the layouting of other elements.
.boxes {
position: relative;
}
.box {
position: relative;
display: inline-block;
float: left;
width: 200px;
height: 200px;
font-weight: bold;
color: #333;
margin-right: 10px;
margin-bottom: 10px;
background-color: #eaeaea;
}
.h-center {
text-align: center;
}
.v-center span {
position: absolute;
left: 0;
right: 0;
top: 50%;
transform: translate(0, -50%);
}
_x000D_
<div class="boxes">
<div class="box h-center">horizontally centered lorem ipsun dolor sit amet</div>
<div class="box v-center"><span>vertically centered lorem ipsun dolor sit amet lorem ipsun dolor sit amet</span></div>
<div class="box h-center v-center"><span>horizontally and vertically centered lorem ipsun dolor sit amet</span></div>
</div>
_x000D_
Note: This does also work with
:after
and:before
pseudo-elements.
Using Grid
This might just be an overkill, but it depends on your DOM. If you want to use grid anyway, then why not. It is very powerful alternative and you are really maximum flexible with the design.
Note: To align the items vertically we use flexbox in combination with grid. But we could also use
display: grid
on the items.
.grid {
display: grid;
width: 400px;
grid-template-rows: 100px;
grid-template-columns: 100px 100px 100px;
grid-gap: 3px;
align-items: center;
justify-content: center;
background-color: #eaeaea;
border: 1px dotted #333;
}
.item {
display: flex;
justify-content: center;
align-items: center;
border: 1px dotted #333;
box-sizing: border-box;
}
.item-large {
height: 80px;
}
_x000D_
<div class="grid">
<div class="item">Item 1</div>
<div class="item item-large">Item 2</div>
<div class="item">Item 3</div>
</div>
_x000D_
CSS article about grid
CSS article about flexbox
CSS article about centering without flexbox or grid
So after a half day on this and almost immediately after posting my question I found the answer. Bundler 1.5.0 has a bug where it doesn't recognize default gems as referenced here
The solution was to update to bundler 1.5.1 using gem install bundler -v '= 1.5.1'
It means you have a null reference somewhere in there. Can you debug the app and stop the debugger when it gets here and investigate? Probably img1
is null or ConfigurationManager.AppSettings.Get("Url")
is returning null.
This was a fresh linux Mint xfce machine
I have been battling this for a about a week. I'm trying to learn Java on Netbeans IDE and so naturally I get the combo file straight from Oracle. Which is a package of the JDK and the Netbeans IDE together in a tar file located here.
located http://www.oracle.com/technetwork/java/javase/downloads/index.html file name JDK 8u25 with NetBeans 8.0.1
after installing them (or so I thought) I would make/compile a simple program like "hello world" and that would spit out a jar file that you would be able to run in a terminal. Keep in mind that the program ran in the Netbeans IDE.
I would end up with this error: java.lang.UnsupportedClassVersionError:
Even though I ran the file from oracle website I still had the old version of the Java runtime which was not compatible to run my jar file which was compiled with the new java runtime.
After messing with stuff that was mostly over my head from setting Paths to editing .bashrc with no remedy.
I came across a solution that was easy enough for even me. I have come across something that auto installs java and configures it on your system and it works with the latest 1.8.*
One of the steps is adding a PPA wasn't sure about this at first but seems ok as it has worked for me
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer
domenic@domenic-AO532h ~ $ java -version java version "1.8.0_25" Java(TM) SE Runtime Environment (build 1.8.0_25-b17) Java HotSpot(TM) Server VM (build 25.25-b02, mixed mode)
I think it also configures the browser java as well.
I hope this helps others.
#alertlist li:hover:after,#alertlist li.selected:after
{
position:absolute;
top: 0;
right:-10px;
bottom:0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid #303030;
content: "";
}?
You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start()
. The headers will be sent automatically when any HTML is output.
Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.
Move the session_start()
to the top of your document :
<?php session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php'; // more PHP code here.
Try this :
$('.close-button').on('click', function(){
$('.element').removeClass('grown');
$('.element').addClass('spot');
});
$('.element').on('click', function(){
$(this).removeClass('spot');
$(this).addClass('grown');
});
I hope I understood your question.
Extension TabOut was the option i was looking for.
The varying line-ending characters don't matter, assuming the file is open in text mode, which is what you get unless you ask for binary. The compiled program will write out the correct thing for the system compiled for.
The only difference is that std::endl
flushes the output buffer, and '\n'
doesn't. If you don't want the buffer flushed frequently, use '\n'
. If you do (for example, if you want to get all the output, and the program is unstable), use std::endl
.
Supplementing the answer by p.s.w.g
, here are three other ways of achieving this using lodash
4.17.5
, without using _.includes()
:
Say you want to add object entry
to an array of objects numbers
, only if entry
does not exist already.
let numbers = [
{ to: 1, from: 2 },
{ to: 3, from: 4 },
{ to: 5, from: 6 },
{ to: 7, from: 8 },
{ to: 1, from: 2 } // intentionally added duplicate
];
let entry = { to: 1, from: 2 };
/*
* 1. This will return the *index of the first* element that matches:
*/
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) });
// output: 0
/*
* 2. This will return the entry that matches. Even if the entry exists
* multiple time, it is only returned once.
*/
_.find(numbers, (o) => { return _.isMatch(o, entry) });
// output: {to: 1, from: 2}
/*
* 3. This will return an array of objects containing all the matches.
* If an entry exists multiple times, if is returned multiple times.
*/
_.filter(numbers, _.matches(entry));
// output: [{to: 1, from: 2}, {to: 1, from: 2}]
If you want to return a Boolean
, in the first case, you can check the index that is being returned:
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) }) > -1;
// output: true
I've faced same problem and came across to this thread but my problem was with upstream
. Below git command worked for me.
git checkout {remoteName}/{branch} -- {../path/file.js}
git checkout upstream/develop -- public/js/index.js
It is weird that no one has suggested the OOP way:
$date = new \DateTime(); //now
$date->add(new \DateInterval('PT3600S'));//add 3600s / 1 hour
OR
$date = new \DateTime(); //now
$date->add(new \DateInterval('PT60M'));//add 60 min / 1 hour
OR
$date = new \DateTime(); //now
$date->add(new \DateInterval('PT1H'));//add 1 hour
Extract it in string with format:
var_dump($date->format('Y-m-d H:i:s'));
I hope it helps