There are more than a few gateways out there, but I am not aware of a reliable gateway that is free. Most gateways like PayPal will provide you APIs that will allow you to process credit cards, as well as do things like void, charge, or refund.
The other thing you need to worry about is the coming of PCI compliance which basically says if you are not compliant, you (or the company you work for) will be liable by your Merchant Bank and/or Card Vendor for not being compliant by July of 2010. This will impose large fines on you and possibly revoke the ability for you to process credit cards.
All that being said companies like PayPal have a PHP SDK:
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/library_download_sdks
Authorize.Net:
http://developer.authorize.net/samplecode/
Those are two of the more popular ones for the United States.
For PCI Info see:
From Wikipedia,
The Card Security Code is located on the back of MasterCard, Visa and Discover credit or debit cards and is typically a separate group of 3 digits to the right of the signature strip. On American Express cards, the Card Security Code is a printed (NOT embossed) group of four digits on the front towards the right.
The Card Security Code (CSC), sometimes called Card Verification Value (CVV or CV2), Card Verification Value Code (CVVC), Card Verification Code (CVC), Verification Code (V-Code or V Code), or Card Code Verification (CCV)[1] is a security feature for credit or debit card transactions, giving increased protection against credit card fraud.
There are actually several types of security codes:
* The first code, called CVC1 or CVV1, is encoded on the magnetic stripe of the card and used for transactions in person.
* The second code, and the most cited, is CVV2 or CVC2. This CSC (also known as a CCID or Credit Card ID) is often asked for by merchants for them to secure "card not present" transactions occurring over the Internet, by mail, fax or over the phone. In many countries in Western Europe, due to increased attempts at card fraud, it is now mandatory to provide this code when the cardholder is not present in person.
* Contactless Card and Chip cards may supply their own codes generated electronically, such as iCVV or Dynamic CVV.
The CVC should not be confused with the standard card account number appearing in embossed or printed digits. (The standard card number undergoes a separate validation algorithm called the Luhn algorithm which serves to determine whether a given card's number is appropriate.)
The CVC should not be confused with PIN codes such as MasterCard SecureCode or Visa Verified by Visa. These codes are not printed or embedded in the card but are entered at the time of transaction using a keypad.
Just found another solution, it seems to work for me
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
boolean isWorking = (PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, PendingIntent.FLAG_NO_CREATE) != null);
if (isWorking) {Log.d("alarm", "is working");} else {Log.d("alarm", "is not working");}
if(!isWorking) {
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
int timeNotif = 5 * 60 * 1000;//time in ms, 7*24*60*60*1000 for 1 week
Log.d("Notif", "Notification every (ms): " + timeNotif);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), timeNotif, pendingIntent);
}
This is a nice tutorial:
http://android-developers.blogspot.de/2009/05/painless-threading.html
Or this for the UI thread:
http://developer.android.com/guide/faq/commontasks.html#threading
Or here a very practical one:
http://www.androidacademy.com/1-tutorials/43-hands-on/115-threading-with-android-part1
and another one about procceses and threads
http://developer.android.com/guide/components/processes-and-threads.html
It is possible to use raw query within a Spring Repository.
@Query(value = "SELECT A.IS_MUTUAL_AID FROM planex AS A
INNER JOIN planex_rel AS B ON A.PLANEX_ID=B.PLANEX_ID
WHERE B.GOOD_ID = :goodId",nativeQuery = true)
Boolean mutualAidFlag(@Param("goodId")Integer goodId);
Some time this error in Joomla appear because some thing incorrect with SESSION or coockie. That may because incorrect HTTPd server setting or because some before CURL or Server http requests
so PHP code like:
curl_setopt($ch, CURLOPT_URL, $url_page);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_REFERER, $url_page);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);
will need replace to PHP code
curl_setopt($ch, CURLOPT_URL, $url_page);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
//curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_REFERER, $url_page);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
//curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // !!!!!!!!!!!!!
//if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);
May be some body reply how this options connected with "Curl error: Operation timed out after .."
A quick note that if you are using AWS ec2 instance then there is one more extra step that I believe is also mandatory. I missed the step-3 and it took me whole day to figure out to add an inbound rule to security group
Step 1(as previous): in your redis.conf change bind 127.0.0.1 to bind 0.0.0.0
Step2(as previous): in your redis.conf change protected-mode yes to protected-mode no
Step3: In your current ec2 machine go to the security group. add an inbound rule for custom TCP with 6379 port and select option "use from anywhere".
The following code works more or less as one would expect a type-switch that only looks at the actual type (e.g. what is returned by GetType()
).
public static void TestTypeSwitch()
{
var ts = new TypeSwitch()
.Case((int x) => Console.WriteLine("int"))
.Case((bool x) => Console.WriteLine("bool"))
.Case((string x) => Console.WriteLine("string"));
ts.Switch(42);
ts.Switch(false);
ts.Switch("hello");
}
Here is the machinery required to make it work.
public class TypeSwitch
{
Dictionary<Type, Action<object>> matches = new Dictionary<Type, Action<object>>();
public TypeSwitch Case<T>(Action<T> action) { matches.Add(typeof(T), (x) => action((T)x)); return this; }
public void Switch(object x) { matches[x.GetType()](x); }
}
ref and out work just like passing by references and passing by pointers as in C++.
For ref, the argument must declared and initialized.
For out, the argument must declared but may or may not be initialized
double nbr = 6; // if not initialized we get error
double dd = doit.square(ref nbr);
double Half_nbr ; // fine as passed by out, but inside the calling method you initialize it
doit.math_routines(nbr, out Half_nbr);
Adding /r/n between the Strings solved the problem for me. give it a try. On pasting dont include the '//' for excluding.
Eg: Option01\r\nOption02\r\nOption03
this will give output as
Option01
Option02
Option03
No, you cannot know when a page was last updated or last changed or uploaded to a server (which might, depending on interpretation, be three different things) just by accessing the page.
A server may, and should (according to the HTTP 1.1 protocol), send a Last-Modified
header, which you can find out in several ways, e.g. using Rex Swain’s HTTP Viewer. However, according to the protocol, this is just
“the date and time at which the origin server believes the variant was last modified”.
And the protocol realistically adds:
“The exact meaning of this header field depends on the implementation of the origin server and the nature of the original resource. For files, it may be just the file system last-modified time. For entities with dynamically included parts, it may be the most recent of the set of last-modify times for its component parts. For database gateways, it may be the last-update time stamp of the record. For virtual objects, it may be the last time the internal state changed.”
In practice, web pages are very often dynamically created from a Content Management System or otherwise, and in such cases, the Last-Modified
header typically shows a data stamp of creating the response, which is normally very close to the time of the request. This means that the header is practically useless in such cases.
Even in the case of a “static” page (the server simply picks up a file matching the request and sends it), the Last-Modified
date stamp normally indicates just the last write access to the file on the server. This might relate to a time when the file was restored from a backup copy, or a time when the file was edited on the server without making any change to the content, or a time when it was uploaded onto the server, possibly replacing an older identical copy. In these cases, assuming that the time stamp is technically correct, it indicates a time after which the page has not been changed (but not necessarily the time of last change).
An abbreviated version of your code worked for me,
class Remote: NSObject {
var data = NSMutableData()
func connect(query:NSString) {
var url = NSURL.URLWithString("http://www.google.com")
var request = NSURLRequest(URL: url)
var conn = NSURLConnection(request: request, delegate: self, startImmediately: true)
}
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
println("didReceiveResponse")
}
func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) {
self.data.appendData(conData)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
println(self.data)
}
deinit {
println("deiniting")
}
}
This is the code I used in the calling class,
class ViewController: UIViewController {
var remote = Remote()
@IBAction func downloadTest(sender : UIButton) {
remote.connect("/apis")
}
}
You didn't specify in your question where you had this code,
var remote = Remote()
remote.connect("/apis")
If var is a local variable, then the Remote class will be deallocated right after the connect(query:NSString) method finishes, but before the data returns. As you can see by my code, I usually implement reinit (or dealloc up to now) just to make sure when my instances go away. You should add that to your Remote class to see if that's your problem.
Once I packed JS code doing that to a tiny library:
https://github.com/AlexLibs/client-side-csv-generator
The Code, Documentation and Demo/Playground are provided on Github.
Enjoy :)
Pull requests are welcome.
The easy way, if you have a fixed width and height:
#divElement{
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
}?
Please don't use inline styles! Here is a working example http://jsfiddle.net/S5bKq/.
The proper way as of now is to use a solution recommended by @Roman Kuzmin in comments to @M. Dudley answer:
[IO.File]::WriteAllLines($filename, $content)
(I've also shortened it a bit by stripping unnecessary System
namespace clarification - it will be substituted automatically by default.)
create database if not exists `test`;
USE `test`;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
/*Table structure for table `test` */
***CREATE TABLE IF NOT EXISTS `tblsample` (
`id` int(11) NOT NULL auto_increment,
`recid` int(11) NOT NULL default '0',
`cvfilename` varchar(250) NOT NULL default '',
`cvpagenumber` int(11) NULL,
`cilineno` int(11) NULL,
`batchname` varchar(100) NOT NULL default '',
`type` varchar(20) NOT NULL default '',
`data` varchar(100) NOT NULL default '',
PRIMARY KEY (`id`)
);***
Agree with @Pom12, @abayer. To complete the answer you need to add script block
Try something like this:
pipeline {
agent any
environment {
ENV_NAME = "${env.BRANCH_NAME}"
}
// ----------------
stages {
stage('Build Container') {
steps {
echo 'Building Container..'
script {
if (ENVIRONMENT_NAME == 'development') {
ENV_NAME = 'Development'
} else if (ENVIRONMENT_NAME == 'release') {
ENV_NAME = 'Production'
}
}
echo 'Building Branch: ' + env.BRANCH_NAME
echo 'Build Number: ' + env.BUILD_NUMBER
echo 'Building Environment: ' + ENV_NAME
echo "Running your service with environemnt ${ENV_NAME} now"
}
}
}
}
I've found a more reliable method (at least on Excel 2016 for Mac) is:
Assuming your long list is in column A, and the list of things to be removed from this is in column B, then paste this into all the rows of column C:
= IF(COUNTIF($B$2:$B$99999,A2)>0,"Delete","Keep")
Then just sort the list by column C to find what you have to delete.
From what I've read, this error means that you're not referencing the table name correctly. One common reason is that the table is defined with a mixed-case spelling, and you're trying to query it with all lower-case.
In other words, the following fails:
CREATE TABLE "SF_Bands" ( ... );
SELECT * FROM sf_bands; -- ERROR!
Use double-quotes to delimit identifiers so you can use the specific mixed-case spelling as the table is defined.
SELECT * FROM "SF_Bands";
Re your comment, you can add a schema to the "search_path" so that when you reference a table name without qualifying its schema, the query will match that table name by checked each schema in order. Just like PATH
in the shell or include_path
in PHP, etc. You can check your current schema search path:
SHOW search_path
"$user",public
You can change your schema search path:
SET search_path TO showfinder,public;
See also http://www.postgresql.org/docs/8.3/static/ddl-schemas.html
The easiest solution I found for this:
git commit -m "fixing merge conflicts"
git push
I prefer to use the HTML5 data API, check this documentation:
$('#some-list li').click(function() {_x000D_
var textLoaded = 'Loading element with id='_x000D_
+ $(this).data('id');_x000D_
$('#loading-content').text(textLoaded);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<ul id='some-list'>_x000D_
<li data-id='1'>One </li>_x000D_
<li data-id='2'>Two </li>_x000D_
<!-- ... more li -->_x000D_
<li data-id='n'>Other</li>_x000D_
</ul>_x000D_
_x000D_
<h1 id='loading-content'></h1>
_x000D_
example:
AliceBlue
AntiqueWhite
Aqua
Aquamarine
Beige
Replcae \n with ","
AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige
Now append "(double-quote) at the start and end
"AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige"
If your text contains blank lines in between you can use regular expression \n+ instead of \n
example:
AliceBlue
AntiqueWhite
Aqua
Aquamarine
Beige
Replcae \n+ with "," (in regex mode)
AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige
Now append "(double-quote) at the start and end
"AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige"
If you install macports you can install gcc select, and then choose your gcc version.
/opt/local/bin/port install gcc_select
To see your versions use
port select --list gcc
To select a version use
sudo port select --set gcc gcc40
this is an out of topic answer, but, for those who are interested, it maybe valuable.
As in @John Kugelman's answer, % is related to job specification. how to efficiently find that? use less's &pattern command, seems man use less pager (not that sure), in man bash type &% then type Enter will only show lines that containing '%', to reshow all, type &. then Enter.
In my fairly complex scenario the accepted answer for how to do this in Chrome doesn't work for me. You may want to try the Firefox debugger instead (part of the Firefox developer tools), which shows all of the 'Sources', including those that are part of an iFrame
Try unbinding the event.
$("span").click(function(){
alert($(this).text());
$("span").not($(this)).unbind('click');
});
Here is the fiddle
The other possible answer to this question may depend on the reason you are opening the file. Is this a property file or a file that has some configuration related to your application?
If this is the case you may consider trying to load the file through the classpath loader, this way you can load any file Java has access to.
Wouldn't setting a css rule for all tables, and then a subsequent one for tables where class="dojoxGrid" work? Or am I missing something?
The cool thing about the new Google Recaptcha is that the validation is now completely encapsulated in the widget. That means, that the widget will take care of asking questions, validating responses all the way till it determines that a user is actually a human, only then you get a g-recaptcha-response value.
But that does not keep your site safe from HTTP client request forgery.
Anyone with HTTP POST knowledge could put random data inside of the g-recaptcha-response form field, and foll your site to make it think that this field was provided by the google widget. So you have to validate this token.
In human speech it would be like,
Validating the response is really easy. Just make a GET Request to
And replace the response_string with the value that you earlier got by the g-recaptcha-response field.
You will get a JSON Response with a success field.
More information here: https://developers.google.com/recaptcha/docs/verify
Edit: It's actually a POST, as per documentation here.
very simple DateTime.Now.ToString("hh:mm:ss tt")
Use @ViewChildren
from @angular/core
to get a reference to the components
template
<div *ngFor="let v of views">
<customcomponent #cmp></customcomponent>
</div>
component
import { ViewChildren, QueryList } from '@angular/core';
/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components:QueryList<CustomComponent>;
ngAfterViewInit(){
// print array of CustomComponent objects
console.log(this.components.toArray());
}
If you define
#!/bin/bash
fun1(){
echo "Fun1 from file1 $1"
}
fun1 Hello
. file2
fun1 Hello
exit 0
in file1(chmod 750 file1) and file2
fun1(){
echo "Fun1 from file2 $1"
}
fun2(){
echo "Fun1 from file1 $1"
}
and run ./file2 you'll get Fun1 from file1 Hello Fun1 from file2 Hello Surprise!!! You overwrite fun1 in file1 with fun1 from file2... So as not to do so you must
declare -f pr_fun1=$fun1
. file2
unset -f fun1
fun1=$pr_fun1
unset -f pr_fun1
fun1 Hello
it's save your previous definition for fun1 and restore it with the previous name deleting not needed imported one. Every time you import functions from another file you may remember two aspects:
It's equivalent to
def tag_names
@tag_names || tags.map { |tag| tag.name }.join(' ')
end
This may help Setting the header:
WebClient client = new WebClient();
string authInfo = this.credentials.UserName + ":" + this.credentials.Password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
client.Headers["Authorization"] = "Basic " + authInfo;
You want the concat
method.
var finalObj = json1.concat(json2);
Script its left
and top
properties as the number of pixels from the left edge and top edge respectively. It must have position: absolute;
var d = document.getElementById('yourDivId');
d.style.position = "absolute";
d.style.left = x_pos+'px';
d.style.top = y_pos+'px';
Or do it as a function so you can attach it to an event like onmousedown
function placeDiv(x_pos, y_pos) {
var d = document.getElementById('yourDivId');
d.style.position = "absolute";
d.style.left = x_pos+'px';
d.style.top = y_pos+'px';
}
You can also set this directly from Interface Builder under the Attributes Inspector.
Taken from XCode 5.1
Does this really make sense?
There is no "first" record in a relational database, you can only delete one random record.
Try the following query:
;WITH CTE_DocTotal
AS
(
SELECT SUM(Sale + VAT) AS DocTotal_1
FROM PEDI_InvoiceDetail
GROUP BY InvoiceNumber
)
UPDATE CTE_DocTotal
SET DocTotal = CTE_DocTotal.DocTotal_1
Seems like you could use date() and the lowercase "L" format character in the following way:
$weekday_name = date("l", $timestamp);
Works well for me, here is the doc: http://php.net/manual/en/function.date.php
With the help of dr answer, I wrote a workaround that makes the conversion to put in your .bashrc. It won't break anything if you don't have any timestamp or already correct timestamps.
dmesg_with_human_timestamps () {
$(type -P dmesg) "$@" | perl -w -e 'use strict;
my ($uptime) = do { local @ARGV="/proc/uptime";<>}; ($uptime) = ($uptime =~ /^(\d+)\./);
foreach my $line (<>) {
printf( ($line=~/^\[\s*(\d+)\.\d+\](.+)/) ? ( "[%s]%s\n", scalar localtime(time - $uptime + $1), $2 ) : $line )
}'
}
alias dmesg=dmesg_with_human_timestamps
Also, a good reading on the dmesg timestamp conversion logic & how to enable timestamps when there are none: https://supportcenter.checkpoint.com/supportcenter/portal?eventSubmit_doGoviewsolutiondetails=&solutionid=sk92677
In Python 3.7.0 the insertion-order preservation nature of dict
objects has been declared to be an official part of the Python language spec. Therefore, you can depend on it.
As of Python 3.6, for the CPython implementation of Python, dictionaries maintain insertion order by default. This is considered an implementation detail though; you should still use collections.OrderedDict
if you want insertion ordering that's guaranteed across other implementations of Python.
Use the collections.OrderedDict
class when you need a dict
that
remembers the order of items inserted.
Just a little more clarification: A property without 'get','set' won't be able to be bound
I'm facing the case just like the asker's case. And I must have the following things in order for the bind to work properly:
//(1) Declare a property with 'get','set' in code behind
public partial class my_class:Window {
public String My_Property { get; set; }
...
//(2) Initialise the property in constructor of code behind
public partial class my_class:Window {
...
public my_class() {
My_Property = "my-string-value";
InitializeComponent();
}
//(3) Set data context in window xaml and specify a binding
<Window ...
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<TextBlock Text="{Binding My_Property}"/>
</Window>
Use the Font-property on the gridview. See MSDN for details and samples:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.font.aspx
The loop is great; it's what's inside the loop that's wrong. You need a variable named sum
, and at each step, add i+1
to sum
. At the end of the loop, sum
will have the right value, so print it.
Manual method works well with import android.util.Base64, but be sure to set Base64.NO_WRAP on calling encode:
String basicAuth = "Basic " + new String(Base64.encode("user:pass".getBytes(),Base64.NO_WRAP ));
connection.setRequestProperty ("Authorization", basicAuth);
If you're not wanting to save changes set savechanges to false
Sub CloseBook2()
ActiveWorkbook.Close savechanges:=False
End Sub
for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used
ActiveWorkbook.Close False
before you write set(XXXXX)
you have used "set" as a variable
e.g.
set = 90 #you have used "set" as an object
…
…
a = set(["Blah", "Hello"])
a = list(a)
As Jiri mentioned, you can use scp -r user@host:/some/remote/path /some/local/path
to copy files recursively. This assumes that there's a single directory containing all of the files you want to transfer (and nothing else).
However, SFTP provides an alternative if you want to transfer files from multiple different directories, and the destinations are not identical:
sftp user@host << EOF
get /some/remote/path1/file1 /some/local/path1/file1
get /some/remote/path2/file2 /some/local/path2/file2
get /some/remote/path3/file3 /some/local/path3/file3
EOF
This uses the "here doc" syntax to define a sequence of SFTP input commands. As an alternative, you could put the SFTP commands into a text file and execute sftp user@host -b batchFile.txt
To Open a File in Android Programatically,you can use this code :- We use File Provider for internal file access .You can also see details about File Provider here in this linkfileprovidr1,file provider2,file provider3. Create a File Provider and defined in Manifest File .
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.packagename.app.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths">
</meta-data>
</provider>
Define file_path in resources file.
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="my_images"
path="Android/data/com.packagename.app/files/Pictures" />
<external-files-path name="vivalinkComProp" path="Android/data/com.vivalink.app/vivalinkComProp/docs"/>
<external-path
name="external"
path="." />
<external-files-path
name="external_files"
path="." />
<cache-path
name="cache"
path="." />
<external-cache-path
name="external_cache"
path="." />
<files-path
name="files"
path="." />
</paths>
Define Intent For View
String directory_path = Environment.getExternalStorageDirectory().getPath() + "/MyFile/";
String targetPdf = directory_path + fileName + ".pdf";
File filePath = new File(targetPdf);
Intent intentShareFile = new Intent(Intent.ACTION_VIEW);
File fileWithinMyDir = new File(targetPdf);
Uri bmpUri = FileProvider.getUriForFile(activity, "com.packagename.app.fileprovider", filePath);
if (fileWithinMyDir.exists()) {
intentShareFile.setDataAndType(bmpUri,"application/pdf");
intentShareFile.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intentShareFile.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(Intent.createChooser(intentShareFile, "Open File Using..."));
}
You can use different way to create a file provider in android . Hope this will help you.
You can't specify a range in the case statement, can do as follows.
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
MessageBox.Show("You are only " + age + " years old\n You must be kidding right.\nPlease fill in your *real* age.");
break;
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
MessageBox.Show("You are only " + age + " years old\n That's too young!");
break;
...........etc.
In addition to the Python 2 approach here are the equivalents for Python 3:
# Create a range that does not contain 50
for i in [x for x in range(100) if x != 50]:
print(i)
# Create 2 ranges [0,49] and [51, 100]
from itertools import chain
concatenated = chain(range(50), range(51, 100))
for i in concatenated:
print(i)
# Create a iterator and skip 50
xr = iter(range(100))
for i in xr:
print(i)
if i == 49:
next(xr)
# Simply continue in the loop if the number is 50
for i in range(100):
if i == 50:
continue
print(i)
Ranges are lists in Python 2 and iterators in Python 3.
If you want to suppress the warnings and some other error types (for example, notices) while displaying all other errors, you can do:
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
This should works to you
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT LayoutParams.MATCH_PARENT);
param.weight=1.0f;
If you are using EL 3.0+, the best approach in this case is as this other answer explained in another topic:
For a
Collection
it's easy, just use theColleciton#contains()
method in EL.<h:panelGroup id="p1" rendered="#{bean.panels.contains('p1')}">...</h:panelGroup> <h:panelGroup id="p2" rendered="#{bean.panels.contains('p2')}">...</h:panelGroup> <h:panelGroup id="p3" rendered="#{bean.panels.contains('p3')}">...</h:panelGroup>
For an
Object[]
(array), you'd need a minimum of EL 3.0 and utilize its new Lambda support.<h:panelGroup id="p1" rendered="#{bean.panels.stream().anyMatch(v -> v == 'p1').get()}">...</h:panelGroup> <h:panelGroup id="p2" rendered="#{bean.panels.stream().anyMatch(v -> v == 'p2').get()}">...</h:panelGroup> <h:panelGroup id="p3" rendered="#{bean.panels.stream().anyMatch(v -> v == 'p3').get()}">...</h:panelGroup>
If you're not on EL 3.0 yet, you'd need to create a custom EL function. [...]
$.ajax({
url: '//.xml',
dataType: 'xml',
success: onTrue,
error: function (err) {
console.error('Error: ', err);
}
});
$('a').each(function () {
$(this).click(function (e) {
var l = e.target.text;
//array.sort(sorteerOp(l));
//functionToAdaptHtml();
});
});
All those results generate garbage in a zealous attempt to handle more than two arguments. I'd be curious to see how they perform compared to good 'ol:
def max (a,b)
a>b ? a : b
end
which is, by-the-way, my official answer to your question.
OR
.section:hover > div {
background-color: #0CF;
}
NOTE Parent element state can only affect a child's element state so you can use:
.image:hover + .layer {
background-color: #0CF;
}
.image:hover {
background-color: #0CF;
}
but you can not use
.layer:hover + .image {
background-color: #0CF;
}
I think cURL would be a good solution. This is not tested, but you can try something like this:
$body = '{
"kind": "blogger#post",
"blog": {
"id": "8070105920543249955"
},
"title": "A new post",
"content": "With <b>exciting</b> content..."
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/blogger/v3/blogs/8070105920543249955/posts/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Authorization: OAuth 2.0 token here"));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$result = curl_exec($ch);
Normally I would recommend floating but from your 3 requirements I would suggest this:
position: absolute;
right: 10px;
top: 5px;
Don't forget position: relative;
on the parent div
Here's how to do it without numpy, using only python to calculate the percentile.
import math
def percentile(data, percentile):
size = len(data)
return sorted(data)[int(math.ceil((size * percentile) / 100)) - 1]
p5 = percentile(mylist, 5)
p25 = percentile(mylist, 25)
p50 = percentile(mylist, 50)
p75 = percentile(mylist, 75)
p95 = percentile(mylist, 95)
In terms of coding, a bidirectional relationship is more complex to implement because the application is responsible for keeping both sides in synch according to JPA specification 5 (on page 42). Unfortunately the example given in the specification does not give more details, so it does not give an idea of the level of complexity.
When not using a second level cache it is usually not a problem to do not have the relationship methods correctly implemented because the instances get discarded at the end of the transaction.
When using second level cache, if anything gets corrupted because of wrongly implemented relationship handling methods, this means that other transactions will also see the corrupted elements (the second level cache is global).
A correctly implemented bi-directional relationship can make queries and the code simpler, but should not be used if it does not really make sense in terms of business logic.
Alex's answer is great. but It is importanting to note that that calls the default fancybox style. If you have your own custom rules, you should just call .trigger click on that specific anchor
$(document).ready(function() {
$("#hidden_link").fancybox({
'padding': 0,
'cyclic': true,
'width': 625,
'height': 350,
'padding': 0,
'margin': 0,
'speedIn': 300,
'speedOut': 300,
'transitionIn': 'elastic',
'transitionOut': 'elastic',
'easingIn': 'swing',
'easingOut': 'swing',
'titleShow' : false
});
$("#hidden_link").trigger('click');
});
Here's my webpack 4 + font awesome 5 solution:
webpack plugin:
new CopyWebpackPlugin([
{ from: 'node_modules/font-awesome/fonts', to: 'font-awesome' }
]),
global css style:
@font-face {
font-family: 'FontAwesome';
src: url('/font-awesome/fontawesome-webfont.eot');
src: url('/font-awesome/fontawesome-webfont.eot?#iefix') format('embedded-opentype'),
url('/font-awesome/fontawesome-webfont.woff2') format('woff2'),
url('/font-awesome/fontawesome-webfont.woff') format('woff'),
url('/font-awesome/fontawesome-webfont.ttf') format('truetype'),
url('/font-awesome/fontawesome-webfont.svgfontawesomeregular') format('svg');
font-weight: normal;
font-style: normal;
}
i {
font-family: "FontAwesome";
}
The proper solution to your problem is to add the -vm line pointing to jvm.dll file of your Java folder in ini fie.
-vm
C:\Program Files\Java\jre1.8.0_202\bin\server\jvm.dll
/*there is no dquote for path, and path points to right java version folder mentioned in ini file*/
If the above fix is not fruitful, then do not attempt anything else. Most of the advice in this thread is misguided. Some of these hacks might work temporarily or on certain machine configurations, but the contents of eclipse.ini are not trivial nor arbitrary. For the authoritative reference, see this [wiki page]:https://wiki.eclipse.org/Eclipse.ini#Specifying_the_JVM that explains the contents of the file. Also note the See Also links at the bottom of that page for more details about things like heap size, etc. DO NOT delete eclipse.ini, EVER. It is also inadvisable to remove the -vm or Xmx options. If you do, you're asking for trouble.
Here are references from the wiki page pertaining to your problem:
Put the code so it executes after the elements are defined, either with a DOM ready callback or place the source under the elements in the HTML.
document.getElementById()
returns null
if the element couldn't be found. Property assignment can only occur on objects. null
is not an object (contrary to what typeof
says).
I solve that Bulit path--->libraries--->add library--->Junit check junit4
This approach avoids the warnings while preserving the array-oriented evaluation.
import numpy as np
def isnat(x):
"""
datetime64 analog to isnan.
doesn't yet exist in numpy - other ways give warnings
and are likely to change.
"""
return x.astype('i8') == np.datetime64('NaT').astype('i8')
If you want ot know what is the directory where your solution is located, you need to do this:
var parent = Directory.GetParent(Directory.GetCurrentDirectory()).Parent;
if (parent != null)
{
var directoryInfo = parent.Parent;
string startDirectory = null;
if (directoryInfo != null)
{
startDirectory = directoryInfo.FullName;
}
if (startDirectory != null)
{ /*Do whatever you want "startDirectory" variable*/}
}
If you let only with GetCurrrentDirectory()
method, you get the build folder no matter if you are debugging or releasing. I hope this help! If you forget about validations it would be like this:
var startDirectory = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName;
we had this same issue starting this morning and goti it solved... hope this helps...
SSL on IIS 8
Hope this helps!!!
If you install the SDK, the offline documentation can be found in $ANDROID_SDK/docs/
.
I needed a row of clickable elephants, vertically centered, but without using a table to get around some Internet Explorer 9 weirdness.
I eventually found the nicest CSS (for my needs) and it's great with Firefox, Chrome, and Internet Explorer 11. Sadly Internet Explorer 9 is still laughing at me...
div {_x000D_
border: 1px dotted blue;_x000D_
display: inline;_x000D_
line-height: 100px;_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
span {_x000D_
border: 1px solid red;_x000D_
display: inline-block;_x000D_
line-height: normal;_x000D_
vertical-align: middle;_x000D_
}_x000D_
_x000D_
.out {_x000D_
border: 3px solid silver;_x000D_
display: inline-block;_x000D_
}
_x000D_
<div class="out" onclick="alert(1)">_x000D_
<div> <span><img src="http://www.birdfolk.co.uk/littleredsolo.png"/></span> </div>_x000D_
<div> <span>A lovely clickable option.</span> </div>_x000D_
</div>_x000D_
_x000D_
<div class="out" onclick="alert(2)">_x000D_
<div> <span><img src="http://www.birdfolk.co.uk/bang2/Ship01.png"/></span> </div>_x000D_
<div> <span>Something charming to click on.</span> </div>_x000D_
</div>
_x000D_
Obviously you don't need the borders, but they can help you see how it works.
A daily task? Sounds like it should just be a scheduled task (control panel) - no need for a service here.
A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]
A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.
From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.
There is an additional architecture that wasn't mentioned - SQL-based database services that enable horizontal scaling without the complexity of manual sharding. These services do the sharding in the background, so they enable you to run a traditional SQL database and scale out like you would with NoSQL engines like MongoDB or CouchDB. Two services I am familiar with are EnterpriseDB for PostgreSQL and Xeround for MySQL. I saw an in-depth post by Xeround which explains why scale-out on SQL databases is difficult and how they do it differently - treat this with a grain of salt as it is a vendor post. Also check out Wikipedia's Cloud Database entry, there is a nice explanation of SQL vs. NoSQL and service vs. self-hosted, a list of vendors and scaling options for each combination. ;)
It is a very bad idea to get all files in one go, you should rather get it in batches.
One implementation which I use to fetch a particular folder (directory) from S3 is,
def get_directory(directory_path, download_path, exclude_file_names):
# prepare session
session = Session(aws_access_key_id, aws_secret_access_key, region_name)
# get instances for resource and bucket
resource = session.resource('s3')
bucket = resource.Bucket(bucket_name)
for s3_key in self.client.list_objects(Bucket=self.bucket_name, Prefix=directory_path)['Contents']:
s3_object = s3_key['Key']
if s3_object not in exclude_file_names:
bucket.download_file(file_path, download_path + str(s3_object.split('/')[-1])
and still if you want to get the whole bucket use it via CIL as @John Rotenstein mentioned as below,
aws s3 cp --recursive s3://bucket_name download_path
Had the same problem, but I used instanceof instead. Did it this way:
List<Object> listCheck = (List<Object>)(Object) stringList;
if (!listCheck.isEmpty()) {
if (listCheck.get(0) instanceof String) {
System.out.println("List type is String");
}
if (listCheck.get(0) instanceof Integer) {
System.out.println("List type is Integer");
}
}
}
This involves using unchecked casts so only do this when you know it is a list, and what type it can be.
You missed single quote sign:
SELECT *
FROM TABLENAME
WHERE DateTime >= '12/04/2011 12:00:00 AM' AND DateTime <= '25/05/2011 3:53:04 AM'
Also, it is recommended to use ISO8601 format YYYY-MM-DDThh:mm:ss.nnn[ Z ], as this one will not depend on your server's local culture.
SELECT *
FROM TABLENAME
WHERE
DateTime >= '2011-04-12T00:00:00.000' AND
DateTime <= '2011-05-25T03:53:04.000'
The input date value format needs the date specified as per http://tools.ietf.org/html/rfc3339#section-5.6 full-date.
So I've ended up doing:
<input type="date" id="last-start-date" value="@string.Format("{0:yyyy-MM-dd}", Model.LastStartDate)" />
I did try doing it "properly" using:
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime LastStartDate
{
get { return lastStartDate; }
set { lastStartDate = value; }
}
with
@Html.TextBoxFor(model => model.LastStartDate,
new { type = "date" })
Unfortunately that always seemed to set the value attribute of the input to a standard date time so I've ended up applying the formatting directly as above.
Edit:
According to Jorn if you use
@Html.EditorFor(model => model.LastStartDate)
instead of TextBoxFor it all works fine.
You can get value like this
this.form.controls['your form control name'].value
the best way (for me) to make it it's the next infrastructure:
<form method="POST">
<input type="submit" formaction="default_url_when_press_enter" style="visibility: hidden; display: none;">
<!-- all your inputs -->
<input><input><input>
<!-- all your inputs -->
<button formaction="action1">Action1</button>
<button formaction="action2">Action2</button>
<input type="submit" value="Default Action">
</form>
with this structure you will send with enter a direction and the infinite possibilities for the rest of buttons.
Terminal 1:
$ mysql_safe
Terminal 2:
$ mysql -u root
mysql> UPDATE mysql.user SET Password=PASSWORD('new-password') WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> quit
You can see the list of supported codecs in the official documentation:
Uri myUri = Uri.parse("http://www.google.com");
Here's the doc http://developer.android.com/reference/android/net/Uri.html#parse%28java.lang.String%29
Through this you can get absolute path of any file located in any directory.
File.join(Dir.pwd,'some-dir','some-file-name')
This will return
=> "/User/abc/xyz/some-dir/some-file-name"
I just sent a pull request in pip with the enhancement Hugo Tavares said:
(specloud as example)
$ pip show specloud
Package: specloud
Version: 0.4.4
Requires:
nose
figleaf
pinocchio
Consider using Joda Time. I love this library and wish it would replace the current horrible mess that are the existing Java Date and Calendar classes. It's date handling done right.
EDIT: It's not 2009 any more, and Java 8's been out for ages. Use Java 8's built in java.time classes which are based on Joda Time, as Basil Bourque mentions above. In this case you'll want the Period class, and here's Oracle's tutorial on how to use it.
I recently had the problem of deleting the tnsnames.ora from the path where I had it, my solution was to create an environment variable called TNS_NAME with the value the path where the tnsnames.ora file is located and ready
This means that you must declare strict mode by writing "use strict"
at the beginning of the file or the function to use block-scope declarations.
EX:
function test(){
"use strict";
let a = 1;
}
As I can see the code
System.out.println("Managers choice this week" + anyItem + "our recommendation to you");
is unreachable.
Two options, that have different uses:
HTML:
<a class="example" href="http://www.example.com">example</a>
CSS:
.example { text-align: center; }
Or:
.example { display:block; width:100px; margin:0 auto;}
Even if it is really discouraged to use merge cells in Excel (use Center Across Selection
for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).
Hence, you can get the value of merged cells in range B4:B11
in several ways:
Range("B4").Value
Range("B4:B11").Cells(1).Value
Range("B4:B11").Cells(1,1).Value
You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty
.
Also note that Range("B4:B11").Value
won't work (raises an execution error number 13 if you try to Debug.Print
it) because it returns an array.
After I read Parthian Shot's answer, I dig into /usr/sbin/nginx
binary file. Then I found out that the file contains these three lines.
Server: nginx/1.12.2
Server: nginx/1.12.2
Server: nginx
Basically first two of them are meant for server_tokens on;
directive (Server version included).
Then I change the search criteria to match those lines within the binary file.
sed -i 's/Server: nginx/Server: thing/' `which nginx`
After I dig farther I found out that the error message produced by nginx is also included in this file.
<hr><center>nginx</center>
There are three of them, one without the version, two of them included the version. So I run the following command to replace nginx string within the error message.
sed -i 's/center>nginx/center>thing/' `which nginx`
If you find search and replace faster to use, you could use a regex replace like this:
Find (regex): (^|\G) {2}
(Instead of " {2}" <space>{2}
you can just write two spaces. Used it here for clarity.)
Replace with 4 spaces, or whatever you want, like \t
.
One thing I mentioned in another thread that is worth pointing out -- if you are building different versions of your app for different densities, you should know about the "mipmap" resource directory. This is exactly like "drawable" resources, except it does not participate in density stripping when creating the different apk targets.
https://plus.google.com/105051985738280261832/posts/QTA9McYan1L
For clarity purposes, I often use the select argument in subset
. With newer folks, I've learned that keeping the # of commands they need to pick up to a minimum helps adoption. As their skills increase, so too will their coding ability. And subset is one of the first commands I show people when needing to select data within a given criteria.
Something like:
> subset(mtcars, select = c("mpg", "cyl", "vs", "am"))
mpg cyl vs am
Mazda RX4 21.0 6 0 1
Mazda RX4 Wag 21.0 6 0 1
Datsun 710 22.8 4 1 1
....
I'm sure this will test slower than most other solutions, but I'm rarely at the point where microseconds make a difference.
I had the same challenge. When I collapsed some menus I had on the left of my web app, the datatable would not resize. Adding "autoWidth": false duirng initialization worked for me.
$('#dataTable').DataTable({'autoWidth':false, ...});
For me better this:
var uA = window.navigator.userAgent,
onlyIEorEdge = /msie\s|trident\/|edge\//i.test(uA) && !!( document.uniqueID || window.MSInputMethodContext),
checkVersion = (onlyIEorEdge && +(/(edge\/|rv:|msie\s)([\d.]+)/i.exec(uA)[2])) || NaN;
Go run: http://output.jsbin.com/solicul/1/ o http://jsfiddle.net/Webnewbie/apa1nvu8/
PowerShell currently doesn't didn't have a native Inline If (or ternary If) but you could consider to use the custom cmdlet:
IIf <condition> <condition-is-true> <condition-is-false>
With __future__
module's inclusion, you can slowly be accustomed to incompatible changes or to such ones introducing new keywords.
E.g., for using context managers, you had to do from __future__ import with_statement
in 2.5, as the with
keyword was new and shouldn't be used as variable names any longer. In order to use with
as a Python keyword in Python 2.5 or older, you will need to use the import from above.
Another example is
from __future__ import division
print 8/7 # prints 1.1428571428571428
print 8//7 # prints 1
Without the __future__
stuff, both print
statements would print 1
.
The internal difference is that without that import, /
is mapped to the __div__()
method, while with it, __truediv__()
is used. (In any case, //
calls __floordiv__()
.)
Apropos print
: print
becomes a function in 3.x, losing its special property as a keyword. So it is the other way round.
>>> print
>>> from __future__ import print_function
>>> print
<built-in function print>
>>>
#include<iostream>
using namespace std;
class employee
{
int idnum;
double salary;
public:
employee(){}
employee(int a,int b)
{
idnum=a;
salary=b;
}
void dis()
{
cout<<"1st emp:"<<endl<<"idnum="<<idnum<<endl<<"salary="<<salary<<endl<<endl;
}
void operator=(employee &emp)
{
idnum=emp.idnum;
salary=emp.salary;
}
void show()
{
cout<<"2nd emp:"<<endl<<"idnum="<<idnum<<endl<<"salary="<<salary<<endl;
}
};
main()
{
int a;
double b;
cout<<"enter id num and salary"<<endl;
cin>>a>>b;
employee e1(a,b);
e1.dis();
employee e2;
e2=e1;
e2.show();
}
I figured out myself.
cmp
calls ComputeBetasAndNuHat
which returns a list which has objective
as minusloglik
So I can change the function cmp
to get this value.
I have mentioned that the Maven dependency in the pom.xml is wrong. It should be
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
All the answers above are correct, What I prefer is to use tui mode (ctrl+X A or 'tui enable') which shows your location and the function in a separate window which is very helpful for the users. Hope that helps too.
Integer
objects are immutable, so you cannot modify the value once they have been created. You will need to create a new Integer
and replace the existing one.
playerID = new Integer(playerID.intValue() + 1);
I know this is an old thread, but I just cannot steer away from posting some useful info on this. I see the Zip question come up a lot and this answers nearlly most of the common questions.
To get around framework issues of using 4.5+... Their is a ZipStorer class created by jaime-olivares: https://github.com/jaime-olivares/zipstorer, he also has added an example of how to use this class as well and has also added an example of how to search for a specific filename as well.
And for reference on how to use this and iterate through for a certain file extension as example you could do this:
#region
/// <summary>
/// Custom Method - Check if 'string' has '.png' or '.PNG' extension.
/// </summary>
static bool HasPNGExtension(string filename)
{
return Path.GetExtension(filename).Equals(".png", StringComparison.InvariantCultureIgnoreCase)
|| Path.GetExtension(filename).Equals(".PNG", StringComparison.InvariantCultureIgnoreCase);
}
#endregion
private void button1_Click(object sender, EventArgs e)
{
//NOTE: I recommend you add path checking first here, added the below as example ONLY.
string ZIPfileLocationHere = @"C:\Users\Name\Desktop\test.zip";
string EXTRACTIONLocationHere = @"C:\Users\Name\Desktop";
//Opens existing zip file.
ZipStorer zip = ZipStorer.Open(ZIPfileLocationHere, FileAccess.Read);
//Read all directory contents.
List<ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();
foreach (ZipStorer.ZipFileEntry entry in dir)
{
try
{
//If the files in the zip are "*.png or *.PNG" extract them.
string path = Path.Combine(EXTRACTIONLocationHere, (entry.FilenameInZip));
if (HasPNGExtension(path))
{
//Extract the file.
zip.ExtractFile(entry, path);
}
}
catch (InvalidDataException)
{
MessageBox.Show("Error: The ZIP file is invalid or corrupted");
continue;
}
catch
{
MessageBox.Show("Error: An unknown error ocurred while processing the ZIP file.");
continue;
}
}
zip.Close();
}
You can always use the good old observer pattern if you want to avoid the tyranny and overhead of $watch
.
In the service:
factory('aService', function() {
var observerCallbacks = [];
//register an observer
this.registerObserverCallback = function(callback){
observerCallbacks.push(callback);
};
//call this when you know 'foo' has been changed
var notifyObservers = function(){
angular.forEach(observerCallbacks, function(callback){
callback();
});
};
//example of when you may want to notify observers
this.foo = someNgResource.query().$then(function(){
notifyObservers();
});
});
And in the controller:
function FooCtrl($scope, aService){
var updateFoo = function(){
$scope.foo = aService.foo;
};
aService.registerObserverCallback(updateFoo);
//service now in control of updating foo
};
The following should work
.carousel .item {
height: 300px;
}
.item img {
position: absolute;
top: 0;
left: 0;
min-height: 300px;
}
JSFille for reference.
You can both highlight and select the item with the following 1-liner:
navigationView.getMenu().performIdentifierAction(R.id.posts, 0);
I had the same problem in Visual Studio Pro 2017: missing MSVCP120.dll file in Release mode and missing MSVCP120d.dll file in Debug mode. I installed Visual C++ Redistributable Packages for Visual Studio 2013 and Update for Visual C++ 2013 and Visual C++ Redistributable Package as suggested here Microsoft answer this fixed the release mode. For the debug mode what eventually worked was to copy msvcp120d.dll and msvcr120d.dll from a different computer (with Visual studio 2013) into C:\Windows\System32
Follow the instructions given here at NodeSource which is dedicated to creating a sustainable ecosystem for Node.js.
For Node.js >= 4.X
# Using Ubuntu
curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -
sudo apt-get install -y nodejs
# Using Debian, as root
curl -sL https://deb.nodesource.com/setup_4.x | bash -
apt-get install -y nodejs
lscpu
gathers CPU architecture information form /proc/cpuinfon in human-read-able format:
# lscpu
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 8
On-line CPU(s) list: 0-7
Thread(s) per core: 1
Core(s) per socket: 4
CPU socket(s): 2
NUMA node(s): 1
Vendor ID: GenuineIntel
CPU family: 6
Model: 15
Stepping: 7
CPU MHz: 1866.669
BogoMIPS: 3732.83
Virtualization: VT-x
L1d cache: 32K
L1i cache: 32K
L2 cache: 4096K
NUMA node0 CPU(s): 0-7
See also https://unix.stackexchange.com/questions/468766/understanding-output-of-lscpu.
Make use of LiNQ OrderBy
List<Order> objListOrder=new List<Order> ();
objListOrder=GetOrderList().OrderBy(o=>o.orderid).ToList();
The answer is on this stackoverflow post, by cdvv7788 Migrations in Django 1.7
If it is the first time you are migrating that app you have to use:
manage.py makemigrations myappname Once you do that you can do:
manage.py migrate If you had your app in database, modified its model and its not updating the changes on makemigrations you probably havent migrated it yet. Change your model back to its original form, run the first command (with the app name) and migrate...it will fake it. Once you do that put back the changes on your model, run makemigrations and migrate again and it should work.
I was having the exact same trouble and doing the above worked perfectly.
I had moved my django app to cloud9 and for some reason I never caught the initial migration.
You can use :+
to append element to array and +:
to prepend it:
0 +: array :+ 4
should produce:
res3: Array[Int] = Array(0, 1, 2, 3, 4)
It's the same as with any other implementation of Seq
.
To input AN ENTIRE LINE containing lot of spaces you can use getline(cin,string_variable);
eg:
string input;
getline(cin, input);
This format captures all the spaces in the sentence untill return
is pressed
The CSS styles for text input controls such as TextField for JavaFX 8 are defined in the modena.css stylesheet as below. Create a custom CSS stylesheet and modify the colors as you wish. Use the CSS reference guide if you need help understanding the syntax and available attributes and values.
.text-input {
-fx-text-fill: -fx-text-inner-color;
-fx-highlight-fill: derive(-fx-control-inner-background,-20%);
-fx-highlight-text-fill: -fx-text-inner-color;
-fx-prompt-text-fill: derive(-fx-control-inner-background,-30%);
-fx-background-color: linear-gradient(to bottom, derive(-fx-text-box-border, -10%), -fx-text-box-border),
linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
-fx-background-insets: 0, 1;
-fx-background-radius: 3, 2;
-fx-cursor: text;
-fx-padding: 0.333333em 0.583em 0.333333em 0.583em; /* 4 7 4 7 */
}
.text-input:focused {
-fx-highlight-fill: -fx-accent;
-fx-highlight-text-fill: white;
-fx-background-color:
-fx-focus-color,
-fx-control-inner-background,
-fx-faint-focus-color,
linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
-fx-background-insets: -0.2, 1, -1.4, 3;
-fx-background-radius: 3, 2, 4, 0;
-fx-prompt-text-fill: transparent;
}
Although using an external stylesheet is a preferred way to do the styling, you can style inline, using something like below:
textField.setStyle("-fx-text-inner-color: red;");
Two ways I can think of are
var TestApp = React.createClass({
getComponent: function(index) {
$(this.getDOMNode()).find('li:nth-child(' + index + ')').css({
'background-color': '#ccc'
});
},
render: function() {
return (
<div>
<ul>
<li onClick={this.getComponent.bind(this, 1)}>Component 1</li>
<li onClick={this.getComponent.bind(this, 2)}>Component 2</li>
<li onClick={this.getComponent.bind(this, 3)}>Component 3</li>
</ul>
</div>
);
}
});
React.renderComponent(<TestApp /> , document.getElementById('soln1'));
This is my personal favorite.
var ListItem = React.createClass({
getInitialState: function() {
return {
isSelected: false
};
},
handleClick: function() {
this.setState({
isSelected: true
})
},
render: function() {
var isSelected = this.state.isSelected;
var style = {
'background-color': ''
};
if (isSelected) {
style = {
'background-color': '#ccc'
};
}
return (
<li onClick={this.handleClick} style={style}>{this.props.content}</li>
);
}
});
var TestApp2 = React.createClass({
getComponent: function(index) {
$(this.getDOMNode()).find('li:nth-child(' + index + ')').css({
'background-color': '#ccc'
});
},
render: function() {
return (
<div>
<ul>
<ListItem content="Component 1" />
<ListItem content="Component 2" />
<ListItem content="Component 3" />
</ul>
</div>
);
}
});
React.renderComponent(<TestApp2 /> , document.getElementById('soln2'));
Here is a DEMO
I hope this helps.
After doing many tests in Litmus, i could not find a way to have perfect rendering in all emails readers, but here is the better solution i found :
<table width="100%" cellpadding="0" cellspacing="0" style="background-color:#333;color:#fff;border-radius:3px;border-spacing:0;" >
<tr>
<td style="width:12px;" > </td>
<td valign="middle" style="padding-top:6px;padding-bottom:6px;padding-right:0;padding-left:0;" >
<span style="color:#fff;" ><strong>Your text here</strong> and here</span></a>
</td>
<td style="width:12px;" > </td>
</tr>
</table>
In this piece of code, i aimed to emulate padding : 6px 12px;
There are 2 "12px table columns" that handles the right and left padding.
And I'm using "padding: 6px 0;" on my td content, to manage top and bottom padding : Outlook 2010 and 2013 will ignore this and will use their own padding.
The text won't be perfectly aligned in Outlook 2010 and Outlook 2013 (slightly too far from top) but it works with all other email readers i tried : Apple Mail, Gmail, Outlook 2011 (yes..), Hotmail, Yahoo and many more.
If the extension is already there but you don't see the uuid_generate_v4() function when you do a describe functions \df command then all you need to do is drop the extension and re-add it so that the functions are also added. Here is the issue replication:
db=# \df
List of functions
Schema | Name | Result data type | Argument data types | Type
--------+------+------------------+---------------------+------
(0 rows)
CREATE EXTENSION "uuid-ossp";
ERROR: extension "uuid-ossp" already exists
DROP EXTENSION "uuid-ossp";
CREATE EXTENSION "uuid-ossp";
db=# \df
List of functions
Schema | Name | Result data type | Argument data types | Type
--------+--------------------+------------------+---------------------------+--------
public | uuid_generate_v1 | uuid | | normal
public | uuid_generate_v1mc | uuid | | normal
public | uuid_generate_v3 | uuid | namespace uuid, name text | normal
public | uuid_generate_v4 | uuid | | normal
db=# select uuid_generate_v4();
uuid_generate_v4
--------------------------------------
b19d597c-8f54-41ba-ba73-02299c1adf92
(1 row)
What probably happened is that the extension was originally added to the cluster at some point in the past and then you probably created a new database within that cluster afterward. If that was the case then the new database will only be "aware" of the extension but it will not have the uuid functions added which happens when you add the extension. Therefore you must re-add it.
The answers are OK if you only require those two fields, but for a more complex object, maybe this approach could be useful:
from x in db.Serials
group x by x.Serial_Number into g
orderby g.Key
select g.OrderByDescending(z => z.uid)
.FirstOrDefault()
... this will avoid the "select new"
I had same error and this is how I solved it in my case. This means your postgresql version is 9.2.1 but you have started postgresql service of 9.1.6.
If you run psql postgres
you will see:
psql (9.2.1, server 9.1.6)
What I did to solve this problem is:
brew services stop [email protected]
brew services restart [email protected]
Now run psql postgres
and you should have: psql (9.2.1)
You can also run brew services list
to see the status of your postgres.
I'd suggest:
table {_x000D_
empty-cells: show;_x000D_
border: 1px solid #000;_x000D_
}_x000D_
_x000D_
table td,_x000D_
table th {_x000D_
min-width: 2em;_x000D_
min-height: 2em;_x000D_
border: 1px solid #000;_x000D_
}
_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th rowspan="2"></th>_x000D_
<th colspan="4"> </th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>I</th>_x000D_
<th>II</th>_x000D_
<th>III</th>_x000D_
<th>IIII</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>1</td>_x000D_
<td>2</td>_x000D_
<td>3</td>_x000D_
<td>4</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
References:
run "export TEMPDIR=/someDir" where some dir is a valid directory other than /tmp. Run this on prompt before running your python command. In my case it is "pip install rasa[spacy]" which was earlier failing.
The export command allows you to temporarily use the specified dir as temp dir.
open wp-config.php
file and add the following line:
define('FS_METHOD', 'direct');
this is working for me ...Thanks
If you do this a lot, NumPy is the way to go.
If for some reason you can't use NumPy:
>>> map(lambda x:sum(x)/float(len(x)), zip(*a))
[45.0, 10.5]
SJLJ (setjmp/longjmp): – available for 32 bit and 64 bit – not “zero-cost”: even if an exception isn’t thrown, it incurs a minor performance penalty (~15% in exception heavy code) – allows exceptions to traverse through e.g. windows callbacks
DWARF (DW2, dwarf-2) – available for 32 bit only – no permanent runtime overhead – needs whole call stack to be dwarf-enabled, which means exceptions cannot be thrown over e.g. Windows system DLLs.
SEH (zero overhead exception) – will be available for 64-bit GCC 4.8.
source: https://wiki.qt.io/MinGW-64-bit
>>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower())
Actually, above codes can be:
>>> sorted(['Some','words','sort','differently'],key=str.lower)
According to https://docs.python.org/2/library/functions.html?highlight=sorted#sorted, key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).
So how do we copy this arr?
let arr = [1,2,3,4,5];
let arrCopy = [...arr];
let arrCopy = arr.slice();
let arrCopy = [].concat(arr);
Passing one varible to another on Compound values such as Object/Array behave difrently. Using asign operator on copand values we pass reference to an object. This is why the value of both arrays are changing when removing/adding arr elements.
arrCopy[1] = 'adding new value this way will unreference';
When you assign a new value to the variable, you are changing the reference itself and it doesn’t affect the original Object/Array.
You can use jquery.form.js plugin to upload image via ajax to the server.
http://malsup.com/jquery/form/
Here is the sample jQuery ajax image upload script
(function() {
$('form').ajaxForm({
beforeSubmit: function() {
//do validation here
},
beforeSend:function(){
$('#loader').show();
$('#image_upload').hide();
},
success: function(msg) {
///on success do some here
}
}); })();
If you have any doubt, please refer following ajax image upload tutorial here
http://www.smarttutorials.net/ajax-image-upload-using-jquery-php-mysql/
Find out which react-native is installed globally:
npm ls react-native -g
Test with [char]9, such as:
$Tab = [char]9
Write-Output "$Tab hello"
Output:
hello
Lot's of great answer. I just want to add a small note about decoupling the stream.
cin.tie(NULL);
I have faced an issue while decoupling the stream with CodeChef platform. When I submitted my code, the platform response was "Wrong Answer" but after tying the stream and testing the submission. It worked.
So, If anyone wants to untie the stream, the output stream must be flushed.
Edit: I am not familiar with all the platform but this is what I have experienced.
Looping through all the files in the folder is relatively easy:
files = dir('*.csv');
for file = files'
csv = load(file.name);
% Do some stuff
end
In Bootstrap 4.1.3:
This worked for me when I was trying to center a bootstrap badge inside of a container > row > column
next to a h1
title.
What did work was some simple css:
.my-valign-center {
vertical-align: 50%;
}
or
<span class="badge badge-pill" style="vertical-align: 50%;">My Badge</span>
You should probably use either DateTime.ParseExact
or DateTime.TryParseExact
instead. They allow you to specify specific formats. I personally prefer the Try
-versions since I think they produce nicer code for the error cases.
If you want to find a workable C solution,
I believe you need this.
https://github.com/littlstar/b64.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "b64.h"
int
main (void) {
unsigned char *str = "brian the monkey and bradley the kinkajou are friends";
char *enc = b64_encode(str, strlen(str));
printf("%s\n", enc); // YnJpYW4gdGhlIG1vbmtleSBhbmQgYnJhZGxleSB0aGUga2lua2Fqb3UgYXJlIGZyaWVuZHM=
char *dec = b64_decode(enc, strlen(enc));
printf("%s\n", dec); // brian the monkey and bradley the kinkajou are friends
free(enc);
free(dec);
return 0;
}
To achieve this you can use a Regular Expression to remove all the whitespace in the string. If the length of the resulting string is 0
, then you can be sure the original only contained whitespace. Try this:
var str = " ";_x000D_
if (!str.replace(/\s/g, '').length) {_x000D_
console.log('string only contains whitespace (ie. spaces, tabs or line breaks)');_x000D_
}
_x000D_
for i in range(100):
try:
#Your code here
break
except:
continue
This one worked for me.
In general, these answer the question: How to change your user settings file? But the question I wanted answered was how to change my local maven repository location. The answer is that you have to edit settings.xml. If the file does not exist, you have to create it. You set or change the location of the file at Window > Preferences > Maven > User Settings. It's the User Settings entry at
It's the second file input; the first with information in it.
If it's not clear, [redacted]
should be replaced with the local file path to your .m2 folder.
If you click the "open file" link, it opens the settings.xml file for editing in Eclipse.
If you have no settings.xml file yet, the following will set the local repository to the Windows 10 default value for a user named mdfst13:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
https://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>C:\Users\mdfst13\.m2\repository</localRepository>
</settings>
You should set this to a value appropriate to your system. I haven't tested it, but I suspect that in Linux, the default value would be /home/mdfst13/.m2/repository
. And of course, you probably don't want to set it to the default value. If you are reading this, you probably want to set it to some other value. You could just delete it if you wanted the default.
Credit to this comment by @ejaenv for the name of the element in the settings file: <localRepository>
. See Maven — Settings Reference for more information.
Credit to @Ajinkya's answer for specifying the location of the User Settings value in Eclipse Photon.
If you already have a settings.xml file, you should merge this into your existing file. I.e. <settings
and <localRepository>
should only appear once in the file, and you probably want to retain any settings already there. Or to say that another way, edit any existing local repository entry if it exists or just add that line to the file if it doesn't.
I had to restart Eclipse for it to load data into the new repository. Neither "Update Settings" nor "Reindex" was sufficient.
To my knowledge, no.
Circumstantial indications from $LC_CTYPE
, locale
and such might seem alluring, but these are completely separated from the encoding the terminal application (actually an emulator) happens to be using when displaying characters on the screen.
They only way to detect encoding for sure is to output something only present in the encoding, e.g. ä
, take a screenshot, analyze that image and check if the output character is correct.
So no, it's not possible, sadly.
Can someone point me to a book or website which explains these basics clearly ?
You can check this XML Tutorial with examples.
But what about the encoding part ? Why is that necessary ?
W3C provides explanation about encoding :
"The document character set for XML and HTML 4.0 is Unicode (aka ISO 10646). This means that HTML browsers and XML processors should behave as if they used Unicode internally. But it doesn't mean that documents have to be transmitted in Unicode. As long as client and server agree on the encoding, they can use any encoding that can be converted to Unicode..."
const makeCancelable = promise => {
let rejectFn;
const wrappedPromise = new Promise((resolve, reject) => {
rejectFn = reject;
Promise.resolve(promise)
.then(resolve)
.catch(reject);
});
wrappedPromise.cancel = () => {
rejectFn({ canceled: true });
};
return wrappedPromise;
};
Usage:
const cancelablePromise = makeCancelable(myPromise);
// ...
cancelablePromise.cancel();
Try this:
ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) +
geom_bar(position = 'dodge', stat='identity') +
geom_text(aes(label=Number), position=position_dodge(width=0.9), vjust=-0.25)
This is not a good way when you want to seeding database.
Use faker instead of hard coding, and before all this maybe it's better to truncate tables.
Consider this example :
// Truncate table.
DB::table('users')->truncate();
// Create an instance of faker.
$faker = Faker::create();
// define an array for fake data.
$users = [];
// Make an array of 500 users with faker.
foreach (range(1, 500) as $index)
{
$users[] = [
'group_id' => rand(1, 3),
'name' => $faker->name,
'company' => $faker->company,
'email' => $faker->email,
'phone' => $faker->phoneNumber,
'address' => "{$faker->streetName} {$faker->postCode} {$faker->city}",
'about' => $faker->sentence($nbWords = 20, $variableNbWords = true),
'created_at' => new DateTime,
'updated_at' => new DateTime,
];
}
// Insert into database.
DB::table('users')->insert($users);
So why don't you simply use a key-value literal?
var params = {
'slide0001.html': 'Looking Ahead',
'slide0002.html': 'Forecase',
...
};
return params['slide0001.html']; // returns: Looking Ahead
Try this:
<select id="sel">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
<input type="button" value="Change option to 2" onclick="changeOpt()"/>
<script>
function changeOpt(){
document.getElementById("sel").options[1].selected = true;
alert("changed")
}
</script>
You can create button in a simple way, such as:
Button button = new Button();
button.Click += new EventHandler(button_Click);
protected void button_Click (object sender, EventArgs e)
{
Button button = sender as Button;
// identify which button was clicked and perform necessary actions
}
But event probably will not fire, because the element/elements must be recreated at every postback or you will lose the event handler.
I tried this solution that verify that ViewState is already Generated and recreate elements at every postback,
for example, imagine you create your button on an event click:
protected void Button_Click(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) != "true")
{
CreateDynamicElements();
}
}
on postback, for example on page load, you should do this:
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) == "true") {
CreateDynamicElements();
}
}
In CreateDynamicElements() you can put all the elements you need, such as your button.
This worked very well for me.
public void CreateDynamicElements(){
Button button = new Button();
button.Click += new EventHandler(button_Click);
}
Bizarrely if I remove the proxy from the environment and add it to the command line it works for me. For example to upgrade pip
itself:
env http_proxy= https_proxy= pip install pip --upgrade --proxy 'http://proxy-url:80'
My issue was having the proxy in the environment. It seems that pip only honors the one in argument.
This can be accessed through Javascript because it's a property of the loaded document, not of its parent.
Here's a quick example:
<script type="text/javascript">
document.write(document.referrer);
</script>
The same thing in PHP would be:
<?php echo $_SERVER["HTTP_REFERER"]; ?>
I was getting this error in websphere 8.5:
java.lang.UnsupportedClassVersionError: JVMCFRE003 bad major version; class=com/xxx/Whatever, offset=6
I had my project JDK level set at 1.7 in eclipse and was8 by default runs on JDK 1.6 so there was a clash. I had to install the optional SDK 1.7 to my websphere server and then the problem went away. I guess I could have also set my project level down to 1.6 in eclipse but I wanted to code to 1.7.
editText.setFocusable(false);
editText.setClickable(false);
Just use append:
list1 = [1, 2, 3, 4, 5]
list2 = [123, 234, 456]
d = {'a': [], 'b': []}
d['a'].append(list1)
d['a'].append(list2)
print d['a']
Derive from dict and and implement __getattr__
and __setattr__
.
Or you can use Bunch which is very similar.
I don't think it's possible to monkeypatch built-in dict class.
The primary difference is that SELECT INTO MyTable will create a new table called MyTable with the results, while INSERT INTO requires that MyTable already exists.
You would use SELECT INTO only in the case where the table didn't exist and you wanted to create it based on the results of your query. As such, these two statements really are not comparable. They do very different things.
In general, SELECT INTO is used more often for one off tasks, while INSERT INTO is used regularly to add rows to tables.
EDIT:
While you can use CREATE TABLE and INSERT INTO to accomplish what SELECT INTO does, with SELECT INTO you do not have to know the table definition beforehand. SELECT INTO is probably included in SQL because it makes tasks like ad hoc reporting or copying tables much easier.
I see no one has mentioned the section in the Baseline Requirements yet. I feel they are important.
Q: SSL - How do Common Names (CN) and Subject Alternative Names (SAN) work together?
A: Not at all. If there are SANs, then CN can be ignored. -- At least if the software that does the checking adheres very strictly to the CABForum's Baseline Requirements.
(So this means I can't answer the "Edit" to your question. Only the original question.)
CABForum Baseline Requirements, v. 1.2.5 (as of 2 April 2015), page 9-10:
9.2.2 Subject Distinguished Name Fields
a. Subject Common Name Field
Certificate Field: subject:commonName (OID 2.5.4.3)
Required/Optional: Deprecated (Discouraged, but not prohibited)
Contents: If present, this field MUST contain a single IP address or Fully-Qualified Domain Name that is one of the values contained in the Certificate’s subjectAltName extension (see Section 9.2.1).
RFC 2818: HTTP Over TLS, 2000, Section 3.1: Server Identity:
If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.
RFC 6125: Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS), 2011, Section 6.4.4: Checking of Common Names:
[...] if and only if the presented identifiers do not include a DNS-ID, SRV-ID, URI-ID, or any application-specific identifier types supported by the client, then the client MAY as a last resort check for a string whose form matches that of a fully qualified DNS domain name in a Common Name field of the subject field (i.e., a CN-ID).
A simple one would be
\d{4}-\d{2}-\d{2}
but this does not restrict month to 1-12 and days from 1 to 31.
There are more complex checks like in the other answers, by the way pretty clever ones. Nevertheless you have to check for a valid date, because there are no checks for if a month has 28, 30, or 31 days.
Cross origin protection is a feature of the browser. Curl does not care for CORS, as you presumed. That explains why your curls are successful, while the browser requests are not.
If you send the browser request with the wrong credentials, spring will try to forward the client to a login page. This response (off the login page) does not contain the header 'Access-Control-Allow-Origin' and the browser reacts as you describe.
You must make spring to include the haeder for this login response, and may be for other response, like error pages etc.
This can be done like this :
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain2.com")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(false).maxAge(3600);
}
}
This is copied from cors-support-in-spring-framework
I would start by adding cors mapping for all resources with :
registry.addMapping("/**")
and also allowing all methods headers.. Once it works you may start to reduce that again to the needed minimum.
Please note, that the CORS configuration changes with Release 4.2.
If this does not solve your issues, post the response you get from the failed ajax request.
You can just use a list comprehension:
my_list = [1, 2, 3, 4, 5]
my_new_list = [i * 5 for i in my_list]
>>> print(my_new_list)
[5, 10, 15, 20, 25]
Note that a list comprehension is generally a more efficient way to do a for
loop:
my_new_list = []
for i in my_list:
my_new_list.append(i * 5)
>>> print(my_new_list)
[5, 10, 15, 20, 25]
As an alternative, here is a solution using the popular Pandas package:
import pandas as pd
s = pd.Series(my_list)
>>> s * 5
0 5
1 10
2 15
3 20
4 25
dtype: int64
Or, if you just want the list:
>>> (s * 5).tolist()
[5, 10, 15, 20, 25]
Below is how I got this working.
The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.
[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]
[HttpPost]
public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)
{
var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
}
The JQuery script used to call this action method:
var requestData = {
InvoiceNumber: $.trim(this.value),
SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
};
$.ajax({
url: '/en/myController/GetDataForInvoiceNumber',
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
CheckIfInvoiceFound(result);
},
async: true,
processData: false
});
You can also get them with pure javascript.
For example:
new URL(location.href).searchParams.get('page')
For this url: websitename.com/user/?page=1, it would return a value of 1
"npm start"
I just closed the terminal and open a new one. Went to project location by cd command. And then just simply type - "npm start". and then 'r' for reload. Everything just vanished. I think everybody should try this at once.
Your check
function should return the found
boolean and use that to determine what to print.
def check():
datafile = file('example.txt')
found = False
for line in datafile:
if blabla in line:
found = True
break
return found
found = check()
if found:
print "true"
else:
print "false"
the second block could also be condensed to:
if check():
print "true"
else:
print "false"
The Python Tutorial simply calls it 'the *
-operator'. It performs unpacking of arbitrary argument lists.
I tried the solutions above and I do not achieve results, so I found a different solution that works for me. The ascending=False is to order the dataframe in descending order, by default it is True. I am using python 3.6.6 and pandas 0.23.4 versions.
final_df = df.sort_values(by=['2'], ascending=False)
You can see more details in pandas documentation here.
1. How can I completely avoid reverse engineering of an Android APK? Is this possible?
Impossible
2. How can I protect all the app's resources, assets and source code so that hackers can't hack the APK file in any way?
Impossible
3. Is there a way to make hacking more tough or even impossible? What more can I do to protect the source code in my APK file?
More tough - possible, but in fact it will be more tough mostly for the average user, who is just googling for hacking guides. If somebody really wants to hack your app - it will be hacked, sooner or later.
In C or C++ local objects are usually allocated on the stack. You are allocating a large array on the stack, more than the stack can handle, so you are getting a stackoverflow.
Don't allocate it local on stack, use some other place instead. This can be achieved by either making the object global or allocating it on the global heap. Global variables are fine, if you don't use the from any other compilation unit. To make sure this doesn't happen by accident, add a static storage specifier, otherwise just use the heap.
This will allocate in the BSS segment, which is a part of the heap:
static int c[1000000];
int main()
{
cout << "done\n";
return 0;
}
This will allocate in the DATA segment, which is a part of the heap too:
int c[1000000] = {};
int main()
{
cout << "done\n";
return 0;
}
This will allocate at some unspecified location in the heap:
int main()
{
int* c = new int[1000000];
cout << "done\n";
return 0;
}
You may want to try window.focus() - but it may be annoying if the screen switches around
The best way to check for a null values is
if ( testVar !== null )
{
// do action here
}
and for undefined
if ( testVar !== undefined )
{
// do action here
}
You can assign a avariable with undefined.
testVar = undefined;
//typeof(testVar) will be equal to undefined.
Rather than relying on errors, you can query INFORMATION_SCHEMA.TABLES
to see if the table exists. If there's a record, it exists. If there's no record, it doesn't exist.
You call tarfile.open with mode='w:gz'
, meaning "Open for gzip compressed writing."
You'll probably want to end the filename (the name
argument to open
) with .tar.gz
, but that doesn't affect compression abilities.
BTW, you usually get better compression with a mode of 'w:bz2'
, just like tar
can usually compress even better with bzip2
than it can compress with gzip
.
The connections I made in preparing this for posting really cleared it up for me, once and for all. It's not completely obvious what goes in the Main Class:
box until you see the connections. (Note that the class containing the main
method need not necessarily be named Main
but the main
method can have no other name.)
You can use the strip() to remove trailing and leading spaces.
>>> s = ' abd cde '
>>> s.strip()
'abd cde'
Note: the internal spaces are preserved
Using LINQ to xml if you are using framework 3.5
using System.Xml.Linq;
XDocument xmlFile = XDocument.Load("books.xml");
var query = from c in xmlFile.Elements("catalog").Elements("book")
select c;
foreach (XElement book in query)
{
book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");
There are three different setups that providing a stack to run an application on (This will help us to recognize what a container is and what makes it so much powerful than other solutions):
1) Traditional Servers(bare metal)
2) Virtual machines (VMs)
3) Containers
1) Traditional server stack consist of a physical server that runs an operating system and your application.
Advantages:
Utilization of raw resources
Isolation
Disadvantages:
2) The VM stack consist of a physical server which runs an operating system and a hypervisor that manages your virtual machine, shared resources, and networking interface. Each Vm runs a Guest Operating System, an application or set of applications.
Advantages:
Disadvantages:
3) The Container Setup, the key difference with other stack is container-based virtualization uses the kernel of the host OS to rum multiple isolated guest instances. These guest instances are called as containers. The host can be either a physical server or VM.
Advantages:
Disadvantages:
By comparing the container setup with its predecessors, we can conclude that containerization is the fastest, most resource effective, and most secure setup we know to date. Containers are isolated instances that run your application. Docker spin up the container in a way, layers get run time memory with default storage drivers(Overlay drivers) those run within seconds and copy-on-write layer created on top of it once we commit into the container, that powers the execution of containers. In case of VM's that will take around a minute to load everything into the virtualize environment. These lightweight instances can be replaced, rebuild, and moved around easily. This allows us to mirror the production and development environment and is tremendous help in CI/CD processes. The advantages containers can provide are so compelling that they're definitely here to stay.
Just if this helps, I was using Junit5 but the @RunWith(SpringRunner.class) was pointing towards import org.springframework.test.context.junit4.SpringRunner, which was messing around with things and hence was giving the initialization error. I fixed this and it worked.
Dietrich's answer is probably just the thing you need for what you describe, sending bytes, but a closer analogue to the code you've provided for example would be using the bytearray
type.
>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> bytes(key)
b'\x13\x00\x00\x00\x08\x00'
>>>
What I do for abstract classes and interfaces is the following: I write a test, that uses the object as it is concrete. But the variable of type X (X is the abstract class) is not set in the test. This test-class is not added to the test-suite, but subclasses of it, that have a setup-method that set the variable to a concrete implementation of X. That way I don't duplicate the test-code. The subclasses of the not used test can add more test-methods if needed.
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
for the maven users, comment the scope provided in the following dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<!--<scope>provided</scope>-->
</dependency>
UPDATE
As feed.me mentioned you have to uncomment the provided part depending on what kind of app you are deploying.
Here is a useful link with the details: http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#build-tool-plugins-maven-packaging
$ which nc
/bin/nc
$ rpm -qf /bin/nc
nmap-ncat-7.40-7.fc26.x86_64
$ ssh -o "ProxyCommand nc --proxy <addr[:port]> %h %p" USER@HOST
$ ssh -o "ProxyCommand nc --proxy <addr[:port]> --proxy-type <type> --proxy-auth <auth> %h %p" USER@HOST
Note : This answer is now out-of-date. This changes the theme in "preview" only as @imjohnking and @john-ktejik pointed out. As @Shahzeb mentioned, theme can modified in res>values>styles
Android Studio 0.8.2 provides a slightly easier way to change the theme. In the preview window, you can select the theme of "Holo.Light.DarkActionBar" by clicking on the theme combo box just above the phone.
Or do a ctrl + click on the @style/AppTheme in the Android manifest file. It will open styles.xml file where you can change the parent attribute of the style tag.
When using the Support Library, you must instead use the Theme.AppCompat themes:
Source http://forums.udacity.com/questions/100200635/choosing-theme-in-android-studio-08x
For Latest Info About SSIS > https://docs.microsoft.com/en-us/sql/integration-services/sql-server-integration-services
From the above referenced site:
Microsoft Integration Services is a platform for building enterprise-level data integration and data transformations solutions. Use Integration Services to solve complex business problems by copying or downloading files, loading data warehouses, cleansing and mining data, and managing SQL Server objects and data.
Integration Services can extract and transform data from a wide variety of sources such as XML data files, flat files, and relational data sources, and then load the data into one or more destinations.
Integration Services includes a rich set of built-in tasks and transformations, graphical tools for building packages, and the Integration Services Catalog database, where you store, run, and manage packages.
You can use the graphical Integration Services tools to create solutions without writing a single line of code. You can also program the extensive Integration Services object model to create packages programmatically and code custom tasks and other package objects.
Getting Started with SSIS - http://msdn.microsoft.com/en-us/sqlserver/bb671393.aspx
If you are Integration Services Information Worker - http://msdn.microsoft.com/en-us/library/ms141667.aspx
If you are Integration Services Administrator - http://msdn.microsoft.com/en-us/library/ms137815.aspx
If you are Integration Services Developer - http://msdn.microsoft.com/en-us/library/ms137709.aspx
If you are Integration Services Architect - http://msdn.microsoft.com/en-us/library/ms142161.aspx
Overview of SSIS - http://msdn.microsoft.com/en-us/library/ms141263.aspx
Integration Services How-to Topics - http://msdn.microsoft.com/en-us/library/ms141767.aspx
The issue turned out to be certificate-related. The WCF service called by the console app uses an X509 cert for authentication, which is installed on the servers that this script is hosted and run from.
On other servers, where the same services are consumed, the certificates were configured as follows:
winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "NETWORK SERVICE"
As they ran within the context of IIS. However, when the script was being run as it would in production, it's under the context of the user themselves. So, the script needed to be modified to the following:
winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "USERS"
Once that change was made, all was well. Thanks to everyone who offered assistance.
Some of the key features of case classes
are listed below
new
keyword.Sample scala code on scala fiddle, taken from the scala docs.
Subclassing dict
is one method, though not efficient. Here if you supply an integer it will return d[list(d)[n]]
, otherwise access the dictionary as expected:
class mydict(dict):
def __getitem__(self, value):
if isinstance(value, int):
return self.get(list(self)[value])
else:
return self.get(value)
d = mydict({'a': 'hello', 'b': 'this', 'c': 'is', 'd': 'a',
'e': 'test', 'f': 'dictionary', 'g': 'testing'})
d[0] # 'hello'
d[1] # 'this'
d['c'] # 'is'
Show file and track error
systemctl status nginx.service
Like this:
dataGridView1.Columns[0].Name = "column2";
dataGridView1.Columns[1].Name = "column6";
string[] row1 = new string[] { "column2 value", "column6 value" };
dataGridView1.Rows.Add(row1);
Or you need to set there values individually use the propery .Rows()
, like this:
dataGridView1.Rows[1].Cells[0].Value = "cell value";
I might be missing something in your question here... but from what I can gather, by using the subtract method this should be what you're looking to do:
var timeStr = "00:03:15";
timeStr = timeStr.split(':');
var h = timeStr[1],
m = timeStr[2];
var newTime = moment("01:20:00 06-26-2014")
.subtract({'hours': h, 'minutes': m})
.format('hh:mm');
var str = h + " hours and " + m + " minutes earlier: " + newTime;
console.log(str); // 3 hours and 15 minutes earlier: 10:05
$(document).ready(function(){ _x000D_
var timeStr = "00:03:15";_x000D_
timeStr = timeStr.split(':');_x000D_
_x000D_
var h = timeStr[1],_x000D_
m = timeStr[2];_x000D_
_x000D_
var newTime = moment("01:20:00 06-26-2014")_x000D_
.subtract({'hours': h, 'minutes': m})_x000D_
.format('hh:mm');_x000D_
_x000D_
var str = h + " hours and " + m + " minutes earlier: " + newTime;_x000D_
_x000D_
$('#new-time').html(str);_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script>_x000D_
_x000D_
_x000D_
<p id="new-time"></p>
_x000D_
If you are using the default cursor, a MySQLdb.cursors.Cursor
, the entire result set will be stored on the client side (i.e. in a Python list) by the time the cursor.execute()
is completed.
Therefore, even if you use
for row in cursor:
you will not be getting any reduction in memory footprint. The entire result set has already been stored in a list (See self._rows
in MySQLdb/cursors.py).
However, if you use an SSCursor or SSDictCursor:
import MySQLdb
import MySQLdb.cursors as cursors
conn = MySQLdb.connect(..., cursorclass=cursors.SSCursor)
then the result set is stored in the server, mysqld. Now you can write
cursor = conn.cursor()
cursor.execute('SELECT * FROM HUGETABLE')
for row in cursor:
print(row)
and the rows will be fetched one-by-one from the server, thus not requiring Python to build a huge list of tuples first, and thus saving on memory.
Otherwise, as others have already stated, cursor.fetchall()
and list(cursor)
are essentially the same.
Now you may have a better solution to resolve this scenario, but other way which i preferred.
const arr = [1,3,12]
if( arr.includes(foo)) { // it will return true if you `foo` is one of array values else false
// code here
}
I preferred above solution over the indexOf check where you need to check index as well.
if ( arr.indexOf( foo ) !== -1 ) { }
I'm a little confused why you are putting a WebView
into a ScrollView
in the first place. A WebView
has it's own built-in scrolling system.
Regarding your actual question, if you want the Scrollbar
to show up on top, you can use
view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY) or
android:scrollbarStyle="insideOverlay"
Bootstrap 4 includes sizing utilities. You can change the size to 25/50/75/100% of the page width (I wish there were even more increments).
To use these we will replace the modal-lg
class. Both the default width and modal-lg
use css max-width
to control the modal's width, so first add the mw-100
class to effectively disable max-width
. Then just add the width class you want, e.g. w-75
.
Note that you should place the mw-100
and w-75
classes in the div with the modal-dialog
class, not the modal
div e.g.,
<div class='modal-dialog mw-100 w-75'>
...
</div>
Automatic indentation:
gg
(go to start of document)
=
(indent time!)
shift-g
(go to end of document)
You'll need 'filetype plugin indent on' in your .vimrc
file, and probably appropriate 'shiftwidth' and 'expandtab' settings.
I'd say yes - because virtually all existing (at least all non-trivial) javascript code would break if a browser's javascript engine were to run it asynchronously.
Add to that the fact that HTML5 already specifies Web Workers (an explicit, standardized API for multi-threading javascript code) introducing multi-threading into the basic Javascript would be mostly pointless.
(Note to others commenters: Even though setTimeout/setInterval
, HTTP-request onload events (XHR), and UI events (click, focus, etc.) provide a crude impression of multi-threadedness - they are still all executed along a single timeline - one at a time - so even if we don't know their execution order beforehand, there's no need to worry about external conditions changing during the execution of an event handler, timed function or XHR callback.)
This is an extension to BigJim's brilliant answer.
In my case I had a NodeBase
class with a Children
dictionary, and I needed a way to generically do O(1) lookups from the children. I was attempting to return a private dictionary field in the getter of Children
, so obviously I wanted to avoid expensive copying/iterating. Therefore I used Bigjim's code to cast the Dictionary<whatever specific type>
to a generic Dictionary<NodeBase>
:
// Abstract parent class
public abstract class NodeBase
{
public abstract IDictionary<string, NodeBase> Children { get; }
...
}
// Implementing child class
public class RealNode : NodeBase
{
private Dictionary<string, RealNode> containedNodes;
public override IDictionary<string, NodeBase> Children
{
// Using a modification of Bigjim's code to cast the Dictionary:
return new IDictionary<string, NodeBase>().CastDictionary<string, RealNode, NodeBase>();
}
...
}
This worked well. However, I eventually ran into unrelated limitations and ended up creating an abstract FindChild()
method in the base class that would do the lookups instead. As it turned out this eliminated the need for the casted dictionary in the first place. (I was able to replace it with a simple IEnumerable
for my purposes.)
So the question you might ask (especially if performance is an issue prohibiting you from using .Cast<>
or .ConvertAll<>
) is:
"Do I really need to cast the entire collection, or can I use an abstract method to hold the special knowledge needed to perform the task and thereby avoid directly accessing the collection?"
Sometimes the simplest solution is the best.
It was discussed before here.
In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback or it might happen at later time, as in an asynchronous callback.
This is my case: it's run Environment: AspNet Core 2.1 Controller:
public class MyController
{
// ...
[HttpPost]
public ViewResult Search([FromForm]MySearchModel searchModel)
{
// ...
return View("Index", viewmodel);
}
}
View:
<form method="post" asp-controller="MyController" asp-action="Search">
<input name="MySearchModelProperty" id="MySearchModelProperty" />
<input type="submit" value="Search" />
</form>
Set the CSS class of your image container tag to image-class
:
<div class="image-full"></div>
and add this you your CSS stylesheet.
.image-full {
background: url(...some image...) no-repeat;
background-size: cover;
background-position: center center;
}
If you try it on CellContentClick
Event
Use:
dataGridView1.EndEdit(); //Stop editing of cell.
MessageBox.Show("0 = " + dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());