For another instance of Glibc, download gcc 4.7.2, for instance from this github repo (although an official source would be better) and extract it to some folder, then update LD_LIBRARY_PATH
with the path where you have extracted glib.
export LD_LIBRARY_PATH=$glibpath/glib-2.49.4-kgesagxmtbemim2denf65on4iixy3miy/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$glibpath/libffi-3.2.1-wk2luzhfdpbievnqqtu24pi774esyqye/lib64:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$glibpath/pcre-8.39-itdbuzevbtzqeqrvna47wstwczud67wx/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$glibpath/gettext-0.19.8.1-aoweyaoufujdlobl7dphb2gdrhuhikil/lib:$LD_LIBRARY_PATH
This should keep you safe from bricking your CentOS*.
*Disclaimer: I just completed the thought it looks like the OP was trying to express, but I don't fully agree.
I was able to install libc6 2.17
in Debian Wheezy
by editing the recommendations in perror's answer:
IMPORTANT
You need to exit out of your display manager by pressing CTRL-ALT-F1.
Then you can stop x (slim
) with sudo /etc/init.d/slim stop
(replace slim with mdm
or lightdm
or whatever)
Add the following line to the file /etc/apt/sources.list
:
deb http://ftp.debian.org/debian experimental main
Should be changed to:
deb http://ftp.debian.org/debian sid main
Then follow the rest of perror's post:
Update your package database:
apt-get update
Install the eglibc
package:
apt-get -t sid install libc6-amd64 libc6-dev libc6-dbg
IMPORTANT
After done updating libc6
, restart computer, and you should comment out or remove the sid source you just added (deb http://ftp.debian.org/debian sid main
), or else you risk upgrading your whole distro to sid.
Hope this helps. It took me a while to figure out.
You are correct in that glibc uses symbol versioning. If you are curious, the symbol versioning implementation introduced in glibc 2.1 is described here and is an extension of Sun's symbol versioning scheme described here.
One option is to statically link your binary. This is probably the easiest option.
You could also build your binary in a chroot build environment, or using a glibc-new => glibc-old cross-compiler.
According to the http://www.trevorpounds.com blog post Linking to Older Versioned Symbols (glibc), it is possible to to force any symbol to be linked against an older one so long as it is valid by using the same .symver
pseudo-op that is used for defining versioned symbols in the first place. The following example is excerpted from the blog post.
The following example makes use of glibc’s realpath, but makes sure it is linked against an older 2.2.5 version.
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
__asm__(".symver realpath,realpath@GLIBC_2.2.5");
int main()
{
const char* unresolved = "/lib64";
char resolved[PATH_MAX+1];
if(!realpath(unresolved, resolved))
{ return 1; }
printf("%s\n", resolved);
return 0;
}
For anyone who is looking for solutions here, I had a similar issue with C++: malloc(): smallbin double linked list corrupted:
This was due to a function not returning a value it was supposed to.
std::vector<Object> generateStuff(std::vector<Object>& target> {
std::vector<Object> returnValue;
editStuff(target);
// RETURN MISSING
}
Don't know why this was able to compile after all. Probably there was a warning about it.
@msb gives a safe solution.
I met this problem when I did import tensorflow as tf
in conda environment in CentOS 6.5
which only has glibc-2.12
.
ImportError: /lib64/libc.so.6: version `GLIBC_2.16' not found (required by /home/
I want to supply some details:
First install glibc
to your home directory:
mkdir ~/glibc-install; cd ~/glibc-install
wget http://ftp.gnu.org/gnu/glibc/glibc-2.17.tar.gz
tar -zxvf glibc-2.17.tar.gz
cd glibc-2.17
mkdir build
cd build
../configure --prefix=/home/myself/opt/glibc-2.17 # <-- where you install new glibc
make -j<number of CPU Cores> # You can find your <number of CPU Cores> by using **nproc** command
make install
Second, follow the same way to install patchelf;
Third, patch your Python:
[myself@nfkd ~]$ patchelf --set-interpreter /home/myself/opt/glibc-2.17/lib/ld-linux-x86-64.so.2 --set-rpath /home/myself/opt/glibc-2.17/lib/ /home/myself/miniconda3/envs/tensorflow/bin/python
as mentioned by @msb
Now I can use tensorflow-2.0 alpha
in CentOS 6.5
.
ref: https://serverkurma.com/linux/how-to-update-glibc-newer-version-on-centos-6-x/
looks to me yum install glibc.i686 should have worked. Unless Peter was not root. He has the 64 bit glib installed, he is installing a 32 bit package that requires the 32 bit glib which is glib.i686 for intel processors.
Merge commits: retains all of the commits in your branch and interleaves them with commits on the base branch
Merge Squash: retains the changes but omits the individual commits from history
Rebase: This moves the entire feature branch to begin on the tip of the master branch, effectively incorporating all of the new commits in master
More on here
It is better to rely on regexps like ^[^0-9]+$
rather than on regexps like [a-zA-Z]+
as your app may one day accept user inputs from users speaking language like Polish, where many more characters should be accepted rather than only [a-zA-Z]+
. Using ^[^0-9]+$
easily rules out any such undesired side effects.
This is the stupidest thing I've ever seen, but it works, and you can't argue with results.
SELECT *
FROM (
SELECT table1.field1 FROM table1 ORDER BY table1.field1
UNION
SELECT table2.field1 FROM table2 ORDER BY table2.field1
) derivedTable
The interior of the derived table will not execute on its own, but as a derived table works perfectly fine. I've tried this on SS 2000, SS 2005, SS 2008 R2, and all three work.
In my case I had a row of Ids, and it was neccessary to cast it to char, otherwise, the result was encoded into binary format :
SELECT CAST(GROUP_CONCAT(field SEPARATOR ',') AS CHAR) FROM table
Probably very late to the answer but I just read this while preparing for my 70-480
exam, and found this to work -
var elem = document.getElementById('myCanvas');
elem.onclick = function() { alert("hello world"); }
Notice the event as onclick
instead of onClick
.
JS Bin example.
your mail.php
on config you declare host as smtp.mailgun.org
and port is 587
while on env is different. you need to change your mail.php
to
'host' => env('MAIL_HOST', 'mailtrap.io'),
'port' => env('MAIL_PORT', 2525),
if you desire to use mailtrap.Then run
php artisan config:cache
TLDR : check if packaging
element inside the pom.xml file is set to jar
.
Like this - <packaging>jar</packaging>
. If it set to pom
your target folder will not be created even after you Clean and Build your project and Maven executable won't be able to find .class
files (because they don't exist), after which you get Error: Could not find or load main class your.package.name.MainClass
After creating a Maven POM project in Netbeans 8.2, the content of the default pom.xml
file are as follows -
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>myproject</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
Here packaging
element is set to pom
. Hence the target
directory is not created as we are not enabling maven to package our application as a jar
file. Change it to jar
then Clean and Build your project, you should see target directory created at root location. Now you should be able to run that java file with main method.
When no packaging is declared, Maven assumes the packaging as jar
. Other core packaging values are pom
, war
, maven-plugin
, ejb
, ear
, rar
. These define the goals that execute on each corresponsding build life-cycle phase of that package. See more here
All other answers don't quite solve the issue. They print the date formatted as mm/dd/yyyy but the question was regarding MM/dd/yyyy. Notice the subtle difference? MM indicates that a leading zero must pad the month if the month is a single digit, thus having it always be a double digit number.
i.e. whereas mm/dd would be 3/31, MM/dd would be 03/31.
I've created a simple function to achieve this. Notice that the same padding is applied not only to the month but also to the day of the month, which in fact makes this MM/DD/yyyy:
function getFormattedDate(date) {_x000D_
var year = date.getFullYear();_x000D_
_x000D_
var month = (1 + date.getMonth()).toString();_x000D_
month = month.length > 1 ? month : '0' + month;_x000D_
_x000D_
var day = date.getDate().toString();_x000D_
day = day.length > 1 ? day : '0' + day;_x000D_
_x000D_
return month + '/' + day + '/' + year;_x000D_
}
_x000D_
Update for ES2017 using String.padStart(), supported by all major browsers except IE.
function getFormattedDate(date) {_x000D_
let year = date.getFullYear();_x000D_
let month = (1 + date.getMonth()).toString().padStart(2, '0');_x000D_
let day = date.getDate().toString().padStart(2, '0');_x000D_
_x000D_
return month + '/' + day + '/' + year;_x000D_
}
_x000D_
CSS table display is ideal for this:
.parent {_x000D_
display: table;_x000D_
width: 100%;_x000D_
}_x000D_
.parent > div {_x000D_
display: table-cell;_x000D_
}_x000D_
.child-left {_x000D_
background: powderblue;_x000D_
}_x000D_
.child-right {_x000D_
background: papayawhip;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child-left">Short</div>_x000D_
<div class="child-right">Tall<br>Tall</div>_x000D_
</div>
_x000D_
Original answer (assumed any column could be taller):
You're trying to make the parent's height dependent on the children's height and children's height dependent on parent's height. Won't compute. CSS Faux columns is the best solution. There's more than one way of doing that. I'd rather not use JavaScript.
The answer from JoseK can't be used when your in your service layer, where you don't want to introduce a coupling with the web layer from the reference to the HTTP request. If you're looking into resolving the roles while in the service layer, Gopi's answer is the way to go.
However, it's a bit long winded. The authorities can be accessed right from the Authentication. Hence, if you can assume that you have a user logged in, the following does it:
/**
* @return true if the user has one of the specified roles.
*/
protected boolean hasRole(String[] roles) {
boolean result = false;
for (GrantedAuthority authority : SecurityContextHolder.getContext().getAuthentication().getAuthorities()) {
String userRole = authority.getAuthority();
for (String role : roles) {
if (role.equals(userRole)) {
result = true;
break;
}
}
if (result) {
break;
}
}
return result;
}
you can define it like this :
let table = $('.datatable-sales').DataTable({
processing: true,
responsive: true,
serverSide: true,
ajax: {
url: "<?php echo site_url("your url"); ?>",
cache: false,
type: "POST",
data: {
<?php echo your api; ?>,
}
}
or like this :
$.get({url: <?php echo json_encode(site_url('your api'))?>, cache: false})
hope it helps
An Integer is pretty much just a wrapper for the primitive type int. It allows you to use all the functions of the Integer class to make life a bit easier for you.
If you're new to Java, something you should learn to appreciate is the Java documentation. For example, anything you want to know about the Integer Class is documented in detail.
This is straight out of the documentation for the Integer class:
The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.
I believe that you will have to drop the foreign key constraints first. Then update all of the appropriate tables and remap them as they were.
ALTER TABLE [dbo.Details_tbl] DROP CONSTRAINT [FK_Details_tbl_User_tbl];
-- Perform more appropriate alters
ALTER TABLE [dbo.Details_tbl] ADD FOREIGN KEY (FK_Details_tbl_User_tbl)
REFERENCES User_tbl(appId);
-- Perform all appropriate alters to bring the key constraints back
However, unless memory is a really big issue, I would keep the identity as an INT. Unless you are 100% positive that your keys will never grow past the TINYINT restraints. Just a word of caution :)
A stateful server keeps state between connections. A stateless server does not.
So, when you send a request to a stateful server, it may create some kind of connection object that tracks what information you request. When you send another request, that request operates on the state from the previous request. So you can send a request to "open" something. And then you can send a request to "close" it later. In-between the two requests, that thing is "open" on the server.
When you send a request to a stateless server, it does not create any objects that track information regarding your requests. If you "open" something on the server, the server retains no information at all that you have something open. A "close" operation would make no sense, since there would be nothing to close.
HTTP and NFS are stateless protocols. Each request stands on its own.
Sometimes cookies are used to add some state to a stateless protocol. In HTTP (web pages), the server sends you a cookie and then the browser holds the state, only to send it back to the server on a subsequent request.
SMB is a stateful protocol. A client can open a file on the server, and the server may deny other clients access to that file until the client closes it.
print didn't transition from statement to function until Python 3.0. If you're using older Python then you can suppress the newline with a trailing comma like so:
print "Foo %10s bar" % baz,
you might try this if you logged in with root:
mysqld --user=root
/**
* @param initialTime - in format HH:mm:ss
* @param finalTime - in format HH:mm:ss
* @param timeToCheck - in format HH:mm:ss
* @return initialTime <= timeToCheck < finalTime
* @throws IllegalArgumentException if passed date with wrong format
*/
public static boolean isTimeBetweenTwoTime(String initialTime, String finalTime, String timeToCheck) throws IllegalArgumentException {
String reg = "^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
if (initialTime.matches(reg) && finalTime.matches(reg) && timeToCheck.matches(reg)) {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
Date inTime = parseDate(dateFormat, initialTime);
Date finTime = parseDate(dateFormat, finalTime);
Date checkedTime = parseDate(dateFormat, timeToCheck);
if (finalTime.compareTo(initialTime) < 0) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(finTime);
calendar.add(Calendar.DAY_OF_YEAR, 1);
finTime = calendar.getTime();
if (timeToCheck.compareTo(initialTime) < 0) {
calendar.setTime(checkedTime);
calendar.add(Calendar.DAY_OF_YEAR, 1);
checkedTime = calendar.getTime();
}
}
return (checkedTime.after(inTime) || checkedTime.compareTo(inTime) == 0) && checkedTime.before(finTime);
} else {
throw new IllegalArgumentException("Not a valid time, expecting HH:MM:SS format");
}
}
/**
* @param initialTime - in format HH:mm:ss
* @param finalTime - in format HH:mm:ss
* @return initialTime <= now < finalTime
* @throws IllegalArgumentException if passed date with wrong format
*/
public static boolean isNowBetweenTwoTime(String initialTime, String finalTime) throws IllegalArgumentException {
return isTimeBetweenTwoTime(initialTime, finalTime,
String.valueOf(DateFormat.format("HH:mm:ss", new Date()))
);
}
private static Date parseDate(SimpleDateFormat dateFormat, String data) {
try {
return dateFormat.parse(data);
} catch (ParseException e) {
throw new IllegalArgumentException("Not a valid time");
}
}
Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.
Wrote a little python package to PyPi that might help viewers of this question. The package acts as workaround if one wishes to be able to run python files containing imports containing upper level packages from within a package / project without being directly in the importing file's directory. https://pypi.org/project/import-anywhere/
Here's a plain JavaScript version:
function scroll(e) {
var delta = (e.type === "mousewheel") ? e.wheelDelta : e.detail * -40;
if (delta < 0 && (this.scrollHeight - this.offsetHeight - this.scrollTop) <= 0) {
this.scrollTop = this.scrollHeight;
e.preventDefault();
} else if (delta > 0 && delta > this.scrollTop) {
this.scrollTop = 0;
e.preventDefault();
}
}
document.querySelectorAll(".scroller").addEventListener("mousewheel", scroll);
document.querySelectorAll(".scroller").addEventListener("DOMMouseScroll", scroll);
Simply create a new DataGridViewCellStyle object, set its back color and then assign the cell's style to it:
DataGridViewCellStyle style = new DataGridViewCellStyle();
style.BackColor = Color.FromArgb(((GesTest.dsEssais.FMstatusAnomalieRow)row.DataBoundItem).iColor);
style.ForeColor = Color.Black;
row.Cells[color.Index].Style = style;
Just Try With The Following :
PHP Part :
<?php
/*******EDIT LINES 3-8*******/
$DB_Server = "localhost"; //MySQL Server
$DB_Username = "username"; //MySQL Username
$DB_Password = "password"; //MySQL Password
$DB_DBName = "databasename"; //MySQL Database Name
$DB_TBLName = "tablename"; //MySQL Table Name
$filename = "excelfilename"; //File Name
/*******YOU DO NOT NEED TO EDIT ANYTHING BELOW THIS LINE*******/
//create MySQL connection
$sql = "Select * from $DB_TBLName";
$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database
$Db = @mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());
//execute query
$result = @mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
$file_ending = "xls";
//header info for browser
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
/*******Start of Formatting for Excel*******/
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo mysql_field_name($result,$i) . "\t";
}
print("\n");
//end of printing column names
//start while loop to get data
while($row = mysql_fetch_row($result))
{
$schema_insert = "";
for($j=0; $j<mysql_num_fields($result);$j++)
{
if(!isset($row[$j]))
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
else
$schema_insert .= "".$sep;
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}
?>
I think this may help you to resolve your problem.
All the answers are complete. But Wanted to add one thing,
set FirstName=%~1
set LastName=%~2
This line should have worked, you needed a small change.
set "FirstName=%~1"
set "LastName=%~2"
Include the complete assignment within quotes. It will remove quotes without an issue. This is a prefered way of assignment which fixes unwanted issues with quotes in arguments.
I dont know why all these complicated answers are on here but this is what I would do
where pdate >= CURRENT_TIMESTAMP -30
OR WHERE CAST(PDATE AS DATE) >= GETDATE() -30
I would make a new image of the dog's silhouette (black) and the rest the same as the original image. In the html, add a wrapper div with this silhouette as as background. Now, make the original image semi-transparent. The dog will become darker and the background of the dog will stay the same. You can do :hover tricks by setting the opacity of the original image to 100% on hover. Then the dog pops out when you mouse over him!
style
.wrapper{background-image:url(silhouette.png);}
.original{opacity:0.7:}
.original:hover{opacity:1}
<div class="wrapper">
<div class="img">
<img src="original.png">
</div>
</div>
AES is a symmetric cryptographic algorithm, while RSA is an asymmetric (or public key) cryptographic algorithm. Encryption and decryption is done with a single key in AES, while you use separate keys (public and private keys) in RSA. The strength of a 128-bit AES key is roughly equivalent to 2600-bits RSA key.
/Images/myImage.png
this has to be in root of your domain/subdomain
http://website.to/Images/myImage.png
and it will work
However, I think it would work like this, too
style.css:
body{
background: url(../images/yourimage.png);
}
You have to put all your assets in app/public
folder, and to access them from your views you can use asset()
helper method.
Ex. you can retrieve assets/images/image.png
in your view as following:
<img src="{{asset('assets/images/image.png')}}">
If you ensure that every place holder, in each of the contexts involved, is ignoring unresolvable keys then both of these approaches work. For example:
<context:property-placeholder
location="classpath:dao.properties,
classpath:services.properties,
classpath:user.properties"
ignore-unresolvable="true"/>
or
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:dao.properties</value>
<value>classpath:services.properties</value>
<value>classpath:user.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
I'm unsure of what causes this issue but one method I used to resolve the porblem successfully was to run pod update on my cocoa pods.
The error (for me anyway) was showing a problem with one of the pods signing. Updating the pods resolved that signing issue.
pod update [PODNAME] //For an individual pod
or
pod update //For all pods.
Hopefully, this will help someone who is having the same "Command CodeSign failed with a nonzero exit code" error.
Faster is not an attribute of JSON or XML or a result that a comparison between those would yield. If any, then it is an attribute of the parsers or the bandwidth with which you transmit the data.
Here is (the beginning of) a list of advantages and disadvantages of JSON and XML:
Pro:
Con:
Simple syntax, only a handful of different data types are supported.
No support for comments.
Pro:
Con:
So in the end you have to decide what you need. Obviously both formats have their legitimate use cases. If you are mostly going to use JavaScript then you should go with JSON.
Please feel free to add pros and cons. I'm not an XML expert ;)
If I were you I'd just use a scanner and use ".nextByte()". You can cast that to a char and you're good.
I ended up using inipp which is not mentioned in this thread.
https://github.com/mcmtroffaes/inipp
Was a MIT licensed header only implementation which was simple enough to add to a project and 4 lines to use.
Why not use a Single liner ...
IEnumerable<Book> _Book_IE= _Book_List as IEnumerable<Book>;
you can use something like this :
string [] filePaths = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
instead of using "." you can type the name of the file or just the type like "*.txt" also SearchOption.AllDirectories is to search in all subfolders you can change that if you only want one level more about how to use it on here
If you are sending multiple objects, it's often simplest to put them some kind of holder/collection like an Object[]
or List
. It saves you having to explicitly check for end of stream and takes care of transmitting explicitly how many objects are in the stream.
EDIT: Now that I formatted the code, I see you already have the messages in an array. Simply write the array to the object stream, and read the array on the server side.
Your "server read method" is only reading one object. If it is called multiple times, you will get an error since it is trying to open several object streams from the same input stream. This will not work, since all objects were written to the same object stream on the client side, so you have to mirror this arrangement on the server side. That is, use one object input stream and read multiple objects from that.
(The error you get is because the objectOutputStream writes a header, which is expected by objectIutputStream. As you are not writing multiple streams, but simply multiple objects, then the next objectInputStream created on the socket input fails to find a second header, and throws an exception.)
To fix it, create the objectInputStream when you accept the socket connection. Pass this objectInputStream to your server read method and read Object from that.
With the package pROC
you can use the function auc()
like this example from the help page:
> data(aSAH)
>
> # Syntax (response, predictor):
> auc(aSAH$outcome, aSAH$s100b)
Area under the curve: 0.7314
FileReader
uses Java's platform default encoding, which depends on the system settings of the computer it's running on and is generally the most popular encoding among users in that locale.
If this "best guess" is not correct then you have to specify the encoding explicitly. Unfortunately, FileReader
does not allow this (major oversight in the API). Instead, you have to use new InputStreamReader(new FileInputStream(filePath), encoding)
and ideally get the encoding from metadata about the file.
Understand does a very good job of creating call graphs.
Also, would I be right in concluding that a list comprehension is the most efficient way to do this?
Maybe. List comprehensions are not inherently computationally efficient. It is still running in linear time.
From my personal experience: I have significantly reduced computation time when dealing with large data sets by replacing list comprehensions (specifically nested ones) with for-loop/list-appending type structures you have above. In this application I doubt you will notice a difference.
When you #include
a header, it's exactly as if you put the code into the source file itself. In both cases the varGlobal
variable is defined in the source so it will work no matter how it's declared.
Also as pointed out in the comments, C++ variables at file scope are not static in scope even though they will be assigned to static storage. If the variable were a class member for example, it would need to be accessible to other compilation units in the program by default and non-class members are no different.
var byteCharacters = atob(response.data);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var file = new Blob([byteArray], { type: 'application/pdf;base64' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
You return a base64 string from the API or another source. You can also download it.
cat /etc/issue
Or cat /etc/fedora-release
as suggested by @Bruce ONeel
in my case deleted the obj folder in project root and rebuild project solved my problem!!!
Another way of initializing an array of structs is to initialize the array members explicitly. This approach is useful and simple if there aren't too many struct and array members.
Use the typedef
specifier to avoid re-using the struct
statement everytime you declare a struct variable:
typedef struct
{
double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
}Body;
Then declare your array of structs. Initialization of each element goes along with the declaration:
Body bodies[n] = {{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0},
{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0},
{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}};
To repeat, this is a rather simple and straightforward solution if you don't have too many array elements and large struct members and if you, as you stated, are not interested in a more dynamic approach. This approach can also be useful if the struct members are initialized with named enum-variables (and not just numbers like the example above) whereby it gives the code-reader a better overview of the purpose and function of a structure and its members in certain applications.
For Firefox use
iframewin.print()
for IE use
iframedocument.execCommand('print', false, null);
see also Unable to print an iframe on IE using JavaScript, prints parent page instead
XAMPP for linux and mac comes with ProFTPD. Make sure to start the service from XAMPP control panel -> manage servers.
Further complete instructions can be found at localhost XAMPP dashboard -> How-to guides -> Configure FTP Access. I have pasted them below :
Open a new Linux terminal and ensure you are logged in as root.
Create a new group named ftp. This group will contain those user accounts allowed to upload files via FTP.
groupadd ftp
usermod -a -G ftp susan
cd /opt/lampp chown root.ftp htdocs chmod 775 htdocs
You can now transfer files to the XAMPP server using the steps below:
If you’re connecting to the server from the same system, use "127.0.0.1" as the host address. If you’re connecting from a different system, use the network hostname or IP address of the XAMPP server.
Use "21" as the port.
Enter your Linux username and password as your FTP credentials.
Your FTP client should now connect to the server and enter the /opt/lampp/htdocs/ directory, which is the default Web server document root.
Once the file is successfully transferred, you should be able to see it in action.
No you can't use bind variables that way. In your second example :into_bind
in v_query_str
is just a placeholder for value of variable v_num_of_employees
. Your select into statement will turn into something like:
SELECT COUNT(*) INTO FROM emp_...
because the value of v_num_of_employees
is null
at EXECUTE IMMEDIATE
.
Your first example presents the correct way to bind the return value to a variable.
Edit
The original poster has edited the second code block that I'm referring in my answer to use OUT
parameter mode for v_num_of_employees
instead of the default IN
mode. This modification makes the both examples functionally equivalent.
The good, clean, fast, easy and readable ways is:
add something similar like this:
public sealed class myKey : Tuple<TypeA, TypeB, TypeC>
{
public myKey(TypeA dataA, TypeB dataB, TypeC dataC) : base (dataA, dataB, dataC) { }
public TypeA DataA => Item1;
public TypeB DataB => Item2;
public TypeC DataC => Item3;
}
So you can use it with dictionary:
var myDictinaryData = new Dictionary<myKey, string>()
{
{new myKey(1, 2, 3), "data123"},
{new myKey(4, 5, 6), "data456"},
{new myKey(7, 8, 9), "data789"}
};
So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.my_layout); Bitmap bitmap = getIntent().getParcelableExtra("image"); ImageView imageView = (ImageView) findViewById(R.id.imageview); imageView.setImageBitmap(bitmap); }
Let's start by describing DOM elements' event handling.
First of all you wouldn't want to work with DOM node directly. Instead you probably would want to utilize Ext.Element
interface. For the purpose of assigning event handlers, Element.addListener
and Element.on
(these are equivalent) were created. So, for example, if we have html:
<div id="test_node"></div>
and we want add click
event handler.
Let's retrieve Element
:
var el = Ext.get('test_node');
Now let's check docs for click
event. It's handler may have three parameters:
click( Ext.EventObject e, HTMLElement t, Object eOpts )
Knowing all this stuff we can assign handler:
// event name event handler
el.on( 'click' , function(e, t, eOpts){
// handling event here
});
Widgets event handling is pretty much similar to DOM nodes event handling.
First of all, widgets event handling is realized by utilizing Ext.util.Observable
mixin. In order to handle events properly your widget must containg Ext.util.Observable
as a mixin. All built-in widgets (like Panel, Form, Tree, Grid, ...) has Ext.util.Observable
as a mixin by default.
For widgets there are two ways of assigning handlers. The first one - is to use on method (or addListener
). Let's for example create Button
widget and assign click
event to it. First of all you should check event's docs for handler's arguments:
click( Ext.button.Button this, Event e, Object eOpts )
Now let's use on
:
var myButton = Ext.create('Ext.button.Button', {
text: 'Test button'
});
myButton.on('click', function(btn, e, eOpts) {
// event handling here
console.log(btn, e, eOpts);
});
The second way is to use widget's listeners config:
var myButton = Ext.create('Ext.button.Button', {
text: 'Test button',
listeners : {
click: function(btn, e, eOpts) {
// event handling here
console.log(btn, e, eOpts);
}
}
});
Notice that Button
widget is a special kind of widgets. Click event can be assigned to this widget by using handler
config:
var myButton = Ext.create('Ext.button.Button', {
text: 'Test button',
handler : function(btn, e, eOpts) {
// event handling here
console.log(btn, e, eOpts);
}
});
First of all you need to register an event using addEvents method:
myButton.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */);
Using the addEvents
method is optional. As comments to this method say there is no need to use this method but it provides place for events documentation.
To fire your event use fireEvent method:
myButton.fireEvent('myspecialevent1', arg1, arg2, arg3, /* ... */);
arg1, arg2, arg3, /* ... */
will be passed into handler. Now we can handle your event:
myButton.on('myspecialevent1', function(arg1, arg2, arg3, /* ... */) {
// event handling here
console.log(arg1, arg2, arg3, /* ... */);
});
It's worth mentioning that the best place for inserting addEvents method call is widget's initComponent
method when you are defining new widget:
Ext.define('MyCustomButton', {
extend: 'Ext.button.Button',
// ... other configs,
initComponent: function(){
this.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */);
// ...
this.callParent(arguments);
}
});
var myButton = Ext.create('MyCustomButton', { /* configs */ });
To prevent bubbling you can return false
or use Ext.EventObject.preventDefault()
. In order to prevent browser's default action use Ext.EventObject.stopPropagation()
.
For example let's assign click event handler to our button. And if not left button was clicked prevent default browser action:
myButton.on('click', function(btn, e){
if (e.button !== 0)
e.preventDefault();
});
You can use any bash looping constructs like FOR
, with is compatible to Linux and Mac.
https://tiswww.case.edu/php/chet/bash/bashref.html#Looping-Constructs
In your specific case you can define N
iterations, with N
is a number defining how many curl
executions you want.
for n in {1..N}; do curl <arguments>; done
ex:
for n in {1..20}; do curl -d @notification.json -H 'Content-Type: application/json' localhost:3000/dispatcher/notify; done
You may also use:
request.POST.get('section','') # => [39]
request.POST.get('MAINS','') # => [137]
request.GET.get('section','') # => [39]
request.GET.get('MAINS','') # => [137]
Using this ensures that you don't get an error. If the POST/GET data with any key is not defined then instead of raising an exception the fallback value (second argument of .get() will be used).
You can make a default constraint on this column that will put a default getdate() as a value.
Example:
alter table dbo.TABLE
add constraint df_TABLE_DATE default getdate() for DATE_COLUMN
When you log in to your developer account, you can find a link at the bottom of the download section for Xcode that says "Looking for an older version of Xcode?". In there you can find download links to older versions of Xcode and other developer tools
To run Java class file from the command line, the syntax is:
java -classpath /path/to/jars <packageName>.<MainClassName>
where packageName (usually starts with either com
or org
) is the folder name where your class file is present.
For example if your main class name is App and Java package name of your app is com.foo.app
, then your class file needs to be in com/foo/app
folder (separate folder for each dot), so you run your app as:
$ java com.foo.app.App
Note: $
is indicating shell prompt, ignore it when typing
If your class doesn't have any package
name defined, simply run as: java App
.
If you've any other jar dependencies, make sure you specified your classpath parameter either with -cp
/-classpath
or using CLASSPATH
variable which points to the folder with your jar/war/ear/zip/class files. So on Linux you can prefix the command with: CLASSPATH=/path/to/jars
, on Windows you need to add the folder into system variable. If not set, the user class path consists of the current directory (.
).
Given we've created sample project using Maven as:
$ mvn archetype:generate -DgroupId=com.foo.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
and we've compiled our project by mvn compile
in our my-app/
dir, it'll generate our class file is in target/classes/com/foo/app/App.class
.
To run it, we can either specify class path via -cp
or going to it directly, check examples below:
$ find . -name "*.class"
./target/classes/com/foo/app/App.class
$ CLASSPATH=target/classes/ java com.foo.app.App
Hello World!
$ java -cp target/classes com.foo.app.App
Hello World!
$ java -classpath .:/path/to/other-jars:target/classes com.foo.app.App
Hello World!
$ cd target/classes && java com.foo.app.App
Hello World!
To double check your class and package name, you can use Java class file disassembler tool, e.g.:
$ javap target/classes/com/foo/app/App.class
Compiled from "App.java"
public class com.foo.app.App {
public com.foo.app.App();
public static void main(java.lang.String[]);
}
Note: javap
won't work if the compiled file has been obfuscated.
Yes of course, function are objects and can be passed, but of course you must declare it:
function firstFunction(){
//some code
var callbackfunction = function(data){
//do something with the data returned from the ajax request
}
//a callback function is written for $.post() to execute
secondFunction("var1","var2",callbackfunction);
}
an interesting thing is that your callback function has also access to every variable you might have declared inside firstFunction() (variables in javascript have local scope).
Subclass UILabel, and override -drawInRect:
Grep DOES NOT use "wildcards" for search – that's shell globbing, like *.jpg. Grep uses "regular expressions" for pattern matching. While in the shell '*' means "anything", in grep it means "match the previous item zero or more times".
More information and examples here: http://www.regular-expressions.info/reference.html
To answer of your question - you can find files matching some pattern with grep:
find /somedir -type f -print | grep 'LMN2011' # that will show files whose names contain LMN2011
Then you can search their content (case insensitive):
find /somedir -type f -print | grep -i 'LMN2011' | xargs grep -i 'LMN20113456'
If the paths can contain spaces, you should use the "zero end" feature:
find /somedir -type f -print0 | grep -iz 'LMN2011' | xargs -0 grep -i 'LMN20113456'
replace code in onClick() method with this:
Intent myIntent = new Intent(this, Katra_home.class);
startActivity(myIntent);
Have a look at this sample:
public class A {
//statements
}
public class B extends A {
public void foo() { }
}
A a=new B();
//To execute **foo()** method.
((B)a).foo();
You just need:
if (!empty($_POST['search_term']) && !empty($_POST['postcode']))
isset && !empty
is redundant.
Used pattern :
ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"
Used reference file:
'<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>'
Example for Input:
<input type="number" require ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"><input type="submit">
I thought I'd try code this up for fun:
graph = {
'1': ['2', '3', '4'],
'2': ['5', '6'],
'5': ['9', '10'],
'4': ['7', '8'],
'7': ['11', '12']
}
def bfs(graph, forefront, end):
# assumes no cycles
next_forefront = [(node, path + ',' + node) for i, path in forefront if i in graph for node in graph[i]]
for node,path in next_forefront:
if node==end:
return path
else:
return bfs(graph,next_forefront,end)
print bfs(graph,[('1','1')],'11')
# >>>
# 1, 4, 7, 11
If you want cycles you could add this:
for i, j in for_front: # allow cycles, add this code
if i in graph:
del graph[i]
In the .NET world AOP isn't too popular, so for DI a framework is your only real option, whether you write one yourself or use another framework.
If you used AOP you can inject when you compile your application, which is more common in Java.
There are many benefits to DI, such as reduced coupling so unit testing is easier, but how will you implement it? Do you want to use reflection to do it yourself?
The CD / DVD wanted to be on the IDE controller on my system, not the SATA controller
You can also use events to trigger the Popdown.
Here's a fiddle based on satchmorun's solution. It dispenses with the PopdownAPI, and the top-level controller instead $broadcast
s 'success' and 'error' events down the scope chain:
$scope.success = function(msg) { $scope.$broadcast('success', msg); };
$scope.error = function(msg) { $scope.$broadcast('error', msg); };
The Popdown module then registers handler functions for these events, e.g:
$scope.$on('success', function(event, msg) {
$scope.status = 'success';
$scope.message = msg;
$scope.toggleDisplay();
});
This works, at least, and seems to me to be a nicely decoupled solution. I'll let others chime in if this is considered poor practice for some reason.
Why not just use separate console.log()
for each var, and separate with a comma rather than converting them all to strings? That would give you separate lines, AND give you the true value of each variable rather than the string representation of each (assuming they may not all be strings).
console.log('roleName',roleName);
console.log('role_ID',role_ID);
console.log('modal_ID',modal_ID);
console.log('related',related);
And I think it would be easier to read/maintain.
extension UIView {
func applyGradient(isVertical: Bool, colorArray: [UIColor]) {
layer.sublayers?.filter({ $0 is CAGradientLayer }).forEach({ $0.removeFromSuperlayer() })
let gradientLayer = CAGradientLayer()
gradientLayer.colors = colorArray.map({ $0.cgColor })
if isVertical {
//top to bottom
gradientLayer.locations = [0.0, 1.0]
} else {
//left to right
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
}
backgroundColor = .clear
gradientLayer.frame = bounds
layer.insertSublayer(gradientLayer, at: 0)
}
}
USAGE
someView.applyGradient(isVertical: true, colorArray: [.green, .blue])
HTML Code:
<form method="post" action="#" id="#">
<div class="form-group files color">
<input type="file" class="form-control" multiple="">
</div>
CSS:
.files input {
outline: 2px dashed #92b0b3;
outline-offset: -10px;
-webkit-transition: outline-offset .15s ease-in-out, background-color .15s linear;
transition: outline-offset .15s ease-in-out, background-color .15s linear;
padding: 120px 0px 85px 35%;
text-align: center !important;
margin: 0;
width: 100% !important;
height: 400px;
}
.files input:focus{
outline: 2px dashed #92b0b3;
outline-offset: -10px;
-webkit-transition: outline-offset .15s ease-in-out, background-color .15s linear;
transition: outline-offset .15s ease-in-out, background-color .15s linear;
border:1px solid #92b0b3;
}
.files{ position:relative}
.files:after { pointer-events: none;
position: absolute;
top: 60px;
left: 0;
width: 50px;
right: 0;
height: 400px;
content: "";
background-image: url('../../images/');
display: block;
margin: 0 auto;
background-size: 100%;
background-repeat: no-repeat;
}
.color input{ background-color:#f1f1f1;}
.files:before {
position: absolute;
bottom: 10px;
left: 0; pointer-events: none;
width: 100%;
right: 0;
height: 400px;
display: block;
margin: 0 auto;
color: #2ea591;
font-weight: 600;
text-transform: capitalize;
text-align: center;
}
public static Set<Double> getMode(double[] data) {
if (data.length == 0) {
return new TreeSet<>();
}
TreeMap<Double, Integer> map = new TreeMap<>(); //Map Keys are array values and Map Values are how many times each key appears in the array
for (int index = 0; index != data.length; ++index) {
double value = data[index];
if (!map.containsKey(value)) {
map.put(value, 1); //first time, put one
}
else {
map.put(value, map.get(value) + 1); //seen it again increment count
}
}
Set<Double> modes = new TreeSet<>(); //result set of modes, min to max sorted
int maxCount = 1;
Iterator<Integer> modeApperance = map.values().iterator();
while (modeApperance.hasNext()) {
maxCount = Math.max(maxCount, modeApperance.next()); //go through all the value counts
}
for (double key : map.keySet()) {
if (map.get(key) == maxCount) { //if this key's value is max
modes.add(key); //get it
}
}
return modes;
}
//std dev function for good measure
public static double getStandardDeviation(double[] data) {
final double mean = getMean(data);
double sum = 0;
for (int index = 0; index != data.length; ++index) {
sum += Math.pow(Math.abs(mean - data[index]), 2);
}
return Math.sqrt(sum / data.length);
}
public static double getMean(double[] data) {
if (data.length == 0) {
return 0;
}
double sum = 0.0;
for (int index = 0; index != data.length; ++index) {
sum += data[index];
}
return sum / data.length;
}
//by creating a copy array and sorting it, this function can take any data.
public static double getMedian(double[] data) {
double[] copy = Arrays.copyOf(data, data.length);
Arrays.sort(copy);
return (copy.length % 2 != 0) ? copy[copy.length / 2] : (copy[copy.length / 2] + copy[(copy.length / 2) - 1]) / 2;
}
Even adding responseType, I dealt with it for days with no success. Finally I got it. Make sure that in your backend script you don't define header as -("Content-Type: application/json);
Becuase if you turn it to text but backend asks for json, it will return an error...
One way to do it is:
isVisible(elm) {
while(elm.tagName != 'BODY') {
if(!$(elm).visible()) return false;
elm = elm.parentNode;
}
return true;
}
Credits: https://github.com/atetlaw/Really-Easy-Field-Validation/blob/master/validation.js#L178
1) Should i use Double or double???
Double
and double
is the same thing. double
is just a C# keyword working as alias for the class System.Double
The most common thing is to use the aliases! The same for string
(System.String
), int
(System.Int32
)
Also see Built-In Types Table (C# Reference)
To loop over the key/values, use a for in
loop:
for (let key in myDictionary) {
let value = myDictionary[key];
// Use `key` and `value`
}
You can also check whether an element is in set or not while inserting the element. The single element version return a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the equivalent element already in the set. The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent element already existed.
For example: Suppose the set already has 20 as an element.
std::set<int> myset;
std::set<int>::iterator it;
std::pair<std::set<int>::iterator,bool> ret;
ret=myset.insert(20);
if(ret.second==false)
{
//do nothing
}
else
{
//do something
}
it=ret.first //points to element 20 already in set.
If the element is newly inserted than pair::first will point to the position of new element in set.
I use this function which is saved in .bash_profile and it works a treat for me.
function show_hidden () {
{ defaults write com.apple.finder AppleShowAllFiles $1; killall -HUP Finder; }
}
How to use:
show_hidden true|false
We could do without any xxxFactory
, xxxManager
or xxxRepository
classes if we modeled the real world correctly:
Universe.Instance.Galaxies["Milky Way"].SolarSystems["Sol"]
.Planets["Earth"].Inhabitants.OfType<Human>().WorkingFor["Initech, USA"]
.OfType<User>().CreateNew("John Doe");
;-)
<style>
.row-2 UL LI A
{
margin-top: 10px; /* or whatever amount you need it to move down */
}
</style>
Set both :focusable
and :focusableInTouchMode
to true and call requestFocus
. It does the trick.
Whenever the Python interpreter reads a source file, it does two things:
it sets a few special variables like __name__
, and then
it executes all of the code found in the file.
Let's see how this works and how it relates to your question about the __name__
checks we always see in Python scripts.
Let's use a slightly different code sample to explore how imports and scripts work. Suppose the following is in a file called foo.py
.
# Suppose this is foo.py.
print("before import")
import math
print("before functionA")
def functionA():
print("Function A")
print("before functionB")
def functionB():
print("Function B {}".format(math.sqrt(100)))
print("before __name__ guard")
if __name__ == '__main__':
functionA()
functionB()
print("after __name__ guard")
When the Python interpreter reads a source file, it first defines a few special variables. In this case, we care about the __name__
variable.
When Your Module Is the Main Program
If you are running your module (the source file) as the main program, e.g.
python foo.py
the interpreter will assign the hard-coded string "__main__"
to the __name__
variable, i.e.
# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__"
When Your Module Is Imported By Another
On the other hand, suppose some other module is the main program and it imports your module. This means there's a statement like this in the main program, or in some other module the main program imports:
# Suppose this is in some other main program.
import foo
The interpreter will search for your foo.py
file (along with searching for a few other variants), and prior to executing that module, it will assign the name "foo"
from the import statement to the __name__
variable, i.e.
# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"
After the special variables are set up, the interpreter executes all the code in the module, one statement at a time. You may want to open another window on the side with the code sample so you can follow along with this explanation.
Always
It prints the string "before import"
(without quotes).
It loads the math
module and assigns it to a variable called math
. This is equivalent to replacing import math
with the following (note that __import__
is a low-level function in Python that takes a string and triggers the actual import):
# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")
It prints the string "before functionA"
.
It executes the def
block, creating a function object, then assigning that function object to a variable called functionA
.
It prints the string "before functionB"
.
It executes the second def
block, creating another function object, then assigning it to a variable called functionB
.
It prints the string "before __name__ guard"
.
Only When Your Module Is the Main Program
__name__
was indeed set to "__main__"
and it calls the two functions, printing the strings "Function A"
and "Function B 10.0"
.Only When Your Module Is Imported by Another
__name__
will be "foo"
, not "__main__"
, and it'll skip the body of the if
statement.Always
"after __name__ guard"
in both situations.Summary
In summary, here's what'd be printed in the two cases:
# What gets printed if foo is the main program
before import
before functionA
before functionB
before __name__ guard
Function A
Function B 10.0
after __name__ guard
# What gets printed if foo is imported as a regular module
before import
before functionA
before functionB
before __name__ guard
after __name__ guard
You might naturally wonder why anybody would want this. Well, sometimes you want to write a .py
file that can be both used by other programs and/or modules as a module, and can also be run as the main program itself. Examples:
Your module is a library, but you want to have a script mode where it runs some unit tests or a demo.
Your module is only used as a main program, but it has some unit tests, and the testing framework works by importing .py
files like your script and running special test functions. You don't want it to try running the script just because it's importing the module.
Your module is mostly used as a main program, but it also provides a programmer-friendly API for advanced users.
Beyond those examples, it's elegant that running a script in Python is just setting up a few magic variables and importing the script. "Running" the script is a side effect of importing the script's module.
Question: Can I have multiple __name__
checking blocks? Answer: it's strange to do so, but the language won't stop you.
Suppose the following is in foo2.py
. What happens if you say python foo2.py
on the command-line? Why?
# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
def functionA():
print("a1")
from foo2 import functionB
print("a2")
functionB()
print("a3")
def functionB():
print("b")
print("t1")
if __name__ == "__main__":
print("m1")
functionA()
print("m2")
print("t2")
__name__
check in foo3.py
:# Suppose this is foo3.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
def functionA():
print("a1")
from foo3 import functionB
print("a2")
functionB()
print("a3")
def functionB():
print("b")
print("t1")
print("m1")
functionA()
print("m2")
print("t2")
# Suppose this is in foo4.py
__name__ = "__main__"
def bar():
print("bar")
print("before __name__ guard")
if __name__ == "__main__":
bar()
print("after __name__ guard")
Setting:
request.Referer = @"http://www.somesite.com/";
and adding cookies
than worked for me
Building of off an earlier example, I think there is a cleaner way of doing this. Create an index.html
file in your project and using Stephen's code from above, just convert it into an HTML doc.
<!DOCTYPE html>
<html>
<base target="_top">
<script>
function onSuccess(url) {
var a = document.createElement("a");
a.href = url;
a.target = "_blank";
window.close = function () {
window.setTimeout(function() {
google.script.host.close();
}, 9);
};
if (document.createEvent) {
var event = document.createEvent("MouseEvents");
if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) {
window.document.body.append(a);
}
event.initEvent("click", true, true);
a.dispatchEvent(event);
} else {
a.click();
}
close();
}
function onFailure(url) {
var div = document.getElementById('failureContent');
var link = '<a href="' + url + '" target="_blank">Process</a>';
div.innerHtml = "Failure to open automatically: " + link;
}
google.script.run.withSuccessHandler(onSuccess).withFailureHandler(onFailure).getUrl();
</script>
<body>
<div id="failureContent"></div>
</body>
<script>
google.script.host.setHeight(40);
google.script.host.setWidth(410);
</script>
</html>
Then, in your Code.gs
script, you can have something like the following,
function getUrl() {
return 'http://whatever.com';
}
function openUrl() {
var html = HtmlService.createHtmlOutputFromFile("index");
html.setWidth(90).setHeight(1);
var ui = SpreadsheetApp.getUi().showModalDialog(html, "Opening ..." );
}
This is where we appreciate all the power of CSS3:
.bloc {_x000D_
display: inline-block;_x000D_
vertical-align: top;_x000D_
overflow: hidden;_x000D_
border: solid grey 1px;_x000D_
}_x000D_
_x000D_
.bloc select {_x000D_
padding: 10px;_x000D_
margin: -5px -20px -5px -5px;_x000D_
}
_x000D_
<div class="bloc">_x000D_
<select name="year" size="5">_x000D_
<option value="2010">2010</option>_x000D_
<option value="2011">2011</option>_x000D_
<option value="2012" SELECTED>2012</option>_x000D_
<option value="2013">2013</option>_x000D_
<option value="2014">2014</option>_x000D_
</select>_x000D_
</div>
_x000D_
Do you have control over running the transformation? If so, you could pass in the current date to the XSL and use $current-date from inside your XSL. Below is how you declare the incoming parameter, but with knowing how you are running the transformation, I can't tell you how to pass in the value.
<xsl:param name="current-date" />
For example, from the bash script, use:
xsltproc --stringparam current-date `date +%Y-%m-%d` -o output.html path-to.xsl path-to.xml
Then, in the xsl you can use:
<xsl:value-of select="$current-date"/>
The commands below are for Mac but pretty similar to Linux (see the links below)
#Install pyenv
brew update
brew install pyenv
Let's say you have python 3.6 as your primary version on your mac:
python --version
Output:
Python <your current version>
pyenv install -l
Let's take 3.7.3:
pyenv install 3.7.3
Make sure to run this in the Terminal (add it to ~/.bashrc or ~/.zshrc):
export PATH="/Users/username/.pyenv:$PATH"
eval "$(pyenv init -)"
Now let's run it only on the opened terminal/shell:
pyenv shell 3.7.3
python --version
Output:
Python 3.7.3
And not less important unset it in the opened shell/iTerm:
pyenv shell --unset
Instead of using sed
to filter out the certificate, you can also pipe the openssl s_client
output through openssl x509 -out certfile.txt
, for example:
echo "" | openssl s_client -connect my.server.com:443 -showcerts 2>/dev/null | openssl x509 -out certfile.txt
According to 'Getting Started With LLVM Core Libraries' book (c):
In fact, the name LLVM might refer to any of the following:
The LLVM project/infrastructure: This is an umbrella for several projects that, together, form a complete compiler: frontends, backends, optimizers, assemblers, linkers, libc++, compiler-rt, and a JIT engine. The word "LLVM" has this meaning, for example, in the following sentence: "LLVM is comprised of several projects".
An LLVM-based compiler: This is a compiler built partially or completely with the LLVM infrastructure. For example, a compiler might use LLVM for the frontend and backend but use GCC and GNU system libraries to perform the final link. LLVM has this meaning in the following sentence, for example: "I used LLVM to compile C programs to a MIPS platform".
LLVM libraries: This is the reusable code portion of the LLVM infrastructure. For example, LLVM has this meaning in the sentence: "My project uses LLVM to generate code through its Just-in-Time compilation framework".
LLVM core: The optimizations that happen at the intermediate language level and the backend algorithms form the LLVM core where the project started. LLVM has this meaning in the following sentence: "LLVM and Clang are two different projects".
The LLVM IR: This is the LLVM compiler intermediate representation. LLVM has this meaning when used in sentences such as "I built a frontend that translates my own language to LLVM".
I was struggling with the same problem and found one solution. I guess it can help you.
when you run python manage.py runserver
, it will take 127.0.0.1 as default ip address and 8000 as default port number which can be configured in your python environment.
In your python setting, go to <your python env>\Lib\site-packages\django\core\management\commands\runserver.py
and set
1. default_port = '<your_port>'
2. find this under def handle and set
if not options.get('addrport'):
self.addr = '0.0.0.0'
self.port = self.default_port
Now if you run "python manage.py runserver" it will run by default on "0.0.0.0:
Enjoy coding .....
I'd just like to point out a third alternative which also works if the cursor is not at the start position:
if (cursor.moveToFirst()) {
do {
// do what you need with the cursor here
} while (cursor.moveToNext());
}
There are basically 3 approaches to that: not exists
, not in
and left join / is null
.
SELECT l.*
FROM t_left l
LEFT JOIN
t_right r
ON r.value = l.value
WHERE r.value IS NULL
SELECT l.*
FROM t_left l
WHERE l.value NOT IN
(
SELECT value
FROM t_right r
)
SELECT l.*
FROM t_left l
WHERE NOT EXISTS
(
SELECT NULL
FROM t_right r
WHERE r.value = l.value
)
Which one is better? The answer to this question might be better to be broken down to major specific RDBMS vendors. Generally speaking, one should avoid using select ... where ... in (select...)
when the magnitude of number of records in the sub-query is unknown. Some vendors might limit the size. Oracle, for example, has a limit of 1,000. Best thing to do is to try all three and show the execution plan.
Specifically form PostgreSQL, execution plan of NOT EXISTS
and LEFT JOIN / IS NULL
are the same. I personally prefer the NOT EXISTS
option because it shows better the intent. After all the semantic is that you want to find records in A that its pk do not exist in B.
Old but still gold, specific to PostgreSQL though: https://explainextended.com/2009/09/16/not-in-vs-not-exists-vs-left-join-is-null-postgresql/
After trying a few of these answers and finding they don't scale well with multiple links (for example the accepted answer requires a line of jquery for every link you have), I came across a way that requires minimal code to get working, and it also appears to work perfectly, at least on Chrome.
You add this line to activate it:
$('[data-toggle="popover"]').popover();
And these settings to your anchor links:
data-toggle="popover" data-trigger="hover"
See it in action here, I'm using the same imports as the accepted answer so it should work fine on older projects.
Redirect and Request dispatcher are two different methods to move form one page to another. if we are using redirect to a new page actually a new request is happening from the client side itself to the new page. so we can see the change in the URL. Since redirection is a new request the old request values are not available here.
There are basically two ways
store the previous value of window.onload
so your code can call a previous handler if present before or after your code executes
using the addEventListener
approach (that of course Microsoft doesn't like and requires you to use another different name).
The second method will give you a bit more safety if another script wants to use window.onload
and does it without thinking to cooperation but the main assumption for Javascript is that all the scripts will cooperate like you are trying to do.
Note that a bad script that is not designed to work with other unknown scripts will be always able to break a page for example by messing with prototypes, by contaminating the global namespace or by damaging the dom.
Well, if you don't want to do the work yourself (object
elements aren't really all that hard), you could always use Mike Alsup's Media plugin: http://jquery.malsup.com/media/
Solution from EvilRygy didn't worked for me. In Postgres you can do another workaround:
$ids = array(1,2,3,7,8,9);
$db = new PDO(...);
$stmt = $db->prepare(
'SELECT *
FROM table
WHERE id = ANY (string_to_array(:an_array, ','))'
);
$stmt->bindParam(':an_array', implode(',', $ids));
$stmt->execute();
First install openpyxl:
pip install openpyxl
Then:
from openpyxl import Workbook
import csv
wb = Workbook()
ws = wb.active
with open('test.csv', 'r') as f:
for row in csv.reader(f):
ws.append(row)
wb.save('name.xlsx')
Facing the blank screen in Laravel 5.8. Every thing seems fine with both storage and bootstrap folder given 777 rights. On
php artisan cache:clear
It shows the problem it was the White spaces in App Name of .env file
Set "VM options" like: "-cp $Classpath$;your_classpath"
The only (& even though cumbersome but yet expedient / relatively quick) way I can do this, is to concatenate the any-dimensional array, and reduce it to 1 dimension, with "/[column number]//\|" as the delimiter.
& use a single-cell result multiple lookupall macro function on the this 1-d column.
& then index match to pull out the positions. (usuing multiple find match)
That way you get all matching occurrences of the element/string your looking for, in the original any-dimension array, and their positions. In one cell.
Wish I could write a macro / function for this entire process. It would save me more fuss.
If you don't know the number of columns ahead of time, add each column to a list and cbind
at the end.
List <- list()
for(i in 1:n)
{
normF <- #something
List[[i]] <- normF
}
Matrix = do.call(cbind, List)
That works too:
document.querySelector([attribute="value"]);
So:
document.querySelector([data-foo="bar"]);
There is no one better solution; however, I would like to argue that double quotes may be more desirable at times:
"
to identify a passage of quoted text. If we were to use a single quote '
, the reader may misinterpret it as a contraction. The other meaning of a passage of text surrounded by the '
indicates the 'colloquial' meaning. It makes sense to stay consistent with pre-existing languages, and this may likely ease the learning and interpretation of code."I'm going to the mall"
, vs. the otherwise escaped version: 'I\'m going to the mall'
.Double quotes mean a string in many other languages. When you learn a new language like Java or C, double quotes are always used. In Ruby, PHP and Perl, single-quoted strings imply no backslash escapes while double quotes support them.
JSON notation is written with double quotes.
Nonetheless, as others have stated, it is most important to remain consistent.
echo "LOAD_SETTLED LOAD_INIT 2011-01-13 03:50:01" | awk -v var="test" 'BEGIN { FS = "[ \t]+" } ; { print $1 "\t" var "\t" $3 }'
While the functionalty is to a great extent the same (especially in the Turing sense), malicious tongues claim that Ruby was created for Pythonistas that could not split up with the Perlish coding style.
Unfortunately I found solutions presented by @dualed have various flaws.
Using substr($sapi_type, 0, 3) == 'cgi'
is not enogh to detect fast CGI. When using PHP-FPM FastCGI Process Manager, php_sapi_name()
returns fpm not cgi
Fasctcgi and php-fpm expose another bug mentioned by @Josh - using header('X-PHP-Response-Code: 404', true, 404);
does work properly under PHP-FPM (FastCGI)
header("HTTP/1.1 404 Not Found");
may fail when the protocol is not HTTP/1.1 (i.e. 'HTTP/1.0'). Current protocol must be detected using $_SERVER['SERVER_PROTOCOL']
(available since PHP 4.1.0
There are at least 2 cases when calling http_response_code()
result in unexpected behaviour:
For your reference here there is the full list of HTTP response status codes (this list includes codes from IETF internet standards as well as other IETF RFCs. Many of them are NOT currently supported by PHP http_response_code function): http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
You can easily test this bug by calling:
http_response_code(521);
The server will send "500 Internal Server Error" HTTP response code resulting in unexpected errors if you have for example a custom client application calling your server and expecting some additional HTTP codes.
My solution (for all PHP versions since 4.1.0):
$httpStatusCode = 521;
$httpStatusMsg = 'Web server is down';
$phpSapiName = substr(php_sapi_name(), 0, 3);
if ($phpSapiName == 'cgi' || $phpSapiName == 'fpm') {
header('Status: '.$httpStatusCode.' '.$httpStatusMsg);
} else {
$protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
header($protocol.' '.$httpStatusCode.' '.$httpStatusMsg);
}
Conclusion
http_response_code() implementation does not support all HTTP response codes and may overwrite the specified HTTP response code with another one from the same group.
The new http_response_code() function does not solve all the problems involved but make things worst introducing new bugs.
The "compatibility" solution offered by @dualed does not work as expected, at least under PHP-FPM.
The other solutions offered by @dualed also have various bugs. Fast CGI detection does not handle PHP-FPM. Current protocol must be detected.
Any tests and comments are appreciated.
First list all iptables rules with this command:
iptables -S
it lists like:
-A XYZ -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
Then copy the desired line, and just replace -A
with -D
to delete that:
iptables -D XYZ -p ...
if u r using navigation bar to change fragment then u can add change it where u r changing Fragment like below example :
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.clientsidedrawer:
// Toast.makeText(getApplicationContext(),"Client selected",Toast.LENGTH_SHORT).show();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new clients_fragment()).commit();
break;
case R.id.adddatasidedrawer:
getSupportActionBar().setTitle("Add Client");
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new addclient_fragment()).commit();
break;
case R.id.editid:
getSupportActionBar().setTitle("Edit Clients");
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Editclient()).commit();
break;
case R.id.taskid:
getSupportActionBar().setTitle("Task manager");
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new Taskmanager()).commit();
break;
if u r using simple activity then just call :
getSupportActionBar().setTitle("Contact Us");
to change actionbar/toolbar color in activity use :
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#06023b")));
to set gradient to actionbar first create gradient : Example directry created > R.drawable.gradient_contactus
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<gradient
android:angle="90"
android:startColor="#2980b9"
android:centerColor="#6dd5fa"
android:endColor="#2980b9">
</gradient>
</shape>
and then set it like this :
getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.gradient_contactus));
<style>
#outer { text-align: center; }
#inner { width:500px; text-align: left; margin: 0 auto; }
.t { float: left; width:240px; border: 1px solid black;}
#clearit { clear: both; }
</style>
I also noticed that you can provide a group of coroutines in wait() by simply specifying the list:
result=loop.run_until_complete(asyncio.wait([
say('first hello', 2),
say('second hello', 1),
say('third hello', 4)
]))
Whereas grouping in gather() is done by just specifying multiple coroutines:
result=loop.run_until_complete(asyncio.gather(
say('first hello', 2),
say('second hello', 1),
say('third hello', 4)
))
Put this two lines in style.css
In your specified div
class.
display: block;
margin: auto;
and then try to run it, you will be able to see that .svg aligned in the center.
You can install vim/vi for windows and set windows PATH variable and open it in command line.
Probably the best way to check for errors in runtime API code is to define an assert style handler function and wrapper macro like this:
#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
if (code != cudaSuccess)
{
fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
if (abort) exit(code);
}
}
You can then wrap each API call with the gpuErrchk
macro, which will process the return status of the API call it wraps, for example:
gpuErrchk( cudaMalloc(&a_d, size*sizeof(int)) );
If there is an error in a call, a textual message describing the error and the file and line in your code where the error occurred will be emitted to stderr
and the application will exit. You could conceivably modify gpuAssert
to raise an exception rather than call exit()
in a more sophisticated application if it were required.
A second related question is how to check for errors in kernel launches, which can't be directly wrapped in a macro call like standard runtime API calls. For kernels, something like this:
kernel<<<1,1>>>(a);
gpuErrchk( cudaPeekAtLastError() );
gpuErrchk( cudaDeviceSynchronize() );
will firstly check for invalid launch argument, then force the host to wait until the kernel stops and checks for an execution error. The synchronisation can be eliminated if you have a subsequent blocking API call like this:
kernel<<<1,1>>>(a_d);
gpuErrchk( cudaPeekAtLastError() );
gpuErrchk( cudaMemcpy(a_h, a_d, size * sizeof(int), cudaMemcpyDeviceToHost) );
in which case the cudaMemcpy
call can return either errors which occurred during the kernel execution or those from the memory copy itself. This can be confusing for the beginner, and I would recommend using explicit synchronisation after a kernel launch during debugging to make it easier to understand where problems might be arising.
Note that when using CUDA Dynamic Parallelism, a very similar methodology can and should be applied to any usage of the CUDA runtime API in device kernels, as well as after any device kernel launches:
#include <assert.h>
#define cdpErrchk(ans) { cdpAssert((ans), __FILE__, __LINE__); }
__device__ void cdpAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
if (code != cudaSuccess)
{
printf("GPU kernel assert: %s %s %d\n", cudaGetErrorString(code), file, line);
if (abort) assert(0);
}
}
Here's a function that will do the trick:
def myformat(x):
return ('%.2f' % x).rstrip('0').rstrip('.')
And here are your examples:
>>> myformat(1.00)
'1'
>>> myformat(1.20)
'1.2'
>>> myformat(1.23)
'1.23'
>>> myformat(1.234)
'1.23'
>>> myformat(1.2345)
'1.23'
Edit:
From looking at other people's answers and experimenting, I found that g does all of the stripping stuff for you. So,
'%.3g' % x
works splendidly too and is slightly different from what other people are suggesting (using '{0:.3}'.format() stuff). I guess take your pick.
selected disabled="true"
Use this. It will work in new browsers
The only way I found to overcome this problem is by executing the last statement with print.
Do not forget that cell magic starts with %%
and line magic starts with %
.
%%time
clf = tree.DecisionTreeRegressor().fit(X_train, y_train)
res = clf.predict(X_test)
print(res)
Notice that any changes performed inside the cell are not taken into consideration in the next cells, something that is counter intuitive when there is a pipeline:
char originalString[] = "THESTRINGHASNOSPACES";
char aux[5];
int j=0;
for(int i=0;i<strlen(originalString);i++){
aux[j] = originalString[i];
if(j==3){
aux[j+1]='\0';
printf("%s\n",aux);
j=0;
}else{
j++;
}
}
jScrollPane is a good solution to cross browser scrollbars and degrades nicely.
Solved in my case, i look at
sudo tail -f /var/log/nginx/error.log
and error is php5-fpm.sock not found
I look at sudo ls -lah /var/run/
there was no php5-fpm.sock
I edit the www.conf
sudo vim /etc/php5/fpm/pool.d/www.conf
change
listen = 127.0.0.1:9000
for
listen = /var/run/php5-fpm.sock
and reboot
This is because the element hadn't been loaded at the time when the bundle js was being executed.
I'd move the <script src="sample.js" type="text/javascript"></script>
to the very bottom of the index.html
file. This way you can ensure script is executed after all the html elements have been parsed and rendered .
JLS§14.14.1, The basic for Statement, makes it clear that the ForUpdate expression(s) are evaluated and the value(s) are discarded. The effect is to make the two forms identical in the context of a for
statement.
They are implemented in very different ways.
hash_map
(unordered_map
in TR1 and Boost; use those instead) use a hash table where the key is hashed to a slot in the table and the value is stored in a list tied to that key.
map
is implemented as a balanced binary search tree (usually a red/black tree).
An unordered_map
should give slightly better performance for accessing known elements of the collection, but a map
will have additional useful characteristics (e.g. it is stored in sorted order, which allows traversal from start to finish). unordered_map
will be faster on insert and delete than a map
.
On CENTOS 6 /etc/my.cnf , under [mysqld] section the correct syntax is:
[mysqld]
# added to avoid err "Got a packet bigger than 'max_allowed_packet' bytes"
#
net_buffer_length=1000000
max_allowed_packet=1000000000
#
library(plyr)
ddply(tbl, .(Category), summarise, sum = sum(Frequency))
For this, just needed simple lines not complicated
in your onBindViewHolder method add below code
final boolean isExpanded = position==mExpandedPosition;
holder.details.setVisibility(isExpanded?View.VISIBLE:View.GONE);
holder.itemView.setActivated(isExpanded);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mExpandedPosition = isExpanded ? -1:position;
notifyItemChanged(position);
}
});
mExpandedPosition is an int global variable initialized to -1
first declare a global variable with previousExpandedPosition = -1
then
final boolean isExpanded = position==mExpandedPosition;
holder.details.setVisibility(isExpanded?View.VISIBLE:View.GONE);
holder.itemView.setActivated(isExpanded);
if (isExpanded)
previousExpandedPosition = position;
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mExpandedPosition = isExpanded ? -1:position;
notifyItemChanged(previousExpandedPosition);
notifyItemChanged(position);
}
});
Done!!!. Simple and humble .. :)
How about this? Here you split the array using the length you want to have.
a = np.random.randint(0,10,[4,4])
a
Out[27]:
array([[1, 5, 8, 7],
[3, 2, 4, 0],
[7, 7, 6, 2],
[7, 4, 3, 0]])
a[0:2,:]
Out[28]:
array([[1, 5, 8, 7],
[3, 2, 4, 0]])
a[2:4,:]
Out[29]:
array([[7, 7, 6, 2],
[7, 4, 3, 0]])
I understand that the answer was useful however for some reason it does not work for me however I have moved the situation with the following code and it is perfect
<?php
$codigoarticulo = $_POST['codigoarticulo'];
$nombrearticulo = $_POST['nombrearticulo'];
$seccion = $_POST['seccion'];
$precio = $_POST['precio'];
$fecha = $_POST['fecha'];
$importado = $_POST['importado'];
$paisdeorigen = $_POST['paisdeorigen'];
try {
$server = 'mysql: host=localhost; dbname=usuarios';
$user = 'root';
$pass = '';
$base = new PDO($server, $user, $pass);
$base->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$base->query("SET character_set_results = 'utf8',
character_set_client = 'utf8',
character_set_connection = 'utf8',
character_set_database = 'utf8',
character_set_server = 'utf8'");
$base->exec("SET character_set_results = 'utf8',
character_set_client = 'utf8',
character_set_connection = 'utf8',
character_set_database = 'utf8',
character_set_server = 'utf8'");
$sql = "
INSERT INTO productos
(CÓDIGOARTÍCULO, NOMBREARTÍCULO, SECCIÓN, PRECIO, FECHA, IMPORTADO, PAÍSDEORIGEN)
VALUES
(:c_art, :n_art, :sec, :pre, :fecha_art, :import, :p_orig)";
// SE ejecuta la consulta ben prepare
$result = $base->prepare($sql);
// se pasan por parametros aqui
$result->bindParam(':c_art', $codigoarticulo);
$result->bindParam(':n_art', $nombrearticulo);
$result->bindParam(':sec', $seccion);
$result->bindParam(':pre', $precio);
$result->bindParam(':fecha_art', $fecha);
$result->bindParam(':import', $importado);
$result->bindParam(':p_orig', $paisdeorigen);
$result->execute();
echo 'Articulo agregado';
} catch (Exception $e) {
echo 'Error';
echo $e->getMessage();
} finally {
}
?>
No,its check like if string is "john" OR "mary" OR "peter" OR "etc."
you should check using ||
Like.,,if(str.equals("john") || str.equals("mary") || str.equals("peter"))
I had similar problem with the data frame:
group time weight.loss
1 Control wl1 4.500000
2 Diet wl1 5.333333
3 DietEx wl1 6.200000
4 Control wl2 3.333333
5 Diet wl2 3.916667
6 DietEx wl2 6.100000
7 Control wl3 2.083333
8 Diet wl3 2.250000
9 DietEx wl3 2.200000
I think the variable for x axis should be numeric, so that geom_line knows how to connect the points to draw the line.
after I change the 2nd column to numeric:
group time weight.loss
1 Control 1 4.500000
2 Diet 1 5.333333
3 DietEx 1 6.200000
4 Control 2 3.333333
5 Diet 2 3.916667
6 DietEx 2 6.100000
7 Control 3 2.083333
8 Diet 3 2.250000
9 DietEx 3 2.200000
then it works.
You had thead
in your selector, but there is no thead
in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr
class to the th
, not vice-versa (although your comment seems to contradict what you wrote up above).
$('tr th').each(function(index){ if($('tr td').eq(index).attr('class') != ''){ // get the class of the td var tdClass = $('tr td').eq(index).attr('class'); // add it to this th $(this).addClass(tdClass ); } });
Just for completeness: Stream solution since Java 8.
final String[] shiftedArray = Arrays.stream(array)
.skip(1)
.toArray(String[]::new);
I think I sticked with the System.arraycopy()
in your situtation. But the best long-term solution might be to convert everything to Immutable Collections (Guava, Vavr), as long as those collections are short-lived.
With mongoose it's as simple as:
collection.find().sort('-date').exec(function(err, collectionItems) {
// here's your code
})
You need to open the file first. This doesn't work:
json_file = json.load('test.json')
But this works:
f = open('test.json')
json_file = json.load(f)
In Laravel 6.2
Add the following route to : web.php
Route::post('logout', 'Auth\LoginController@logout')->name('logout');
Using Achor tag with logout using a POST form. This way you will also need the CSRF token.
<a class="log-out-btn" href="#" onclick="event.preventDefault();document.getElementById('logout-form').submit();"> Logout </a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
Late, but since I had the same problem I add my solution:
function newFile(data, fileName) {
var json = JSON.stringify(data);
//IE11 support
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
let blob = new Blob([json], {type: "application/json"});
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {// other browsers
let file = new File([json], fileName, {type: "application/json"});
let exportUrl = URL.createObjectURL(file);
window.location.assign(exportUrl);
URL.revokeObjectURL(exportUrl);
}
}
Use DateTime Structure with milliseconds and format like this:
string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff",
CultureInfo.InvariantCulture);
timestamp = timestamp.Replace("-", ".");
Are you sure you can't alter the HTML in the popup window?
If you can, add a <script>
tag at the end of the popup's HTML, and call window.print()
inside it. Then it won't be called until the HTML has loaded.
For me i had already created a folder with name excel in wwroot D:\working directory\OnlineExam\wwwroot\excel And i was trying to copy a file with name excel which was already existing as a folder name. the path which was required was D:\working directory\OnlineExam\wwwroot\excel\finance.csv so according i changed the code as below
string copyPath = Path.Combine(_webHostEnvironment.WebRootPath, "excel\\finance");
questionExcelUpload.Upload.CopyTo(new FileStream(copyPath, FileMode.Create));
Basically check if a folder or a file with same name as your path exist already.
Try this:
$('element').attr('id', 'value');
So it becomes;
$(function() {
$('span .breadcrumb').each(function(){
$('#nav').attr('id', $(this).text());
$('#container').attr('id', $(this).text());
$('.stretch_footer').attr('id', $(this).text())
$('#footer').attr('id', $(this).text());
});
});
So you are changing/overwriting the id of three elements and adding an id to one element. You can modify as per you needs...
I tried many but this worked fine for me.
npm config rm proxy
npm config rm https-proxy
above 2 commands is enough if it doesn't work try this as well.
npm config --global rm proxy
npm config --global rm https-proxy
this command solve my problem on github CI job and virtualbox
brew install [email protected]
cp /usr/local/opt/[email protected]/lib/pkgconfig/*.pc /usr/local/lib/pkgconfig/
The best way to work with already created tables is that, Go to Sql Server Query Editor
Type: sp_help <tablename>
This will show table's structure , see the details for the desired field under COLLATE column.
then type in the query like :
SELECT myColumn FROM myTable
WHERE myColumn COLLATE SQL_Latin1_General_CP1_CI_AS = 'Case'
It could be different character schema <SQL_Latin1_General_CP1_CI_AS
>, so better to find out the exact schema that has been used against that column.
Try this way:
select * from tab
where DateCol between DateAdd(DD,-7,GETDATE() ) and GETDATE()
Try setting the initial value when you instantiate the form:
form = MyForm(initial={'max_number': '3'})
Easy quick solution which worked for me. 1. Go to the root folder. Copy the default.aspx file. 2. Delete the original file. 3. Rename the copied file to default.aspx.
Its all set to experiment again. Not sure how sharepoint referencing these webparts in that page. But works :)
This is a safety measure to avoid pushing branches that are not ready to be published. Loosely speaking, by executing "git push", only local branches that already exist on the server with the same name will be pushed, or branches that have been pushed using the localbranch:remotebranch syntax.
To push all local branches to the remote repository, use --all
:
git push REMOTENAME --all
git push --all
or specify all branches you want to push:
git push REMOTENAME master exp-branch-a anotherbranch bugfix
In addition, it's useful to add -u
to the "git push" command, as this will tell you if your local branch is ahead or behind the remote branch. This is shown when you run "git status" after a git fetch.
You want to use http.request
to create a similar request to the remote API and return its response.
Something like this:
const http = require('http');
// or use import http from 'http';
/* your app config here */
app.post('/api/BLABLA', (oreq, ores) => {
const options = {
// host to forward to
host: 'www.google.com',
// port to forward to
port: 80,
// path to forward to
path: '/api/BLABLA',
// request method
method: 'POST',
// headers to send
headers: oreq.headers,
};
const creq = http
.request(options, pres => {
// set encoding
pres.setEncoding('utf8');
// set http status code based on proxied response
ores.writeHead(pres.statusCode);
// wait for data
pres.on('data', chunk => {
ores.write(chunk);
});
pres.on('close', () => {
// closed, let's end client request as well
ores.end();
});
pres.on('end', () => {
// finished, let's finish client request as well
ores.end();
});
})
.on('error', e => {
// we got an error
console.log(e.message);
try {
// attempt to set error message and http status
ores.writeHead(500);
ores.write(e.message);
} catch (e) {
// ignore
}
ores.end();
});
creq.end();
});
Notice: I haven't really tried the above, so it might contain parse errors hopefully this will give you a hint as to how to get it to work.
No, you cannot.
From SQL Server Books Online:
User-defined functions cannot be used to perform actions that modify the database state.
Ref.
I tried all of the other answers first but none of them seemed to work so I set the pear path statically in the pear config file
C:\xampp\php\pear\Config.php
find this code:
if (!defined('PEAR_INSTALL_DIR') || !PEAR_INSTALL_DIR) {
$PEAR_INSTALL_DIR = PHP_LIBDIR . DIRECTORY_SEPARATOR . 'pear';
}
else {
$PEAR_INSTALL_DIR = PEAR_INSTALL_DIR;
}
and just replace it with this:
$PEAR_INSTALL_DIR = "C:\\xampp\\php\\pear";
I restarted apache and used the command:
pear config-all
make sure the all of the paths no longer start with C:\php\pear
The isinstance
built-in is the preferred way if you really must, but even better is to remember Python's motto: "it's easier to ask forgiveness than permission"!-) (It was actually Grace Murray Hopper's favorite motto;-). I.e.:
def my_print(text, begin, end):
"Print 'text' in UPPER between 'begin' and 'end' in lower"
try:
print begin.lower() + text.upper() + end.lower()
except (AttributeError, TypeError):
raise AssertionError('Input variables should be strings')
This, BTW, lets the function work just fine on Unicode strings -- without any extra effort!-)
You can use simple way for genarate RSA . Use rsa library
pip install rsa
A simple way to achieve what you want:
import cv2
s_img = cv2.imread("smaller_image.png")
l_img = cv2.imread("larger_image.jpg")
x_offset=y_offset=50
l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img
I suppose you want to take care of the alpha channel too. Here is a quick and dirty way of doing so:
s_img = cv2.imread("smaller_image.png", -1)
y1, y2 = y_offset, y_offset + s_img.shape[0]
x1, x2 = x_offset, x_offset + s_img.shape[1]
alpha_s = s_img[:, :, 3] / 255.0
alpha_l = 1.0 - alpha_s
for c in range(0, 3):
l_img[y1:y2, x1:x2, c] = (alpha_s * s_img[:, :, c] +
alpha_l * l_img[y1:y2, x1:x2, c])
Mozilla has a simple way for drawing SVG on canvas called "Drawing DOM objects into a canvas"
If you want to load modules from a path relative to where the script runs, such as from a "lib" subfolder", you need to use one of the following:
$PSScriptRoot
which works when invoked as a script, such as via the PowerShell command
$psISE.CurrentFile.FullPath
which works when you're running inside ISE
But if you're in neither, and just typing away within a PowerShell shell, you can use:
pwd.Path
You can could assign one of the three to a variable called $base
depending on the environment you're running under, like so:
$base=$(if ($psISE) {Split-Path -Path $psISE.CurrentFile.FullPath} else {$(if ($global:PSScriptRoot.Length -gt 0) {$global:PSScriptRoot} else {$global:pwd.Path})})
Then in your scripts, you can use it like so:
Import-Module $base\lib\someConstants.psm1
Import-Module $base\lib\myCoolPsModule1.psm1
#etc.
Since you are asking for space between
, I would add an override to the last item to get rid of the extra margin there:
li {_x000D_
background: red;_x000D_
margin-bottom: 40px;_x000D_
}_x000D_
_x000D_
li:last-child {_x000D_
margin-bottom: 0px;_x000D_
}_x000D_
_x000D_
ul {_x000D_
background: silver;_x000D_
padding: 1px; _x000D_
padding-left: 40px;_x000D_
}
_x000D_
<ul>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
</ul>
_x000D_
The result of it might not be visual at all times, because of margin-collapsing and stuff... in the example snippets I've included, I've added a small 1px padding
to the ul
-element to prevent the collapsing. Try removing the li:last-child
-rule, and you'll see that the last item now extends the size of the ul
-element.
Try this:
df = spark.createDataFrame([('2018-07-27 10:30:00',)], ['Date_col'])
df.select(from_unixtime(unix_timestamp(df.Date_col, 'yyyy-MM-dd HH:mm:ss')).alias('dt_col'))
df.show()
+-------------------+
| Date_col|
+-------------------+
|2018-07-27 10:30:00|
+-------------------+
Might as well throw up an actual response with my solution, which was inspired by Peter Liljenberg's:
$ mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $12"%" }'
0.75%
This will use awk
to print out 100 minus the 12th field (idle), with a percentage sign after it. awk
will only do this for a line where the 12th field has numbers and dots only ($12 ~ /[0-9]+/
).
You can also average five samples, one second apart:
$ mpstat 1 5 | awk 'END{print 100-$NF"%"}'
Test it like this:
$ mpstat 1 5 | tee /dev/tty | awk 'END{print 100-$NF"%"}'
This one shows how to print only selected element on the page with dpi/resolution
adjustments
HTML:
<html>
<body>
<header>This is the header</header>
<div id="content">
This is the element you only want to capture
</div>
<button id="print">Download Pdf</button>
<footer>This is the footer</footer>
</body>
</html>
CSS:
body {
background: beige;
}
header {
background: red;
}
footer {
background: blue;
}
#content {
background: yellow;
width: 70%;
height: 100px;
margin: 50px auto;
border: 1px solid orange;
padding: 20px;
}
JS:
$('#print').click(function() {
var w = document.getElementById("content").offsetWidth;
var h = document.getElementById("content").offsetHeight;
html2canvas(document.getElementById("content"), {
dpi: 300, // Set to 300 DPI
scale: 3, // Adjusts your resolution
onrendered: function(canvas) {
var img = canvas.toDataURL("image/jpeg", 1);
var doc = new jsPDF('L', 'px', [w, h]);
doc.addImage(img, 'JPEG', 0, 0, w, h);
doc.save('sample-file.pdf');
}
});
});
http://tylenoly.wordpress.com/2010/10/27/how-to-finish-activity-with-results/
With a slight modification for "param_result"
/* Start Activity */
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClassName("com.thinoo.ActivityTest", "com.thinoo.ActivityTest.NewActivity");
startActivityForResult(intent,90);
}
/* Called when the second activity's finished */
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case 90:
if (resultCode == RESULT_OK) {
Bundle res = data.getExtras();
String result = res.getString("param_result");
Log.d("FIRST", "result:"+result);
}
break;
}
}
private void finishWithResult()
{
Bundle conData = new Bundle();
conData.putString("param_result", "Thanks Thanks");
Intent intent = new Intent();
intent.putExtras(conData);
setResult(RESULT_OK, intent);
finish();
}
There are two ways to specify label for element:
So, the proper way to find element's label is
var $element = $( ... )
var $label = $("label[for='"+$element.attr('id')+"']")
if ($label.length == 0) {
$label = $element.closest('label')
}
if ($label.length == 0) {
// label wasn't found
} else {
// label was found
}
For those using react-native
:
import React, {
Component,
StyleSheet,
} from 'react-native';
may produce this error.
Whereas referencing react
directly is the more stable way to go:
import React, { Component } from 'react';
import { StyleSheet } from 'react-native';
assertEquals
uses the equals
method for comparison. There is a different assert, assertSame
, which uses the ==
operator.
To understand why ==
shouldn't be used with strings you need to understand what ==
does: it does an identity check. That is, a == b
checks to see if a
and b
refer to the same object. It is built into the language, and its behavior cannot be changed by different classes. The equals
method, on the other hand, can be overridden by classes. While its default behavior (in the Object
class) is to do an identity check using the ==
operator, many classes, including String
, override it to instead do an "equivalence" check. In the case of String
, instead of checking if a
and b
refer to the same object, a.equals(b)
checks to see if the objects they refer to are both strings that contain exactly the same characters.
Analogy time: imagine that each String
object is a piece of paper with something written on it. Let's say I have two pieces of paper with "Foo" written on them, and another with "Bar" written on it. If I take the first two pieces of paper and use ==
to compare them it will return false
because it's essentially asking "are these the same piece of paper?". It doesn't need to even look at what's written on the paper. The fact that I'm giving it two pieces of paper (rather than the same one twice) means it will return false
. If I use equals
, however, the equals
method will read the two pieces of paper and see that they say the same thing ("Foo"), and so it'll return true
.
The bit that gets confusing with Strings is that the Java has a concept of "interning" Strings, and this is (effectively) automatically performed on any string literals in your code. This means that if you have two equivalent string literals in your code (even if they're in different classes) they'll actually both refer to the same String
object. This makes the ==
operator return true
more often than one might expect.
Adding the primary key worked for me too !
Once that is done, here's how to update the data model without deleting it -
Right click on the edmx Entity designer page and 'Update Model from Database'.
With a command
npm install -g @angular/cli@latest
It works fine, I am able to run ng command now.
You need to create installer, which will check if user has required .NET Framework 4.0. You can use WiX to create installer. It's very powerfull and customizable. Also you can use ClickOnce to create installer - it's very simple to use. It will allow you with one click add requirement to install .NET Framework 4.0.
Try std::find
vector<int>::iterator it = std::find(v.begin(), v.end(), 123);
if(it==v.end()){
std::cout<<"Element not found";
}
This worked for me...
private void BackupButtonClick(object sender, RoutedEventArgs e)
{
// FILE NAME WITH DATE DISTICNTION
string fileName = string.Format("SchoolBackup_{0}.bak", DateTime.Now.ToString("yyyy_MM_dd_h_mm_tt"));
try
{
// YOUR SEREVER OR MACHINE NAME
Server dbServer = new Server (new ServerConnection("DESKTOP"));
Microsoft.SqlServer.Management.Smo.Backup dbBackup = new Microsoft.SqlServer.Management.Smo.Backup()
{
Action = BackupActionType.Database,
Database = "School"
};
dbBackup.Devices.AddDevice(@backupDirectory() +"\\"+ fileName, DeviceType.File);
dbBackup.Initialize = true;
dbBackup.SqlBackupAsync(dbServer);
MessageBox.Show("Backup", "Backup Completed!");
}
catch(Exception err)
{
System.Windows.MessageBox.Show(err.ToString());
}
}
// THE DIRECTOTRY YOU WANT TO SAVE IN
public string backupDirectory()
{
using (var dialog = new FolderBrowserDialog())
{
var result = dialog.ShowDialog();
return dialog.SelectedPath;
}
}
Yep, the limit is set by the kernel; check out this thread on Stack Overflow for more details: Increasing the maximum number of tcp/ip connections in linux
To use arrow functions with function.prototype.call
, I made a helper function on the object prototype:
// Using
// @func = function() {use this here} or This => {use This here}
using(func) {
return func.call(this, this);
}
usage
var obj = {f:3, a:2}
.using(This => This.f + This.a) // 5
Edit
You don't NEED a helper. You could do:
var obj = {f:3, a:2}
(This => This.f + This.a).call(undefined, obj); // 5
Based on your patterns one improvement would be to change to using StartsWith instead of Contains. StartsWith need only iterate through each string until it finds the first mismatch instead of having to restart the search at every character position when it finds one.
Also, based on your patterns, it looks like you may be able to extract the first part of the path for myString, then reverse the comparison -- looking for the starting path of myString in the list of strings rather than the other way around.
string[] pathComponents = myString.Split( Path.DirectorySeparatorChar );
string startPath = pathComponents[0] + Path.DirectorySeparatorChar;
return listOfStrings.Contains( startPath );
EDIT: This would be even faster using the HashSet idea @Marc Gravell mentions since you could change Contains
to ContainsKey
and the lookup would be O(1) instead of O(N). You would have to make sure that the paths match exactly. Note that this is not a general solution as is @Marc Gravell's but is tailored to your examples.
Sorry for the C# example. I haven't had enough coffee to translate to VB.
From official documentation, FailedPreconditionError
This exception is most commonly raised when running an operation that reads a tf.Variable before it has been initialized.
In your case the error even explains what variable was not initialized: Attempting to use uninitialized value Variable_1
. One of the TF tutorials explains a lot about variables, their creation/initialization/saving/loading
Basically to initialize the variable you have 3 options:
tf.global_variables_initializer()
tf.variables_initializer(list_of_vars)
. Notice that you can use this function to mimic global_variable_initializer: tf.variable_initializers(tf.global_variables())
var_name.initializer
I almost always use the first approach. Remember you should put it inside a session run. So you will get something like this:
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
If your are curious about more information about variables, read this documentation to know how to report_uninitialized_variables
and check is_variable_initialized
.
if you use Windows 10, this is the directory:
C:\Users<UserName>\AppData\Local\
+
<ProjectName.exe_Url_somedata>\1.0.0.0<filename.config>
I also face the same problem. do the simple steps
There are no performance implications since the compiler will translate your lambda expression into an equivalent delegate. Lambda expressions are nothing more than a language feature that the compiler translates into the exact same code that you are used to working with.
The compiler will convert the code you have to something like this:
public partial class MyPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//snip
MyButton.Click += new EventHandler(delegate (Object o, EventArgs a)
{
//snip
});
}
}
If you're using Leopard (Mac OS X 10.5) or later, you can use the Instruments application to find and track memory leaks. After building your program in Xcode, select Run > Start with Performance Tool > Leaks.
Even if your app doesn't show any leaks, you may be keeping objects around too long. In Instruments, you can use the ObjectAlloc instrument for this. Select the ObjectAlloc instrument in your Instruments document, and bring up the instrument's detail (if it isn't already showing) by choosing View > Detail (it should have a check mark next to it). Under "Allocation Lifespan" in the ObjectAlloc detail, make sure you choose the radio button next to "Created & Still Living".
Now whenever you stop recording your application, selecting the ObjectAlloc tool will show you how many references there are to each still-living object in your application in the "# Net" column. Make sure you not only look at your own classes, but also the classes of your NIB files' top-level objects. For example, if you have no windows on the screen, and you see references to a still-living NSWindow, you may have not released it in your code.
301
is a cacheable response per HTTP RFC and browsers will cache it depending on the HTTP caching headers you have on the response. Use FireBug or Charles to examine response headers to know the exact duration the response will be cached for.
If you would like to control the caching duration, you can use the the HTTP response headers Cache-Control
and Expires
to do the same. Alternatively, if you don't want to cache the 301
response at all, use the following headers.
Cache-Control: no-store, no-cache, must-revalidate
Expires: Thu, 01 Jan 1970 00:00:00 GMT
There is a JSONObject constructor to turn a String into a JSONObject:
http://developer.android.com/reference/org/json/JSONObject.html#JSONObject(java.lang.String)
If you want to use $PSScriptRoot you can do
Join-Path -Path $PSScriptRoot -ChildPath ..\.. -Resolve
On my installation of SQL Server 2012 Developer Edition, installed with default settings, I just had to load the SQL Server Configuration Manager -> SQL Server Network Configuration -> Protocols for MSSQLSERVER and change TCP/IP from Disabled to Enabled.
Outputwise both are equivalent. Though the second expression goes through a top down lookup from the DOM root. You might want to avoid the additional overhead (however minuscule it may be) if you already have document.body object in hand for JQuery to wrap over. See http://api.jquery.com/jQuery/ #Selector Context
Makefile.am -- a user input file to automake
configure.in -- a user input file to autoconf
autoconf generates configure from configure.in
automake gererates Makefile.in from Makefile.am
configure generates Makefile from Makefile.in
For ex:
$]
configure.in Makefile.in
$] sudo autoconf
configure configure.in Makefile.in ...
$] sudo ./configure
Makefile Makefile.in
In WPF, you can easily do it in this way:
this.button.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Case: Light text with jaggy web font on dark background Firefox (v35)/Windows
Example: Google Web Font Ruda
Surprising solution -
adding following property to the applied selectors:
selector {
text-shadow: 0 0 0;
}
Actually, result is the same just with text-shadow: 0 0;
, but I like to explicitly set blur-radius.
It's not an universal solution, but might help in some cases. Moreover I haven't experienced (also not thoroughly tested) negative performance impacts of this solution so far.
Is there a way to get a list of all the keys in a Go language map?
ks := reflect.ValueOf(m).MapKeys()
how do I iterate over all the keys?
Use the accepted answer:
for k, _ := range m { ... }
You can use belw code for show and hide bootstrap model.
$('#my-model').on('shown.bs.modal', function (e) {
// do something here...
})
and if you want to hide model then you can use below code.
$('#my-model').on('hidden.bs.modal', function() {
// do something here...
});
I hope this answer is useful for your project.
Wrap the code within $(document).ready(function(){...........});
handler , also remove the ;
after if
$(document).ready(function(){
$('#purpose').on('change', function() {
if ( this.value == '1')
//.....................^.......
{
$("#business").show();
}
else
{
$("#business").hide();
}
});
});
pip install --download
is deprecated. Starting from version 8.0.0 you should use pip download
command:
pip download <package-name>
Consider using a package to automatically generate inline styles from your css files. A good one is Grunt Critical or Critical css for Laravel.
Create a Java archive (.jar) file using NetBeans as follows:
Clean and Build will first delete build artifacts (such as .class
files), whereas Build will retain any existing .class
files, creating new versions necessary. To elucidate, imagine a project with two classes, A and B.
When built the first time, the IDE creates A.class
and B.class
. Now you delete B.java
but don't clear out B.class
. Executing Build should leave B.class
in the build directory, and bundle it into the JAR. Selecting Clean and Build will delete B.class
. Since B.java
was deleted, no longer will B.class
be bundled.
The JAR file is built. To view it inside NetBeans:
Ensure files aren't being excluded when building the JAR file.
I had a similar issue. I resolved it by changing
<basicHttpBinding>
to
<basicHttpsBinding>
and also changed my URL to use https:// instead of http://.
Also in <endpoint> node, change
binding="basicHttpBinding"
to
binding="basicHttpsBinding"
This worked.
I got the same problem and my solution was to remove webconfig file from the directory.. then it works..
SOLUTION
As stated by others very well, HTTP_REFERER is set by the local machine of the user, specifically the browser, which means it's not reliable for security. However, this still is entirely the way in which Google Analytics monitors where you're getting your visitors from, so, it can actually be useful to check, exclude, include, etc..
If you think you should see an HTTP_REFERER and do not, add this to your PHP code, preferably at the top:
ini_set('session.referer_check', 'TRUE');
A more appropriate long-term solution, of course, is to actually update your php.ini or equivalent file. This is a nice and quick way of verifying, though.
TESTING
Run print($_SERVER['HTTP_REFERER']);
on your site, go to google.com, inspect some text, edit it to be <a href="https://example.com">LINK!</a>
, apply the change, then click the link. If it works, all is well and running precisely!
But maybe $_SERVER is wrong, or the test above says it's broken. Update your page with this, and then test again...
<script type="text/javascript">
console.log("REFER!" + document.referrer + "|" + location.referrer + "|");
</script>
USES
I use HTTP REFERER to block spam sites in GoogleAnalytics. Below is a graph focusing on one particular website's referrals. From 0 to 44 in one day, it wasn't caused by real users. It was caused by a botted site trying to get my attention to buy their services. But it just started because php.ini was updated to ignore the referer, which meant these spam, junk garbage sites were not getting their appropriate ERROR 403, "Access Denied."
For boolean fields in Rails 3.2.6 at least, this will work in your migration.
def change
add_column :users, :eula_accepted, :boolean, default: false
end
Putting a 1
or 0
for a default will not work here, since it is a boolean field. It must be a true
or false
value.
The col
argument in the plot
function assign colors automatically to a vector of integers. If you convert iris$Species
to numeric, notice you have a vector of 1,2 and 3s So you can apply this as:
plot(iris$Sepal.Length, iris$Sepal.Width, col=as.numeric(iris$Species))
Suppose you want red, blue and green instead of the default colors, then you can simply adjust it:
plot(iris$Sepal.Length, iris$Sepal.Width, col=c('red', 'blue', 'green')[as.numeric(iris$Species)])
You can probably see how to further modify the code above to get any unique combination of colors.
Sorry but that's just much too much overhead (above), short and quick, if you have the MapFragment, you also have to map, just do the following:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true)
} else {
// Show rationale and request permission.
}
Code is in Kotlin, hope you don't mind.
have fun
Btw I think this one is a duplicate of: Show Current Location inside Google Map Fragment
I was looking for a way to do this in the terminal and filter lines in the normal "grep behaviour". Have your strings in a file strings.txt
:
string1
string2
...
Then you can build a regular expression like (string1|string2|...)
and use it for filtering:
cmd1 | grep -P "($(cat strings.txt | tr '\n' '|' | head -c -1))" | cmd2
Edit: Above only works if you don't use any regex characters, if escaping is required, it could be done like:
cat strings.txt | python3 -c "import re, sys; [sys.stdout.write(re.escape(line[:-1]) + '\n') for line in sys.stdin]" | ...
Set the property RetainSameConnection
on the Connection Manager
to True
so that temporary table created in one Control Flow task can be retained in another task.
Here is a sample SSIS package written in SSIS 2008 R2
that illustrates using temporary tables.
Create a stored procedure that will create a temporary table named ##tmpStateProvince
and populate with few records. The sample SSIS package will first call the stored procedure and then will fetch the temporary table data to populate the records into another database table. The sample package will use the database named Sora
Use the below create stored procedure script.
USE Sora;
GO
CREATE PROCEDURE dbo.PopulateTempTable
AS
BEGIN
SET NOCOUNT ON;
IF OBJECT_ID('TempDB..##tmpStateProvince') IS NOT NULL
DROP TABLE ##tmpStateProvince;
CREATE TABLE ##tmpStateProvince
(
CountryCode nvarchar(3) NOT NULL
, StateCode nvarchar(3) NOT NULL
, Name nvarchar(30) NOT NULL
);
INSERT INTO ##tmpStateProvince
(CountryCode, StateCode, Name)
VALUES
('CA', 'AB', 'Alberta'),
('US', 'CA', 'California'),
('DE', 'HH', 'Hamburg'),
('FR', '86', 'Vienne'),
('AU', 'SA', 'South Australia'),
('VI', 'VI', 'Virgin Islands');
END
GO
Create a table named dbo.StateProvince
that will be used as the destination table to populate the records from temporary table. Use the below create table script to create the destination table.
USE Sora;
GO
CREATE TABLE dbo.StateProvince
(
StateProvinceID int IDENTITY(1,1) NOT NULL
, CountryCode nvarchar(3) NOT NULL
, StateCode nvarchar(3) NOT NULL
, Name nvarchar(30) NOT NULL
CONSTRAINT [PK_StateProvinceID] PRIMARY KEY CLUSTERED
([StateProvinceID] ASC)
) ON [PRIMARY];
GO
Create an SSIS package using Business Intelligence Development Studio (BIDS)
. Right-click on the Connection Managers tab at the bottom of the package and click New OLE DB Connection...
to create a new connection to access SQL Server 2008 R2 database.
Click New...
on Configure OLE DB Connection Manager.
Perform the following actions on the Connection Manager dialog.
Native OLE DB\SQL Server Native Client 10.0
from Provider since the package will connect to SQL Server 2008 R2 databaseMACHINENAME\INSTANCE
Use Windows Authentication
from Log on to the server section or whichever you prefer.Select or enter a database name
, the sample uses the database name Sora
.Test Connection
OK
on the Test connection succeeded message.OK
on Connection ManagerThe newly created data connection will appear on Configure OLE DB Connection Manager. Click OK
.
OLE DB connection manager KIWI\SQLSERVER2008R2.Sora
will appear under the Connection Manager tab at the bottom of the package. Right-click the connection manager and click Properties
Set the property RetainSameConnection
on the connection KIWI\SQLSERVER2008R2.Sora
to the value True
.
Right-click anywhere inside the package and then click Variables
to view the variables pane. Create the following variables.
A new variable named PopulateTempTable
of data type String
in the package scope SO_5631010
and set the variable with the value EXEC dbo.PopulateTempTable
.
A new variable named FetchTempData
of data type String
in the package scope SO_5631010
and set the variable with the value SELECT CountryCode, StateCode, Name FROM ##tmpStateProvince
Drag and drop an Execute SQL Task
on to the Control Flow tab. Double-click the Execute SQL Task to view the Execute SQL Task Editor.
On the General
page of the Execute SQL Task Editor, perform the following actions.
Create and populate temp table
OLE DB
KIWI\SQLSERVER2008R2.Sora
Variable
from SQLSourceTypeUser::PopulateTempTable
from SourceVariableOK
Drag and drop a Data Flow Task
onto the Control Flow tab. Rename the Data Flow Task as Transfer temp data to database table
. Connect the green arrow from the Execute SQL Task to the Data Flow Task.
Double-click the Data Flow Task
to switch to Data Flow tab. Drag and drop an OLE DB Source
onto the Data Flow tab. Double-click OLE DB Source to view the OLE DB Source Editor.
On the Connection Manager
page of the OLE DB Source Editor, perform the following actions.
KIWI\SQLSERVER2008R2.Sora
from OLE DB Connection ManagerSQL command from variable
from Data access modeUser::FetchTempData
from Variable nameColumns
pageClicking Columns
page on OLE DB Source Editor will display the following error because the table ##tmpStateProvince
specified in the source command variable does not exist and SSIS is unable to read the column definition.
To fix the error, execute the statement EXEC dbo.PopulateTempTable
using SQL Server Management Studio (SSMS) on the database Sora
so that the stored procedure will create the temporary table. After executing the stored procedure, click Columns
page on OLE DB Source Editor, you will see the column information. Click OK
.
Drag and drop OLE DB Destination
onto the Data Flow tab. Connect the green arrow from OLE DB Source to OLE DB Destination. Double-click OLE DB Destination
to open OLE DB Destination Editor.
On the Connection Manager
page of the OLE DB Destination Editor, perform the following actions.
KIWI\SQLSERVER2008R2.Sora
from OLE DB Connection ManagerTable or view - fast load
from Data access mode[dbo].[StateProvince]
from Name of the table or the viewMappings
pageClick Mappings
page on the OLE DB Destination Editor would automatically map the columns if the input and output column names are same. Click OK
. Column StateProvinceID
does not have a matching input column and it is defined as an IDENTITY
column in database. Hence, no mapping is required.
Data Flow tab should look something like this after configuring all the components.
Click the OLE DB Source
on Data Flow tab and press F4 to view Properties
. Set the property ValidateExternalMetadata
to False so that SSIS would not try to check for the existence of the temporary table during validation phase of the package execution.
Execute the query select * from dbo.StateProvince
in the SQL Server Management Studio (SSMS) to find the number of rows in the table. It should be empty before executing the package.
Execute the package. Control Flow shows successful execution.
In Data Flow tab, you will notice that the package successfully processed 6 rows. The stored procedure created early in this posted inserted 6 rows into the temporary table.
Execute the query select * from dbo.StateProvince
in the SQL Server Management Studio (SSMS) to find the 6 rows successfully inserted into the table. The data should match with rows founds in the stored procedure.
The above example illustrated how to create and use temporary table within a package.
I am using this example in my project:
html:
<hr class="my-3 dividerClass"/>
css:
.dividerClass{
border-top-color: #999
}