For a web based service, check out loader.io.
Summary:
loader.io is a free load testing service that allows you to stress test your web-apps/apis with thousands of concurrent connections.
They also have an API.
Code example of ItemListener
implementation
class ItemChangeListener implements ItemListener{
@Override
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
Object item = event.getItem();
// do something with object
}
}
}
Now we will get only selected item.
Then just add listener to your JComboBox
addItemListener(new ItemChangeListener());
The problem is you're not doing anything with the result of replace
. In Python strings are immutable so anything that manipulates a string returns a new string instead of modifying the original string.
line[8] = line[8].replace(letter, "")
Adding to the selected answer (as I haven't enough rep to add comment), one way to see the list of available versions (from ref) try:
$ rbenv install -l
The instructions in the official Python documentation worked for me: https://docs.python.org/2/using/windows.html#executing-scripts
Launch a command prompt.
Associate the correct file group with .py scripts:
assoc .py=Python.File
Redirect all Python files to the new executable:
ftype Python.File=C:\Path\to\pythonw.exe "%1" %*
The example shows how to associate the .py extension with the .pyw executable, but it works if you want to associate the .py extension with the Anaconda Python executable. You need administrative rights. The name "Python.File" could be anything, you just have to make sure is the same name in the ftype command. When you finish and before you try double-clicking the .py file, you must change the "Open with" in the file properties. The file type will be now ".py" and it is opened with the Anaconda python.exe.
In addition to max, you can also sort:
>>> lis
[(101, 153), (255, 827), (361, 961)]
>>> sorted(lis,key=lambda x: x[1], reverse=True)[0]
(361, 961)
To load python code reliably, have that code in a module, and that module installed in python's library.
Installed modules can always be loaded from the top level namespace with import <name>
There is a great sample project available officially here: https://github.com/pypa/sampleproject
Basically, you can have a directory structure like so:
the_foo_project/
setup.py
bar.py # `import bar`
foo/
__init__.py # `import foo`
baz.py # `import foo.baz`
faz/ # `import foo.faz`
__init__.py
daz.py # `import foo.faz.daz` ... etc.
.
Be sure to declare your setuptools.setup()
in setup.py
,
official example: https://github.com/pypa/sampleproject/blob/master/setup.py
In our case we probably want to export bar.py
and foo/__init__.py
, my brief example:
#!/usr/bin/env python3
import setuptools
setuptools.setup(
...
py_modules=['bar'],
packages=['foo'],
...
entry_points={},
# Note, any changes to your setup.py, like adding to `packages`, or
# changing `entry_points` will require the module to be reinstalled;
# `python3 -m pip install --upgrade --editable ./the_foo_project
)
.
Now we can install our module into the python library;
with pip, you can install the_foo_project
into your python library in edit mode,
so we can work on it in real time
python3 -m pip install --editable=./the_foo_project
# if you get a permission error, you can always use
# `pip ... --user` to install in your user python library
.
Now from any python context, we can load our shared py_modules and packages
#!/usr/bin/env python3
import bar
import foo
print(dir(bar))
print(dir(foo))
Additional hint: If you have multiple projects with different toolchains open, check the build console header for the failing project's path.
I've just spent half an hour trying to fix a build that showed this error because another project with hopelessly outdated toolchain settings was open in the same workbench. Closing the other project re-enabled the build.
Use rsync so that you can continue if the connection gets broken. And if something changes you can copy them much faster too!
Rsync works with SSH so your copy operation is secure.
Provided my_command
is canonically designed, ie returns 0 when succeeds, then &&
is exactly the opposite of what you want. You want ||
.
Also note that (
does not seem right to me in bash, but I cannot try from where I am. Tell me.
my_command || {
echo 'my_command failed' ;
exit 1;
}
I had the same issue and I solved by adding an empty class annotated with SpringBootApplication
in the root package of the folder src/test/java
package org.enricogiurin.core;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CoreTestConfiguration {}
Let's call keys
the list/iterator of keys that you are given to remove. I'd do this:
keys_to_remove = set(keys).intersection(set(mydict.keys()))
for key in keys_to_remove:
del mydict[key]
You calculate up front all the affected items and operate on them.
I prefer to create a new dictionary over mutating an existing one, so I would probably also consider this:
keys_to_keep = set(mydict.keys()) - set(keys)
new_dict = {k: v for k, v in mydict.iteritems() if k in keys_to_keep}
or:
keys_to_keep = set(mydict.keys()) - set(keys)
new_dict = {k: mydict[k] for k in keys_to_keep}
In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.
EDIT
It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.
var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>"
I submitted a pull request to update this.
Use javascript's splice() function.
This may help: http://www.w3schools.com/jsref/jsref_splice.asp
For Java 7 you can use try-with-resource for more compact code:
private static boolean available(int port) {
try (Socket ignored = new Socket("localhost", port)) {
return false;
} catch (IOException ignored) {
return true;
}
}
You should find them by default in a folder like /etc/my.cnf
, maybe also depends on versions. From MySQL Configuration File:
Interestingly, the scope of this file can be set according to its location. The settings will be considered global to all MySQL servers if stored in /etc/my.cnf. It will be global to a specific server if located in the directory where the MySQL databases are stored (/usr/local/mysql/data for a binary installation, or /usr/local/var for a source installation). Finally, its scope could be limited to a specific user if located in the home directory of the MySQL user (~/.my.cnf). Keep in mind that even if MySQL does locate a my.cnf file in /etc/my.cnf (global to all MySQL servers on that machine), it will continue its search for a server-specific file, and then a user-specific file. You can think of the final configuration settings as being the result of the /etc/my.cnf, mysql-data-dir/my.cnf, and ~/.my.cnf files.
There are a few switches to package managers to list specific files.
RPM Sytems:
There are switches to rpm
command, -q
for query, and -c
or --configfiles
to list config files. There is also -l
or --list
The --configfiles
one didn't quiet work for me, but --list
did list a few .cnf
files held by mysql-server
rpm -q --list mysql-server
DEB Systems:
Also with limited success: dpkg --listfiles mysql-server
You can label each line separately, in your case:
\begin{align}
\lambda_i + \mu_i = 0 \label{eq:1}\\
\mu_i \xi_i = 0 \label{eq:2}\\
\lambda_i [y_i( w^T x_i + b) - 1 + \xi_i] = 0 \label{eq:3}
\end{align}
Note that this only works for AMS environments that are designed for multiple equations (as opposed to multiline single equations).
The following code send and recieve the current date and time from and to the server
//The following code is for the server application:
namespace Server
{
class Program
{
const int PORT_NO = 5000;
const string SERVER_IP = "127.0.0.1";
static void Main(string[] args)
{
//---listen at the specified IP and port no.---
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
Console.WriteLine("Listening...");
listener.Start();
//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received : " + dataReceived);
//---write back the text to the client---
Console.WriteLine("Sending back : " + dataReceived);
nwStream.Write(buffer, 0, bytesRead);
client.Close();
listener.Stop();
Console.ReadLine();
}
}
}
//this is the code for the client
namespace Client
{
class Program
{
const int PORT_NO = 5000;
const string SERVER_IP = "127.0.0.1";
static void Main(string[] args)
{
//---data to send to the server---
string textToSend = DateTime.Now.ToString();
//---create a TCPClient object at the IP and port no.---
TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
NetworkStream nwStream = client.GetStream();
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);
//---send the text---
Console.WriteLine("Sending : " + textToSend);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
//---read back the text---
byte[] bytesToRead = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
Console.WriteLine("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
Console.ReadLine();
client.Close();
}
}
}
To Achieve ellipses for the text use the Text property numberofLines={1} which will automatically truncate the text with an ellipsis you can specify the ellipsizeMode as "head", "middle", "tail" or "clip" By default it is tail
Try to run npm run dev
in powershell. This worked for me.
You can use the curses.h
library in linux as mentioned in the other answer.
You can install it in Ubuntu by:
sudo apt-get update
sudo apt-get install ncurses-dev
I took the installation part from here.
The following will cover all browsers worth covering:
text-shadow: 0 0 2px #fff; /* Firefox 3.5+, Opera 9+, Safari 1+, Chrome, IE10 */
filter: progid:DXImageTransform.Microsoft.Glow(Color=#ffffff,Strength=1); /* IE<10 */
//path to directory to scan
$directory = "../data/team/";
//get all text files with a .txt extension.
$texts = glob($directory . "*.txt");
//print each file name
foreach($texts as $text)
{
echo $text;
}
Although it is not recommended, but if you really want to let your web application access a folder outside its deployment directory. You need to add following permission in java.policy
file (path is as in the reply of Petey B)
permission java.io.FilePermission "your folder path", "write"
In your case it would be
permission java.io.FilePermission "S:/PDSPopulatingProgram/-", "write"
Here /-
means any files or sub-folders inside this folder.
Warning: But by doing this, you are inviting some security risk.
I would follow this guide: https://github.com/bmoeskau/Extensible/blob/master/recurrence-overview.md
Also make sure you use the iCal format so not to reinvent the wheel and remember Rule #0: Do NOT store individual recurring event instances as rows in your database!
wordlists is not a function, it is a list. You need the bracket subscript
print wordlists[len(words)]
from pyspark.sql.types import IntegerType
data_df = data_df.withColumn("Plays", data_df["Plays"].cast(IntegerType()))
data_df = data_df.withColumn("drafts", data_df["drafts"].cast(IntegerType()))
You can run loop for each column but this is the simplest way to convert string column into integer.
I think you want (this won't fit in a int
though, you'll need to store it as a long
):
long result = dateDate.Year * 10000000000 + dateDate.Month * 100000000 + dateDate.Day * 1000000 + dateDate.Hour * 10000 + dateDate.Minute * 100 + dateDate.Second;
Alternatively, storing the ticks is a better idea.
You can run it through Number()
var myInt = Number(new Date(dates_as_int[0]));
If the parameter is a Date object, the Number() function returns the number of milliseconds since midnight January 1, 1970 UTC.
I used to use height
and line-height
with the same values, but the proved to be inconsistent across the interwebs. My current approach is to mix that with padding like so.
select {
font-size:14px;
height:18px;
line-height:18px;
padding:5px 0;
width:200px;
text-align:center;
}
You could also use padding
for the horizontal value instead of the width
+ text-align
Try this
export class Collection{
public more (): Observable<Response> {
if (this.hasMore()) {
return this.fetch();
}
else{
return this.returnEmpty();
}
}
public returnEmpty(): any {
let subscription = source.subscribe(
function (x) {
console.log('Next: %s', x);
},
function (err) {
console.log('Error: %s', err);
},
function () {
console.log('Completed');
});
}
}
let source = Observable.empty();
var month = 5;
var cultureSwe = "sv-SE";
var monthSwe = CultureInfo.CreateSpecificCulture(cultureSwe).DateTimeFormat.GetAbbreviatedMonthName(month);
Console.WriteLine(monthSwe);
var cultureEn = "en-US";
var monthEn = CultureInfo.CreateSpecificCulture(cultureEn).DateTimeFormat.GetAbbreviatedMonthName(month);
Console.WriteLine(monthEn);
Output
maj
may
Good question.
I don't think there is. I believe it would have been quite well known if there was an easy way, and I see that Microsoft is creating a mechanism in Visual Studio 2010 for deploying different configuration files for deployment and test.
With that said, however; I have found that you in the ConnectionStrings
section have a kind of placeholder called "|DataDirectory|". Maybe you could have a look at what's at work there...
Here's a piece from machine.config
showing it:
<connectionStrings>
<add
name="LocalSqlServer"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
Count and show keys in a dictionary (run in console):
o=[];count=0; for (i in topicNames) { ++count; o.push(count+": "+ i) } o.join("\n")
Sample output:
"1: Phase-out Left-hand
2: Define All Top Level Taxonomies But Processes
3: 987
4: 16:00
5: Identify suppliers"
Simple count function:
function size_dict(d){c=0; for (i in d) ++c; return c}
I had a similar problem recently with Oracle 12c. I created a new user with a lower case password and was able to login fine from the database server but all clients failed with an ORA-01017. The fix turned out to be simple in the end (reset the password to upper case) but took a lot of frustrating effort to get there.
you can find multiple options listed at http://httpd.apache.org/docs/current/platform/windows.html#down
ApacheHaus Apache Lounge BitNami WAMP Stack WampServer XAMPP
Easiest way:
$injector = angular.element(document.body).injector()
Then use that to run invoke()
or get()
As the other answers state:
count
will perform an SQL COUNT
querylength
will calculate the length of the resulting arraysize
will try to pick the most appropriate of the two to avoid excessive queriesBut there is one more thing. We noticed a case where size
acts differently to count
/length
altogether, and I thought I'd share it since it is rare enough to be overlooked.
If you use a :counter_cache
on a has_many
association, size
will use the cached count directly, and not make an extra query at all.
class Image < ActiveRecord::Base
belongs_to :product, counter_cache: true
end
class Product < ActiveRecord::Base
has_many :images
end
> product = Product.first # query, load product into memory
> product.images.size # no query, reads the :images_count column
> product.images.count # query, SQL COUNT
> product.images.length # query, loads images into memory
This behaviour is documented in the Rails Guides, but I either missed it the first time or forgot about it.
Collation determines how your data is sorted and compared. It's very often important with regards to internazionalization, e.g. how do you sort japanese kanji?
If you google collation and sql server you'll find plenty of articles discussing it!
Even though this is an older thread, there is a newer way to do this which avoids some of the pitfalls of the IDENTITY column in older versions of SQL Server, like gaps in the identity values after server reboots. Sequences are available in SQL Server 2016 and forward which is the newer way is to create a SEQUENCE object using TSQL. This allows you create your own numeric sequence object in SQL Server and control how it increments.
Here is an example:
CREATE SEQUENCE CountBy1
START WITH 1
INCREMENT BY 1 ;
GO
Then in TSQL you would do the following to get the next sequence ID:
SELECT NEXT VALUE FOR CountBy1 AS SequenceID
GO
Here are the links to CREATE SEQUENCE and NEXT VALUE FOR
The better way is using 'background-size'.
.pnx-msg-icon .pnx-icon-msg-warning{
background-image: url("../pics/edit.png");
background-repeat: no-repeat;
background-size: 10px;
width: 10px;
height: 10px;
cursor: pointer;
}
even if your icon dimensions is bigger than 10px it will be 10px.
The class format of JDK8 has changed and thats the reason why Tomcat is not able to compile JSPs. Try to get a newer version of Tomcat.
I recently had the same problem. This is a bug in Tomcat, or rather, JDK 8 has a slightly different class file format than what prior-JDK8 versions had. This causes inconsistency and Tomcat is not able to compile JSPs in JDK8.
See following references:
For UTC:
string unixTimestamp = Convert.ToString((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
For local system:
string unixTimestamp = Convert.ToString((int)DateTime.Now.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
If using cocoapods, try reinstalling the pods by running the following command.
pod install
You can use http_build_query to generate a URL-encoded querystring from an array in PHP. Whilst the resulting querystring will be expanded, you can decide on a unique separator you want as a parameter to the http_build_query
method, so when it comes to decoding, you can check what separator was used. If it was the unique one you chose, then that would be the array querystring otherwise it would be the normal querystrings.
If you want to click on all elements selected by some class, you can use this example (used on last.fm on the Loved tracks page to Unlove all).
var divs = document.querySelectorAll('.love-button.love-button--loved');
for (i = 0; i < divs.length; ++i) {
divs[i].click();
};
With ES6 and Babel (cannot be run in the browser console directly)
[...document.querySelectorAll('.love-button.love-button--loved')]
.forEach(div => { div.click(); })
For Swift 4
let indexPath = IndexPath(row: 0, section: 0)
let cell = tableView.cellForRow(at: indexPath)
You have to use RegExp object if your pattern is string
var xxx = "victoria";
var yyy = "i";
var rgxp = new RegExp(yyy, "g");
alert(xxx.match(rgxp).length);
If pattern is not dynamic string:
var xxx = "victoria";
var yyy = /i/g;
alert(xxx.match(yyy).length);
If you have trouble with caching ajax you can turn it off:
$.ajaxSetup({cache: false});
yes, sql server doesn't allow to insert single quote in table field due to the sql injection attack. so we must replace single appostrophe by double while saving.
(he doesn't work for me) must be => (he doesn''t work for me)
This is because an XML documentation file has been specified in your Project Properties and Your Method/Class is public and lack documentation.
You can either :
Right Click on your Project -> Properties -> 'Build' tab -> uncheck XML Documentation File.
Summary of XML documentation goes like this:
/// <summary>
/// Description of the class/method/variable
/// </summary>
..declaration goes here..
This will put the option values of #myselectbox
into a nice clean array for you:
// First, get the elements into a list
var options = $('#myselectbox option');
// Next, translate that into an array of just the values
var values = $.map(options, e => $(e).val())
If str
is null, undefined or 0, this code will set it to "hai"
function(nodeBox, str) {
str = str || "hai";
.
.
.
If you also need to pass 0, you can use:
function(nodeBox, str) {
if (typeof str === "undefined" || str === null) {
str = "hai";
}
.
.
.
Based on cocco's idea, here's a less compact -but hopefully more comprehensive- example.
<!DOCTYPE html>
<html>
<head>
<title>File info</title>
<script>
<!--
function fileSize(bytes) {
var exp = Math.log(bytes) / Math.log(1024) | 0;
var result = (bytes / Math.pow(1024, exp)).toFixed(2);
return result + ' ' + (exp == 0 ? 'bytes': 'KMGTPEZY'[exp - 1] + 'B');
}
function info(input) {
input.nextElementSibling.textContent = fileSize(input.files[0].size);
}
-->
</script>
</head>
<body>
<label for="upload-file"> File: </label>
<input id="upload-file" type="file" onchange="info(this)">
<div></div>
</body>
</html>
There's very little reason not to open multiple workbooks in Excel. Key lines of code are:
Application.EnableEvents = False
Application.ScreenUpdating = False
...then you won't see anything whilst the code runs, and no code will run that is associated with the opening of the second workbook. Then there are...
Application.DisplayAlerts = False
Application.Calculation = xlManual
...so as to stop you getting pop-up messages associated with the content of the second file, and to avoid any slow re-calculations. Ensure you set back to True/xlAutomatic at end of your programming
If opening the second workbook is not going to cause performance issues, you may as well do it. In fact, having the second workbook open will make it very beneficial when attempting to debug your code if some of the secondary files do not conform to the expected format
Here is some expert guidance on using multiple Excel files that gives an overview of the different methods available for referencing data
An extension question would be how to cycle through multiple files contained in the same folder. You can use the Windows folder picker using:
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
If .Selected.Items.Count = 1 the InputFolder = .SelectedItems(1)
End With
FName = VBA.Dir(InputFolder)
Do While FName <> ""
'''Do function here
FName = VBA.Dir()
Loop
Hopefully some of the above will be of use
Just to make one point clear about
Main-Class: <packagename>.<classname>
If you don't have package you have to ignore that part, like this:
Main-Class: <classname>
I would like to present another answer to this as the currently accepted answer doesn't work for me (I use LibreOffice). This solution should work in Excel, LibreOffice and OpenOffice:
First, insert a new row at the beginning of the sheet. Within that row, define the names you need:
Then, in the menu bar, go to View -> Freeze Cells -> Freeze First Row. It'll look like this now:
Now whenever you scroll down in the document, the first row will be "pinned" to the top:
You can indicate the new process should be started with elevated permissions by setting the Verb property of your startInfo object to 'runas', as follows:
startInfo.Verb = "runas";
This will cause Windows to behave as if the process has been started from Explorer with the "Run as Administrator" menu command.
This does mean the UAC prompt will come up and will need to be acknowledged by the user: if this is undesirable (for example because it would happen in the middle of a lengthy process), you'll need to run your entire host process with elevated permissions by Create and Embed an Application Manifest (UAC) to require the 'highestAvailable' execution level: this will cause the UAC prompt to appear as soon as your app is started, and cause all child processes to run with elevated permissions without additional prompting.
Edit: I see you just edited your question to state that "runas" didn't work for you. That's really strange, as it should (and does for me in several production apps). Requiring the parent process to run with elevated rights by embedding the manifest should definitely work, though.
Try this if you are on ubuntu:
sudo apt-get update
sudo apt-get install build-essential libpq-dev libssl-dev openssl libffi-dev zlib1g-dev
sudo apt-get install python3-pip python3.7-dev
sudo apt-get install python3.7
In case you don't have the repository and so it fires a not-found package you first have to install this:
sudo apt-get install -y software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
more info here: http://devopspy.com/python/install-python-3-6-ubuntu-lts/
I'm doing it this way:
function f(data,d){
console.log(d);
console.log(data);
}
$.ajax({
url:u,
success:function(data){ f(data,d); }
});
Please try this.
<Router>
<div>
<Route exact path="/" component={Home} />
<Route path="/news" component={NewsFeed} />
</div>
</Router>
Your XML is not entirely clear, but arrays XML can cause force closes if you make them numbers, and/or put white space in their definition.
Make sure they are defined like No Leading or Trailing Whitespace
If you had use strict
turned on, you would have found out that $++foo
doesn't make any sense.
Here's how to do it:
use strict;
use warnings;
my $file = 'SnPmaster.txt';
open my $info, $file or die "Could not open $file: $!";
while( my $line = <$info>) {
print $line;
last if $. == 2;
}
close $info;
This takes advantage of the special variable $.
which keeps track of the line number in the current file. (See perlvar)
If you want to use a counter instead, use
my $count = 0;
while( my $line = <$info>) {
print $line;
last if ++$count == 2;
}
You can turn off the "Disable Script Debugging"
option inside of Internet Explorer and start debugging with Visual Studio
if you happen to have that around.
I've found that it is one of few ways to diagnose some of those IE
specific issues.
MySQL Workbench also has this feature neatly in the GUI. Simply run a query, click the save icon next to Export/Import:
Then choose "SQL INSERT statements (*.sql)" in the list.
Enter a name, click save, confirm the table name and you will have your dump file.
boto3 also has a method for uploading a file directly:
s3 = boto3.resource('s3')
s3.Bucket('bucketname').upload_file('/local/file/here.txt','folder/sub/path/to/s3key')
http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Bucket.upload_file
You can you with your source folder so whenever you build, those files are automatically copied to the classes directory.
Instead of using properties file, use XML file.
If the data is too small, you can even use web.xml for accessing the properties.
Please note that any of these approach will require app server restart for changes to be reflected.
Using "+" symbol u can concatenate strings.
String a="I";
String b="Love.";
String c="Java.";
System.out.println(a+b+c);
Try this one, I assure you that it will work perfectly.
import scipy.optimize as opt
from numpy import exp
import timeit
st1 = timeit.default_timer()
def f(variables) :
(x,y) = variables
first_eq = x + y**2 -4
second_eq = exp(x) + x*y - 3
return [first_eq, second_eq]
solution = opt.fsolve(f, (0.1,1) )
print(solution)
st2 = timeit.default_timer()
print("RUN TIME : {0}".format(st2-st1))
->
[ 0.62034452 1.83838393]
RUN TIME : 0.0009331008900937708
FYI. as mentioned above, you can also use 'Broyden's approximation' by replacing 'fsolve' with 'broyden1'. It works. I did it.
I don't know exactly how Broyden's approximation works, but it took 0.02 s.
And I recommend you do not use Sympy's functions <- convenient indeed, but in terms of speed, it's quite slow. You will see.
string alpha = "abcdefghijklmnopqrstuvwxyz";
string newAlpha = "";
for (int i = 5; i < alpha.Length; i += 6)
{
newAlpha = alpha.Insert(i, "-");
alpha = newAlpha;
}
This is an interesting question, and I started thinking about how I would implement something like this.
I came up with this (fiddle);
Basically, instead of trying to call a directive from a controller, I created a module to house all the popdown logic:
var PopdownModule = angular.module('Popdown', []);
I put two things in the module, a factory
for the API which can be injected anywhere, and the directive
for defining the behavior of the actual popdown element:
The factory just defines a couple of functions success
and error
and keeps track of a couple of variables:
PopdownModule.factory('PopdownAPI', function() {
return {
status: null,
message: null,
success: function(msg) {
this.status = 'success';
this.message = msg;
},
error: function(msg) {
this.status = 'error';
this.message = msg;
},
clear: function() {
this.status = null;
this.message = null;
}
}
});
The directive gets the API injected into its controller, and watches the api for changes (I'm using bootstrap css for convenience):
PopdownModule.directive('popdown', function() {
return {
restrict: 'E',
scope: {},
replace: true,
controller: function($scope, PopdownAPI) {
$scope.show = false;
$scope.api = PopdownAPI;
$scope.$watch('api.status', toggledisplay)
$scope.$watch('api.message', toggledisplay)
$scope.hide = function() {
$scope.show = false;
$scope.api.clear();
};
function toggledisplay() {
$scope.show = !!($scope.api.status && $scope.api.message);
}
},
template: '<div class="alert alert-{{api.status}}" ng-show="show">' +
' <button type="button" class="close" ng-click="hide()">×</button>' +
' {{api.message}}' +
'</div>'
}
})
Then I define an app
module that depends on Popdown
:
var app = angular.module('app', ['Popdown']);
app.controller('main', function($scope, PopdownAPI) {
$scope.success = function(msg) { PopdownAPI.success(msg); }
$scope.error = function(msg) { PopdownAPI.error(msg); }
});
And the HTML looks like:
<html ng-app="app">
<body ng-controller="main">
<popdown></popdown>
<a class="btn" ng-click="success('I am a success!')">Succeed</a>
<a class="btn" ng-click="error('Alas, I am a failure!')">Fail</a>
</body>
</html>
I'm not sure if it's completely ideal, but it seemed like a reasonable way to set up communication with a global-ish popdown directive.
Again, for reference, the fiddle.
Put this code in the <head></head>
tags:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
They are the same when used for output, e.g. with printf
.
However, these are different when used as input specifier e.g. with scanf
, where %d
scans an integer as a signed decimal number, but %i
defaults to decimal but also allows hexadecimal (if preceded by 0x
) and octal (if preceded by 0
).
So 033
would be 27 with %i
but 33 with %d
.
String[] splitArray = subjectString.split("\\|\\|");
You use a function:
public String[] stringSplit(String string){
String[] splitArray = string.split("\\|\\|");
return splitArray;
}
The following code works very well with Google SMTP server. You need to supply your Google username and password.
import com.sun.mail.smtp.SMTPTransport;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
*
* @author doraemon
*/
public class GoogleMail {
private GoogleMail() {
}
/**
* Send email using GMail SMTP server.
*
* @param username GMail username
* @param password GMail password
* @param recipientEmail TO recipient
* @param title title of the message
* @param message message to be sent
* @throws AddressException if the email address parse failed
* @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage
*/
public static void Send(final String username, final String password, String recipientEmail, String title, String message) throws AddressException, MessagingException {
GoogleMail.Send(username, password, recipientEmail, "", title, message);
}
/**
* Send email using GMail SMTP server.
*
* @param username GMail username
* @param password GMail password
* @param recipientEmail TO recipient
* @param ccEmail CC recipient. Can be empty if there is no CC recipient
* @param title title of the message
* @param message message to be sent
* @throws AddressException if the email address parse failed
* @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage
*/
public static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message) throws AddressException, MessagingException {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// Get a Properties object
Properties props = System.getProperties();
props.setProperty("mail.smtps.host", "smtp.gmail.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.setProperty("mail.smtps.auth", "true");
/*
If set to false, the QUIT command is sent and the connection is immediately closed. If set
to true (the default), causes the transport to wait for the response to the QUIT command.
ref : http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html
http://forum.java.sun.com/thread.jspa?threadID=5205249
smtpsend.java - demo program from javamail
*/
props.put("mail.smtps.quitwait", "false");
Session session = Session.getInstance(props, null);
// -- Create a new message --
final MimeMessage msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(username + "@gmail.com"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));
if (ccEmail.length() > 0) {
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
}
msg.setSubject(title);
msg.setText(message, "utf-8");
msg.setSentDate(new Date());
SMTPTransport t = (SMTPTransport)session.getTransport("smtps");
t.connect("smtp.gmail.com", username, password);
t.sendMessage(msg, msg.getAllRecipients());
t.close();
}
}
Username + password is no longer a recommended solution. This is due to
I tried this and Gmail sent the email used as username in this code an email saying that We recently blocked a sign-in attempt to your Google Account, and directed me to this support page: support.google.com/accounts/answer/6010255 so it looks for it to work, the email account being used to send needs to reduce their own security
Google had released Gmail API - https://developers.google.com/gmail/api/?hl=en. We should use oAuth2 method, instead of username + password.
Here's the code snippet to work with Gmail API.
import com.google.api.client.util.Base64;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.Message;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
*
* @author doraemon
*/
public class GoogleMail {
private GoogleMail() {
}
private static MimeMessage createEmail(String to, String cc, String from, String subject, String bodyText) throws MessagingException {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
InternetAddress tAddress = new InternetAddress(to);
InternetAddress cAddress = cc.isEmpty() ? null : new InternetAddress(cc);
InternetAddress fAddress = new InternetAddress(from);
email.setFrom(fAddress);
if (cAddress != null) {
email.addRecipient(javax.mail.Message.RecipientType.CC, cAddress);
}
email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
email.setSubject(subject);
email.setText(bodyText);
return email;
}
private static Message createMessageWithEmail(MimeMessage email) throws MessagingException, IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
email.writeTo(baos);
String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
Message message = new Message();
message.setRaw(encodedEmail);
return message;
}
public static void Send(Gmail service, String recipientEmail, String ccEmail, String fromEmail, String title, String message) throws IOException, MessagingException {
Message m = createMessageWithEmail(createEmail(recipientEmail, ccEmail, fromEmail, title, message));
service.users().messages().send("me", m).execute();
}
}
To construct an authorized Gmail service through oAuth2, here's the code snippet.
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.oauth2.Oauth2;
import com.google.api.services.oauth2.model.Userinfoplus;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.yccheok.jstock.engine.Pair;
/**
*
* @author yccheok
*/
public class Utils {
/** Global instance of the JSON factory. */
private static final GsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
/** Global instance of the HTTP transport. */
private static HttpTransport httpTransport;
private static final Log log = LogFactory.getLog(Utils.class);
static {
try {
// initialize the transport
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
} catch (IOException ex) {
log.error(null, ex);
} catch (GeneralSecurityException ex) {
log.error(null, ex);
}
}
private static File getGmailDataDirectory() {
return new File(org.yccheok.jstock.gui.Utils.getUserDataDirectory() + "authentication" + File.separator + "gmail");
}
/**
* Send a request to the UserInfo API to retrieve the user's information.
*
* @param credentials OAuth 2.0 credentials to authorize the request.
* @return User's information.
* @throws java.io.IOException
*/
public static Userinfoplus getUserInfo(Credential credentials) throws IOException
{
Oauth2 userInfoService =
new Oauth2.Builder(httpTransport, JSON_FACTORY, credentials).setApplicationName("JStock").build();
Userinfoplus userInfo = userInfoService.userinfo().get().execute();
return userInfo;
}
public static String loadEmail(File dataStoreDirectory) {
File file = new File(dataStoreDirectory, "email");
try {
return new String(Files.readAllBytes(Paths.get(file.toURI())), "UTF-8");
} catch (IOException ex) {
log.error(null, ex);
return null;
}
}
public static boolean saveEmail(File dataStoreDirectory, String email) {
File file = new File(dataStoreDirectory, "email");
try {
//If the constructor throws an exception, the finally block will NOT execute
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
try {
writer.write(email);
} finally {
writer.close();
}
return true;
} catch (IOException ex){
log.error(null, ex);
return false;
}
}
public static void logoutGmail() {
File credential = new File(getGmailDataDirectory(), "StoredCredential");
File email = new File(getGmailDataDirectory(), "email");
credential.delete();
email.delete();
}
public static Pair<Pair<Credential, String>, Boolean> authorizeGmail() throws Exception {
// Ask for only the permissions you need. Asking for more permissions will
// reduce the number of users who finish the process for giving you access
// to their accounts. It will also increase the amount of effort you will
// have to spend explaining to users what you are doing with their data.
// Here we are listing all of the available scopes. You should remove scopes
// that you are not actually using.
Set<String> scopes = new HashSet<>();
// We would like to display what email this credential associated to.
scopes.add("email");
scopes.add(GmailScopes.GMAIL_SEND);
// load client secrets
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(Utils.JSON_FACTORY,
new InputStreamReader(Utils.class.getResourceAsStream("/assets/authentication/gmail/client_secrets.json")));
return authorize(clientSecrets, scopes, getGmailDataDirectory());
}
/** Authorizes the installed application to access user's protected data.
* @return
* @throws java.lang.Exception */
private static Pair<Pair<Credential, String>, Boolean> authorize(GoogleClientSecrets clientSecrets, Set<String> scopes, File dataStoreDirectory) throws Exception {
// Set up authorization code flow.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, JSON_FACTORY, clientSecrets, scopes)
.setDataStoreFactory(new FileDataStoreFactory(dataStoreDirectory))
.build();
// authorize
return new MyAuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
public static Gmail getGmail(Credential credential) {
Gmail service = new Gmail.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName("JStock").build();
return service;
}
}
To provide a user friendly way of oAuth2 authentication, I made use of JavaFX, to display the following input dialog
The key to display user friendly oAuth2 dialog can be found in MyAuthorizationCodeInstalledApp.java and SimpleSwingBrowser.java
How to fix on Laravel 7:
Download the latest cacert.pem file from cURL website.
wget https://curl.haxx.se/ca/cacert.pem
Edit php.ini (you can do php --ini
to find it), update (or create if they don't exist already) those two lines:
curl.cainfo="/path/to/downloaded/cacert.pem"
...
openssl.cafile="/path/to/downloaded/cacert.pem"
Those lines should already exist but commented out, so uncomment them and edit both values with the path to the downloaded cacert.pem
Restart PHP and Nginx/Apache.
Edit: You may need to chown/chmod the downloaded certificate file so PHP (and its user) can read it.
try:
if val is None: # The variable
print('It is None')
except NameError:
print ("This variable is not defined")
else:
print ("It is defined and has a value")
If your input always has a time zone of "zulu" ("Z" = UTC), then you can use DateTimeFormatter.ISO_INSTANT
(implicitly):
final Instant parsed = Instant.parse(dateTime);
If time zone varies and has the form of "+01:00" or "+01:00:00" (when not "Z"), then you can use DateTimeFormatter.ISO_OFFSET_DATE_TIME
:
DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
final ZonedDateTime parsed = ZonedDateTime.parse(dateTime, formatter);
If neither is the case, you can construct a DateTimeFormatter
in the same manner as DateTimeFormatter.ISO_OFFSET_DATE_TIME
is constructed.
Your current pattern has several problems:
ResolverStyle.STRICT
);yyyy
instead of uuuu
(yyyy
will not work in strict mode);hh
instead of 24-hour HH
;S
for fractional seconds, but input has three.Adding the following line into the form worked for me:
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
Python functionsorted
returns ASCII based result for string.
INCORRECT: In the example below, e
and d
is behind H
and W
due it's to ASCII value.
>>>a = "Hello World!"
>>>"".join(sorted(a))
' !!HWdellloor'
CORRECT: In order to write the sorted string without changing the case of letter. Use the code:
>>> a = "Hello World!"
>>> "".join(sorted(a,key=lambda x:x.lower()))
' !deHllloorW'
If you want to remove all punctuation and numbers. Use the code:
>>> a = "Hello World!"
>>> "".join(filter(lambda x:x.isalpha(), sorted(a,key=lambda x:x.lower())))
'deHllloorW'
Check the step by step upgrade details from Angular 5 to Angular 6. These provides details on issues you encounter during upgrade and how to resolve them.
{
"rulesDirectory": [
"node_modules/rxjs-tslint"
],
"rules": {
"rxjs-collapse-imports": true,
"rxjs-pipeable-operators-only": true,
"rxjs-no-static-observable-methods": true,
"rxjs-proper-imports": true
}
}
Operators Name change:
do -> tap,
catch -> catchError,
switch -> switchAll,
finally -> finalize
All operators moved to rxjs/operators
import { map, filter, reduce } from 'rxjs/operators';
Observable creation methods are moved to rxjs
import { Observable, Subject, of, from } from 'rxjs';
You are all set. Welcome to Angular 6 :) Check my blog post here on how to upgrade
If you like UI more, find the process Node.js in windows task manager and kill it.
Create Table:
Create Table EmployeeProfile (
EmpId int,
EmpName varchar(50) not null,
EmpPhoto varbinary(max) not null )
Go
Insert statement:
Insert EmployeeProfile
(EmpId, EmpName, EmpPhoto)
Select 1001, 'Vadivel', BulkColumn
from Openrowset( Bulk 'C:\Image1.jpg', Single_Blob) as EmployeePicture
This Sql Query Working Fine.
If program name is always the first thing in (), and doesn't contain other )s than the one at end, then $yourstring -match "[(][^)]+[)]"
does the matching, result will be in $Matches[0]
Load url helper in controller
$this->load->helper('url');
A few answers here seem incomplete. Here are several variations:
<style>
.box {
height: 200px;
width: 200px;
border: 4px solid gray;
}
</style>
<!-- This works: .container>.row>.center-block.box -->
<div class="container">
<div class="row">
<div class="center-block bg-primary box">This div is centered with .center-block</div>
</div>
</div>
<!-- This does not work -->
<div class="container">
<div class="row">
<div class="center-block bg-primary box col-xs-4">This div is centered with .center-block</div>
</div>
</div>
<!-- This is the hybrid solution from other answers:
.container>.row>.col-xs-6>.center-block.box
-->
<div class="container">
<div class="row">
<div class="col-xs-6 bg-info">
<div class="center-block bg-primary box">This div is centered with .center-block</div>
</div>
</div>
</div>
To make it work with col-* classes, you need to wrap the .center-block inside a .col-* class, but remember to either add another class that sets the width (.box in this case), or to alter the .center-block itself by giving it a width.
Check it out on bootply.
The method I used included part of Richard Harrison's method:
So, install SQL Server 2008 Express edition,
This requires the download of the Web Platform Installer "wpilauncher_n.exe" Once you have this installed click on the database selection ( you are also required to download Frameworks and Runtimes)
After instalation go to the windows command prompt and:
use sqlcmd -S \SQLExpress (whilst logged in as administrator)
then issue the following command.
restore filelistonly from disk='c:\temp\mydbName-2009-09-29-v10.bak'; GO This will list the contents of the backup - what you need is the first fields that tell you the logical names - one will be the actual database and the other the log file.
RESTORE DATABASE mydbName FROM disk='c:\temp\mydbName-2009-09-29-v10.bak' WITH MOVE 'mydbName' TO 'c:\temp\mydbName_data.mdf', MOVE 'mydbName_log' TO 'c:\temp\mydbName_data.ldf'; GO
I fired up Web Platform Installer and from the what's new tab I installed SQL Server Management Studio and browsed the db to make sure the data was there...
At that point i tried the tool included with MSSQL "SQL Import and Export Wizard" but the result of the csv dump only included the column names...
So instead I just exported results of queries like "select * from users" from the SQL Server Management Studio
Load environment variables from a file you create at runtime.
export MYVAR="my_var_outside"
cat > build/env.sh <<EOF
MYVAR=${MYVAR}
EOF
... then in the Dockerfile
ADD build /build
RUN /build/test.sh
where test.sh loads MYVAR from env.sh
#!/bin/bash
. /build/env.sh
echo $MYVAR > /tmp/testfile
End each of the lines with a double slash "//". That will keep eclipse from moving them all onto the same line.
The COLLATE keyword specify what kind of character set and rules (order, confrontation rules) you are using for string values.
For example in your case you are using Latin rules with case insensitive (CI) and accent sensitive (AS)
You can refer to this Documentation
There is a CSS3 working draft that will (hopefully soon) allow you to write just:
p { text-indent: 200px hanging; }
Keep an eye on: https://developer.mozilla.org/en-US/docs/Web/CSS/text-indent
Mockito cannot capture static methods, but since Mockito 2.14.0 you can simulate it by creating invocation instances of static methods.
Example (extracted from their tests):
public class StaticMockingExperimentTest extends TestBase {
Foo mock = Mockito.mock(Foo.class);
MockHandler handler = Mockito.mockingDetails(mock).getMockHandler();
Method staticMethod;
InvocationFactory.RealMethodBehavior realMethod = new InvocationFactory.RealMethodBehavior() {
@Override
public Object call() throws Throwable {
return null;
}
};
@Before
public void before() throws Throwable {
staticMethod = Foo.class.getDeclaredMethod("staticMethod", String.class);
}
@Test
public void verify_static_method() throws Throwable {
//register staticMethod call on mock
Invocation invocation = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
"some arg");
handler.handle(invocation);
//verify staticMethod on mock
//Mockito cannot capture static methods so we will simulate this scenario in 3 steps:
//1. Call standard 'verify' method. Internally, it will add verificationMode to the thread local state.
// Effectively, we indicate to Mockito that right now we are about to verify a method call on this mock.
verify(mock);
//2. Create the invocation instance using the new public API
// Mockito cannot capture static methods but we can create an invocation instance of that static invocation
Invocation verification = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
"some arg");
//3. Make Mockito handle the static method invocation
// Mockito will find verification mode in thread local state and will try verify the invocation
handler.handle(verification);
//verify zero times, method with different argument
verify(mock, times(0));
Invocation differentArg = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
"different arg");
handler.handle(differentArg);
}
@Test
public void stubbing_static_method() throws Throwable {
//register staticMethod call on mock
Invocation invocation = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
"foo");
handler.handle(invocation);
//register stubbing
when(null).thenReturn("hey");
//validate stubbed return value
assertEquals("hey", handler.handle(invocation));
assertEquals("hey", handler.handle(invocation));
//default null value is returned if invoked with different argument
Invocation differentArg = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
"different arg");
assertEquals(null, handler.handle(differentArg));
}
static class Foo {
private final String arg;
public Foo(String arg) {
this.arg = arg;
}
public static String staticMethod(String arg) {
return "";
}
@Override
public String toString() {
return "foo:" + arg;
}
}
}
Their goal is not to directly support static mocking, but to improve its public APIs so that other libraries, like Powermockito, don't have to rely on internal APIs or directly have to duplicate some Mockito code. (source)
Disclaimer: Mockito team thinks that the road to hell is paved with static methods. However, Mockito's job is not to protect your code from static methods. If you don’t like your team doing static mocking, stop using Powermockito in your organization. Mockito needs to evolve as a toolkit with an opinionated vision on how Java tests should be written (e.g. don't mock statics!!!). However, Mockito is not dogmatic. We don't want to block unrecommended use cases like static mocking. It's just not our job.
Here's one more alternative:
var classElements = document.getElementsByClassName("className");
function setClassHeight (classElements, desiredHeightValue)
{
var arrayElements = Object.entries(classElements);
for(var i = 0; i< arrayElements.length; i++) {
arrayElements[i][1].style.height = desiredHeightValue;
}
}
You will find Python's string literal documentation here:
http://docs.python.org/tutorial/introduction.html#strings
and here:
http://docs.python.org/reference/lexical_analysis.html#literals
The simplest example would be using the 'r' prefix:
ss = r'Hello\nWorld'
print(ss)
Hello\nWorld
To solve this issue the first thing you need to do is to get the last version of composer :
curl -sS https://getcomposer.org/installer | php
I recommend you to move the composer.phar file to a global “bin” directoy, in my case (OS X) the path is:
mv composer.phar /usr/local/bin/composer.phar
than you need to create an alias file for an easy access
alias composer='/usr/local/bin/composer.phar'
If everything is ok, now it is time to verify our Composer version:
composer --version
Let's make composer great again.
There is no direct indexOf function in java arrays.
Add this to html:
<svg id="mySVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"/>
Try this function and adapt for you program:
var svgNS = "http://www.w3.org/2000/svg";
function createCircle()
{
var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle. for rectangle use "rectangle"
myCircle.setAttributeNS(null,"id","mycircle");
myCircle.setAttributeNS(null,"cx",100);
myCircle.setAttributeNS(null,"cy",100);
myCircle.setAttributeNS(null,"r",50);
myCircle.setAttributeNS(null,"fill","black");
myCircle.setAttributeNS(null,"stroke","none");
document.getElementById("mySVG").appendChild(myCircle);
}
Here more flexible variant: it uses external shell, but allows to check for arbitrary conditions:
ifeq ($(shell test ".$(GCC_MINOR)" = .4 -o \
".$(GCC_MINOR)" = .5 -o \
".$(TODAY)" = .Friday && printf "true"), true)
CFLAGS += -fno-strict-overflow
endif
<?php
if(!function_exists('apache_get_modules') ){ phpinfo(); exit; }
$res = 'Module Unavailable';
if(in_array('mod_rewrite',apache_get_modules()))
$res = 'Module Available';
?>
<html>
<head>
<title>A mod_rewrite availability check !</title></head>
<body>
<p><?php echo apache_get_version(),"</p><p>mod_rewrite $res"; ?></p>
</body>
</html>
You have to edit your tests Runner xml file. See this example:
<test name="Employees Test">
<classes>
<class name="packagename.classname">
</class>
</classes>
</test>
In <class name="packagename.classname">
row you must enter your tests package name then name of class that you want to run.
Thanks and wish you all the best.
function array_unique(nav_array) {
nav_array = nav_array.sort(function (a, b) { return a*1 - b*1; });
var ret = [nav_array[0]];
// Start loop at 1 as element 0 can never be a duplicate
for (var i = 1; i < nav_array.length; i++) {
if (nav_array[i-1] !== nav_array[i]) {
ret.push(nav_array[i]);
}
}
return ret;
}
Just to add my views -
A variable that is declared only, and never used anywhere, is removed off by an optimizing compiler in case of compiled languages like C++[or a warning is flagged in the IDE]. It ultimately means that the variable is non-existent because it's memory is never allocated.
In case of javascript interpreter, [I guess] a variable is treated as existing only from the point onwards where it is given a value. Before that point, it's type is "undefined", and no memory is allocated for it. And, so its type is undefined.
A null in javascript is a value that represents an address, but that address points to nothing yet[non-existent reference]. Nevertheless, its a value.
In C++, references can't be null. If you want to optionally return null if nothing is found, you need to return a pointer, not a reference:
Attr *getAttribute(const string& attribute_name) const {
//search collection
//if found at i
return &attributes[i];
//if not found
return nullptr;
}
Otherwise, if you insist on returning by reference, then you should throw an exception if the attribute isn't found.
(By the way, I'm a little worried about your method being const
and returning a non-const
attribute. For philosophical reasons, I'd suggest returning const Attr *
. If you also may want to modify this attribute, you can overload with a non-const
method returning a non-const
attribute as well.)
I would suggest a two step query
I'm assuming you have an autoincrementing primary key because you say your PK is (max+1) which sounds like the definition of an autioincrementing key.
I'm calling the PK id
, substitute with whatever your PK is called.
1 - figure out the primary key number for column 1000.
SELECT @id:= id FROM smartmeter_usage LIMIT 1 OFFSET 1000
2 - update the table.
UPDATE smartmeter_usage.users_reporting SET panel_id = 3
WHERE panel_id IS NULL AND id >= @id
ORDER BY id
LIMIT 1000
Please test to see if I didn't make an off-by-one error; you may need to add or subtract 1 somewhere.
>>> " xyz ".rstrip()
' xyz'
There is more about rstrip
in the documentation.
I don't think you can both within the same jenkins job, what you need to do is to configure a new jenkins job which will have access to your github to retrieve branches and then you can choose which one to manually build.
Just mark it as a parameterized build, specify a name, and a parameter configured as git parameter
and now you can configure git options:
It's OK to run Docker-in-Docker (DinD) and in fact Docker (the company) has an official DinD image for this.
The caveat however is that it requires a privileged container, which depending on your security needs may not be a viable alternative.
The alternative solution of running Docker using sibling containers (aka Docker-out-of-Docker or DooD) does not require a privileged container, but has a few drawbacks that stem from the fact that you are launching the container from within a context that is different from that one in which it's running (i.e., you launch the container from within a container, yet it's running at the host's level, not inside the container).
I wrote a blog describing the pros/cons of DinD vs DooD here.
Having said this, Nestybox (a startup I just founded) is working on a solution that runs true Docker-in-Docker securely (without using privileged containers). You can check it out at www.nestybox.com.
On MySQL 5.1.51, both queries have identical execution plans:
mysql> explain select * from table1 a inner join table2 b on a.pid = b.pid;
+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+
| 1 | SIMPLE | b | ALL | PRIMARY | NULL | NULL | NULL | 986 | |
| 1 | SIMPLE | a | ref | pid | pid | 4 | schema.b.pid | 70 | |
+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+
2 rows in set (0.02 sec)
mysql> explain select * from table1 a, table2 b where a.pid = b.pid;
+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+
| 1 | SIMPLE | b | ALL | PRIMARY | NULL | NULL | NULL | 986 | |
| 1 | SIMPLE | a | ref | pid | pid | 4 | schema.b.pid | 70 | |
+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+
2 rows in set (0.00 sec)
table1
has 166208 rows; table2
has about 1000 rows.
This is a very simple case; it doesn't by any means prove that the query optimizer wouldn't get confused and generate different plans in a more complicated case.
You're storing the .Text
properties of the textboxes directly into the database, this doesn't work. The .Text
properties are String
s (i.e. simple text) and not typed as DateTime
instances. Do the conversion first, then it will work.
Do this for each date parameter:
Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) )
Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse
or DateTime.TryParseExact
, but implementing that is an exercise for the reader.
From Python Documentation:
An except clause may name multiple exceptions as a parenthesized tuple, for example
except (IDontLikeYouException, YouAreBeingMeanException) as e:
pass
Or, for Python 2 only:
except (IDontLikeYouException, YouAreBeingMeanException), e:
pass
Separating the exception from the variable with a comma will still work in Python 2.6 and 2.7, but is now deprecated and does not work in Python 3; now you should be using as
.
If nothing happens even if you added all the annotation needed, try to add this dependency to your pom.xml
, I just faced the same problem and resolved it by adding this one here:
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.9</version>
</dependency>
There is a statement you can issue at the module level:
Option Compare Text
This makes all "text comparisons" case insensitive. This means the following code will show the message "this is true":
Option Compare Text
Sub testCase()
If "UPPERcase" = "upperCASE" Then
MsgBox "this is true: option Compare Text has been set!"
End If
End Sub
See for example http://www.ozgrid.com/VBA/vba-case-sensitive.htm . I'm not sure it will completely solve the problem for all instances (such as the Application.Match
function) but it will take care of all the if a=b
statements. As for Application.Match
- you may want to convert the arguments to either upper case or lower case using the LCase
function.
Function isset()
is faster, check http://www.php.net/manual/en/function.array-key-exists.php#82867
Did you declare the jobparameters as map properly as bean?
Or did you perhaps accidently instantiate a JobParameters object, which has no getter for the filename?
For more on expression language you can find information in Spring documentation here.
Cloning the objects before adding them. For example, instead of newList.addAll(oldList);
for(Person p : oldList) {
newList.add(p.clone());
}
Assuming clone
is correctly overriden inPerson
.
You can do it like this and you mod function will work perfect let me know if you want a code pen
<div ng-repeat="icon in icons">
<div class="row" ng-if="$index % 3 == 0 ">
<i class="col col-33 {{icons[$index + n].icon}} custom-icon"></i>
<i class="col col-33 {{icons[$index + n + 1].icon}} custom-icon"></i>
<i class="col col-33 {{icons[$index + n + 2].icon}} custom-icon"></i>
</div>
</div>
The simplest solution is to go to your XML layout containing your webview. Change your android:layout_width and android:layout_height from "wrap_content" to "match_parent".
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webView"/>
make sure the submit button is not of type "submit", make it a button. Then use the onclick event to trigger some javascript. There you can do whatever you want before you actually post your data.
React hooks are a new way (still being developed) to access the core features of react such as state
without having to use classes, in your example if you want to increment a counter directly in the handler function without specifying it directly in the onClick
prop, you could do something like:
...
const [count, setCounter] = useState(0);
const [moreStuff, setMoreStuff] = useState(...);
...
const setCount = () => {
setCounter(count + 1);
setMoreStuff(...);
...
};
and onClick:
<button onClick={setCount}>
Click me
</button>
Let's quickly explain what is going on in this line:
const [count, setCounter] = useState(0);
useState(0)
returns a tuple where the first parameter count
is the current state of the counter and setCounter
is the method that will allow us to update the counter's state. We can use the setCounter
method to update the state of count
anywhere - In this case we are using it inside of the setCount
function where we can do more things; the idea with hooks is that we are able to keep our code more functional and avoid class based components if not desired/needed.
I wrote a complete article about hooks with multiple examples (including counters) such as this codepen, I made use of useState
, useEffect
, useContext
, and custom hooks. I could get into more details about how hooks work on this answer but the documentation does a very good job explaining the state hook and other hooks in detail, hope it helps.
update: Hooks are not longer a proposal, since version 16.8 they're now available to be used, there is a section in React's site that answers some of the FAQ.
While I agree with everyone else, if you are dead set on using frames anyway, you can just do index.html in XHTML and then do the contents of the frames in HTML5.
I would suggest to use a variable instead of a public field:
public class Variables
{
private static string name = "";
public static string Name
{
get { return name; }
set { name = value; }
}
}
From another class, you call your variable like this:
public class Main
{
public void DoSomething()
{
string var = Variables.Name;
}
}
<?php
$file = "http://example.com/go.exe";
header("Content-Description: File Transfer");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"". basename($file) ."\"");
readfile ($file);
exit();
?>
Or, when the file is not openable with the browser, you can just use the Location
header:
<?php header("Location: http://example.com/go.exe"); ?>
You're running your Python 3 code with a Python 2 interpreter. If you weren't, your print
statement would throw up a SyntaxError
before it ever prompted you for input.
The result is that you're using Python 2's input
, which tries to eval
your input (presumably sdas
), finds that it's invalid Python, and dies.
This is happening because this is a dynamic component and you didn't add it to entryComponents
under @NgModule
.
Simply add it there:
@NgModule({
/* ----------------- */
entryComponents: [ DialogResultExampleDialog ] // <---- Add it here
Look at how the Angular team talks about entryComponents
:
entryComponents?: Array<Type<any>|any[]>
Specifies a list of components that should be compiled when this module is defined. For each component listed here, Angular will create a ComponentFactory and store it in the ComponentFactoryResolver.
Also, this is the list of the methods on @NgModule
including entryComponents
...
As you can see, all of them are optional (look at the question marks), including entryComponents
which accept an array of components:
@NgModule({
providers?: Provider[]
declarations?: Array<Type<any>|any[]>
imports?: Array<Type<any>|ModuleWithProviders|any[]>
exports?: Array<Type<any>|any[]>
entryComponents?: Array<Type<any>|any[]>
bootstrap?: Array<Type<any>|any[]>
schemas?: Array<SchemaMetadata|any[]>
id?: string
})
for ((i=0; i<=1000; i++)); do
echo "http://example.com/$i.jpg"
done
This is easy to do, you can render the report as a PDF, and save the resulting byte array as a PDF file on disk. To do this in the background, that's more a question of how your app is written. You can just spin up a new thread, or use a BackgroundWorker (if this is a WinForms app), etc. There, of course, may be multithreading issues to be aware of.
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string filenameExtension;
byte[] bytes = reportViewer.LocalReport.Render(
"PDF", null, out mimeType, out encoding, out filenameExtension,
out streamids, out warnings);
using (FileStream fs = new FileStream("output.pdf", FileMode.Create))
{
fs.Write(bytes, 0, bytes.Length);
}
Difficult task. I would normally suggest to grab a debugger/memory profiler like Valgrind and run the programs one after one in it. Soon or later you will find the program that leaks and can tell it the devloper or fix it yourself.
There's a much easier way to do this, using iconv
- from the user notes, this seems to be what you want to do: characters transliteration
// PHP.net User notes
<?php
$string = "?ABBASABAD";
echo iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $string);
// output: [nothing, and you get a notice]
echo iconv('UTF-8', 'ISO-8859-1//IGNORE', $string);
// output: ABBSBD
echo iconv('UTF-8', 'ISO-8859-1//TRANSLIT//IGNORE', $string);
// output: ABBASABAD
// Yay! That's what I wanted!
?>
Be very conscientious with your character encodings, so you are keeping the same encoding at all stages in the process - front end, form submission, encoding of the source files. Default encoding in PHP and in forms is ISO-8859-1, before PHP 5.4 where it changed to be UTF8 (finally!).
There's a couple of functions you can play around with for ideas. First is from CakePHP's inflector class, called slug
:
public static function slug($string, $replacement = '_') {
$quotedReplacement = preg_quote($replacement, '/');
$merge = array(
'/[^\s\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]/mu' => ' ',
'/\\s+/' => $replacement,
sprintf('/^[%s]+|[%s]+$/', $quotedReplacement, $quotedReplacement) => '',
);
$map = self::$_transliteration + $merge;
return preg_replace(array_keys($map), array_values($map), $string);
}
It depends on a self::$_transliteration
array which is similar to what you were doing in your question - you can see the source for inflector on github.
Another is a function I use personally, which comes from here.
function slugify($text,$strict = false) {
$text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
// replace non letter or digits by -
$text = preg_replace('~[^\\pL\d.]+~u', '-', $text);
// trim
$text = trim($text, '-');
setlocale(LC_CTYPE, 'en_GB.utf8');
// transliterate
if (function_exists('iconv')) {
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
}
// lowercase
$text = strtolower($text);
// remove unwanted characters
$text = preg_replace('~[^-\w.]+~', '', $text);
if (empty($text)) {
return 'empty_$';
}
if ($strict) {
$text = str_replace(".", "_", $text);
}
return $text;
}
What those functions do is transliterate and create 'slugs' from arbitrary text input, which is a very very useful thing to have in your toolchest when making web apps. Hope this helps!
To put it on one line:
currentLoad = IIf(IsNumeric(oXLSheet2.Cells(4, 6).Value), CInt(oXLSheet2.Cells(4, 6).Value), 0)
I had the same problem and mine was caused by an old selenium version. I cannot update to a newer version due to development environment. The problem is caused by HTMLUnitWebElement.switchFocusToThisIfNeeded(). When you navigate to a new page it might happen that the element you clicked on the old page is the oldActiveElement
(see below). Selenium tries to get context from the old element and fails. That's why they built a try catch in future releases.
Code from selenium-htmlunit-driver version < 2.23.0:
private void switchFocusToThisIfNeeded() {
HtmlUnitWebElement oldActiveElement =
((HtmlUnitWebElement)parent.switchTo().activeElement());
boolean jsEnabled = parent.isJavascriptEnabled();
boolean oldActiveEqualsCurrent = oldActiveElement.equals(this);
boolean isBody = oldActiveElement.getTagName().toLowerCase().equals("body");
if (jsEnabled &&
!oldActiveEqualsCurrent &&
!isBody) {
oldActiveElement.element.blur();
element.focus();
}
}
Code from selenium-htmlunit-driver version >= 2.23.0:
private void switchFocusToThisIfNeeded() {
HtmlUnitWebElement oldActiveElement =
((HtmlUnitWebElement)parent.switchTo().activeElement());
boolean jsEnabled = parent.isJavascriptEnabled();
boolean oldActiveEqualsCurrent = oldActiveElement.equals(this);
try {
boolean isBody = oldActiveElement.getTagName().toLowerCase().equals("body");
if (jsEnabled &&
!oldActiveEqualsCurrent &&
!isBody) {
oldActiveElement.element.blur();
}
} catch (StaleElementReferenceException ex) {
// old element has gone, do nothing
}
element.focus();
}
Without updating to 2.23.0 or newer you can just give any element on the page focus. I just used element.click()
for example.
Echoing f.in and f.out will seperate the concept of what to loop and what not to loop when used in a for /f loop.
::Get the files seperated
echo f.in>files_to_pass_through.txt
echo f.out>>files_to_pass_through.txt
for /F %%a in (files_to_pass_through.txt) do (
for /R %%b in (*.*) do (
if "%%a" NEQ "%%b" (
echo %%b>>dont_pass_through_these.txt
)
)
)
::I'm assuming the base name is the whole string "f".
::If I'm right then all the files begin with "f".
::So all you have to do is display "f". right?
::But that would be too easy.
::Let's do this the right way.
for /f %%C in (dont_pass_through_these.txt)
::displays the filename and not the extention
echo %~nC
)
Although you didn't ask, a good way to pass commands into f.in and f.out would be to...
for /F %%D "tokens=*" in (dont_pass_through_these.txt) do (
for /F %%E in (%%D) do (
start /wait %%E
)
)
A link to all the Windows XP commands:link
I apologize if I did not answer this correctly. The question was very hard for me to read.
instead of push() function use concat function for IE. example,
var a=a.concat(a,new Array('amin'));
It will not return the name of variable but you can create dictionary from global variable easily.
class CustomDict(dict):
def __add__(self, other):
return CustomDict({**self, **other})
class GlobalBase(type):
def __getattr__(cls, key):
return CustomDict({key: globals()[key]})
def __getitem__(cls, keys):
return CustomDict({key: globals()[key] for key in keys})
class G(metaclass=GlobalBase):
pass
x, y, z = 0, 1, 2
print('method 1:', G['x', 'y', 'z']) # Outcome: method 1: {'x': 0, 'y': 1, 'z': 2}
print('method 2:', G.x + G.y + G.z) # Outcome: method 2: {'x': 0, 'y': 1, 'z': 2}
This is a simple example
COUNTER=1
for i in {1..5}
do
echo $COUNTER;
//echo "Welcome $i times"
((COUNTER++));
done
Just install this package and your code will work:=> Install-Package Microsoft.Owin.Host.SystemWeb -Version 2.1.0
The typeof
operator isn't an infix (so the LHS of your example doesn't make sense).
You need to use it like so...
if (typeof a_string == 'string') {
// This is a string.
}
Remember, typeof
is an operator, not a function. Despite this, you will see typeof(var)
being used a lot in the wild. This makes as much sense as var a = 4 + (1)
.
Also, you may as well use ==
(equality comparison operator) since both operands are String
s (typeof
always returns a String
), JavaScript is defined to perform the same steps had I used ===
(strict comparison operator).
As Box9 mentions, this won't detect a instantiated String
object.
You can detect for that with....
var isString = str instanceof String;
...or...
var isString = str.constructor == String;
But this won't work in a multi window
environment (think iframe
s).
You can get around this with...
var isString = Object.prototype.toString.call(str) == '[object String]';
But again, (as Box9 mentions), you are better off just using the literal String
format, e.g. var str = 'I am a string';
.
Keep track of your index: That's how it is done in Java:
int index = 0;
for (Element song: question){
// Do whatever
index++;
}
if you are using SQL Server use convert
e.g. select convert(varchar(10), DeliveryDate, 103) as ShortDate
more information here: http://msdn.microsoft.com/en-us/library/aa226054(v=sql.80).aspx
ANTS Profiler. I haven't used many, but I don't really have any complaints about ANTS. The visualization is really helpful.
If you are pressed by performance issuses, have a look at GMPY
For anybody else stumbling over this, the same happened to me while trying to send a SOAP request header to a SOAP service. The issue was a wrong order in the code, I requested the input stream first before sending the XML body. In the code snipped below, the line InputStream in = conn.getInputStream();
came immediately after ByteArrayOutputStream out = new ByteArrayOutputStream();
which is the incorrect order of things.
ByteArrayOutputStream out = new ByteArrayOutputStream();
// send SOAP request as part of HTTP body
byte[] data = request.getHttpBody().getBytes("UTF-8");
conn.getOutputStream().write(data);
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.d(TAG, "http response code is " + conn.getResponseCode());
return null;
}
InputStream in = conn.getInputStream();
FileNotFound
in this case was an unfortunate way to encode HTTP response code 400.
This will give you exactly what you need (path does NOT have to exist for this to work)
DirectoryInfo di = new DirectoryInfo(@"C:\blah\..\bling");
string cleanPath = di.FullName;
Lots of these answers no longer apply, so here's mine:
Use the Share Dialog described at the Facebook Dev Page.
Example:
https://www.facebook.com/dialog/share?
app_id=<your_app_id>
&display=popup
&href=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2F
&redirect_uri=https%3A%2F%2Fdevelopers.facebook.com%2Ftools%2Fexplorer
But you have to put in your registered app_id, the href, and a redirect uri.
Not only try to show an alert but it can also be invoked when you finish a particular instance of activity and try to start new activity/service or try to stop it.
Example:
OldActivity instance;
oncreate() {
instance=this;
}
instance.finish();
instance.startActivity(new Intent(ACTION_MAIN).setClass(instance, NewActivity.class));
I got this error while trying to copy an object. I fixed it by encoding the copySource. This is actually described in the method documentation:
Params: copySource – The name of the source bucket and key name of the source object, separated by a slash (/). Must be URL-encoded.
CopyObjectRequest objectRequest = CopyObjectRequest.builder()
.copySource(URLEncoder.encode(bucket + "/" + oldFileKey, "UTF-8"))
.destinationBucket(bucket)
.destinationKey(newFileKey)
.build();
It's still not possible.
var angle = 0;
$('#button').on('click', function() {
angle += 90;
$('#image').css('transform','rotate(' + angle + 'deg)');
});
Try this code.
I tried all of above. What helps me:
this C:\MinGW\bin
to environment variables.mingw-get
into command line.mingw-get install mingw32-make
.C:\MinGW\bin
to folder where your Makefile is.
Done! Now You might be able to use make-commands in this folder.The answer, from this page in CSS:
pre {
white-space: pre-wrap; /* Since CSS 2.1 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
There's a jQuery Timer plugin you may want to try
I also got this error, but for a .h
file. The fix was to go into the file Properties
(via Solution Explorer's file popup menu) and set the file type correctly. It was set to C/C++ Compiler
instead of the correct C/C++ header
.
Try this code:
private void RegisterInStartup(bool isChecked)
{
RegistryKey registryKey = Registry.CurrentUser.OpenSubKey
("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (isChecked)
{
registryKey.SetValue("ApplicationName", Application.ExecutablePath);
}
else
{
registryKey.DeleteValue("ApplicationName");
}
}
Source (dead): http://www.dotnetthoughts.net/2010/09/26/run-the-application-at-windows-startup/
Archived link: https://web.archive.org/web/20110104113608/http://www.dotnetthoughts.net/2010/09/26/run-the-application-at-windows-startup/
Instead of using re.search
use re.findall
it will return you all matches in a List
. Or you could also use re.finditer
(which i like most to use) it will return an Iterator Object
and you can just use it to iterate over all found matches.
line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
for match in re.finditer('<form>(.*?)</form>', line, re.S):
print match.group(1)
Demo :
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
Based on your question:
<connectionStrings>
<add name="itmall" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True" />
</connectionStrings>
Refer links:
http://www.connectionstrings.com/store-connection-string-in-webconfig/
Retrive connection string from web.config file:
write the below code in your file where you want;
string connstring=ConfigurationManager.ConnectionStrings["itmall"].ConnectionString;
SqlConnection con = new SqlConnection(connstring);
or you can go in your way like
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["itmall"].ConnectionString);
Note:
The "name" which you gave in web.config file and name which you used in connection string must be same(like "itmall" in this solution.)
Rules are used to enhance the behaviour of each test method in a generic way. Junit rule intercept the test method and allows us to do something before a test method starts execution and after a test method has been executed.
For example, Using @Timeout rule we can set the timeout for all the tests.
public class TestApp {
@Rule
public Timeout globalTimeout = new Timeout(20, TimeUnit.MILLISECONDS);
......
......
}
@TemporaryFolder rule is used to create temporary folders, files. Every time the test method is executed, a temporary folder is created and it gets deleted after the execution of the method.
public class TempFolderTest {
@Rule
public TemporaryFolder tempFolder= new TemporaryFolder();
@Test
public void testTempFolder() throws IOException {
File folder = tempFolder.newFolder("demos");
File file = tempFolder.newFile("Hello.txt");
assertEquals(folder.getName(), "demos");
assertEquals(file.getName(), "Hello.txt");
}
}
You can see examples of some in-built rules provided by junit at this link.
While Phairoh's solution seems theoretically sound, I have also found another solution to this problem. By passing the UpdatePanels id as a paramater (event target) for the doPostBack function the update panel will post back but not the entire page.
__doPostBack('myUpdatePanelId','')
*note: second parameter is for addition event args
hope this helps someone!
EDIT: so it seems this same piece of advice was given above as i was typing :)
@Sotirios Delimanolis answer do the job however I was looking for comparing strings within this mockMvc assertion
So here it is
.andExpect(content().string("\"Username already taken - please try with different username\""));
Of course my assertion fail:
java.lang.AssertionError: Response content expected:
<"Username already taken - please try with different username"> but was:<"Something gone wrong">
because:
MockHttpServletResponse:
Body = "Something gone wrong"
So this is proof that it works!
The most efficient, but not the C++ way would be:
FILE* f = fopen(filename, "r");
// Determine file size
fseek(f, 0, SEEK_END);
size_t size = ftell(f);
char* where = new char[size];
rewind(f);
fread(where, sizeof(char), size, f);
delete[] where;
#
EDIT - 2Just tested the std::filebuf
variant also. Looks like it can be called the best C++ approach, even though it's not quite a C++ approach, but more a wrapper. Anyway, here is the chunk of code that works almost as fast as plain C does.
std::ifstream file(filename, std::ios::binary);
std::streambuf* raw_buffer = file.rdbuf();
char* block = new char[size];
raw_buffer->sgetn(block, size);
delete[] block;
I've done a quick benchmark here and the results are following. Test was done on reading a 65536K binary file with appropriate (std::ios:binary
and rb
) modes.
[==========] Running 3 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 4 tests from IO
[ RUN ] IO.C_Kotti
[ OK ] IO.C_Kotti (78 ms)
[ RUN ] IO.CPP_Nikko
[ OK ] IO.CPP_Nikko (106 ms)
[ RUN ] IO.CPP_Beckmann
[ OK ] IO.CPP_Beckmann (1891 ms)
[ RUN ] IO.CPP_Neil
[ OK ] IO.CPP_Neil (234 ms)
[----------] 4 tests from IO (2309 ms total)
[----------] Global test environment tear-down
[==========] 4 tests from 1 test case ran. (2309 ms total)
[ PASSED ] 4 tests.
Perhaps the console is clearing. Try:
Console.WriteLine("Test");
Console.ReadLine();
And it will hopefully stay there until you press enter.
I had the same issue with my Android app. I was trying out notifications and found that notifications were showing on my Android emulator which ran a Android 7.0 (Nougat) system, whereas it wasn't running on my phone which had Android 8.1 (Oreo).
After reading the documentation, I found that Android had a feature called notification channel, without which notifications won't show up on Oreo devices. Below is the link to official Android documentation on notification channels.
You need to escape the backslash \
:
println yourString.replace("\\", "/")
Mine did not start because the Server did not accept the 'Dedicated MySQL Server' setting in the Configuration.
As the documentation for MethodInfo.Invoke states, the first argument is ignored for static methods so you can just pass null.
foreach (var tempClass in macroClasses)
{
// using reflection I will be able to run the method as:
tempClass.GetMethod("Run").Invoke(null, null);
}
As the comment points out, you may want to ensure the method is static when calling GetMethod
:
tempClass.GetMethod("Run", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);
You can install pidof
with Homebrew:
brew install pidof
pidof <process_name>
add "MainContent_" to ID value!
Example: (Error)
document.getElementById("Password").value = text;
(ok!)
document.getElementById("**MainContent_**Password").value = text;
Please try below:
myDropDown.SelectedIndex =
myDropDown.Items.IndexOf(myDropDown.Items.FindByValue("myValue"))
Adding Json.stringfy
around the json that fixed the issue
use labelpad parameter:
pl.xlabel("...", labelpad=20)
or set it after:
ax.xaxis.labelpad = 20
A similar approach to https://stackoverflow.com/a/13864910/2323964 that works in Java 8 is to use an interface with default getters. This will be more whitespace verbose, but is mockable, and it's great for when you have a bunch of instances where you actually want to draw attention to the parameters.
public class Foo() {
public interface Parameters {
String getRequired();
default int getOptionalInt(){ return 23; }
default String getOptionalString(){ return "Skidoo"; }
}
public Foo(Parameters parameters){
//...
}
public static void baz() {
final Foo foo = new Foo(new Person() {
@Override public String getRequired(){ return "blahblahblah"; }
@Override public int getOptionalInt(){ return 43; }
});
}
}
You can't really force the optimizer to do anything, but you can guide it.
UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93
You may be misleaded about the username you use locally. That was my case in Windows 10 Home. When I look at users in control panel, I see the name usrpc01. However when I type net config workstation
, it appears that the user's name is spc01. Seems like someone renamed the user, but the internal name remained unchanged.
Not knowing how to fix windows user name (and the folder name under C:\Users
, which also refers to the original internal name), I added a new user accout on my db server.
Your syntax is incorrect. The var
keyword in your for
loop must be followed by a variable name, in this case its propName
var propValue;
for(var propName in nyc) {
propValue = nyc[propName]
console.log(propName,propValue);
}
I suggest you have a look here for some basics:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
EXEC msdb.dbo.sp_help_job @Job_name = 'Your Job Name'
check field execution_status
0 - Returns only those jobs that are not idle or suspended.
1 - Executing.
2 - Waiting for thread.
3 - Between retries.
4 - Idle.
5 - Suspended.
7 - Performing completion actions.
If you need the result of execution, check the field last_run_outcome
0 = Failed
1 = Succeeded
3 = Canceled
5 = Unknown
Any of the following should work!!
df <- data.frame(x=1:3,y=4:6)
mean(df$x)
mean(df[,1])
mean(df[["x"]])
You could try https://hacss.io:
<a href="http://www.google.com" class=":hover{text-decoration:none;}">Google</a>
Here's another solution that uses some of VBA's built in date functions and stores all the date data in an array for comparison, which may give better performance if you get a lot of data:
Public Sub MoveData(MonthNum As Integer, FromSheet As Worksheet, ToSheet As Worksheet)
Const DateCol = "A" 'column where dates are store
Const DestCol = "A" 'destination column where dates are stored. We use this column to find the last populated row in ToSheet
Const FirstRow = 2 'first row where date data is stored
'Copy range of values to Dates array
Dates = FromSheet.Range(DateCol & CStr(FirstRow) & ":" & DateCol & CStr(FromSheet.Range(DateCol & CStr(FromSheet.Rows.Count)).End(xlUp).Row)).Value
Dim i As Integer
For i = LBound(Dates) To UBound(Dates)
If IsDate(Dates(i, 1)) Then
If Month(CDate(Dates(i, 1))) = MonthNum Then
Dim CurrRow As Long
'get the current row number in the worksheet
CurrRow = FirstRow + i - 1
Dim DestRow As Long
'get the destination row
DestRow = ToSheet.Range(DestCol & CStr(ToSheet.Rows.Count)).End(xlUp).Row + 1
'copy row CurrRow in FromSheet to row DestRow in ToSheet
FromSheet.Range(CStr(CurrRow) & ":" & CStr(CurrRow)).Copy ToSheet.Range(DestCol & CStr(DestRow))
End If
End If
Next i
End Sub
cd
has a parameter /d
, which will change drive and path with one command:
cd /d d:\temp
( see cd /?
)
Don't forget that the jQuery css function allows objects to be passed which allows you to set multiple items at the same time. The answered code would then look like this:
$(this).css({'background-image':'url(' + imageUrl + ')'})
This will show last run status/time or if running, it shows current run time, step number/info, and SPID (if it has associated SPID). It also shows enabled/disabled and job user where it converts to NT SID format for unresolved user accounts.
CREATE TABLE #list_running_SQL_jobs
(
job_id UNIQUEIDENTIFIER NOT NULL
, last_run_date INT NOT NULL
, last_run_time INT NOT NULL
, next_run_date INT NOT NULL
, next_run_time INT NOT NULL
, next_run_schedule_id INT NOT NULL
, requested_to_run INT NOT NULL
, request_source INT NOT NULL
, request_source_id sysname NULL
, running INT NOT NULL
, current_step INT NOT NULL
, current_retry_attempt INT NOT NULL
, job_state INT NOT NULL
);
DECLARE @sqluser NVARCHAR(128)
, @is_sysadmin INT;
SELECT @is_sysadmin = ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0);
DECLARE read_sysjobs_for_running CURSOR FOR
SELECT DISTINCT SUSER_SNAME(owner_sid)FROM msdb.dbo.sysjobs;
OPEN read_sysjobs_for_running;
FETCH NEXT FROM read_sysjobs_for_running
INTO @sqluser;
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO #list_running_SQL_jobs
EXECUTE master.dbo.xp_sqlagent_enum_jobs @is_sysadmin, @sqluser;
FETCH NEXT FROM read_sysjobs_for_running
INTO @sqluser;
END;
CLOSE read_sysjobs_for_running;
DEALLOCATE read_sysjobs_for_running;
SELECT j.name
, 'Enbld' = CASE j.enabled
WHEN 0
THEN 'no'
ELSE 'YES'
END
, '#Min' = DATEDIFF(MINUTE, a.start_execution_date, ISNULL(a.stop_execution_date, GETDATE()))
, 'Status' = CASE
WHEN a.start_execution_date IS NOT NULL
AND a.stop_execution_date IS NULL
THEN 'Executing'
WHEN h.run_status = 0
THEN 'FAILED'
WHEN h.run_status = 2
THEN 'Retry'
WHEN h.run_status = 3
THEN 'Canceled'
WHEN h.run_status = 4
THEN 'InProg'
WHEN h.run_status = 1
THEN 'Success'
ELSE 'Idle'
END
, r.current_step
, spid = p.session_id
, owner = ISNULL(SUSER_SNAME(j.owner_sid), 'S-' + CONVERT(NVARCHAR(12), CONVERT(BIGINT, UNICODE(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 1))) - CONVERT(BIGINT, 256) * CONVERT(BIGINT, UNICODE(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 1)) / 256)) + '-' + CONVERT(NVARCHAR(12), UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 4), 1)) / 256 + CONVERT(BIGINT, NULLIF(UNICODE(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 1)) / 256, 0)) - CONVERT(BIGINT, UNICODE(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 1)) / 256)) + ISNULL('-' + CONVERT(NVARCHAR(12), CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 5), 1))) + CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 6), 1))) * CONVERT(BIGINT, 65536) + CONVERT(BIGINT, NULLIF(SIGN(LEN(CONVERT(NVARCHAR(256), j.owner_sid)) - 6), -1)) * 0), '') + ISNULL('-' + CONVERT(NVARCHAR(12), CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 7), 1))) + CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 8), 1))) * CONVERT(BIGINT, 65536) + CONVERT(BIGINT, NULLIF(SIGN(LEN(CONVERT(NVARCHAR(256), j.owner_sid)) - 8), -1)) * 0), '') + ISNULL('-' + CONVERT(NVARCHAR(12), CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 9), 1))) + CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 10), 1))) * CONVERT(BIGINT, 65536) + CONVERT(BIGINT, NULLIF(SIGN(LEN(CONVERT(NVARCHAR(256), j.owner_sid)) - 10), -1)) * 0), '') + ISNULL('-' + CONVERT(NVARCHAR(12), CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 11), 1))) + CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 12), 1))) * CONVERT(BIGINT, 65536) + CONVERT(BIGINT, NULLIF(SIGN(LEN(CONVERT(NVARCHAR(256), j.owner_sid)) - 12), -1)) * 0), '') + ISNULL('-' + CONVERT(NVARCHAR(12), CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 13), 1))) + CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 14), 1))) * CONVERT(BIGINT, 65536) + CONVERT(BIGINT, NULLIF(SIGN(LEN(CONVERT(NVARCHAR(256), j.owner_sid)) - 14), -1)) * 0), '')) --SHOW as NT SID when unresolved
, a.start_execution_date
, a.stop_execution_date
, t.subsystem
, t.step_name
FROM msdb.dbo.sysjobs j
LEFT OUTER JOIN (SELECT DISTINCT * FROM #list_running_SQL_jobs) r
ON j.job_id = r.job_id
LEFT OUTER JOIN msdb.dbo.sysjobactivity a
ON j.job_id = a.job_id
AND a.start_execution_date IS NOT NULL
--AND a.stop_execution_date IS NULL
AND NOT EXISTS
(
SELECT *
FROM msdb.dbo.sysjobactivity at
WHERE at.job_id = a.job_id
AND at.start_execution_date > a.start_execution_date
)
LEFT OUTER JOIN sys.dm_exec_sessions p
ON p.program_name LIKE 'SQLAgent%0x%'
AND j.job_id = SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 7, 2) + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 5, 2) + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 3, 2) + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 1, 2) + '-' + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 11, 2) + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 9, 2) + '-' + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 15, 2) + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 13, 2) + '-' + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 17, 4) + '-' + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 21, 12)
LEFT OUTER JOIN msdb.dbo.sysjobhistory h
ON j.job_id = h.job_id
AND h.instance_id = a.job_history_id
LEFT OUTER JOIN msdb.dbo.sysjobsteps t
ON t.job_id = j.job_id
AND t.step_id = r.current_step
ORDER BY 1;
DROP TABLE #list_running_SQL_jobs;
The string splitting is required in many cases like where you have to sort the characters of the string given, replacing a character with an another character etc. But all these operations can be performed with the following mentioned string splitting methods.
The string splitting can be done in two ways:
Slicing the given string based on the length of split.
Converting the given string to a list with list(str) function, where characters of the string breakdown to form the the elements of a list. Then do the required operation and join them with 'specified character between the characters of the original string'.join(list) to get a new processed string.
Works for me:
List<Item> list = Task.Run(() => manager.GetList()).Result;
in this way it is not necessary to mark the method with async in the call.
Further to @cw24's answer • as of Laravel 5.4
you would instead have the following amendment in public/index.php
try {
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
} catch(\Exception $e) {
echo "<pre>";
echo $e;
echo "</pre>";
}
And in my case, I had forgotten to fire up MySQL.
Which, by the way, is usually mysql.server start
in Terminal
you can create options menu like below:
Menu XML code:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/Menu_AboutUs"
android:icon="@drawable/ic_about_us_over_black"
android:title="About US"/>
<item
android:id="@+id/Menu_LogOutMenu"
android:icon="@drawable/ic_arrow_forward_black"
android:title="Logout"/>
</menu>
How you can get the menu from MENU XML(Convert menu XML to java):
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my_options_menu,menu);
return super.onCreateOptionsMenu(menu);
}
How to get Selected Item from Menu:
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.Menu_AboutUs:
//About US
break;
case R.id.Menu_LogOutMenu:
//Do Logout
break;
}
return super.onOptionsItemSelected(item);
}
"Segmentation fault" means that you tried to access memory that you do not have access to.
The first problem is with your arguments of main
. The main
function should be int main(int argc, char *argv[])
, and you should check that argc
is at least 2 before accessing argv[1]
.
Also, since you're passing in a float
to printf
(which, by the way, gets converted to a double
when passing to printf
), you should use the %f
format specifier. The %s
format specifier is for strings ('\0'
-terminated character arrays).
Here is another option using sql servers count distinct:
DECLARE @T TABLE( [contract] INT, project INT, activity INT )
INSERT INTO @T VALUES( 1000, 8000, 10 )
INSERT INTO @T VALUES( 1000, 8000, 20 )
INSERT INTO @T VALUES( 1000, 8001, 10 )
INSERT INTO @T VALUES( 2000, 9000, 49 )
INSERT INTO @T VALUES( 2000, 9001, 49 )
INSERT INTO @T VALUES( 3000, 9000, 79 )
INSERT INTO @T VALUES( 3000, 9000, 78 )
SELECT DISTINCT [contract], activity FROM @T AS A WHERE
(SELECT COUNT( DISTINCT activity )
FROM @T AS B WHERE B.[contract] = A.[contract]) = 1
I got the same error when xampp was installed on windows 10.
www.example.com:443:0 server certificate does NOT include an ID which matches the server name
So I opened httpd-ssl.conf
file in xampp folder and changed the following line
ServerName www.example.com:443
To
ServerName localhost
And the problem was fixed.
document.getElementById('yourId')
is the correct way.
the document refers the HTML document that is loaded in the DOM.
and it searches the id using the function getElementById() which takes a parameter of the id of an element
Solution will be :
var elem = (document.getElementById('myElement'))? document.getElementById('myElement').value : '';
/* this will assign a value or give you and empty string */
The following uses EventTrigger
to show the Popup
. This means we don't need a ToggleButton
for state binding.
In this example the Click
event of a Button
is used. You can adapt it to use another element/event combination.
<Button x:Name="OpenPopup">Popup
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames
Storyboard.TargetName="ContextPopup"
Storyboard.TargetProperty="IsOpen">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Button.Triggers>
</Button>
<Popup x:Name="ContextPopup"
PlacementTarget="{Binding ElementName=OpenPopup}"
StaysOpen="False">
<Label>Popupcontent...</Label>
</Popup>
Please note that the Popup
is referencing the Button
by name and vice versa. So x:Name="..."
is required on both, the Popup
and the Button
.
It can actually be further simplified by replacing the Storyboard
stuff with a custom SetProperty
EventTrigger Action described in this SO Answer
You can use assign
(doc) to change the value of perf.a1:
> assign(paste("perf.a", "1", sep=""),5)
> perf.a1
[1] 5
Install PAR::Packer from CPAN (it is free) and use pp utility.
Volatile boolean vs AtomicBoolean
The Atomic* classes wrap a volatile primitive of the same type. From the source:
public class AtomicLong extends Number implements java.io.Serializable {
...
private volatile long value;
...
public final long get() {
return value;
}
...
public final void set(long newValue) {
value = newValue;
}
So if all you are doing is getting and setting a Atomic* then you might as well just have a volatile field instead.
What does AtomicBoolean do that a volatile boolean cannot achieve?
Atomic* classes give you methods that provide more advanced functionality such as incrementAndGet()
for numbers, compareAndSet()
for booleans, and other methods that implement multiple operations (get/increment/set, test/set) without locking. That's why the Atomic* classes are so powerful.
For example, if multiple threads are using the following code using ++
, there will be race conditions because ++
is actually: get, increment, and set.
private volatile value;
...
// race conditions here
value++;
However, the following code will work in a multi-threaded environment safely without locks:
private final AtomicLong value = new AtomicLong();
...
value.incrementAndGet();
It's also important to note that wrapping your volatile field using Atomic* class is a good way to encapsulate the critical shared resource from an object standpoint. This means that developers can't just deal with the field assuming it is not shared possibly injecting problems with a field++; or other code that introducing race conditions.
Ok, so very important to realize the implications here.
Docs say that SSL over 465 is NOT supported in SmtpClient.
Seems like you have no choice but to use STARTTLS which may not be supported by your mail host. You may have to use a different library if your host requires use of SSL over 465.
Quoted from http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.enablessl(v=vs.110).aspx
The SmtpClient class only supports the SMTP Service Extension for Secure SMTP over Transport Layer Security as defined in RFC 3207. In this mode, the SMTP session begins on an unencrypted channel, then a STARTTLS command is issued by the client to the server to switch to secure communication using SSL. See RFC 3207 published by the Internet Engineering Task Force (IETF) for more information.
An alternate connection method is where an SSL session is established up front before any protocol commands are sent. This connection method is sometimes called SMTP/SSL, SMTP over SSL, or SMTPS and by default uses port 465. This alternate connection method using SSL is not currently supported.
There are two related concepts, both called "keyword arguments".
On the calling side, which is what other commenters have mentioned, you have the ability to specify some function arguments by name. You have to mention them after all of the arguments without names (positional arguments), and there must be default values for any parameters which were not mentioned at all.
The other concept is on the function definition side: you can define a function that takes parameters by name -- and you don't even have to specify what those names are. These are pure keyword arguments, and can't be passed positionally. The syntax is
def my_function(arg1, arg2, **kwargs)
Any keyword arguments you pass into this function will be placed into a dictionary named kwargs
. You can examine the keys of this dictionary at run-time, like this:
def my_function(**kwargs):
print str(kwargs)
my_function(a=12, b="abc")
{'a': 12, 'b': 'abc'}
Here's a general recipe, modified to fit as an example, that I am using right now for dealing with Python libraries written as packages, that contain interdependent files, where I want to be able to test parts of them piecemeal. Let's call this lib.foo
and say that it needs access to lib.fileA
for functions f1
and f2
, and lib.fileB
for class Class3
.
I have included a few print
calls to help illustrate how this works. In practice you would want to remove them (and maybe also the from __future__ import print_function
line).
This particular example is too simple to show when we really need to insert an entry into sys.path
. (See Lars' answer for a case where we do need it, when we have two or more levels of package directories, and then we use os.path.dirname(os.path.dirname(__file__))
—but it doesn't really hurt here either.) It's also safe enough to do this without the if _i in sys.path
test. However, if each imported file inserts the same path—for instance, if both fileA
and fileB
want to import utilities from the package—this clutters up sys.path
with the same path many times, so it's nice to have the if _i not in sys.path
in the boilerplate.
from __future__ import print_function # only when showing how this works
if __package__:
print('Package named {!r}; __name__ is {!r}'.format(__package__, __name__))
from .fileA import f1, f2
from .fileB import Class3
else:
print('Not a package; __name__ is {!r}'.format(__name__))
# these next steps should be used only with care and if needed
# (remove the sys.path manipulation for simple cases!)
import os, sys
_i = os.path.dirname(os.path.abspath(__file__))
if _i not in sys.path:
print('inserting {!r} into sys.path'.format(_i))
sys.path.insert(0, _i)
else:
print('{!r} is already in sys.path'.format(_i))
del _i # clean up global name space
from fileA import f1, f2
from fileB import Class3
... all the code as usual ...
if __name__ == '__main__':
import doctest, sys
ret = doctest.testmod()
sys.exit(0 if ret.failed == 0 else 1)
The idea here is this (and note that these all function the same across python2.7 and python 3.x):
If run as import lib
or from lib import foo
as a regular package import from ordinary code, __package
is lib
and __name__
is lib.foo
. We take the first code path, importing from .fileA
, etc.
If run as python lib/foo.py
, __package__
will be None and __name__
will be __main__
.
We take the second code path. The lib
directory will already be in sys.path
so there is no need to add it. We import from fileA
, etc.
If run within the lib
directory as python foo.py
, the behavior is the same as for case 2.
If run within the lib
directory as python -m foo
, the behavior is similar to cases 2 and 3. However, the path to the lib
directory is not in sys.path
, so we add it before importing. The same applies if we run Python and then import foo
.
(Since .
is in sys.path
, we don't really need to add the absolute version of the path here. This is where a deeper package nesting structure, where we want to do from ..otherlib.fileC import ...
, makes a difference. If you're not doing this, you can omit all the sys.path
manipulation entirely.)
There is still a quirk. If you run this whole thing from outside:
$ python2 lib.foo
or:
$ python3 lib.foo
the behavior depends on the contents of lib/__init__.py
. If that exists and is empty, all is well:
Package named 'lib'; __name__ is '__main__'
But if lib/__init__.py
itself imports routine
so that it can export routine.name
directly as lib.name
, you get:
$ python2 lib.foo
Package named 'lib'; __name__ is 'lib.foo'
Package named 'lib'; __name__ is '__main__'
That is, the module gets imported twice, once via the package and then again as __main__
so that it runs your main
code. Python 3.6 and later warn about this:
$ python3 lib.routine
Package named 'lib'; __name__ is 'lib.foo'
[...]/runpy.py:125: RuntimeWarning: 'lib.foo' found in sys.modules
after import of package 'lib', but prior to execution of 'lib.foo';
this may result in unpredictable behaviour
warn(RuntimeWarning(msg))
Package named 'lib'; __name__ is '__main__'
The warning is new, but the warned-about behavior is not. It is part of what some call the double import trap. (For additional details see issue 27487.) Nick Coghlan says:
This next trap exists in all current versions of Python, including 3.3, and can be summed up in the following general guideline: "Never add a package directory, or any directory inside a package, directly to the Python path".
Note that while we violate that rule here, we do it only when the file being loaded is not being loaded as part of a package, and our modification is specifically designed to allow us to access other files in that package. (And, as I noted, we probably shouldn't do this at all for single level packages.) If we wanted to be extra-clean, we might rewrite this as, e.g.:
import os, sys
_i = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if _i not in sys.path:
sys.path.insert(0, _i)
else:
_i = None
from sub.fileA import f1, f2
from sub.fileB import Class3
if _i:
sys.path.remove(_i)
del _i
That is, we modify sys.path
long enough to achieve our imports, then put it back the way it was (deleting one copy of _i
if and only if we added one copy of _i
).
For mine was caused by the imported library project, type something in build.gradle and delete it again and press sync now, the error gone.
The idea of non-blocking is that the loop iterations are quick. So to iterate for each tick should take short enough a time that the setTimeout will be accurate to within reasonable precision (off by maybe <100 ms or so).
In theory though you're right. If I write an application and block the tick, then setTimeouts will be delayed. So to answer you're question, who can assure setTimeouts execute on time? You, by writing non-blocking code, can control the degree of accuracy up to almost any reasonable degree of accuracy.
As long as javascript is "single-threaded" in terms of code execution (excluding web-workers and the like), that will always happen. The single-threaded nature is a huge simplification in most cases, but requires the non-blocking idiom to be successful.
Try this code out either in your browser or in node, and you'll see that there is no guarantee of accuracy, on the contrary, the setTimeout will be very late:
var start = Date.now();
// expecting something close to 500
setTimeout(function(){ console.log(Date.now() - start); }, 500);
// fiddle with the number of iterations depending on how quick your machine is
for(var i=0; i<5000000; ++i){}
Unless the interpreter optimises the loop away (which it doesn't on chrome), you'll get something in the thousands. Remove the loop and you'll see it's 500 on the nose...
@JoinColumn(name="reference_column_name")
annotation can be used above that property or field of class that is being referenced from some other entity.
Most likely it means that the open didn't fail.
When Perl opens a file, it checks whether or not the file is a TTY (so that it can answer the -T $fh
filetest operator) by issuing the TCGETS
ioctl against it. If the file is a regular file and not a tty, the ioctl fails and sets errno to ENOTTY
(string value: "Inappropriate ioctl for device"). As ysth says, the most common reason for seeing an unexpected value in $!
is checking it when it's not valid -- that is, anywhere other than immediately after a syscall failed, so testing the result codes of your operations is critically important.
If open
actually did return false for you, and you found ENOTTY
in $!
then I would consider this a small bug (giving a useless value of $!
) but I would also be very curious as to how it happened. Code and/or truss output would be nifty.
Using the ToList() extension method is your best option:
someValues.ToList().ForEach(x => list.Add(x + 1));
There is no extension method in the BCL that implements ForEach directly.
Although there's no extension method in the BCL that does this, there is still an option in the System
namespace... if you add Reactive Extensions to your project:
using System.Reactive.Linq;
someValues.ToObservable().Subscribe(x => list.Add(x + 1));
This has the same end result as the above use of ToList
, but is (in theory) more efficient, because it streams the values directly to the delegate.
For me, the problem was that I wasn't including bootstrap.min.css (I was only including bootstrap-responsive.min.css).