You might want to change the DNS settings of the Docker daemon. You can edit (or create) the configuration file at /etc/docker/daemon.json
with the dns key, as
{
"dns": ["your_dns_address", "8.8.8.8"]
}
In the example above, the first element of the list is the address of your DNS server. The second item is the Google’s DNS which can be used when the first one is not available.
Before proceeding, save daemon.json and restart the docker service.
sudo service docker restart
Once fixed, retry to run the build command.
The problem is that the package that used to connect PHP to MySQL is deprecated (php5-mysql). If you install the new package,
sudo apt-get install php-mysql
this will automatically update Apache and PHP 7.
When installing Apache and PHP under Ubuntu 14.04, I needed to specifically enable php configs by issuing a2enmod php5-cgi
Any executable jar file Should run either by clicking or running using command prompt like java -jar app.jar (use "if path of jar contains space" - i.e. java -jar "C:\folder name\app.jar"). If your executable jar is not running, which means it is not created properly.
For better understanding, extract the jar file (or view using any tool, for windows 7-Zip is nice one) and check the file under /META-INF/MANIFEST.MF. If you find any entry like
Main-Class: your.package.name.ClaaswithMain - then it's fine, otherwise you have to provide it.
Be aware of appending Main-Class entry on MANIFEST.MF file, check where you are saving it!
I had a similar issue last week. It was easy to fix in my IDE (PyCharm).
Here was my fix:
Starting from PyCharm menu bar: File -> Settings... -> Editor -> File Encodings, then set: "IDE Encoding", "Project Encoding" and "Default encoding for properties files" ALL to UTF-8 and she now works like a charm.
Hope this helps!
If you need to keep the original array because you have other references to it that should be updated too, you can clear it without creating a new array by setting its length to zero:
A.length = 0;
Use the length
property of the [String]
type:
if ($dbUserName.length -gt 8) {
Write-Output "Please enter more than 8 characters."
$dbUserName = Read-Host "Re-enter database username"
}
Please note that you have to use -gt
instead of >
in your if
condition. PowerShell uses the following comparison operators to compare values and test conditions:
I used this way in my code
$(function(){
$('.block').affix();
})
Don't know another way of checking this, but this: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#getProperties()" implies "java.version" is a standard system property so I'd expect it to work with other JVMs.
For a native iOS 7 bar code scanner take a look at my project on GitHub:
revalidate
is called on a container once new components are added or old ones removed. this call is an instruction to tell the layout manager to reset based on the new component list. revalidate
will trigger a call to repaint what the component thinks are 'dirty regions.' Obviously not all of the regions on your JPanel
are considered dirty by the RepaintManager
.
repaint
is used to tell a component to repaint itself. It is often the case that you need to call this in order to cleanup conditions such as yours.
select id,first_name,gender,age,
rank() over(partition by gender order by age) rank_g
from person
CREATE TABLE person (id int, first_name varchar(20), age int, gender char(1));
INSERT INTO person VALUES (1, 'Bob', 25, 'M');
INSERT INTO person VALUES (2, 'Jane', 20, 'F');
INSERT INTO person VALUES (3, 'Jack', 30, 'M');
INSERT INTO person VALUES (4, 'Bill', 32, 'M');
INSERT INTO person VALUES (5, 'Nick', 22, 'M');
INSERT INTO person VALUES (6, 'Kathy', 18, 'F');
INSERT INTO person VALUES (7, 'Steve', 36, 'M');
INSERT INTO person VALUES (8, 'Anne', 25, 'F');
INSERT INTO person VALUES (9,'AKSH',32,'M');
Same for XAML's arc. Just close the 99.99% arc with a Z
and you've got a circle!
You'll need to get a compiler. The easiest way is probably to install XCode development environment from the CDs/DVDs you got with your Mac, which will give you gcc. Then you should be able compile it like
gcc -o mybinaryfile mysourcefile.c
I have combine two different answers:
Complete HTML missing tags
$string = strip_tags($strHTML);
$yourText = $strHTML;
if (strlen($string) > 350) {
$stringCut = substr($post->body, 0, 350);
$doc = new DOMDocument();
$doc->loadHTML($stringCut);
$yourText = $doc->saveHTML();
}
$yourText."...<a href=''>View More</a>"
After tried all above, still can't resolved my issue yet. But got new solution for my problem.
At server where you are going to make a request, there should be a entry of your virtual host.
sudo vim /etc/hosts
and insert
192.xxx.x.xx www.domain.com
The reason if you are making request from server to itself then, to resolve your virtual host or to identify it, server would need above stuff, otherwise server won't understand your requesting(origin) host.
This issue seems to like the following.
How to resolve repository certificate error in Gradle build
Below steps may help:
1. Add certificate to keystore-
Import some certifications into Android Studio JDK cacerts from Android Studio’s cacerts.
Android Studio’s cacerts may be located in
{your-home-directory}/.AndroidStudio3.0/system/tasks/cacerts
I used the following import command.
$ keytool -importkeystore -v -srckeystore {src cacerts} -destkeystore {dest cacerts}
2. Add modified cacert path to gradle.properties-
systemProp.javax.net.ssl.trustStore={your-android-studio-directory}\\jre\\jre\\lib\\security\\cacerts
systemProp.javax.net.ssl.trustStorePassword=changeit
SSH doesn't use the :
syntax when specifying a port. The easiest way to do this is to edit your ~/.ssh/config
file and add:
Host git.host.de Port 4019
Then specify just git.host.de
without a port number.
Another difference between a bare and non-bare repository is that a bare repository does not have a default remote origin repository:
~/Projects$ git clone --bare test bare
Initialized empty Git repository in /home/derek/Projects/bare/
~/Projects$ cd bare
~/Projects/bare$ git branch -a
* master
~/Projects/bare$ cd ..
~/Projects$ git clone test non-bare
Initialized empty Git repository in /home/derek/Projects/non-bare/.git/
~/Projects$ cd non-bare
~/Projects/non-bare$ git branch -a
* master
remotes/origin/HEAD -> origin/master
remotes/origin/master
From the manual page for git clone --bare
:
Also the branch heads at the remote are copied directly to corresponding local branch heads, without mapping them to refs/remotes/origin/. When this option is used, neither remote-tracking branches nor the related configuration variables are created.
Presumably, when it creates a bare repository, Git assumes that the bare repository will serve as the origin repository for several remote users, so it does not create the default remote origin. What this means is that basic git pull
and git push
operations won't work since Git assumes that without a workspace, you don't intend to commit any changes to the bare repository:
~/Projects/bare$ git push
fatal: No destination configured to push to.
~/Projects/bare$ git pull
fatal: /usr/lib/git-core/git-pull cannot be used without a working tree.
~/Projects/bare$
I think the best option is to use guide_legend
within guides
:
p + guides(fill=guide_legend(
keywidth=0.1,
keyheight=0.1,
default.unit="inch")
)
Note the use of default.unit
, no need to load grid
package.
Yea I came across the same problem, but luckily I only need the first element... - This is what I did for it.
private String getDefaultPlayerType()
{
String defaultPlayerType = "";
for(LinkedHashMap.Entry<String,Integer> entry : getLeagueByName(currentLeague).getStatisticsOrder().entrySet())
{
defaultPlayerType = entry.getKey();
break;
}
return defaultPlayerType;
}
If you need the last element as well - I'd look into how to reverse the order of your map - store it in a temp variable, access the first element in the reversed map(therefore it would be your last element), kill the temp variable.
Here's some good answers on how to reverse order a hashmap:
How to iterate hashmap in reverse order in Java
If you use help from the above link, please give them up-votes :) Hope this can help someone.
You are trying to call DeckOfCards::shuffle
with a deckOfCards
parameter:
deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck); // shuffle the cards in the deck
But the method takes a vector<Card>&
:
void deckOfCards::shuffle(vector<Card>& deck)
The compiler error messages are quite clear on this. I'll paraphrase the compiler as it talks to you.
Error:
[Error] no matching function for call to 'deckOfCards::shuffle(deckOfCards&)'
Paraphrased:
Hey, pal. You're trying to call a function called
shuffle
which apparently takes a single parameter of type reference-to-deckOfCards
, but there is no such function.
Error:
[Note] candidate is:
In file included from main.cpp
[Note] void deckOfCards::shuffle(std::vector&)
Paraphrased:
I mean, maybe you meant this other function called
shuffle
, but that one takes a reference-tovector<something>
.
Error:
[Note] no known conversion for argument 1 from 'deckOfCards' to 'std::vector&'
Which I'd be happy to call if I knew how to convert from a
deckOfCards
to avector
; but I don't. So I won't.
Try the following-sibling
axis (following-sibling::td
).
I once got into the same problem and found this solution with respect to my needs. It may help Some one.
<input type="number" placeholder="Enter 4 Digits" max="9999" min="0"
onKeyDown="if(this.value.length==4 && event.keyCode>47 && event.keyCode < 58)return false;"
/>
Happy Coding :)
The following solution can do it.
$(function() {_x000D_
$("button").on('click', function() {_x000D_
var data = "";_x000D_
var tableData = [];_x000D_
var rows = $("table tr");_x000D_
rows.each(function(index, row) {_x000D_
var rowData = [];_x000D_
$(row).find("th, td").each(function(index, column) {_x000D_
rowData.push(column.innerText);_x000D_
});_x000D_
tableData.push(rowData.join(","));_x000D_
});_x000D_
data += tableData.join("\n");_x000D_
$(document.body).append('<a id="download-link" download="data.csv" href=' + URL.createObjectURL(new Blob([data], {_x000D_
type: "text/csv"_x000D_
})) + '/>');_x000D_
_x000D_
_x000D_
$('#download-link')[0].click();_x000D_
$('#download-link').remove();_x000D_
});_x000D_
});
_x000D_
table {_x000D_
border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td,_x000D_
th {_x000D_
border: 1px solid #aaa;_x000D_
padding: 0.5rem;_x000D_
text-align: left;_x000D_
}_x000D_
_x000D_
td {_x000D_
font-size: 0.875rem;_x000D_
}_x000D_
_x000D_
.btn-group {_x000D_
padding: 1rem 0;_x000D_
}_x000D_
_x000D_
button {_x000D_
background-color: #fff;_x000D_
border: 1px solid #000;_x000D_
margin-top: 0.5rem;_x000D_
border-radius: 3px;_x000D_
padding: 0.5rem 1rem;_x000D_
font-size: 1rem;_x000D_
}_x000D_
_x000D_
button:hover {_x000D_
cursor: pointer;_x000D_
background-color: #000;_x000D_
color: #fff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Name</th>_x000D_
<th>Author</th>_x000D_
<th>Description</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>jQuery</td>_x000D_
<td>John Resig</td>_x000D_
<td>The Write Less, Do More, JavaScript Library.</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>React</td>_x000D_
<td>Jordan Walke</td>_x000D_
<td>React makes it painless to create interactive UIs.</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Vue.js</td>_x000D_
<td>Yuxi You</td>_x000D_
<td>The Progressive JavaScript Framework.</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
_x000D_
<div class="btn-group">_x000D_
<button>csv</button>_x000D_
</div>
_x000D_
I think the error is caused by the redundant ,
flutter:
uses-material-design: true, # <<< redundant , at the end of the line
assets:
- images/lake.jpg
I'd also suggest to create an assets
folder in the directory that contains the pubspec.yaml
file and move images
there and use
flutter:
uses-material-design: true
assets:
- assets/images/lake.jpg
The assets
directory will get some additional IDE support that you won't have if you put assets somewhere else.
To terminate a process you know the name of, try:
taskkill /IM notepad.exe
This will ask it to close, but it may refuse, offer to "save changes", etc. If you want to forcibly kill it, try:
taskkill /F /IM notepad.exe
The key is whether you are writing a single concatenation all in one place or accumulating it over time.
For the example you gave, there's no point in explicitly using StringBuilder. (Look at the compiled code for your first case.)
But if you are building a string e.g. inside a loop, use StringBuilder.
To clarify, assuming that hugeArray contains thousands of strings, code like this:
...
String result = "";
for (String s : hugeArray) {
result = result + s;
}
is very time- and memory-wasteful compared with:
...
StringBuilder sb = new StringBuilder();
for (String s : hugeArray) {
sb.append(s);
}
String result = sb.toString();
background-size: contain;
suits me
You can implement a class that holds the fields you have in your JSON
class MyData
{
public string t;
public bool a;
public object[] data;
public string[][] type;
}
and then use the generic version of DeserializeObject:
MyData tmp = JsonConvert.DeserializeObject<MyData>(json);
foreach (string typeStr in tmp.type[0])
{
// Do something with typeStr
}
Documentation: Serializing and Deserializing JSON
When you get this vague error message, you can find out the more specific error by running
SHOW ENGINE INNODB STATUS;
The most common reasons are that when creating a foreign key, both the referenced field and the foreign key field need to match:
Another cause of this error is:
You have defined a SET NULL condition though some of the columns are defined as NOT NULL.
Looks to me like to would be something like
library(tutoR)
format(1.128347132904321674821, 2)
Per a little online help.
I found another method: Is necessary to add the "android:maxWidth="40dp"" attribute. Of course, it may not work perfectly, but it gives a line break.
You can use the UpdateProgress control:
What are the advantages of having a contiguous block of memory? Specifically, why would I need to have a contiguous physical block of memory in a system call? Is there any reason I couldn't just use vmalloc?
From Google's "I'm Feeling Lucky" on vmalloc
:
kmalloc is the preferred way, as long as you don't need very big areas. The trouble is, if you want to do DMA from/to some hardware device, you'll need to use kmalloc, and you'll probably need bigger chunk. The solution is to allocate memory as soon as possible, before memory gets fragmented.
As we can see in ActionController::Base
, before_action
is just a new syntax for before_filter
.
However all before_filters
syntax are deprecated in Rails 5.0 and will be removed in Rails 5.1
Topshelf is an OSS project which was started after this question was answered and it makes Windows service much, MUCH easier.I highly recommend looking into it.
RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.
IE 6+ .......... compatible ? Firefox 2+ ..... compatible ? Safari 3.2+ .... compatible ? Chrome 3+ ...... compatible ? Opera 10+ ...... compatible ?
http://requirejs.org/docs/download.html
Add this to your project: https://requirejs.org/docs/release/2.3.5/minified/require.js
and take a look at this http://requirejs.org/docs/api.html
#php -i | grep php.ini
also will work too!
snow leopard is different to the "old" leopard therefore its not surprising that the sources won' work... you should probably wait till the official release on friday and oracle might be releasing a properly working sql version soon.
Eg:
Datatable newTable = new DataTable();
foreach(string s1 in list)
{
if (s1 != string.Empty) {
dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
foreach(DataRow dr in dvProducts.ToTable().Rows)
{
newTable.ImportRow(dr);
}
}
}
ListView1.DataSource = newTable;
ListView1.DataBind();
What's the first part of your Subversion repository URL?
I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.
If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.
The only way around that is to log into a local machine over the VPN, and then do everything from that system.
An else
block can often exist to complement functionality that occurs in every except
block.
try:
test_consistency(valuable_data)
except Except1:
inconsistency_type = 1
except Except2:
inconsistency_type = 2
except:
# Something else is wrong
raise
else:
inconsistency_type = 0
"""
Process each individual inconsistency down here instead of
inside the except blocks. Use 0 to mean no inconsistency.
"""
In this case, inconsistency_type
is set in each except block, so that behaviour is complemented in the no-error case in else
.
Of course, I'm describing this as a pattern that may turn up in your own code someday. In this specific case, you just set inconsistency_type
to 0 before the try
block anyway.
You use the built-in int
function, and pass it the base of the input number, i.e. 2
for a binary number:
>>> int('11111111', 2)
255
How about this?
/^[a-zA-ZÀ-ÖØ-öø-ÿ]+$/
Compare date time objects:
(I picked 10 days - Anything older than 10 days is "OLD", else "NEW")
$now = new DateTime();
$diff=date_diff($yourdate,$now);
$diff_days = $diff->format("%a");
if($diff_days > 10){
echo "OLD! " . $yourdate->format('m/d/Y');
}else{
echo "NEW! " . $yourdate->format('m/d/Y');
}
In this case the variable titled var
in the method Change
is assigned a reference to self.variable
, and you immediately assign a string to var
. It's no longer pointing to self.variable
. The following code snippet shows what would happen if you modify the data structure pointed to by var
and self.variable
, in this case a list:
>>> class PassByReference:
... def __init__(self):
... self.variable = ['Original']
... self.change(self.variable)
... print self.variable
...
... def change(self, var):
... var.append('Changed')
...
>>> q = PassByReference()
['Original', 'Changed']
>>>
I'm sure someone else could clarify this further.
What is the problem here is that you somehow installed into virtualenv using sudo
. Probably by accident. This means root
user will rewrite Python package data, making all file owned by root and your normal user cannot write those files anymore. Usually virtualenv should be used and owned by your normal UNIX user only.
You can fix the issue by changing UNIX file permissions pack to your user. Try:
$ sudo chown -R USERNAME /Users/USERNAME/Library/Logs/pip
$ sudo chown -R USERNAME /Users/USERNAME/Library/Caches/pip
then pip
should be able to write those files again.
I am using WebAPI 3 and was facing the same issue. The issue has resolve as @Rytis added his solution. And I think in WebAPI 3, we don't need to define method RegisterWebApi
.
My change was only in web.config file and is working.
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST" />
</customHeaders>
</httpProtocol>
Thanks for you solution @Rytis!
you can try:
Array(6).join('a').split(''); // returns ['a','a','a','a','a'] (5 times)
Update (01/06/2018):
Now you can have a set of characters repeating.
new Array(5).fill('a'); // give the same result as above;
// or
Array.from({ length: 5 }).fill('a')
Note: Check more about fill(...) and from(...) for compatibility and browser support.
Update (05/11/2019):
Another way, without using fill
or from
, that works for string of any length:
Array.apply(null, Array(3)).map(_ => 'abc') // ['abc', 'abc', 'abc']
Same as above answer. Adding for sake of completeness.
I think Adam was asking how to change umask value for all processes that tying to operate on /opt/lampp/htdocs
directory.
The user file-creation mode mask (umask) is use to determine the file permission for newly created files. It can be used to control the default file permission for new files.
so if you will use some kind of ftp program to upload files into /opt/lampp/htdocs
you need to configure your ftp server to use umask you want.
If files / directories be created for example by php, you need to modify php code
<?php
umask(0022);
// other code
?>
if you will create new files / folders from your bash session, you can set umask value in your shell profile ~/.bashrc
Or you can set up umask in /etc/bashrc
or /etc/profile
file for all users.
add the following to file:
umask 022
Sample umask Values and File Creation Permissions
If umask value set to User permission Group permission Others permission
000 all all all
007 all all none
027 all read / execute none
And to change permissions for already created files you can use find. Hope this helps.
i had same error but different situation. to me it happened out of the blue after a lot of time i could ssh successfully to my remote computer out there. after a lot of searching the solution to my problem were file permissions. it is strange of course because i didn't change any permissions in my computer or the remote one belonging to the ssh's files/directories. so from the good archlinux wiki here it is:
For the local machine do this:
$ chmod 700 ~/
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/id_ecdsa
For the remote machine do that:
$ chmod 700 ~/
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/authorized_keys
after that my ssh started to working again without the permission denied (publickey) thing.
Based on the answer by mouad, here's a more pythonic way to select the variables based on a prefix:
# All the vars that I want to get start with fruit_
fruit_apple = 1
fruit_carrot = 'f'
rotten = 666
prefix = 'fruit_'
sourcedict = locals()
fruitdict = { v[len(prefix):] : sourcedict[v]
for v in sourcedict
if v.startswith(prefix) }
# fruitdict = {'carrot': 'f', 'apple': 1}
You can even put that in a function with prefix and sourcedict as arguments.
The sleep man page says it is declared in <unistd.h>
.
Synopsis:
#include <unistd.h>
unsigned int sleep(unsigned int seconds);
I'm a fan of:
chooseCRANmirror()
Which will print the list of mirrors in the output (no worrying a popup window since you are running it from the terminal) and then you enter the number you want.
It is super easy by changing the heap size as it was mentioned. Just easily by going to Pycharm HELP -> Edit custom VM option ... and change it to:
-Xms2048m
-Xmx2048m
so if you have a table with a row like:
firstname lastname
Bill smith
you can do something like
select firstname + ' ' + lastname from thetable
and you will get "Bill Smith"
To accomplish this in all browsers you need to use a combination of @energee, @Richard and @Feuermurmel methods.
<a href="" style="display: block; z-index: 1;">
<object data="" style="z-index: -1; pointer-events: none;" />
</a>
Adding:
pointer-events: none;
makes it work in Firefox.display: block;
gets it working in Chrome, and Safari.z-index: 1; z-index: -1;
makes it work in IE as well.Just to keep it backward compatible I load Crockfords JSON-library from cloudflare CDN if no native JSON support is given (for simplicity using jQuery):
function winHasJSON(){
json_data = JSON.stringify(obj);
// ... (do stuff with json_data)
}
if(typeof JSON === 'object' && typeof JSON.stringify === 'function'){
winHasJSON();
} else {
$.getScript('//cdnjs.cloudflare.com/ajax/libs/json2/20121008/json2.min.js', winHasJSON)
}
begin
var_number := 10;
if var_number > 100 then
dbms_output.put_line(var_number||' is greater than 100');
else if var_number < 100 then
dbms_output.put_line(var_number||' is less than 100');
else
dbms_output.put_line(var_number||' is equal to 100');
end if;
end if;
This may also happen if you have a slash before the folder name:
path = '/folder1/folder2'
OSError: [Errno 13] Permission denied: '/folder1'
comes up with an error but this one works fine:
path = 'folder1/folder2'
I am using jquery for this. I mad a function to set desired height to the modal(You can change that according to your requirement).
Then I used Modal Shown event to call this function.
Remember not to use $("#modal").show()
rather use $("#modal").modal('show')
otherwise shown.bs.modal will not be fired.
That all I have for this scenario.
var offset=250; //You can set offset accordingly based on your UI_x000D_
function AdjustPopup() _x000D_
{_x000D_
$(".modal-body").css("height","auto");_x000D_
if ($(".modal-body:visible").height() > ($(window).height() - offset)) _x000D_
{_x000D_
$(".modal-body:visible").css("height", ($(window).height() - offset));_x000D_
}_x000D_
}_x000D_
//Execute the function on every trigger on show() event._x000D_
$(document).ready(function(){_x000D_
$('.modal').on('shown.bs.modal', function (e) {_x000D_
AdjustPopup();_x000D_
});_x000D_
});_x000D_
//Remember to show modal like this_x000D_
$("#MyModal").modal('show');
_x000D_
In some situations you can hide the shadow by another container. Eg, if there is a DIV above and below the DIV with the shadow, you can use position: relative; z-index: 1;
on the surrounding DIVs.
You can try this if you want date time string:
use Carbon\Carbon;
$current_date_time = Carbon::now()->toDateTimeString(); // Produces something like "2019-03-11 12:25:00"
If you want timestamp, you can try:
use Carbon\Carbon;
$current_timestamp = Carbon::now()->timestamp; // Produces something like 1552296328
<form id="form1" runat="server" onkeypress="return event.keyCode != 13;">
Add this Code In Your HTML Page...it will disable ...Enter Button..
With the Atom editor open, in the menu bar:
Click Atom >> Install Shell Commands
You should expect to see:
Potentially restart your terminal. (I did just out of habit, not sure if you need to)
Should be:
curl --cert certificate_file.pem:password https://www.example.com/some_protected_page
For non-printing characters, you can do the following:
Sharding is horizontal(row wise) database partitioning as opposed to vertical(column wise) partitioning which is Normalization. It separates very large databases into smaller, faster and more easily managed parts called data shards. It is a mechanism to achieve distributed systems.
Why do we need distributed systems?
You can read more here: Advantages of Distributed database
How sharding help achieve distributed system?
You can partition a search index into N partitions and load each index on a separate server. If you query one server, you will get 1/Nth of the results. So to get complete result set, a typical distributed search system use an aggregator that will accumulate results from each server and combine them. An aggregator also distribute query onto each server. This aggregator program is called MapReduce in big data terminology. In other words, Distributed Systems = Sharding + MapReduce (Although there are other things too).
Use a post-build action in your project, and add the commands to copy the offending DLL. The post-build action are written as a batch script.
The output directory can be referenced as $(OutDir)
. The project directory is available as $(ProjDir)
. Try to use relative pathes where applicable, so that you can copy or move your project folder without breaking the post-build action.
I'm late to the game, but an anonymous objects would do the trick:
[HttpGet]
public HttpResponseMessage Me(string hash)
{
HttpResponseMessage httpResponseMessage;
List<Something> somethings = ...
var returnObjects = somethings.Select(x => new {
Id = x.Id,
OtherField = x.OtherField
});
httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK,
new { result = true, somethings = returnObjects });
return httpResponseMessage;
}
Few tips that may help:
I came across this article in CSS optimization yesterday:
CSS profiling for ... optimization
A lot of useful info on CSS and what CSS causes the most performance drains.
I saw the following presentation on jQueryUK on "hidden secrets" in Googe Chrome (Canary) Dev Tools: DevTools Can do that. Check out the sections on Time to First Paint, repaints and costly CSS.
Also, if you are using a loader like requireJS you could have a look at one of the CSS loader plugins, called require-CSS, which uses CSSO - a optimzer that also does structural optimization, eg. merging blocks with identical properties. I used it a few times and it can save quite a lot of CSS from case to case.
Off the question: I second @Enzino in creating a sprite for all the small icons you are loading. The file sizes are so small it does not really warrant a server roundtrip for each icon. Also keep in mind the total number of concurrent http requests are browser can do. So requests for a larger number of small icons are "render-blocking" as well. Although an empty page compare to yours, I like how duckduckgo loads for example.
cat >> filename
This is text, perhaps pasted in from some other source.
Or else entered at the keyboard, doesn't matter.
^D
Essentially, you can dump any text you want into the file. CTRL-D sends an end-of-file signal, which terminates input and returns you to the shell.
var fs = require('fs');
var path = require('path');
exports.testDir = path.dirname(__filename);
exports.fixturesDir = path.join(exports.testDir, 'fixtures');
exports.libDir = path.join(exports.testDir, '../lib');
exports.tmpDir = path.join(exports.testDir, 'tmp');
exports.PORT = +process.env.NODE_COMMON_PORT || 12346;
// Read File
fs.readFile(exports.tmpDir+'/start.html', 'utf-8', function(err, content) {
if (err) {
got_error = true;
} else {
console.log('cat returned some content: ' + content);
console.log('this shouldn\'t happen as the file doesn\'t exist...');
//assert.equal(true, false);
}
});
You can use the | operator to combine querysets directly without needing Q objects:
result = Item.objects.filter(item.creator = owner) | Item.objects.filter(item.moderated = False)
(edit - I was initially unsure if this caused an extra query but @spookylukey pointed out that lazy queryset evaluation takes care of that)
in my case, i used a third-party library with header files and so file. i subclassed one class, and link error like this occurred when i try to instantiate my subclass.
as mentioned by @sergiy, knowning it could be the problem of 'rtti', i managed to workaround it by put the constructor implementation into separate .cpp file and apply '-fno-rtti' compile flags to the file. it works well.
as i am still not quite clear about the internal of this link error, i am not sure whether my solution is general. however, i think it worth a shot before trying the adaptor way as mentioned by @francois . and of course, if all source codes are available(not in my case), better do recompile with '-frtti' if possible.
one more thing, if you choose to try my solution, try make the separate file as simple as possible, and do not use some fancy features of C++. take special attention on boost related things, cause much of it depends on rtti.
Here is an example I came up with that wraps another class with a debouncer. This lends itself nicely to being made into a decorator/higher order function:
export class DebouncedThingy extends React.Component {
static ToDebounce = ['someProp', 'someProp2'];
constructor(props) {
super(props);
this.state = {};
}
// On prop maybe changed
componentWillReceiveProps = (nextProps) => {
this.debouncedSetState();
};
// Before initial render
componentWillMount = () => {
// Set state then debounce it from here on out (consider using _.throttle)
this.debouncedSetState();
this.debouncedSetState = _.debounce(this.debouncedSetState, 300);
};
debouncedSetState = () => {
this.setState(_.pick(this.props, DebouncedThingy.ToDebounce));
};
render() {
const restOfProps = _.omit(this.props, DebouncedThingy.ToDebounce);
return <Thingy {...restOfProps} {...this.state} />
}
}
plot(t)
is in this case the same as
plot(t[[1]], t[[2]])
As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1
:
> length(t)
[1] 4
> length(1)
[1] 1
In your second example you plot a list with elements named x
and y
, both vectors of length 2,
so plot
plots these two vectors.
Edit:
If you want to plot lines use
plot(t, type="l")
If you are on Mac OS Big Sur, then you probably have a messed up java installation. I found info on how to fix the issue with this article: https://knasmueller.net/how-to-install-java-openjdk-15-on-macos-big-sur
sudo mv openjdk-15.0.2_osx-x64_bin.tar.gz /Library/Java/JavaVirtualMachines/
cd /Library/Java/JavaVirtualMachines/
sudo tar -xzf openjdk-15.0.2_osx-x64_bin.tar.gz
sudo rm openjdk-15.0.2_osx-x64_bin.tar.gz
Note: it might be 15.0.3 or higher, depending on the date of your download.
/usr/libexec/java_home -v15
and copy the output.bash_profile
or .zshrc
file, depending on which shell you are using. You will probably have only one of these files existing in your home directory (~/.bash_profile
or ~/.zshrc
).JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-15.0.2.jdk/Contents/Home
source ~/.bash_profile
or source ~/.zshrc
java -v
const regex = /myRegexp/
console.log('Hello myRegexp!'.replace(regex, 'World')) // = Hello World!
_x000D_
The Regex literal notation is commonly used to create new instances of RegExp
regex needs no additional escaping
v
/ regex / gm
^ ^ ^
start end optional modifiers
As others sugguested, you can also use the new RegExp('myRegex')
constructor.
But you will have to be especially careful with escaping:
regex: 12\d45
matches: 12345
const regex = new RegExp('12\\d45')
const equalRegex = /12\d45/
If I can add my $0.02, I prefer using PascalCase as enum values in C.
In C, they are basically global, and PEER_CONNECTED gets really tiring as opposed to PeerConnected.
Breath of fresh air.
Literally, it makes me breathe easier.
In Java, it is possible to use raw enum names as long as you static import them from another class.
import static pkg.EnumClass.*;
Now, you can use the unqualified names, that you qualified in a different way already.
I am currently (thinking) about porting some C code to Java and currently 'torn' between choosing Java convention (which is more verbose, more lengthy, and more ugly) and my C style.
PeerConnected would become PeerState.CONNECTED except in switch statements, where it is CONNECTED.
Now there is much to say for the latter convention and it does look nice but certain "idiomatic phrases" such as if (s == PeerAvailable)
become like if (s == PeerState.AVAILABLE)
and nostalgically, this is a loss of meaning to me.
I think I still prefer the Java style because of clarity but I have a hard time looking at the screaming code.
Now I realize PascalCase is already widely used in Java but very confusing it would not really be, just a tad out of place.
__all__
affects how from foo import *
works.
Code that is inside a module body (but not in the body of a function or class) may use an asterisk (*
) in a from
statement:
from foo import *
The *
requests that all attributes of module foo
(except those beginning with underscores) be bound as global variables in the importing module. When foo
has an attribute __all__
, the attribute's value is the list of the names that are bound by this type of from
statement.
If foo
is a package and its __init__.py
defines a list named __all__
, it is taken to be the list of submodule names that should be imported when from foo import *
is encountered. If __all__
is not defined, the statement from foo import *
imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by __init__.py
.
Note that __all__
doesn't have to be a list. As per the documentation on the import
statement, if defined, __all__
must be a sequence of strings which are names defined or imported by the module. So you may as well use a tuple to save some memory and CPU cycles. Just don't forget a comma in case the module defines a single public name:
__all__ = ('some_name',)
See also Why is “import *” bad?
Above answers are in python2. So for python 3 users I am giving this answer. You can use the bellow code:
import pandas as pd
fields = ['star_name', 'ra']
df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
# See the keys
print(df.keys())
# See content in 'star_name'
print(df.star_name)
Things have changed a little in the way Charles provides HTTPS proxying.
First the certificates installation options have been moved to the help menu.
Help -> SSL Proxying -> Install Charles Root Certificate
Help -> SSL Proxying -> Install Charles Root Certificate in iOS Simulators
Second, starting in iOS 9 you must provide a NSAppTransportSecurity
option in your Info.plist
and if you want Charles to work properly as a man in the middle, you must add:
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
as part of the your domains see full example:
<key>NSExceptionDomains</key>
<dict>
<key>yourdomain.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
The reason being (I guess) that Charles at some point communicates in clear http after acting as the man in the middle https server.
Last step is to activate SSL Proxying for this domain in Charles (right click on domain and select Enable SSL Proxying)
I couldn't be more concise than this. For all your other needs and information, Google is your friend.
To close a windows form (System.Windows.Forms.Form) when one of its button is clicked: in Visual Studio, open the form in the designer, right click on the button and open its property page, then select the field DialogResult an set it to OK or the appropriate value.
Suggestions:
true
would allow appending text into the File if it exists. println(...)
on your PrintWriter, writing your new text into the file.close()
of the PrintWriter should be in the try's finally block.e.g.,
PrintWriter pw = null;
try {
File file = new File("fubars.txt");
FileWriter fw = new FileWriter(file, true);
pw = new PrintWriter(fw);
pw.println("Fubars rule!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (pw != null) {
pw.close();
}
}
Easy, no?
There's a new plugin which provides full theming for Eclipse:
http://brainwy.github.io/liclipse/
It's integrated with Eclipse Color Theme so that when a new theme is selected in preferences > general > appearance > color theme, the proper background is also applied to other parts of the IDE (theming everything or just views which are previously registered according to a combo in that same page).
And besides theming it provides a bunch of other things :)
This is a solution how to make autocomplete drop down list with VBA :
Firstly you need to insert a combo box into the worksheet and change its properties, and then running the VBA code to enable the autocomplete.
Get into the worksheet which contains the drop down list you want it to be autocompleted.
Before inserting the Combo box, you need to enable the Developer tab in the ribbon.
a). In Excel 2010 and 2013, click File > Options. And in the Options dialog box, click Customize Ribbon in the right pane, check the Developer box, then click the OK button.
b). In Outlook 2007, click Office button > Excel Options. In the Excel Options dialog box, click Popular in the right bar, then check the Show Developer tabin the Ribbon box, and finally click the OK button.
Then click Developer > Insert > Combo Box under ActiveX Controls.
Draw the combo box in current opened worksheet and right click it. Select Properties in the right-clicking menu.
Turn off the Design Mode with clicking Developer > Design Mode.
Right click on the current opened worksheet tab and click View Code.
Make sure that the current worksheet code editor is opened, and then copy and paste the below VBA code into it.
Code borrowed from extendoffice.com
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'Update by Extendoffice: 2018/9/21
Dim xCombox As OLEObject
Dim xStr As String
Dim xWs As Worksheet
Dim xArr
Set xWs = Application.ActiveSheet
On Error Resume Next
Set xCombox = xWs.OLEObjects("TempCombo")
With xCombox
.ListFillRange = ""
.LinkedCell = ""
.Visible = False
End With
If Target.Validation.Type = 3 Then
Target.Validation.InCellDropdown = False
Cancel = True
xStr = Target.Validation.Formula1
xStr = Right(xStr, Len(xStr) - 1)
If xStr = "" Then Exit Sub
With xCombox
.Visible = True
.Left = Target.Left
.Top = Target.Top
.Width = Target.Width + 5
.Height = Target.Height + 5
.ListFillRange = xStr
If .ListFillRange = "" Then
xArr = Split(xStr, ",")
Me.TempCombo.List = xArr
End If
.LinkedCell = Target.Address
End With
xCombox.Activate
Me.TempCombo.DropDown
End If
End Sub
Private Sub TempCombo_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Select Case KeyCode
Case 9
Application.ActiveCell.Offset(0, 1).Activate
Case 13
Application.ActiveCell.Offset(1, 0).Activate
End Select
End Sub
Click File > Close and Return to Microsoft Excel to close the Microsoft Visual Basic for Application window.
Now, just click the cell with drop down list, you can see the drop-down list is displayed as a combo box, then type the first letter into the box, the corresponding word will be completed automatically.
Note: This VBA code is not applied to merged cells.
Source : How To Autocomplete When Typing In Excel Drop Down List?
It's good practise to extend from a baseController
and implement some base functions
implement a function to check if the user instance is null like this
if the user form the Userinterface
then there is no user logged in
/**
*/
class BaseController extends AbstractController
{
/**
* @return User
*/
protected function getUser(): ?User
{
return parent::getUser();
}
/**
* @return bool
*/
protected function isUserLoggedIn(): bool
{
return $this->getUser() instanceof User;
}
}
You have to walk the objects using reflection. Be careful as you do:
byte
is theoretically 1 byte doesn't mean it takes just one in memory.HashMap
or somesuch using object-equals as the comparator to eliminate infinite loops.@jodonnell: I like the simplicity of your solution, but many objects aren't Serializable (so this would throw an exception), fields can be transient, and objects can override the standard methods.
private void processLine(String[] strings) {
Integer[] intarray=new Integer[strings.length];
for(int i=0;i<strings.length;i++) {
intarray[i]=Integer.parseInt(strings[i]);
}
for(Integer temp:intarray) {
System.out.println("convert int array from String"+temp);
}
}
If you don't want to use an EOF character for this, you can use StringTokenizer :
import java.util.*;
public class Test{
public static void main(){
Scanner sc = new Scanner (System.in);
System.out.print("Enter your sentence: ");
String s=sc.nextLine();
StringTokenizer st=new StringTokenizer(s," ");//" " is the delimiter here.
while (st.hasMoreTokens() ) {
String s1 = st.nextToken();
System.out.println(s1);
}
System.out.println("The loop has been ended");
}
}
This JavaScript must be working for all latest version browsers:
//Detect Browser
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
// At least Safari 3+: "[object HTMLElementConstructor]"
var isChrome = !!window.chrome && !isOpera; // Chrome 1+
var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6
var Host = window.location.host;
//Clear Basic Realm Authentication
if(isIE){
//IE
document.execCommand("ClearAuthenticationCache");
window.location = '/';
}
else if(isSafari)
{//Safari. but this works mostly on all browser except chrome
(function(safeLocation){
var outcome, u, m = "You should be logged out now.";
// IE has a simple solution for it - API:
try { outcome = document.execCommand("ClearAuthenticationCache") }catch(e){}
// Other browsers need a larger solution - AJAX call with special user name - 'logout'.
if (!outcome) {
// Let's create an xmlhttp object
outcome = (function(x){
if (x) {
// the reason we use "random" value for password is
// that browsers cache requests. changing
// password effectively behaves like cache-busing.
x.open("HEAD", safeLocation || location.href, true, "logout", (new Date()).getTime().toString())
x.send("");
// x.abort()
return 1 // this is **speculative** "We are done."
} else {
return
}
})(window.XMLHttpRequest ? new window.XMLHttpRequest() : ( window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : u ))
}
if (!outcome) {
m = "Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser."
}
alert(m);
window.location = '/';
// return !!outcome
})(/*if present URI does not return 200 OK for GET, set some other 200 OK location here*/)
}
else{
//Firefox,Chrome
window.location = 'http://log:out@'+Host+'/';
}
Just use a placeholder
tag in your input instead of value
The Babel docs describe this pretty concisely:
Babel includes a polyfill that includes a custom regenerator runtime and core.js.
This will emulate a full ES6 environment. This polyfill is automatically loaded when using babel-node and babel/register.
Make sure you require it at the entry-point to your application, before anything else is called. If you're using a tool like webpack, that becomes pretty simple (you can tell webpack to include it in the bundle).
If you're using a tool like gulp-babel
or babel-loader
, you need to also install the babel
package itself to use the polyfill.
Also note that for modules that affect the global scope (polyfills and the like), you can use a terse import to avoid having unused variables in your module:
import 'babel/polyfill';
Use a single backspace after each character
printf("hello wor\bl\bd\n");
There are lots of proposed solutions here, some more efficient than others, but perhaps not very readable. Here's one that may not be the most efficient, but certainly usable for most situations, and is quite concise and readable, leveraging Linq:
string stringToclean = "This is a test. Do not try this at home; you might get hurt. Don't believe it?";
var validPunctuation = new HashSet<char>(". -");
var cleanedVersion = new String(stringToclean.Where(x => (x >= 'A' && x <= 'Z') || (x >= 'a' && x <= 'z') || validPunctuation.Contains(x)).ToArray());
var cleanedLowercaseVersion = new String(stringToclean.ToLower().Where(x => (x >= 'a' && x <= 'z') || validPunctuation.Contains(x)).ToArray());
Try "py" instead of "python" from command line:
C:\Users\Cpsa>py
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
The "best" answer has already been submitted, but I thought I would add that you can use nested list comprehensions, as seen in the Python Tutorial.
Here is how you could get a transposed array:
def matrixTranspose( matrix ):
if not matrix: return []
return [ [ row[ i ] for row in matrix ] for i in range( len( matrix[ 0 ] ) ) ]
@alessioalex answer is a perfect demo for fresh node user. But anyway, it's hard to write checkAuth middleware into all routes except login, so it's better to move the checkAuth from every route to one entry with app.use. For example:
function checkAuth(req, res, next) {
// if logined or it's login request, then go next route
if (isLogin || (req.path === '/login' && req.method === 'POST')) {
next()
} else {
res.send('Not logged in yet.')
}
}
app.use('/', checkAuth)
Source control is best way to handle this problem, if you don't want to pay then try bitbucket
It's free, allows private repo for upto 5 members team.
Use the border-image : yourimage
property to set your image and scale it upto the entire border of your screen or window .
I solve it by download the reportviewer.exe and install it. After the installation, all related assemblies will be available in C:\Windows\assembly\GAC_MSIL, then you can refer it in web config
Make a batch file and call the bacth file in Window.open. Here how it works
in html
window.open('file://dotnet/sc/test.bat')
Enjoy..
$('#myDiv').hide();
or
$('#myDiv').slideUp();
or
$('#myDiv').fadeOut();
I had the following problem(s) with the existing answers to this question (and variations of this question on other stackoverflow threads):
Or, slightly more accurately:
My final solution, which loads the script before returning, AND has all scripts properly accessible in the debugger (for Chrome at least) is as follows:
WARNING: The following code should PROBABLY be used only in 'development' mode. (For 'release' mode I recommend prepackaging and minification WITHOUT dynamic script loading, or at least without eval).
//Code User TODO: you must create and set your own 'noEval' variable
require = function require(inFileName)
{
var aRequest
,aScript
,aScriptSource
;
//setup the full relative filename
inFileName =
window.location.protocol + '//'
+ window.location.host + '/'
+ inFileName;
//synchronously get the code
aRequest = new XMLHttpRequest();
aRequest.open('GET', inFileName, false);
aRequest.send();
//set the returned script text while adding special comment to auto include in debugger source listing:
aScriptSource = aRequest.responseText + '\n////# sourceURL=' + inFileName + '\n';
if(noEval)//<== **TODO: Provide + set condition variable yourself!!!!**
{
//create a dom element to hold the code
aScript = document.createElement('script');
aScript.type = 'text/javascript';
//set the script tag text, including the debugger id at the end!!
aScript.text = aScriptSource;
//append the code to the dom
document.getElementsByTagName('body')[0].appendChild(aScript);
}
else
{
eval(aScriptSource);
}
};
I see in your code that you are trying to pass an ARRAY to POST action. In that case follow below working code -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function submitForm() {
var roles = ["role1", "role2", "role3"];
jQuery.ajax({
type: "POST",
url: "@Url.Action("AddUser")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(roles),
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" value="Click" onclick="submitForm()"/>
And the controller action is going to be -
public ActionResult AddUser(List<String> Roles)
{
return null;
}
Then when you click on the button -
For the new android studio 1.2 you find the gradle vm args under:
File
- Settings
- Build, Execution, Deployment
- Build Tools
- Gradle
http://joda-time.sourceforge.net/quickstart.html
Each datetime class provides a variety of constructors. These include the Object constructor. This allows you to construct, for example, DateTime from the following objects:
* Date - a JDK instant
* Calendar - a JDK calendar
* String - in ISO8601 format
* Long - in milliseconds
* any Joda-Time datetime class
Here is the best: Multipart/mixed mime message with attachments and inline images
And image: https://www.qcode.co.uk/images/mime-nesting-structure.png
From: [email protected]
To: to@@qcode.co.uk
Subject: Example Email
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="MixedBoundaryString"
--MixedBoundaryString
Content-Type: multipart/related; boundary="RelatedBoundaryString"
--RelatedBoundaryString
Content-Type: multipart/alternative; boundary="AlternativeBoundaryString"
--AlternativeBoundaryString
Content-Type: text/plain;charset="utf-8"
Content-Transfer-Encoding: quoted-printable
This is the plain text part of the email.
--AlternativeBoundaryString
Content-Type: text/html;charset="utf-8"
Content-Transfer-Encoding: quoted-printable
<html>
<body>=0D
<img src=3D=22cid:masthead.png=40qcode.co.uk=22 width 800 height=3D80=
=5C>=0D
<p>This is the html part of the email.</p>=0D
<img src=3D=22cid:logo.png=40qcode.co.uk=22 width 200 height=3D60 =5C=
>=0D
</body>=0D
</html>=0D
--AlternativeBoundaryString--
--RelatedBoundaryString
Content-Type: image/jpgeg;name="logo.png"
Content-Transfer-Encoding: base64
Content-Disposition: inline;filename="logo.png"
Content-ID: <[email protected]>
amtsb2hiaXVvbHJueXZzNXQ2XHVmdGd5d2VoYmFmaGpremxidTh2b2hydHVqd255aHVpbnRyZnhu
dWkgb2l1b3NydGhpdXRvZ2hqdWlyb2h5dWd0aXJlaHN1aWhndXNpaHhidnVqZmtkeG5qaG5iZ3Vy
...
...
a25qbW9nNXRwbF0nemVycHpvemlnc3k5aDZqcm9wdHo7amlodDhpOTA4N3U5Nnkwb2tqMm9sd3An
LGZ2cDBbZWRzcm85eWo1Zmtsc2xrZ3g=
--RelatedBoundaryString
Content-Type: image/jpgeg;name="masthead.png"
Content-Transfer-Encoding: base64
Content-Disposition: inline;filename="masthead.png"
Content-ID: <[email protected]>
aXR4ZGh5Yjd1OHk3MzQ4eXFndzhpYW9wO2tibHB6c2tqOTgwNXE0aW9qYWJ6aXBqOTBpcjl2MC1t
dGlmOTA0cW05dGkwbWk0OXQwYVttaXZvcnBhXGtsbGo7emt2c2pkZnI7Z2lwb2F1amdpNTh1NDlh
...
...
eXN6dWdoeXhiNzhuZzdnaHQ3eW9zemlqb2FqZWt0cmZ1eXZnamhka3JmdDg3aXV2dWd5aGVidXdz
dhyuhehe76YTGSFGA=
--RelatedBoundaryString--
--MixedBoundaryString
Content-Type: application/pdf;name="Invoice_1.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;filename="Invoice_1.pdf"
aGZqZGtsZ3poZHVpeWZoemd2dXNoamRibngganZodWpyYWRuIHVqO0hmSjtyRVVPIEZSO05SVURF
SEx1aWhudWpoZ3h1XGh1c2loZWRma25kamlsXHpodXZpZmhkcnVsaGpnZmtsaGVqZ2xod2plZmdq
...
...
a2psajY1ZWxqanNveHV5ZXJ3NTQzYXRnZnJhZXdhcmV0eXRia2xhanNueXVpNjRvNWllc3l1c2lw
dWg4NTA0
--MixedBoundaryString
Content-Type: application/pdf;name="SpecialOffer.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;filename="SpecialOffer.pdf"
aXBvY21odWl0dnI1dWk4OXdzNHU5NTgwcDN3YTt1OTQwc3U4NTk1dTg0dTV5OGlncHE1dW4zOTgw
cS0zNHU4NTk0eWI4OTcwdjg5MHE4cHV0O3BvYTt6dWI7dWlvenZ1em9pdW51dDlvdTg5YnE4N3Z3
...
...
OTViOHk5cDV3dTh5bnB3dWZ2OHQ5dTh2cHVpO2p2Ymd1eTg5MGg3ajY4bjZ2ODl1ZGlvcjQ1amts
dfnhgjdfihn=
--MixedBoundaryString--
.
Schema multipart/related/alternative
Header
|From: email
|To: email
|MIME-Version: 1.0
|Content-Type: multipart/mixed; boundary="boundary1";
Message body
|multipart/mixed --boundary1
|--boundary1
| multipart/related --boundary2
| |--boundary2
| | multipart/alternative --boundary3
| | |--boundary3
| | |text/plain
| | |--boundary3
| | |text/html
| | |--boundary3--
| |--boundary2
| |Inline image
| |--boundary2
| |Inline image
| |--boundary2--
|--boundary1
|Attachment1
|--boundary1
|Attachment2
|--boundary1
|Attachment3
|--boundary1--
|
.
I have just tested Google Geocoder and got the same problem as you have. I noticed I only get the OVER_QUERY_LIMIT status once every 12 requests So I wait for 1 second (that's the minimum delay to wait) It slows down the application but less than waiting 1 second every request
info = getInfos(getLatLng(code)); //In here I call Google API
record(code, info);
generated++;
if(generated%interval == 0) {
holdOn(delay); // Every x requests, I sleep for 1 second
}
With the basic holdOn method :
private void holdOn(long delay) {
try {
Thread.sleep(delay);
} catch (InterruptedException ex) {
// ignore
}
}
Hope it helps
Just to share, I've developed my own script to do it. Feel free to use it. It generates "SELECT" statements that you can then run on the tables to generate the "INSERT" statements.
select distinct 'SELECT ''INSERT INTO ' + schema_name(ta.schema_id) + '.' + so.name + ' (' + substring(o.list, 1, len(o.list)-1) + ') VALUES ('
+ substring(val.list, 1, len(val.list)-1) + ');'' FROM ' + schema_name(ta.schema_id) + '.' + so.name + ';'
from sys.objects so
join sys.tables ta on ta.object_id=so.object_id
cross apply
(SELECT ' ' +column_name + ', '
from information_schema.columns c
join syscolumns co on co.name=c.COLUMN_NAME and object_name(co.id)=so.name and OBJECT_NAME(co.id)=c.TABLE_NAME and co.id=so.object_id and c.TABLE_SCHEMA=SCHEMA_NAME(so.schema_id)
where table_name = so.name
order by ordinal_position
FOR XML PATH('')) o (list)
cross apply
(SELECT '''+' +case
when data_type = 'uniqueidentifier' THEN 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''' END '
WHEN data_type = 'timestamp' then '''''''''+CONVERT(NVARCHAR(MAX),CONVERT(BINARY(8),[' + COLUMN_NAME + ']),1)+'''''''''
WHEN data_type = 'nvarchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
WHEN data_type = 'varchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
WHEN data_type = 'char' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
WHEN data_type = 'nchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
when DATA_TYPE='datetime' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],121)+'''''''' END '
when DATA_TYPE='datetime2' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],121)+'''''''' END '
when DATA_TYPE='geography' and column_name<>'Shape' then 'ST_GeomFromText(''POINT('+column_name+'.Lat '+column_name+'.Long)'') '
when DATA_TYPE='geography' and column_name='Shape' then '''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''''
when DATA_TYPE='bit' then '''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''''
when DATA_TYPE='xml' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE(CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + ']),'''''''','''''''''''')+'''''''' END '
WHEN DATA_TYPE='image' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),CONVERT(VARBINARY(MAX),[' + COLUMN_NAME + ']),1)+'''''''' END '
WHEN DATA_TYPE='varbinary' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],1)+'''''''' END '
WHEN DATA_TYPE='binary' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],1)+'''''''' END '
when DATA_TYPE='time' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''' END '
ELSE 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE CONVERT(NVARCHAR(MAX),['+column_name+']) END' end
+ '+'', '
from information_schema.columns c
join syscolumns co on co.name=c.COLUMN_NAME and object_name(co.id)=so.name and OBJECT_NAME(co.id)=c.TABLE_NAME and co.id=so.object_id and c.TABLE_SCHEMA=SCHEMA_NAME(so.schema_id)
where table_name = so.name
order by ordinal_position
FOR XML PATH('')) val (list)
where so.type = 'U'
Try this.
SELECT
CASE
WHEN FRUIT = 'A' THEN 'APPLE'
WHEN FRUIT = 'B' THEN 'BANANA'
ELSE 'UNKNOWN FRUIT'
END AS FRUIT
FROM FRUIT_TABLE;
I'm working with zip files which Java's ZipFile class isn't able to handle. Java 8 apparently can't handle compression method 12 (bzip2 I believe). After trying a number of methods including zip4j (which also fails with these particular files due to another issue), I had success with Apache's commons-compress which supports additional compression methods as mentioned here.
Note that the ZipFile class below is not the one from java.util.zip.
It's actually org.apache.commons.compress.archivers.zip.ZipFile so be careful with the imports.
try (ZipFile zipFile = new ZipFile(archiveFile)) {
Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
while (entries.hasMoreElements()) {
ZipArchiveEntry entry = entries.nextElement();
File entryDestination = new File(destination, entry.getName());
if (entry.isDirectory()) {
entryDestination.mkdirs();
} else {
entryDestination.getParentFile().mkdirs();
try (InputStream in = zipFile.getInputStream(entry); OutputStream out = new FileOutputStream(entryDestination)) {
IOUtils.copy(in, out);
}
}
}
} catch (IOException ex) {
log.debug("Error unzipping archive file: " + archiveFile, ex);
}
For Gradle:
compile 'org.apache.commons:commons-compress:1.18'
Building on N.S's answer, I have a PowerShell script that exports to a CSV file with the quote marks around the field and comma separated and it skips the header information in the file.
add-pssnapin sqlserverprovidersnapin100
add-pssnapin sqlservercmdletsnapin100
$qry = @"
Select
*
From
tablename
"@
Invoke-Sqlcmd -ServerInstance Server -Database DBName -Query $qry | convertto-CSV -notype | select -skip 1 > "full path and filename.csv"
The first two lines enable the ability to use the Invoke-SqlCmd command-let.
AStyle can be customized in great detail for C++ and Java (and others too)
This is a source code formatting tool.
clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.
It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).
It can be configured with a variety of options listed here.
When using config files (named .clang-format
) styles can be per directory - the closest such file in parent directories shall be used for a particular file.
Styles can be inherited from a preset (say LLVM or Google) and can later override different options
It is used by Google and others and is production ready.
Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.
Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.
You can use both !=
or <>
.
However, note that !=
is preferred where <>
is deprecated.
The solution you are really looking for is web sockets. However, the chromium project has developed some new technologies that are direct TCP connections TCP chromium
I met this problem today, however it was a bit different. I had a CUDA DLL project in my solution. Compiling in a clean solution was OK, but otherwise it failed and the compiler always treated the CUDA DLL project as not up to date.
I tried the solution from this post.
But there is no missing header file in my solution. Then I found out the reason in my case.
I have changed the project's Intermediate Directory before, although it didn't cause trouble. And now when I changed the CUDA DLL Project's Intermediate Directory back to $(Configuration)\, everything works right again.
I guess there is some minor problem between CUDA Build Customization and non-default Intermediate Directory.
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>
std::string exec(const char* cmd) {
std::array<char, 128> buffer;
std::string result;
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
if (!pipe) {
throw std::runtime_error("popen() failed!");
}
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
result += buffer.data();
}
return result;
}
Pre-C++11 version:
#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>
std::string exec(const char* cmd) {
char buffer[128];
std::string result = "";
FILE* pipe = popen(cmd, "r");
if (!pipe) throw std::runtime_error("popen() failed!");
try {
while (fgets(buffer, sizeof buffer, pipe) != NULL) {
result += buffer;
}
} catch (...) {
pclose(pipe);
throw;
}
pclose(pipe);
return result;
}
Replace popen
and pclose
with _popen
and _pclose
for Windows.
Adding the sourceURL in the script file helped as mentioned in this page: https://blog.getfirebug.com/2009/08/11/give-your-eval-a-name-with-sourceurl/
You may have as many levels of Object hierarchy as you want, as long you declare an Object as being a property of another parent Object. Pay attention to the commas on each level, that's the tricky part. Don't use commas after the last element on each level:
{el1, el2, {el31, el32, el33}, {el41, el42}}
var MainObj = {_x000D_
_x000D_
prop1: "prop1MainObj",_x000D_
_x000D_
Obj1: {_x000D_
prop1: "prop1Obj1",_x000D_
prop2: "prop2Obj1", _x000D_
Obj2: {_x000D_
prop1: "hey you",_x000D_
prop2: "prop2Obj2"_x000D_
}_x000D_
},_x000D_
_x000D_
Obj3: {_x000D_
prop1: "prop1Obj3",_x000D_
prop2: "prop2Obj3"_x000D_
},_x000D_
_x000D_
Obj4: {_x000D_
prop1: true,_x000D_
prop2: 3_x000D_
} _x000D_
};_x000D_
_x000D_
console.log(MainObj.Obj1.Obj2.prop1);
_x000D_
From Android Studio 3.1 Device Monitor available from the command line only.
In Android Studio 3.1, the Device Monitor serves less of a role than it previously did. In many cases, the functionality available through the Device Monitor is now provided by new and improved tools.
See the Device Monitor documentation for instructions for invoking the Device Monitor from the command line and for details of the tools available through the Device Monitor.
To start the standalone Device Monitor application, enter the following on the command line in the android-sdk/tools/
directory:
monitor
Unit testing is usually done by the developers side, whereas testers are partly evolved in this type of testing where testing is done unit by unit. In Java JUnit test cases can also be possible to test whether the written code is perfectly designed or not.
This type of testing is possible after the unit testing when all/some components are integrated. This type of testing will make sure that when components are integrated, do they affect each others' working capabilities or functionalities?
This type of testing is done at the last when system is integrated successfully and ready to go on production server.
This type of testing will make sure that every important functionality from start to end is working fine and system is ready to deploy on production server.
This type of testing is important to test that unintended/unwanted defects are not present in the system when developer fixed some issues. This testing also make sure that all the bugs are successfully solved and because of that no other issues are occurred.
<style type="text/css" media="print">
@page {
size: auto;
margin: 0;
}
</style>
//now set manual padding to body
<style>
body{
padding-left: 1.3cm;
padding-right: 1.3cm;
padding-top: 1.1cm;
}
</style>
System.IO.DirectoryInfo myDirInfo = new DirectoryInfo(myDirPath);
foreach (FileInfo file in myDirInfo.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in myDirInfo.GetDirectories())
{
dir.Delete(true);
}
Take this example:
original = dict(a=1, b=2, c=dict(d=4, e=5))
new = original.copy()
Now let's change a value in the 'shallow' (first) level:
new['a'] = 10
# new = {'a': 10, 'b': 2, 'c': {'d': 4, 'e': 5}}
# original = {'a': 1, 'b': 2, 'c': {'d': 4, 'e': 5}}
# no change in original, since ['a'] is an immutable integer
Now let's change a value one level deeper:
new['c']['d'] = 40
# new = {'a': 10, 'b': 2, 'c': {'d': 40, 'e': 5}}
# original = {'a': 1, 'b': 2, 'c': {'d': 40, 'e': 5}}
# new['c'] points to the same original['d'] mutable dictionary, so it will be changed
Nothing will be perfect. If you just want something to stop non-programmers then here's a little script I wrote you can use:
<?php
$infile=$_SERVER['argv'][1];
$outfile=$_SERVER['argv'][2];
if (!$infile || !$outfile) {
die("Usage: php {$_SERVER['argv'][0]} <input file> <output file>\n");
}
echo "Processing $infile to $outfile\n";
$data="ob_end_clean();?>";
$data.=php_strip_whitespace($infile);
// compress data
$data=gzcompress($data,9);
// encode in base64
$data=base64_encode($data);
// generate output text
$out='<?ob_start();$a=\''.$data.'\';eval(gzuncompress(base64_decode($a)));$v=ob_get_contents();ob_end_clean();?>';
// write output text
file_put_contents($outfile,$out);
Just use the -fno-objc-arc flag in Build Phases>Compile Sources infront of files to whom you dont want ARC to be apply.
Since the switch
statement expresses the same intent as your if
/ else
chain but in a more restricted, formal manner, your first guess should be that the compiler will be able to optimize it better, since it can draw more conclusions about the conditions placed on your code (i.e. only one state can possibly be true, the value being compared is a primitive type, etc.) This is a pretty safe general truth when you are comparing two similar language structures for runtime performance.
I managed to download the file generated by the rest API URL much easier with this kind of code which worked just fine on my local:
import React, {Component} from "react";
import {saveAs} from "file-saver";
class MyForm extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
const form = event.target;
let queryParam = buildQueryParams(form.elements);
let url = 'http://localhost:8080/...whatever?' + queryParam;
fetch(url, {
method: 'GET',
headers: {
// whatever
},
})
.then(function (response) {
return response.blob();
}
)
.then(function(blob) {
saveAs(blob, "yourFilename.xlsx");
})
.catch(error => {
//whatever
})
}
render() {
return (
<form onSubmit={this.handleSubmit} id="whateverFormId">
<table>
<tbody>
<tr>
<td>
<input type="text" key="myText" name="myText" id="myText"/>
</td>
<td><input key="startDate" name="from" id="startDate" type="date"/></td>
<td><input key="endDate" name="to" id="endDate" type="date"/></td>
</tr>
<tr>
<td colSpan="3" align="right">
<button>Export</button>
</td>
</tr>
</tbody>
</table>
</form>
);
}
}
function buildQueryParams(formElements) {
let queryParam = "";
//do code here
return queryParam;
}
export default MyForm;
Here's yet another option to add to the mix:
$ du -b file.txt
That is: estimate file space usage of file.txt in bytes.
There is a package on npm for easy asynchronous for each loops.
var forEachAsync = require('futures').forEachAsync;
// waits for one request to finish before beginning the next
forEachAsync(['dogs', 'cats', 'octocats'], function (next, element, index, array) {
getPics(element, next);
// then after all of the elements have been handled
// the final callback fires to let you know it's all done
}).then(function () {
console.log('All requests have finished');
});
Also another variation forAllAsync
I found, bizarrely, that I could fix the errors by placing the timezone declaration at the TOP of my php.ini file.
It was already in my php.ini. Twice, actually. And I was pulling my hair out because everyone was saying there must be another ini being loaded... There wasn't.
Hope this can save someone else the time/hair loss.
Another thought here is to extend testing to "internal" classes/methods, giving more of a white-box sense of this testing. You can use InternalsVisibleToAttribute on the assembly to expose these to separate unit testing modules.
In combination with sealed class you can approach such encapsulation that test method are visible only from unittest assembly your methods. Consider that protected method in sealed class is de facto private.
[assembly: InternalsVisibleTo("MyCode.UnitTests")]
namespace MyCode.MyWatch
{
#pragma warning disable CS0628 //invalid because of InternalsVisibleTo
public sealed class MyWatch
{
Func<DateTime> _getNow = delegate () { return DateTime.Now; };
//construktor for testing purposes where you "can change DateTime.Now"
internal protected MyWatch(Func<DateTime> getNow)
{
_getNow = getNow;
}
public MyWatch()
{
}
}
}
And unit test:
namespace MyCode.UnitTests
{
[TestMethod]
public void TestminuteChanged()
{
//watch for traviling in time
DateTime baseTime = DateTime.Now;
DateTime nowforTesting = baseTime;
Func<DateTime> _getNowForTesting = delegate () { return nowforTesting; };
MyWatch myWatch= new MyWatch(_getNowForTesting );
nowforTesting = baseTime.AddMinute(1); //skip minute
//TODO check myWatch
}
[TestMethod]
public void TestStabilityOnFebruary29()
{
Func<DateTime> _getNowForTesting = delegate () { return new DateTime(2024, 2, 29); };
MyWatch myWatch= new MyWatch(_getNowForTesting );
//component does not crash in overlap year
}
}
I had the same problem, and stumbled onto a solution with 'Build Main Project F11'. The ide brought up an "option" that I might want to uncheck 'Compile on Save' in the Build > Compiling portion of the Project configuration dialog. Unchecking 'Complile on Save' and then doing the usual (for me) 'Clean and Build' did the trick for me.
ImmutableMap does not accept null
values whereas Collections.unmodifiableMap()
does. In addition it will never change after construction, while UnmodifiableMap
may. From the JavaDoc:
An immutable, hash-based Map with reliable user-specified iteration order. Does not permit null keys or values.
Unlike Collections.unmodifiableMap(java.util.Map), which is a view of a separate map which can still change, an instance of ImmutableMap contains its own data and will never change. ImmutableMap is convenient for public static final maps ("constant maps") and also lets you easily make a "defensive copy" of a map provided to your class by a caller.
Use the following css:
* {
font: Verdana, Arial, 'sans-serif' !important;/* <-- fonts */
}
The *
-selector means any/all elements, but will obviously be on the bottom of the food chain when it comes to overriding more specific selectors.
Note that the !important
-flag will render the font
-style for *
to be absolute, even if other selectors have been used to set the text (for example, the body
or maybe a p
).
I wanted a simple example of the use of case that I could play with, this doesn't even need a table. This returns odd or even depending whether seconds is odd or even
SELECT CASE MOD(SECOND(NOW()),2) WHEN 0 THEN 'odd' WHEN 1 THEN 'even' END;
You can change the tabs by ctrl-pgup and ctrl-pgdown. On that tab you came from the NERDTree is still selected and you can open another tab.
Hello just create a simple function that looks as shown below.. That returns all rows where the call parameter entered is valid or true.
public DataTable SearchRecords(string Col1, DataTable RecordDT_, int KeyWORD)
{
TempTable = RecordDT_;
DataView DV = new DataView(TempTable);
DV.RowFilter = string.Format(string.Format("Convert({0},'System.String')",Col1) + " LIKE '{0}'", KeyWORD);
return DV.ToTable();
}
and simply call it as shown below;
DataTable RowsFound=SearchRecords("IdColumn", OriginalTable,5);
where 5 is the ID. Thanks..
Package php-dom is a virtual package provided by:
php7.1-xml 7.1.3+-3+deb.sury.org~xenial+1
php7.0-xml 7.0.17-3+deb.sury.org~xenial+1
php5.6-xml 5.6.30-9+deb.sury.org~xenial+1
You should explicitly select one to install.
In case anyone using 5.6 versions then go with this way
sudo apt-get install php5.6-xml
For Php Ver PHP7, Ubuntu:
sudo apt-get install php7.1-xml
or by
yum install php-xml
Try this one,
Create rounded_edittext.xml
file in your Drawable
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="15dp">
<solid android:color="#FFFFFF" />
<corners
android:bottomRightRadius="0dp"
android:bottomLeftRadius="0dp"
android:topLeftRadius="0dp"
android:topRightRadius="0dp" />
<stroke android:width="1dip" android:color="#f06060" />
</shape>
Apply background for your EditText
in xml file
<EditText
android:id="@+id/edit_expiry_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:background="@drawable/rounded_edittext"
android:hint="@string/shop_name"
android:inputType="text" />
You will get output like this
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
This is my solution. I Hide and then confirm check
onclick="return ConfirmSubmit(this);" />
function ConfirmSubmit(sender)
{
sender.disabled = true;
var displayValue = sender.style.
sender.style.display = 'none'
if (confirm('Seguro que desea entregar los paquetes?')) {
sender.disabled = false
return true;
}
sender.disabled = false;
sender.style.display = displayValue;
return false;
}
To remove the .html extension from your URLs, you can use the following code in root/htaccess :
#mode_rerwrite start here
RewriteEngine On
# does not apply to existing directores, meaning that if the folder exists on server then don't change anything and don't run the rule.
RewriteCond %{REQUEST_FILENAME} !-d
#Check for file in directory with .html extension
RewriteCond %{REQUEST_FILENAME}\.html !-f
#Here we actually show the page that has .html extension
RewriteRule ^(.*)$ $1.html [NC,L]
Thanks
Python 3.5, 2018
If you don't know what the encoding but the unicode parser is having issues you can open the file in Notepad++
and in the top bar select Encoding->Convert to ANSI
. Then you can write your python like this
with open('filepath', 'r', encoding='ANSI') as file:
for word in file.read().split():
print(word)
If you're using angularJS or some variant of the Q promise library, then you have a .all()
method that solves this exact problem.
var savePromises = [];
angular.forEach(models, function(model){
savePromises.push(
model.saveToServer()
)
});
$q.all(savePromises).then(
function success(results){...},
function failed(results){...}
);
see the full API:
https://github.com/kriskowal/q/wiki/API-Reference#promiseall
For Ubuntu 16: /etc/mysql/mysql.conf.d/mysqld.cnf
It depends which version of oracle you have, for 9i and below Statspack is what you are after, 10g and above, you want awr , both these tools will give you the top sql's and lots of other stuff.
You didn't specify how the order is determined, but this will give you a rank value in MySQL:
SELECT t.*,
@rownum := @rownum +1 AS rank
FROM TBL_FOO t
JOIN (SELECT @rownum := 0) r
WHERE t.name = 'sarmen'
Then you can pick out what rows you want, based on the rank value.
What worked for me was to go to the root folder, where .git/ is. I was inside one the child folders and got there error.
The X-Frame-Options is defined in the Http Header and not in the <head>
section of the page you want to use in the iframe.
Accepted values are: DENY, SAMEORIGIN and ALLOW-FROM "url"
Ctrl + alt +delete to start TASK MANAGER ,choose Service ,Then you will find MySQL, click that item by right click,then choose start, your MySQL Server will start!
.getBoundingClientRect() returns the size of an element and its position relative to the viewport.We can easily get following
Example :
var element = d3.select('.elementClassName').node();
element.getBoundingClientRect().width;
$(this)
instead of $this
$("tr.item").each(function() {
var quantity1 = $(this).find("input.name").val(),
quantity2 = $(this).find("input.id").val();
});
You can use these kind of programs to emulate an apache web server and run PHP on your computer:
Possible in IE and chrome although it does not work in firefox:
<script>
function toggleZoomScreen() {
document.body.style.zoom = "80%";
}
</script>
<img src="example.jpg" alt="example" onclick="toggleZoomScreen()">
If you're using ngRoute, you can inject $routeParams
into your controller
http://docs.angularjs.org/api/ngRoute/service/$routeParams
If you're using angular-ui-router, you can inject $stateParams
<style>
a {
color: ;
}
</style>
This code changes the color from the default to what is specified in the style. Using a:hover, you can change the color of the text from the default on hover.
@last_run_time
is a 9.4. User-Defined Variables and last_run_time datetime
one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.
Try: SELECT last_run_time;
UPDATE
Example:
/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$
CREATE PROCEDURE `sp_test`()
BEGIN
DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
DECLARE last_run_time DATETIME DEFAULT NULL;
DECLARE current_run_time DATETIME DEFAULT NOW();
-- Define the last run time
SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);
-- if there is no last run time found then use yesterday as starting point
IF(last_run_time IS NULL) THEN
SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
END IF;
SELECT last_run_time;
-- Insert variables in table2
INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$
DELIMITER ;
Apple enabled the attribute playsinline
in all browsers on iOS 10, so this works seamlessly:
<video src="file.mp4" playsinline>
Short answer: use iphone-inline-video, it enables inline playback and syncs the audio.
Long answer: You can work around this issue by simulating the playback by skimming the video instead of actually .play()
'ing it.
Regards to your question... counting one Field? I decided to make it a question, but I hope it helps...
Say I have the following DataFrame
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.normal(0, 1, (5, 2)), columns=["A", "B"])
You could count a single column by
df.A.count()
#or
df['A'].count()
both evaluate to 5.
The cool thing (or one of many w.r.t. pandas
) is that if you have NA
values, count takes that into consideration.
So if I did
df['A'][1::2] = np.NAN
df.count()
The result would be
A 3
B 5
Open the XAMMP php.ini file (the default path is C:\xammp\php\php.ini) and change the code (;extension=ldap) to extension=php_ldap.dll and save. Restart XAMMP and save.
php.ini
; Notes for Windows environments :
;
; - Many DLL files are located in the extensions/ (PHP 4) or ext/ (PHP 5+)
; extension folders as well as the separate PECL DLL download (PHP 5+).
; Be sure to appropriately set the extension_dir directive.
;
extension=bz2
extension=curl
extension=fileinfo
extension=gd2
extension=gettext
;extension=gmp
;extension=intl
;extension=imap
;extension=interbase
extension=php_ldap.dll
days, hours, minutes = td.days, td.seconds // 3600, td.seconds // 60 % 60
As for DST, I think the best thing is to convert both datetime
objects to seconds. This way the system calculates DST for you.
>>> m13 = datetime(2010, 3, 13, 8, 0, 0) # 2010 March 13 8:00 AM
>>> m14 = datetime(2010, 3, 14, 8, 0, 0) # DST starts on this day, in my time zone
>>> mktime(m14.timetuple()) - mktime(m13.timetuple()) # difference in seconds
82800.0
>>> _/3600 # convert to hours
23.0
I would upgrade to newer Netbeans 7.1 or wait few days/weeks for 7.2, it can be a bug in Netbeans 6.8.
I just add to previous two solutions, that you can increase size temporary with ALT(CTRL) + mouse wheel as in browser. (ALT in Netbeans 7.2, CTRL in Netbeans 7.1)
For the sake of completeness, there is also a data.table
solution:
library(data.table)
result <- setDT(df)[, paste0(names(df), "_length") := lapply(.SD, stringr::str_length)]
result
# col1 col2 col1_length col2_length
#1: abc adf qqwe 3 8
#2: abcd d 4 1
#3: a e 1 1
#4: abcdefg f 7 1
This link explains where you're going wrong:
Place the definition of your constructors, destructors methods and whatnot in your header file, and that will correct the problem.
This offers another solution:
How can I avoid linker errors with my template functions?
However this requires you to anticipate how your template will be used and, as a general solution, is counter-intuitive. It does solve the corner case though where you develop a template to be used by some internal mechanism, and you want to police the manner in which it is used.
For current ActiveRecord (4.2.4+) there is a method to_hash
on the Result
object that returns an array of hashes. You can then map over it and convert to symbolized hashes:
# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
{"id" => 2, "title" => "title_2", "body" => "body_2"},
...
]
result.to_hash.map(&:symbolize_keys)
# => [{:id => 1, :title => "title_1", :body => "body_1"},
{:id => 2, :title => "title_2", :body => "body_2"},
...
]
The particular exception message is telling you that the mentioned class is missing in the classpath. As the org.apache.commons.io
package name hints, the mentioned class is part of the http://commons.apache.org/io
project.
And indeed, Commons FileUpload has Commons IO as a dependency. You need to download and drop commons-io.jar
in the /WEB-INF/lib
as well.
Reload the current document:
<script type="text/javascript">
function reloadPage()
{
window.location.reload()
}
</script>
there is a very useful online tool for this, just automatically transform the table into divs:
http://www.html-cleaner.com/features/replace-html-table-tags-with-divs/
And the video that explains it: https://www.youtube.com/watch?v=R1ArAee6wEQ
I'm using this on a daily basis. I hope it helps ;)
fetch
will download any changes from the remote* branch, updating your repository data, but leaving your local* branch unchanged.
pull
will perform a fetch
and additionally merge
the changes into your local branch.
What's the difference? pull
updates you local branch with changes from the pulled branch. A fetch
does not advance your local branch.
Given the following history:
C---D---E local / A---B---F---G remote
merge
joins two development histories together. It does this by replaying the changes that occurred on your local branch after it diverged on top of the remote branch, and record the result in a new commit. This operation preserves the ancestry of each commit.
The effect of a merge
will be:
C---D---E local / \ A---B---F---G---H remote
rebase
will take commits that exist in your local branch and re-apply them on top of the remote branch. This operation re-writes the ancestors of your local commits.
The effect of a rebase
will be:
C'--D'--E' local / A---B---F---G remote
What's the difference? A merge
does not change the ancestry of commits. A rebase
rewrites the ancestry of your local commits.
*
This explanation assumes that the current branch is a local branch, and that the branch specified as the argument to fetch
, pull
, merge
, or rebase
is a remote branch. This is the usual case. pull
, for example, will download any changes from the specified branch, update your repository and merge
the changes into the current branch.
Just an extra info, if you are using DB
:
DB::table('test')->where('id', '>', 0)->pluck('id')->toArray();
And if using Eloquent model:
test::where('id', '>', 0)->lists('id')->toArray();
Found this on github...
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import pandas
You clone a repository with git clone [url]. Like so,
$ git clone https://github.com/libgit2/libgit2
Just a small update to Alec Smart's answer: since AS2 is deprecated now, the '?version=3' is required to get his example to work. See the Youtube reference at YouTube Embedded Players and Player Parameters under "Selecting content to play" for details.
In other words:
<object width="425" height="350" data="http://www.youtube.com/v/Ahg6qcgoay4?version=3" type="application/x-shockwave-flash"><param name="src" value="http://www.youtube.com/v/Ahg6qcgoay4?version=3" /></object>
Apparently, the Youtube reference above does this as follows (the inner embed presumably used as a fallback for browsers that don't yet support the object tag):
<object width="640" height="390">
<param name="movie"
value="https://www.youtube.com/v/u1zgFlCw8Aw?version=3&autoplay=1"></param>
<param name="allowScriptAccess" value="always"></param>
<embed src="https://www.youtube.com/v/u1zgFlCw8Aw?version=3&autoplay=1"
type="application/x-shockwave-flash"
allowscriptaccess="always"
width="640" height="390"></embed>
</object>
Or using iframes (replace http://example.com with your site's domain):
<iframe id="ytplayer" type="text/html" width="640" height="390" src="http://www.youtube.com/embed/u1zgFlCw8Aw?autoplay=1&origin=http://example.com" frameborder="0"/>
There are many ways to achieve this, but the most important consideration to measure elapsed time is to use System.nanoTime()
and TimeUnit.NANOSECONDS
as the time unit. Why should I do this? Well, it is because System.nanoTime()
method returns a high-resolution time source, in nanoseconds since some reference point (i.e. Java Virtual Machine's start up).
This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.
For the same reason, it is recommended to avoid the use of the System.currentTimeMillis()
method for measuring elapsed time. This method returns the wall-clock
time, which may change based on many factors. This will be negative for your measurements.
Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
So here you have one solution based on the System.nanoTime()
method, another one using Guava, and the final one Apache Commons Lang
public class TimeBenchUtil
{
public static void main(String[] args) throws InterruptedException
{
stopWatch();
stopWatchGuava();
stopWatchApacheCommons();
}
public static void stopWatch() throws InterruptedException
{
long endTime, timeElapsed, startTime = System.nanoTime();
/* ... the code being measured starts ... */
// sleep for 5 seconds
TimeUnit.SECONDS.sleep(5);
/* ... the code being measured ends ... */
endTime = System.nanoTime();
// get difference of two nanoTime values
timeElapsed = endTime - startTime;
System.out.println("Execution time in nanoseconds : " + timeElapsed);
}
public static void stopWatchGuava() throws InterruptedException
{
// Creates and starts a new stopwatch
Stopwatch stopwatch = Stopwatch.createStarted();
/* ... the code being measured starts ... */
// sleep for 5 seconds
TimeUnit.SECONDS.sleep(5);
/* ... the code being measured ends ... */
stopwatch.stop(); // optional
// get elapsed time, expressed in milliseconds
long timeElapsed = stopwatch.elapsed(TimeUnit.NANOSECONDS);
System.out.println("Execution time in nanoseconds : " + timeElapsed);
}
public static void stopWatchApacheCommons() throws InterruptedException
{
StopWatch stopwatch = new StopWatch();
stopwatch.start();
/* ... the code being measured starts ... */
// sleep for 5 seconds
TimeUnit.SECONDS.sleep(5);
/* ... the code being measured ends ... */
stopwatch.stop(); // Optional
long timeElapsed = stopwatch.getNanoTime();
System.out.println("Execution time in nanoseconds : " + timeElapsed);
}
}
Tell grep
to treat your input as fixed string using -F
option.
grep -F '*^%Q&$*&^@$&*!^@$*&^&^*&^&' application.log
Option -n
is required to get the line number,
grep -Fn '*^%Q&$*&^@$&*!^@$*&^&^*&^&' application.log
Alternatively, you could differentiate using BuildConfig.BUILD_TYPE;
If you're running debug build
BuildConfig.BUILD_TYPE.equals("debug");
returns true. And for release build BuildConfig.BUILD_TYPE.equals("release");
returns true.
Long Press on Power button, then you will have the option for the screenshot.
Also try System.currentTimeMillis()
Query the sysdepends table:
SELECT distinct schema_name(dependentObject.uid) as schema,
dependentObject.*
FROM sysdepends d
INNER JOIN sysobjects o on d.id = o.id
INNER JOIN sysobjects dependentObject on d.depid = dependentObject.id
WHERE o.name = 'TableName'
A way to look just for views/functions/triggers/procedures that reference the object (or any given text) by name is:
SELECT distinct schema_name(so.uid) + '.' + so.name
FROM syscomments sc
INNER JOIN sysobjects so on sc.id = so.id
WHERE sc.text like '%Name%'
def dropDupeDfCols(df): newcols = [] dupcols = []
for i in range(len(df.columns)):
if df.columns[i] not in newcols:
newcols.append(df.columns[i])
else:
dupcols.append(i)
df = df.toDF(*[str(i) for i in range(len(df.columns))])
for dupcol in dupcols:
df = df.drop(str(dupcol))
return df.toDF(*newcols)
You can use a list comprehension:
indices = [i for i, x in enumerate(my_list) if x == "whatever"]
As mentioned already primitives can not be set to the Object type null.
What I do in such cases is just to use -1
or Long.MIN_VALUE
.
You have to implement KeyListener
,take a look here:
http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyListener.html
More details on how to use it: http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html
This error can also happen when you've downloaded a new version of Google Play Services and not installed the latest SDK. Thats what happened to me. So, as the others mentioned, if you try to import Google Play Services and then open the console, you'll see a compile error. Try installing all the recent Android SDKs and try again, if this is the case.
None of the answers worked with fish
shell (it doesn't have the variables $$
or $0
).
This works for me (tested on sh
, bash
, fish
, ksh
, csh
, true
, tcsh
, and zsh
; openSUSE 13.2):
ps | tail -n 4 | sed -E '2,$d;s/.* (.*)/\1/'
This command outputs a string like bash
. Here I'm only using ps
, tail
, and sed
(without GNU extesions; try to add --posix
to check it). They are all standard POSIX commands. I'm sure tail
can be removed, but my sed
fu is not strong enough to do this.
It seems to me, that this solution is not very portable as it doesn't work on OS X. :(
Follow instructions (steps 1 to 3 don't needed in windows):
Find mysql config to edit:
/etc/mysql/my.cnf (Mysql 5.5)
/etc/mysql/conf.d/mysql.cnf (Mysql 5.6+)
Find bind-address=127.0.0.1
in config file change bind-address=0.0.0.0
(you can set bind address to one of your interface ips or like me use 0.0.0.0)
Restart mysql service run on console:
service restart mysql
Create a user with a safe password for remote connection. To do this run following command in mysql (if you are linux user to reach mysql console run mysql
and if you set password for root run mysql -p
):
GRANT ALL PRIVILEGES
ON *.* TO 'remote'@'%'
IDENTIFIED BY 'safe_password'
WITH GRANT OPTION;`
Now you should have a user with name of user
and password of safe_password
with capability of remote connect.
A thing to note is that you need to send in an object for Lambda expressions and can't use an instance for a class.
Example:
public class Key
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
This will compile but will generate one key per cycle.
var groupedCycles = cycles.GroupBy(x => new Key
{
Prop1 = x.Column1,
Prop2 = x.Column2
})
If you wan't to name the key properties and then retreive them you can do it like this instead. This will GroupBy
correctly and give you the key properties.
var groupedCycles = cycles.GroupBy(x => new
{
Prop1 = x.Column1,
Prop2= x.Column2
})
foreach (var groupedCycle in groupedCycles)
{
var key = new Key();
key.Prop1 = groupedCycle.Key.Prop1;
key.Prop2 = groupedCycle.Key.Prop2;
}
Is your problem similar to this:
l = [[0]] * 4
l[0][0] += 1
print l # prints "[[1], [1], [1], [1]]"
If so, you simply need to copy the objects when you store them:
import copy
l = [copy.copy(x) for x in [[0]] * 4]
l[0][0] += 1
print l # prints "[[1], [0], [0], [0]]"
The objects in question should implement a __copy__
method to copy objects. See the documentation for copy
. You may also be interested in copy.deepcopy
, which is there as well.
EDIT: Here's the problem:
arrayList = []
for x in allValues:
result = model(x)
arrayList.append(wM) # appends the wM object to the list
wM.reset() # clears the wM object
You need to append a copy:
import copy
arrayList = []
for x in allValues:
result = model(x)
arrayList.append(copy.copy(wM)) # appends a copy to the list
wM.reset() # clears the wM object
But I'm still confused as to where wM
is coming from. Won't you just be copying the same wM
object over and over, except clearing it after the first time so all the rest will be empty? Or does model()
modify the wM
(which sounds like a terrible design flaw to me)? And why are you throwing away result
?
This worked for me, no splicing or anything required:
HTML
<div class="row" ng-repeat="row in rows() track by $index">
<div class="col-md-3" ng-repeat="item in items" ng-if="indexInRange($index,$parent.$index)"></div>
</div>
JavaScript
var columnsPerRow = 4;
$scope.rows = function() {
return new Array(columnsPerRow);
};
$scope.indexInRange = function(columnIndex,rowIndex) {
return columnIndex >= (rowIndex * columnsPerRow) && columnIndex < (rowIndex * columnsPerRow) + columnsPerRow;
};
I did not test this with LINQ to Entities:
NorthwindDataContext dc = new NorthwindDataContext();
dc.Log = Console.Out;
var query =
from c in dc.Customers
where !dc.Orders.Any(o => o.CustomerID == c.CustomerID)
select c;
Alternatively:
NorthwindDataContext dc = new NorthwindDataContext();
dc.Log = Console.Out;
var query =
from c in dc.Customers
where dc.Orders.All(o => o.CustomerID != c.CustomerID)
select c;
foreach (var c in query)
Console.WriteLine( c );
wget is capable of doing what you are asking. Just try the following:
wget -p -k http://www.example.com/
The -p
will get you all the required elements to view the site correctly (css, images, etc).
The -k
will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.
From the Wget docs:
‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.
Each link will be changed in one of the two ways:
The links to files that have been downloaded by Wget will be changed to refer
to the file they point to as a relative link.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
downloaded, then the link in doc.html will be modified to point to
‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
combinations of directories.
The links to files that have not been downloaded by Wget will be changed to
include host name and absolute path of the location they point to.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
../bar/img.gif), then the link in doc.html will be modified to point to
http://hostname/bar/img.gif.
Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.
Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads.
please check if code below would work for you; it iterates through cells of the datagris's first column and checks if cell content equals to the textbox.text value and selects the row.
for (int i = 0; i < dataGrid.Items.Count; i++)
{
DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(i);
TextBlock cellContent = dataGrid.Columns[0].GetCellContent(row) as TextBlock;
if (cellContent != null && cellContent.Text.Equals(textBox1.Text))
{
object item = dataGrid.Items[i];
dataGrid.SelectedItem = item;
dataGrid.ScrollIntoView(item);
row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
break;
}
}
hope this helps, regards
Use six
:
from six.moves.urllib.parse import quote
six
will simplify compatibility problems between Python 2 and Python 3, such as different import paths.