System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = @"/c -sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer"
use /c as a cmd argument to close cmd.exe once its finish processing your commands
I started having this issue after upgrading from Rails 5.1 to 5.2
It got solved with:
spring stop
spring binstub --all
spring start
rails s
this tiny jQuery plugin is very simple to use: https://github.com/finnlabs/jquery.observehashchange/
If you have any doubt, use merge.
The only differences between a rebase and a merge are:
So the short answer is to pick rebase or merge based on what you want your history to look like.
There are a few factors you should consider when choosing which operation to use.
If so, don't rebase. Rebase destroys the branch and those developers will have broken/inconsistent repositories unless they use git pull --rebase
. This is a good way to upset other developers quickly.
Rebase is a destructive operation. That means, if you do not apply it correctly, you could lose committed work and/or break the consistency of other developer's repositories.
I've worked on teams where the developers all came from a time when companies could afford dedicated staff to deal with branching and merging. Those developers don't know much about Git and don't want to know much. In these teams I wouldn't risk recommending rebasing for any reason.
Some teams use the branch-per-feature model where each branch represents a feature (or bugfix, or sub-feature, etc.) In this model the branch helps identify sets of related commits. For example, one can quickly revert a feature by reverting the merge of that branch (to be fair, this is a rare operation). Or diff a feature by comparing two branches (more common). Rebase would destroy the branch and this would not be straightforward.
I've also worked on teams that used the branch-per-developer model (we've all been there). In this case the branch itself doesn't convey any additional information (the commit already has the author). There would be no harm in rebasing.
Reverting (as in undoing) a rebase is considerably difficult and/or impossible (if the rebase had conflicts) compared to reverting a merge. If you think there is a chance you will want to revert then use merge.
Rebase operations need to be pulled with a corresponding git pull --rebase
. If you are working by yourself you may be able to remember which you should use at the appropriate time. If you are working on a team this will be very difficult to coordinate. This is why most rebase workflows recommend using rebase for all merges (and git pull --rebase
for all pulls).
Assuming you have the following merge:
B -- C
/ \
A--------D
Some people will state that the merge "destroys" the commit history because if you were to look at the log of only the master branch (A -- D) you would miss the important commit messages contained in B and C.
If this were true we wouldn't have questions like this. Basically, you will see B and C unless you explicitly ask not to see them (using --first-parent). This is very easy to try for yourself.
The two approaches merge differently, but it is not clear that one is always better than the other and it may depend on the developer workflow. For example, if a developer tends to commit regularly (e.g. maybe they commit twice a day as they transition from work to home) then there could be a lot of commits for a given branch. Many of those commits might not look anything like the final product (I tend to refactor my approach once or twice per feature). If someone else was working on a related area of code and they tried to rebase my changes it could be a fairly tedious operation.
If you like to alias rm
to rm -rf
to "save time" then maybe rebase is for you.
I always think that someday I will come across a scenario where Git rebase is the awesome tool that solves the problem. Much like I think I will come across a scenario where Git reflog is an awesome tool that solves my problem. I have worked with Git for over five years now. It hasn't happened.
Messy histories have never really been a problem for me. I don't ever just read my commit history like an exciting novel. A majority of the time I need a history I am going to use Git blame or Git bisect anyway. In that case, having the merge commit is actually useful to me, because if the merge introduced the issue, that is meaningful information to me.
I feel obligated to mention that I have personally softened on using rebase although my general advice still stands. I have recently been interacting a lot with the Angular 2 Material project. They have used rebase to keep a very clean commit history. This has allowed me to very easily see what commit fixed a given defect and whether or not that commit was included in a release. It serves as a great example of using rebase correctly.
Here is how to set a linearGradient on a target element:
<style type="text/css">
path{fill:url('#MyGradient')}
</style>
<defs>
<linearGradient id="MyGradient">
<stop offset="0%" stop-color="#e4e4e3" ></stop>
<stop offset="80%" stop-color="#fff" ></stop>
</linearGradient>
</defs>
Will something like this work for you?
>>> def namestr(**kwargs):
... for k,v in kwargs.items():
... print "%s = %s" % (k, repr(v))
...
>>> namestr(a=1, b=2)
a = 1
b = 2
And in your example:
>>> choice = {'key': 24; 'data': None}
>>> namestr(choice=choice)
choice = {'data': None, 'key': 24}
>>> printvars(**globals())
__builtins__ = <module '__builtin__' (built-in)>
__name__ = '__main__'
__doc__ = None
namestr = <function namestr at 0xb7d8ec34>
choice = {'data': None, 'key': 24}
Probably something like:
ArrayList<DataPoint> myList = new ArrayList<DataPoint>();
//Fill up myList with your Data Points
//Traversal
for(DataPoint myPoint : myList) {
if(myPoint.getName() != null && myPoint.getName().equals("Michael Hoffmann")) {
//Process data do whatever you want
System.out.println("Found it!");
}
}
The answers above were partial. I've spent so much time getting this working, it's insane. Note to my future self, here is what you need to do:
I'm working on Windows 10, with Chrome 65. Firefox is behaving nicely - just confirm localhost as a security exception and it will work. Chrome doesn't:
Step 1. in your backend, create a folder called security
. we will work inside it.
Step 2. create a request config file named req.cnf
with the following content (credit goes to: @Anshul)
req.cnf :
[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = Country initials like US, RO, GE
ST = State
L = Location
O = Organization Name
OU = Organizational Unit
CN = www.localhost.com
[v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = www.localhost.com
DNS.2 = localhost.com
DNS.3 = localhost
An explanation of this fields is here.
Step 3. navigate to the security folder in the terminal and type the following command :
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout cert.key -out cert.pem -config req.cnf -sha256
Step 4. then outside of security
folder, in your express app do something like this: (credit goes to @Diego Mello)
backend
/security
/server.js
server.js:
const express = require('express')
const app = express()
const https = require('https')
const fs = require('fs')
const port = 3000
app.get('/', (req, res) => {
res.send("IT'S WORKING!")
})
const httpsOptions = {
key: fs.readFileSync('./security/cert.key'),
cert: fs.readFileSync('./security/cert.pem')
}
const server = https.createServer(httpsOptions, app)
.listen(port, () => {
console.log('server running at ' + port)
})
Step 5. start the server, node server.js
, and go to https://localhost:3000.
At this point we have the server setup. But the browser should show a warning message.
We need to register our self-signed certificate, as a CA trusted Certificate Authority, in the chrome/windows certificates store. (chrome also saves this in windows,)
Step 6. open Dev Tools in chrome, go to Security panel, then click on View Certificate.
Step 7. go to Details panel, click Copy File, then when the Certificate Export Wizard appears, click Next as below:
Step 8. leave DER encoding, click next, choose Browse
, put it on a easy to access folder like Desktop, and name the certificate localhost.cer, then click Save and then Finish.
. You should be able to see your certificate on Desktop.
Step 9. Open chrome://settings/
by inserting it in the url box. Down below, click on Advanced / Advanced Options
, then scroll down to find Manage Certificates
.
Step 10. Go to Trusted Root Certification Authorities panel, and click import.
We will import the localhost.cer
certificate we just finished exporting in step 8.
Step 11. click browse, find the localhost.cer
, leave the default values click next a bunch of times - until this warning appears, click yes.
Step 12. close everything, and restart chrome. Then, when going to https://localhost:3000
you should see:
I got an error message when following the examples with a newline parameter in the csv.writer function. The following code worked for me.
with open(strFileName, "w") as f:
writer = csv.writer(f, delimiter=',', quoting=csv.QUOTE_MINIMAL)
writer.writerows(result)
Generate the private key and server certificate with specific expiry date or with infinite(XXX) expiry time and self sign it.
$ openssl req -x509 -sha256 -newkey rsa:2048 -keyout key.pem -out cert.pem -days XXX
$ Enter a private key passphrase...`
Then it will work!
Simplest solution in Springboot
I'll give you the simplest one if you use Springboot:
<properties>
<java.version>1.8</java.version>
</properties>
Then, right click on your Eclipse project: Maven > Update project > Update project configuration from pom.xml
That should do.
To add to the above answer (do steps 1-5).
I faced this issue, when I was supplying the executable folder with a, by the .exe requested DLL. In my case, the DLL I supplied to the .exe was searching for another necessary DLL which was not available. The searching DLL was not capable of telling that it can not find the necessary DLL.
You might check the DLLs you're loading and the dependencies of these DLL's.
We can animate images in ios 5 using this simple code.
CGRect imageFrame = imageView.frame;
imageFrame.origin.y = self.view.bounds.size.height;
[UIView animateWithDuration:0.5
delay:1.0
options: UIViewAnimationCurveEaseOut
animations:^{
imageView.frame = imageFrame;
}
completion:^(BOOL finished){
NSLog(@"Done!");
}];
Your question is: are these not modules capable of declaring variables at global scope?
Answer: YES, they are "capable"
The only point is that references to global variables in ThisWorkbook or a Sheet module have to be fully qualified (i.e., referred to as ThisWorkbook.Global1
, e.g.)
References to global variables in a standard module have to be fully qualified only in case of ambiguity (e.g., if there is more than one standard module defining a variable with name Global1, and you mean to use it in a third module).
For instance, place in Sheet1 code
Public glob_sh1 As String
Sub test_sh1()
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
place in ThisWorkbook code
Public glob_this As String
Sub test_this()
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
and in a Standard Module code
Public glob_mod As String
Sub test_mod()
glob_mod = "glob_mod"
ThisWorkbook.glob_this = "glob_this"
Sheet1.glob_sh1 = "glob_sh1"
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
All three subs work fine.
PS1: This answer is based essentially on info from here. It is much worth reading (from the great Chip Pearson).
PS2: Your line Debug.Print ("Hello")
will give you the compile error Invalid outside procedure
.
PS3: You could (partly) check your code with Debug -> Compile VBAProject in the VB editor. All compile errors will pop.
PS4: Check also Put Excel-VBA code in module or sheet?.
PS5: You might be not able to declare a global variable in, say, Sheet1, and use it in code from other workbook (reading http://msdn.microsoft.com/en-us/library/office/gg264241%28v=office.15%29.aspx#sectionSection0; I did not test this point, so this issue is yet to be confirmed as such). But you do not mean to do that in your example, anyway.
PS6: There are several cases that lead to ambiguity in case of not fully qualifying global variables. You may tinker a little to find them. They are compile errors.
Just add all fields to the query and remember to add them to Group By as well.
Select shoppername, a, b, amountpayed, item, count(*) as cnt
from dbo.sales
group by shoppername, a, b, amountpayed, item
having count(*) > 1
In the repository directory you remove the directory named .git and that's all :). On Un*x it is hidden, so you might not see it from file browser, but
cd repository-path/
rm -r .git
should do the trick.
You can do it programatically:
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
public class ActivityName extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// remove title
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
}
}
Or you can do it via your AndroidManifest.xml
file:
<activity android:name=".ActivityName"
android:label="@string/app_name"
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">
</activity>
Edit: I added some lines so that you can show it in fullscreen, as it seems that's what you want.
It selects all elements where the class name contains the string "span"
somewhere. There's also ^=
for the beginning of a string, and $=
for the end of a string. Here's a good reference for some CSS selectors.
I'm only familiar with the bootstrap classes spanX
where X is an integer, but if there were other selectors that ended in span
, it would also fall under these rules.
It just helps to apply blanket CSS rules.
Stateless means there is no memory of the past. Every transaction is performed as if it were being done for the very first time.
Stateful means that there is memory of the past. Previous transactions are remembered and may affect the current transaction.
Stateless:
// The state is derived by what is passed into the function
function int addOne(int number)
{
return number + 1;
}
Stateful:
// The state is maintained by the function
private int _number = 0; //initially zero
function int addOne()
{
_number++;
return _number;
}
You can do like this:
$q="SELECT * FROM projects WHERE Year(Date) = '$year' and Month(Date) = '$month'";
There's already some great answers here. Based on mdsharpe suggestion, here's an extension method that can easily be used when you want to deal with Uri instances:
using System;
using System.Linq;
public static class UriExtensions
{
public static Uri Append(this Uri uri, params string[] paths)
{
return new Uri(paths.Aggregate(uri.AbsoluteUri, (current, path) => string.Format("{0}/{1}", current.TrimEnd('/'), path.TrimStart('/'))));
}
}
And usage example:
var url = new Uri("http://example.com/subpath/").Append("/part1/", "part2").AbsoluteUri;
This will produce http://example.com/subpath/part1/part2
You can try using my custom view, which has capability to blur the background. It does this by faking taking snapshot of the background and blur it, just like the one in Apple's WWDC code. It is very simple to use.
I also made some improvement over to fake the dynamic blur without losing the performance. The background of my view is a scrollView which scrolls with the view, thus provide the blur effect for the rest of the superview.
See the example and code on my GitHub
You can do like this:
SELECT convert(datetime, convert(date, '27-09-2013', 103), 103)
I've had some luck with the Java Service Wrapper
The problem is
listModel.addElement(listaRosa.getSelectedValue());
listModel.removeElement(listaRosa.getSelectedValue());
you may be adding an element and immediatly removing it since both add and remove operations are on the same listModel.
Try
private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) {
DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel();
DefaultListModel lm1 = (DefaultListModel) listaRosa.getModel();
if(lm2 == null)
{
lm2 = new DefaultListModel();
listaTitolari.setModel(lm2);
}
lm2.addElement(listaTitolari.getSelectedValue());
lm1.removeElement(listaTitolari.getSelectedValue());
}
Here's a different approach. I prefer rather than to rely on browser support, or address this at the application layer, to use web server logic.
If you are using Apache, and can put an .htaccess file in the relevant directory you could use the code below. Of course, you could put this in httpd.conf as well, if you have access to that.
<FilesMatch "\.(?i:pdf)$">
Header set Content-Disposition attachment
</FilesMatch>
The FilesMatch directive is just a regex so it could be set as granularly as you want, or you could add in other extensions.
The Header line does the same thing as the first line in the PHP scripts above. If you need to set the Content-Type lines as well, you could do so in the same manner, but I haven't found that necessary.
Blob datatypes stores binary objects like images while text datatypes stores text objects like articles of webpages
In case you get a cross-domain error:
If you have control over the content of the iframe - that is, if it is merely loaded in a cross-origin setup such as on Amazon Mechanical Turk - you can circumvent this problem with the <body onload='my_func(my_arg)'>
attribute for the inner html.
For example, for the inner html, use the this
html parameter (yes - this
is defined and it refers to the parent window of the inner body element):
<body onload='changeForm(this)'>
In the inner html :
function changeForm(window) {
console.log('inner window loaded: do whatever you want with the inner html');
window.document.getElementById('mturk_form').style.display = 'none';
</script>
This works:
<script src="/clock.js" type="text/javascript"></script>
The leading slash means the root directory of your site. Strictly speaking, language="Javascript"
has been deprecated by type="text/javascript"
.
Capitalization of tags and attributes is also widely discouraged.
here you go
var str = "['abc',['def','ghi'],'jkl']";
//'[\'abc\',[\'def\',\'ghi\'],\'jkl\']'
str.replace(/[\[\]']/g,'' );
//'abc,def,ghi,jkl'
Use this after saving the image
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
{
"files.useExperimentalFileWatcher" : true
}
in Code -> Preferences -> Settings
Tested with Visual Studio Code Version 1.26.1 on mac and win
git branch
with no arguments displays the current branch marked with an asterisk in front of it:
user@host:~/gittest$ git branch
* master
someotherbranch
In order to not have to type this all the time, I can recommend git prompt:
https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh
In the AIX box how I can see that I am using master or inside a particular branch. What changes inside .git that drives which branch I am on?
Git stores the HEAD
in the file .git/HEAD
. If you're on the master
branch, it could look like this:
$ cat .git/HEAD
ref: refs/heads/master
To delete all stashes older than 40 days, use:
git reflog expire --expire-unreachable=40.days refs/stash
Add --dry-run
to see which stashes are deleted.
See https://stackoverflow.com/a/44829516/946850 for an explanation and much more detail.
If it is just avoiding the exception you are worried about, the "find_all_by.." family of functions works without throwing exceptions.
Comment.find_all_by_id([2, 3, 5])
will work even if some of the ids don't exist. This works in the
user.comments.find_all_by_id(potentially_nonexistent_ids)
case as well.
Comment.where(id: [2, 3, 5])
I've had the same problem, my fragments were pages of a ViewPager. The reason it was happening is that I was using child fragment manager rather than the activity support fragment manager when instantiating FragmentPagerAdapter.
It's been a while since the last time i touch swing but in general is a bad practice to do this. Some of the main disadvantages that comes to mind:
It's more expensive: you will have to allocate way more resources to draw a JFrame that other kind of window container, such as Dialog or JInternalFrame.
Not user friendly: It is not easy to navigate into a bunch of JFrame stuck together, it will look like your application is a set of applications inconsistent and poorly design.
It's easy to use JInternalFrame This is kind of retorical, now it's way easier and other people smarter ( or with more spare time) than us have already think through the Desktop and JInternalFrame pattern, so I would recommend to use it.
If you use function components and don't want to use a forwardRef
to measure your component's absolute layout, you can get a reference to it from the LayoutChangeEvent
in the onLayout
callback.
This way, you can get the absolute position of the element:
<MyFunctionComp
onLayout={(event) => {
event.target.measure(
(x, y, width, height, pageX, pageX) => {
doSomethingWithAbsolutePosition({
x: x + pageX,
y: y + pageY,
});
},
);
}}
/>
Tested with React Native 0.63.3.
First select current session sql_mode
:
SELECT @@SESSION.sql_mode;
Then you will get something like that default value:
'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'
and then set sql_mode
without 'NO_ZERO_DATE'
:
SET SESSION sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
If you have grants, you can do it also for GLOBAL
:
SELECT @@GLOBAL.sql_mode;
SET GLOBAL sql_mode = '...';
Finally, I've defeated my CiSCO EAP-FAST corporate wifi network, and all our Android devices are now able to connect to it.
The walk-around I've performed in order to gain access to this kind of networks from an Android device are easiest than you can imagine.
There's a Wifi Config Editor in the Google Play Store you can use to "activate" the secondary CISCO Protocols when you are setting up a EAP wifi connection.
Its name is Wifi Config Advanced Editor.
First, you have to setup your wireless network manually as close as you can to your "official" corporate wifi parameters.
Save it.
Go to the WCE and edit the parameters of the network you have created in the previous step.
There are 3 or 4 series of settings you should activate in order to force the Android device to use them as a way to connect (the main site I think you want to visit is Enterprise Configuration, but don't forget to check all the parameters to change them if needed.
As a suggestion, even if you have a WPA2 EAP-FAST Cipher, try LEAP in your setup. It worked for me as a charm.
When you finished to edit the config, go to the main Android wifi controller, and force to connect to this network.
Do not Edit the network again with the Android wifi interface.
I have tested it on Samsung Galaxy 1 and 2, Note mobile devices, and on a Lenovo Thinkpad Tablet.
There's a jQuery Timer plugin you may want to try
If you don't have to come back on the page with keeping form's value, you can do that :
<form method="post" th:action="@{''}" th:object="${form}">
<input class="form-control"
type="text"
th:field="${client.name}"/>
It's some kind of magic :
If you matter keeping you form's input values, like a back on the page with an user input mistake, then you will have to do that :
<form method="post" th:action="@{''}" th:object="${form}">
<input class="form-control"
type="text"
th:name="name"
th:value="${form.name != null} ? ${form.name} : ${client.name}"/>
That means :
Without having to map your client bean to your form bean. And it works because once you submitted the form, the value arn't null but "" (empty)
Open eclipse and right click in the package explorer ? import Select gradle Browse to the location where you checked out Click “Build Model” Select all the projects and hit finish
You might want to also try this application http://pdfbox.apache.org/. A working example can be found at https://www.jinises.com
SELECT MAX(Salary) FROM Employee WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )
This query will return the maximum salary, from the result - which not contains maximum salary from overall table.
Format
converts the values to strings. IsDate
still returns true because it can parse that string and get a valid date.
If you don't want to change the cells to string, don't use Format
. (IOW, don't convert them to strings in the first place.) Use the Cell.NumberFormat
, and set it to the date format you want displayed.
ActiveCell.NumberFormat = "mm/dd/yy" ' Outputs 10/28/13
ActiveCell.NumberFormat = "dd/mm/yyyy" ' Outputs 28/10/2013
wget -r http://mysite.com/configs/.vim/
works for me.
Perhaps you have a .wgetrc which is interfering with it?
NULL isn't equal to anything, not even itself. My personal solution to understanding the behavior of NULL is to avoid using it as much as possible :).
I'm using jQuery 3.3.1
and I received the same error, in my case, the URL was an Object
vs a string.
What happened was, that I took URL = window.location
- which returned an object. Once I've changed it into window.location.href
- it worked w/o the e.indexOf
error.
All the information about web browser is contained in navigator object. The name and version are there.
var appname = window.navigator.appName;
Source: javascript browser detection
The VH 100 does not work well on mobile as it does not factor in the iOS bar (or similar functionality on other platforms).
One solution that works well is to use JavaScript "window.innerHeight".
Simply assign the height of the element to this value e.g. $('.element-name').height(window.innerHeight);
Note: It may be useful to create a function in JS, so that the height can change when the screen is resized. However, I would suggest only calling the function when the width of the screen is changed, this way the element will not jump in height when the iOS bar disappears when the user scrolls down the page.
There is discussion of this, including links to browser testing and backwards compatibility, in the proposed RFC 5987, "Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters."
RFC 2183 indicates that such headers should be encoded according to RFC 2184, which was obsoleted by RFC 2231, covered by the draft RFC above.
Do a git rebase -i FAR_ENOUGH_BACK
and drop the line for the commit you don't want.
Easiest way to do label with different style such as color, font etc. is use property "Attributed" in Attributes Inspector. Just choose part of text and change it like you want
To have access to stuff provided by math
module, like pi
. You need to import the module first:
import math
print (math.pi)
One solution can be to set socket option TCP_MAXSEG (http://linux.die.net/man/7/tcp) to a value that is "safe" with underlying network (e.g. set to 1400 to be safe on ethernet) and then use a large buffer in send system call. This way there can be less system calls which are expensive. Kernel will split the data to match MSS.
This way you can avoid truncated data and your application doesn't have to worry about small buffers.
Create and similar object for comparison works too ex:
from datetime import datetime, date
now = datetime.now()
today = date.today()
# compare now with today
two_month_earlier = date(now.year, now.month - 2, now.day)
if two_month_earlier > today:
print(True)
two_month_earlier = datetime(now.year, now.month - 2, now.day)
if two_month_earlier > now:
print("this will work with datetime too")
A "JSON object" doesn't make sense : JSON is an exchange format based on the structure of Javascript object declaration.
If you want to convert your javascript object to a json string, use JSON.stringify(yourObject)
;
If you want to create a javascript object, simply do it like this :
var yourObject = {
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
};
If you are using Mac OS. Keep the version that you need and then following step help you stop updating chrome permanently.
To Disable auto update:-
Empty these directories:
~/Library/Google/GoogleSoftwareUpdate/
Then change the permissions on these folders named 'GoogleSoftwareUpdate' so that there's no owner and no read/write/execute permissions. In terminal:
cd /Library/Google/
sudo chown nobody:nogroup GoogleSoftwareUpdate
sudo chmod 000 GoogleSoftwareUpdate
cd ~/Library/Google/
sudo chown nobody:nogroup GoogleSoftwareUpdate
sudo chmod 000 GoogleSoftwareUpdate
Then do the same for the folder Google one level up.
cd /Library/
sudo chown nobody:nogroup Google
sudo chmod 000 Google
cd ~/Library/
sudo chown nobody:nogroup Google
sudo chmod 000 Google
Hope this help!
I agree with erickson's answer, with one caveat: for password authentication purposes, bcrypt is far better than a single iteration of SHA-512 - simply because it is far slower. If you don't get why slowness is an advantage in this particular game, read the article you linked to again (scroll down to "Speed is exactly what you don’t want in a password hash function.").
You can of course build a secure password hashing algorithm around SHA-512 by iterating it thousands of times, just like the way PHK's MD5 algorithm works. Ulrich Drepper did exactly this, for glibc's crypt(). There's no particular reason to do this, though, if you already have a tested bcrypt implementation available.
You were close :-)
select count(distinct productId) from table_name where keyword='$keyword'
In general, we want a solution that is vectorised, so here's a better test example:
whitespace <- " \t\n\r\v\f" # space, tab, newline,
# carriage return, vertical tab, form feed
x <- c(
" x y ", # spaces before, after and in between
" \u2190 \u2192 ", # contains unicode chars
paste0( # varied whitespace
whitespace,
"x",
whitespace,
"y",
whitespace,
collapse = ""
),
NA # missing
)
## [1] " x y "
## [2] " ? ? "
## [3] " \t\n\r\v\fx \t\n\r\v\fy \t\n\r\v\f"
## [4] NA
gsub
gsub
replaces all instances of a string (fixed = TRUE
) or regular expression (fixed = FALSE
, the default) with another string. To remove all spaces, use:
gsub(" ", "", x, fixed = TRUE)
## [1] "xy" "??"
## [3] "\t\n\r\v\fx\t\n\r\v\fy\t\n\r\v\f" NA
As DWin noted, in this case fixed = TRUE
isn't necessary but provides slightly better performance since matching a fixed string is faster than matching a regular expression.
If you want to remove all types of whitespace, use:
gsub("[[:space:]]", "", x) # note the double square brackets
## [1] "xy" "??" "xy" NA
gsub("\\s", "", x) # same; note the double backslash
library(regex)
gsub(space(), "", x) # same
"[:space:]"
is an R-specific regular expression group matching all space characters. \s
is a language-independent regular-expression that does the same thing.
stringr
approach: str_replace_all
and str_trim
stringr
provides more human-readable wrappers around the base R functions (though as of Dec 2014, the development version has a branch built on top of stringi
, mentioned below). The equivalents of the above commands, using [str_replace_all][3]
, are:
library(stringr)
str_replace_all(x, fixed(" "), "")
str_replace_all(x, space(), "")
stringr
also has a str_trim
function which removes only leading and trailing whitespace.
str_trim(x)
## [1] "x y" "? ?" "x \t\n\r\v\fy" NA
str_trim(x, "left")
## [1] "x y " "? ? "
## [3] "x \t\n\r\v\fy \t\n\r\v\f" NA
str_trim(x, "right")
## [1] " x y" " ? ?"
## [3] " \t\n\r\v\fx \t\n\r\v\fy" NA
stringi
approach: stri_replace_all_charclass
and stri_trim
stringi
is built upon the platform-independent ICU library, and has an extensive set of string manipulation functions. The equivalents of the above are:
library(stringi)
stri_replace_all_fixed(x, " ", "")
stri_replace_all_charclass(x, "\\p{WHITE_SPACE}", "")
Here "\\p{WHITE_SPACE}"
is an alternate syntax for the set of Unicode code points considered to be whitespace, equivalent to "[[:space:]]"
, "\\s"
and space()
. For more complex regular expression replacements, there is also stri_replace_all_regex
.
stringi
also has trim functions.
stri_trim(x)
stri_trim_both(x) # same
stri_trim(x, "left")
stri_trim_left(x) # same
stri_trim(x, "right")
stri_trim_right(x) # same
The service :
import 'rxjs/add/operator/map';
import { Http } from '@angular/http';
import { Observable } from "rxjs/Rx"
import { Injectable } from '@angular/core';
@Injectable()
export class ItemService {
private api = "your_api_url";
constructor(private http: Http) {
}
toSaveItem(item) {
return new Promise((resolve, reject) => {
this.http
.post(this.api + '/items', { item: item })
.map(res => res.json())
// This catch is very powerfull, it can catch all errors
.catch((err: Response) => {
// The err.statusText is empty if server down (err.type === 3)
console.log((err.statusText || "Can't join the server."));
// Really usefull. The app can't catch this in "(err)" closure
reject((err.statusText || "Can't join the server."));
// This return is required to compile but unuseable in your app
return Observable.throw(err);
})
// The (err) => {} param on subscribe can't catch server down error so I keep only the catch
.subscribe(data => { resolve(data) })
})
}
}
In the app :
this.itemService.toSaveItem(item).then(
(res) => { console.log('success', res) },
(err) => { console.log('error', err) }
)
application/force-download
is not a standard MIME type. It's a hack supported by some browsers, added fairly recently.
Your question doesn't really make any sense. It's like asking why Internet Explorer 4 doesn't support the latest CSS 3 functionality.
It's all about programmer convenience. I can imagine writing quick and dirty programs with this object.
/^0|[1-9]\d*$/
I was facing same problem.Tried every think mentioned here in blog.
But it was basic error to permit device "allow installing app from USB" which did it for me.
The window
binding refers to a built-in object provided by the browser. It represents the browser window that contains the document
. Calling its addEventListener
method registers the second argument (callback function) to be called whenever the event described by its first argument occurs.
<p>Some paragraph.</p>
<script>
window.addEventListener("click", () => {
console.log("Test");
});
</script>
Following points should be noted before select window or document to addEventListners
window
or document
but
some events like resize
, and other events related to loading
,
unloading
, and opening/closing
should all be set on the window.see http://download.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html
for example [A-Za-z0-9]
If you do not want to change the settings or play with command line. There is option to compress the file and upload in phpMyAdmin. It should bring down the size considerably.
I just had the exact same problem and it turned out to be caused by the fact that 2 projects in the same solution were referencing a different version of the 3rd party library.
Once I corrected all the references everything worked perfectly.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
int a = 543210 ;
char arr[10] ="" ;
itoa(a,arr,10) ; // itoa() is a function of stdlib.h file that convert integer
// int to array itoa( integer, targated array, base u want to
//convert like decimal have 10
for( int i= 0 ; i < strlen(arr); i++) // strlen() function in string file thar return string length
printf("%c",arr[i]);
}
def attributeSelection():
balance = 25
print("Your SP balance is currently 25.")
strength = input("How much SP do you want to put into strength?")
balanceAfterStrength = balance - int(strength)
if balanceAfterStrength == 0:
print("Your SP balance is now 0.")
attributeConfirmation()
elif strength < 0:
print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
attributeSelection()
elif strength > balance:
print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
attributeSelection()
elif balanceAfterStrength > 0 and balanceAfterStrength < 26:
print("Ok. You're balance is now at " + str(balanceAfterStrength) + " skill points.")
else:
print("That is an invalid input. Restarting attribute selection.")
attributeSelection()
In addition to the accepted answer, if you are using Android Studio you can
Android Device Monitor
,Devices
tab on the left,File Explorer
tab on the right,Pull a file from the device
button to save it to your local file systemselect Main form -> properties -> Windows style -> icon -> browse your ico
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
If you are locked out and WiFi is turned off in your Androud device then one solution is to connect your phone to a PC (connected to internet) and try to login with your google account. - it worked for me.
$(this).bind('input propertychange', function() {
//your code here
});
This is works for typing, paste, right click mouse paste etc.
The amazing ubiquity of Vim, and the even more amazing ubiquity of Vi-clones in general, on Unix systems alone is enough to make it worth learning.
Besides that, the whole Vi-style thinking is something that I really think has made me a bit more productive. For a person not used to modes such as the command mode and insert mode, it seems a bit excessive to have to enter a mode just to insert text. But, when one has been using Vim for a few months, and has learned quite a few tips and tricks, Vim seems to be an asset that seems to be worth it.
Of course, the Emacs crowd says the same thing regarding Emacs-style thinking, but I gave up on learning Emacs because Vim was simpler and did the job for me.
It's nice that Go has a Duration
type -- having explicitly defined units can prevent real-world problems.
And because of Go's strict type rules, you can't multiply a Duration by an integer -- you must use a cast in order to multiply common types.
/*
MultiplyDuration Hide semantically invalid duration math behind a function
*/
func MultiplyDuration(factor int64, d time.Duration) time.Duration {
return time.Duration(factor) * d // method 1 -- multiply in 'Duration'
// return time.Duration(factor * int64(d)) // method 2 -- multiply in 'int64'
}
The official documentation demonstrates using method #1:
To convert an integer number of units to a Duration, multiply:
seconds := 10
fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
But, of course, multiplying a duration by a duration should not produce a duration -- that's nonsensical on the face of it. Case in point, 5 milliseconds times 5 milliseconds produces 6h56m40s
. Attempting to square 5 seconds results in an overflow (and won't even compile if done with constants).
By the way, the int64
representation of Duration
in nanoseconds "limits the largest representable duration to approximately 290 years", and this indicates that Duration
, like int64
, is treated as a signed value: (1<<(64-1))/(1e9*60*60*24*365.25) ~= 292
, and that's exactly how it is implemented:
// A Duration represents the elapsed time between two instants
// as an int64 nanosecond count. The representation limits the
// largest representable duration to approximately 290 years.
type Duration int64
So, because we know that the underlying representation of Duration
is an int64
, performing the cast between int64
and Duration
is a sensible NO-OP -- required only to satisfy language rules about mixing types, and it has no effect on the subsequent multiplication operation.
If you don't like the the casting for reasons of purity, bury it in a function call as I have shown above.
The reject
actually takes one parameter: that's the exception that occurred in your code that caused the promise to be rejected. So, when you call reject()
the exception value is undefined
, hence the "undefined" part in the error that you get.
You do not show the code that uses the promise, but I reckon it is something like this:
var promise = doSth();
promise.then(function() { doSthHere(); });
Try adding an empty failure call, like this:
promise.then(function() { doSthHere(); }, function() {});
This will prevent the error to appear.
However, I would consider calling reject
only in case of an actual error, and also... having empty exception handlers isn't the best programming practice.
If you even did not get scroll after doing what is written above .....
Set the android:layout_height="250dp"
or you can say xdp
where x
can be any numerical value.
Is very simple, this is the way I use:
JQuery:
$(document).on('change', '[name="nameOfCheckboxes[]"]', function() {
var checkbox = $(this), // Selected or current checkbox
value = checkbox.val(); // Value of checkbox
if (checkbox.is(':checked'))
{
console.log('checked');
}else
{
console.log('not checked');
}
});
Regards!
position: absolute
will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static
.
Have your four divs nested inside the target div, give the target div position: relative
, and use position: absolute
on the others.
Structure your HTML similar to this:
<div id="container">
<div class="top left"></div>
<div class="top right"></div>
<div class="bottom left"></div>
<div class="bottom right"></div>
</div>
And this CSS should work:
#container {
position: relative;
}
#container > * {
position: absolute;
}
.left {
left: 0;
}
.right {
right: 0;
}
.top {
top: 0;
}
.bottom {
bottom: 0;
}
...
LCASE or UCASE respectively.
Example:
SELECT UCASE(MyColumn) AS Upper, LCASE(MyColumn) AS Lower
FROM MyTable
Gson is also good for it: http://code.google.com/p/google-gson/
" Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. "
Check the API examples: https://sites.google.com/site/gson/gson-user-guide#TOC-Overview More examples: http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
value.replaceAll("[^A-Za-z0-9]", "")
[^abc]
When a caret^
appears as the first character inside square brackets, it negates the pattern. This pattern matches any character except a or b or c.
Looking at the keyword as two function:
[(Pattern)] = match(Pattern)
[^(Pattern)] = notMatch(Pattern)
Moreover regarding a pattern:
A-Z = all characters included from A to Z
a-z = all characters included from a to z
0=9 = all characters included from 0 to 9
Therefore it will substitute all the char NOT included in the pattern
You can use the forName
method of Class
:
Class cls = Class.forName(clsName);
Object obj = cls.newInstance();
Just use this constructor of List<T>
. It accepts any IEnumerable<T>
as an argument.
string[] arr = ...
List<string> list = new List<string>(arr);
I don't see a problem here. With the following code using the Mockito API, I managed to do just that :
public class CodeWithPrivateMethod {
public void meaningfulPublicApi() {
if (doTheGamble("Whatever", 1 << 3)) {
throw new RuntimeException("boom");
}
}
private boolean doTheGamble(String whatever, int binary) {
Random random = new Random(System.nanoTime());
boolean gamble = random.nextBoolean();
return gamble;
}
}
And here's the JUnit test :
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.support.membermodification.MemberMatcher.method;
@RunWith(PowerMockRunner.class)
@PrepareForTest(CodeWithPrivateMethod.class)
public class CodeWithPrivateMethodTest {
@Test(expected = RuntimeException.class)
public void when_gambling_is_true_then_always_explode() throws Exception {
CodeWithPrivateMethod spy = PowerMockito.spy(new CodeWithPrivateMethod());
when(spy, method(CodeWithPrivateMethod.class, "doTheGamble", String.class, int.class))
.withArguments(anyString(), anyInt())
.thenReturn(true);
spy.meaningfulPublicApi();
}
}
I tracked the solution down to Interface Builder's insistence that springs cannot be changed on a view that has the simulated screen elements turned on (status bar, etc.). Since the springs were off for the main view, that view could not change size and hence was scrolled down in its entirety when the in-call bar appeared.
Turning the simulated features off, then resizing the view and setting the springs correctly caused the animation to occur and my method to be called.
An extra problem in debugging this is that the simulator quits the app when the in-call status is toggled via the menu. Quit app = no debugger.
I fixed this by passing the redirect url to the FacebookRedirectLoginHelper::getAccessToken()
in my callback function:
Changing from
try {
$accessToken = $helper->getAccessToken();
}
...
to
try {
$accessToken = $helper->getAccessToken($fbRedirectUrl);
}
...
I am developing on a vagrant box, and it seems FacebookRedirectLoginHelper::getCurrentUrl()
had issues generating a valid url.
You can use the following flags --single-branch
&& --depth
to download the specific branch and to limit the amount of history which will be downloaded.
You will clone the repo from a certain point in time and only for the given branch
git clone -b <branch> --single-branch <url> --depth <number of commits>
--[no-]single-branch
Clone only the history leading to the tip of a single branch, either specified by the
--branch
option or the primary branch remote’sHEAD
points at.Further fetches into the resulting repository will only update the
remote-tracking
branch for the branch this option was used for the initial cloning. If the HEAD at the remote did not point at any branch when--single-branch
clone was made, no remote-tracking branch is created.
--depth
Create a shallow clone with a history truncated to the specified number of commits
I use jupyter notebooks daily and had never experienced this issue before... until today. I had the notebook open all day but it wasn't running anything and then for no apparent reason stopped auto-saving with the '_xsrf' argument missing from POST
error message in the top right. FYI - this is a python3 notebook.
I don't know the cause of this problem but I have recently upgraded my python3 version to 3.7.2 and upgraded all of my site-packages to their latest version as of a few days ago which could possibly be the cause.
As for a solution, as suggested in the comment by @AlexK, I opened the same notebook in a new window (different browser in fact), using
jupyter notebook list
in the terminal to get the URL with login token.
This resulted in me having the notebook open and savable again but the information I had entered since the last successful auto-save was missing. Thankfully, my broken instance was still open and working apart from saving so I was able to simply copy and paste the information across then hit save. So, keep the broken instance open if you try this!
I was facing same issue in my exercise. Although not related, yet might give some reference. I didn't get any error once I placed addition_result = 0 inside function. Hope it helps! Apologize if this answer is not in context.
user_input = input("Enter multiple values separated by comma > ")
def add_numbers(num_list):
addition_result = 0
for i in num_list:
addition_result = addition_result + i
print(addition_result)
add_numbers(user_input)
std::vector
orThis fix / solution worked for me: Device Manager --> Ports --> right click on Arduino Uno --> Update Driver Software --> Search automatically for updated driver software
UPDATE:
In scikit-learn 0.22, there's a new feature to plot the confusion matrix directly.
See the documentation: sklearn.metrics.plot_confusion_matrix
OLD ANSWER:
I think it's worth mentioning the use of seaborn.heatmap
here.
import seaborn as sns
import matplotlib.pyplot as plt
ax= plt.subplot()
sns.heatmap(cm, annot=True, ax = ax); #annot=True to annotate cells
# labels, title and ticks
ax.set_xlabel('Predicted labels');ax.set_ylabel('True labels');
ax.set_title('Confusion Matrix');
ax.xaxis.set_ticklabels(['business', 'health']); ax.yaxis.set_ticklabels(['health', 'business']);
Different SQL, same principle. Only insert if the clause in where not exists fails
INSERT INTO FX_USDJPY
(PriceDate,
PriceOpen,
PriceLow,
PriceHigh,
PriceClose,
TradingVolume,
TimeFrame)
SELECT '2014-12-26 22:00',
120.369000000000,
118.864000000000,
120.742000000000,
120.494000000000,
86513,
'W'
WHERE NOT EXISTS
(SELECT 1
FROM FX_USDJPY
WHERE PriceDate = '2014-12-26 22:00'
AND TimeFrame = 'W')
Press Ctrl + Shift + P to open the Command Palette, then write command : Toggle Menu Bar
In the past I have used HttpUtility.HtmlEncode to encode text for xml. It performs the same task, really. I havent ran into any issues with it yet, but that's not to say I won't in the future. As the name implies, it was made for HTML, not XML.
You've probably already read it, but here is an article on xml encoding and decoding.
EDIT: Of course, if you use an xmlwriter or one of the new XElement classes, this encoding is done for you. In fact, you could just take the text, place it in a new XElement instance, then return the string (.tostring) version of the element. I've heard that SecurityElement.Escape will perform the same task as your utility method as well, but havent read much about it or used it.
EDIT2: Disregard my comment about XElement, since you're still on 2.0
var files = Directory.GetFiles(@"E:\ftproot\sales");
The only problem with JSON in Java is that if your XML has a single child, but is an array, it will convert it to an object instead of an array. This can cause problems if you dynamically always convert from XML to JSON, where if your example XML has only one element, you return an object, but if it has 2+, you return an array, which can cause parsing issues for people using the JSON.
Infoscoop's XML2JSON class has a way of tagging elements that are arrays before doing the conversion, so that arrays can be properly mapped, even if there is only one child in the XML.
Here is an example of using it (in a slightly different language, but you can also see how arrays is used from the nodelist2json() method of the XML2JSON link).
I was dealing with DateTimeOffset
and unfortunately the "o" prints out "+0000" not "Z".
So I ended up with:
dateTimeOffset.UtcDateTime.ToString("o")
Swift 3:
override func didMove(toParentViewController parent: UIViewController?) {
super.didMove(toParentViewController: parent)
if parent == nil{
print("Back button was clicked")
}
}
Use the command
git clone --help
to see whether your git supports the command
git clone --branch tag_name
If not, just do the following:
git clone repo_url
cd repo
git checkout tag_name
I was in the same situation and found this one,
I assume that you know how to execute the command using the ProcessBuilder
.
Executing a command from Java always should read the stdout and stderr streams from the process. Otherwise it can happen that the buffer is full and the process cannot continue because writing its stdout or stderr blocks.
After spending far too long troubleshooting this, I found a simple workaround which ensures IntelliJ processes Lombok annotations correctly during builds.
The gradle-lombok plugin is not necessary for this workaround. Your build.gradle
only requires the following:
dependencies {
compileOnly("org.projectlombok:lombok:1.16.18")
}
The workaround is to turn on the following IntelliJ setting:
Build, Execute, Deployment > Build Tools > Gradle > Runner
Delegate IDE build/run actions to gradle
Benefits of this workaround compared to other solutions on this page:
One downside is that IntelliJ will no longer use its own test runner. Instead, tests are always run through Gradle.
Another approach using linq is:
foreach ( int number in numbers.Skip(1))
{
// process number
}
If you want to skip the first in a number of items.
Or use .SkipWhere
if you want to specify a condition for skipping.
Subscribe capturing phase of click to handle click on elements which call preventDefault
.
Retrigger it on document element using the other name click-anywhere
.
document.addEventListener('click', function (event) {
event = $.event.fix(event);
event.type = 'click-anywhere';
$document.trigger(event);
}, true);
Then where you need click outside functionality subscribe on click-anywhere
event on document
and check if the click was outside of the element you are interested in:
$(document).on('click-anywhere', function (event) {
if (!$(event.target).closest('#smth').length) {
// Do anything you need here
}
});
Some notes:
You have to use document
as it would be a perfomance fault to trigger event on all elements outside of which the click occured.
This functionality can be wrapped into special plugin, which calls some callback on outside click.
You can't subscribe capturing phase using jQuery itself.
You don't need document load to subscribe as subscription is on document
, even not on its body
, so it exists always independently ???? script placement and load status.
For Microsoft Azure, it's slightly different.
Azure has a special CORS setting that needs to be set. It's essentially the same thing behind the scenes, but simply setting the header joshuarh mentions will not work. The Azure documentation for enabling cross domain can be found here:
https://docs.microsoft.com/en-us/azure/app-service-api/app-service-api-cors-consume-javascript
I fiddled around with this for a few hours before realizing my hosting platform had this special setting.
Another choice besides JObject is System.Json.JsonValue for Weak-Typed JSON object.
It also has a JsonValue blob = JsonValue.Parse(json);
you can use. The blob will most likely be of type JsonObject
which is derived from JsonValue
, but could be JsonArray
. Check the blob.JsonType
if you need to know.
And to answer you question, YES, you may replace json
with the name of your actual variable that holds the JSON string. ;-D
There is a System.Json.dll you should add to your project References.
-Jesse
You almost got it. It should be this:
<input type="radio" name="group1" id="r1" value="1" />_x000D_
<label for="r1"> button one</label>
_x000D_
The value in for
should be the id of the element you are labeling.
A simple program to print "N" prime numbers. You can use N value as 100.
#include <iostream >
using namespace std;
int main()
{
int N;
cin >> N;
for (int i = 2; N > 0; ++i)
{
bool isPrime = true ;
for (int j = 2; j < i; ++j)
{
if (i % j == 0)
{
isPrime = false ;
break ;
}
}
if (isPrime)
{
--N;
cout << i << "\n";
}
}
return 0;
}
the over partition keyword is as if we are partitioning the data by client_id creation a subset of each client id
select client_id, operation_date,
row_number() count(*) over (partition by client_id order by client_id ) as operationctrbyclient
from client_operations e
order by e.client_id;
this query will return the number of operations done by the client_id
You can use this to refresh an Activity from within itself.
finish();
startActivity(getIntent());
Funny enough there was no non mutating recursive answer:
var shuffle = arr => {_x000D_
const recur = (arr,currentIndex)=>{_x000D_
console.log("What?",JSON.stringify(arr))_x000D_
if(currentIndex===0){_x000D_
return arr;_x000D_
}_x000D_
const randomIndex = Math.floor(Math.random() * currentIndex);_x000D_
const swap = arr[currentIndex];_x000D_
arr[currentIndex] = arr[randomIndex];_x000D_
arr[randomIndex] = swap;_x000D_
return recur(_x000D_
arr,_x000D_
currentIndex - 1_x000D_
);_x000D_
}_x000D_
return recur(arr.map(x=>x),arr.length-1);_x000D_
};_x000D_
_x000D_
var arr = [1,2,3,4,5,[6]];_x000D_
console.log(shuffle(arr));_x000D_
console.log(arr);
_x000D_
foo = [1, 2, 3]
bar = [4, 5, 6]
foo.append(bar) --> [1, 2, 3, [4, 5, 6]]
foo.extend(bar) --> [1, 2, 3, 4, 5, 6]
you can use it like this as i do it for login and manny different things
class Login extends Component {
constructor(props){
super(props);
this.login=this.login.bind(this)
}
login(){
this.props.history.push('/dashboard');
}
render() {
return (
<div>
<button onClick={this.login}>login</login>
</div>
)
There is a way. $q.all(...
You can check the below stuffs:
Follow these steps:
Microsoft Access Database Engine 2016 Redistributable
and installA reset will normally change everything, but you can use git stash
to pick what you want to keep. As you mentioned, stash
doesn't accept a path directly, but it can still be used to keep a specific path with the --keep-index
flag. In your example, you would stash the b directory, then reset everything else.
# How to make files a/* reappear without changing b and without recreating a/c?
git add b #add the directory you want to keep
git stash --keep-index #stash anything that isn't added
git reset #unstage the b directory
git stash drop #clean up the stash (optional)
This gets you to a point where the last part of your script will output this:
After checkout:
# On branch master
# Changes not staged for commit:
#
# modified: b/a/ba
#
no changes added to commit (use "git add" and/or "git commit -a")
a/a/aa
a/b/ab
b/a/ba
I believe this was the target result (b remains modified, a/* files are back, a/c is not recreated).
This approach has the added benefit of being very flexible; you can get as fine-grained as you want adding specific files, but not other ones, in a directory.
The HtmlDocument
class is a wrapper around the native IHtmlDocument2
COM interface.
You cannot easily create it from a string.
You should use the HTML Agility Pack.
You should really post:
Here is my code, which works:
import socket, sys
def alert(msg):
print >>sys.stderr, msg
sys.exit(1)
(family, socktype, proto, garbage, address) = \
socket.getaddrinfo("::1", "http")[0] # Use only the first tuple
s = socket.socket(family, socktype, proto)
try:
s.connect(address)
except Exception, e:
alert("Something's wrong with %s. Exception type is %s" % (address, e))
When the server listens, I get nothing (this is normal), when it doesn't, I get the expected message:
Something's wrong with ('::1', 80, 0, 0). Exception type is (111, 'Connection refused')
Click on choose existing and again choose the location where your jks file is located.
I hope this trick works for you.
function UpdateClick(btn) {
for (i = 0; i < Page_Validators.length; i++) {
ValidatorValidate(Page_Validators[i]);
if (Page_Validators[i].isvalid == false)
return false;
}
btn.disabled = 'false';
btn.value = 'Please Wait...';
return true;
}
With ES6, you can now use the spread operator to create a new array with your new elements inserted before the original elements.
// Prepend a single item._x000D_
const a = [1, 2, 3];_x000D_
console.log([0, ...a]);
_x000D_
// Prepend an array._x000D_
const a = [2, 3];_x000D_
const b = [0, 1];_x000D_
console.log([...b, ...a]);
_x000D_
I intended this answer to present an alternative syntax that I think is more memorable and concise. It should be noted that according to some benchmarks (see this other answer), this syntax is significantly slower. This is probably not going to matter unless you are doing many of these operations in a loop.
Here are some combinations which I tried to login:
# login via user foo
psql -Ufoo -h localhost
sudo -u postgres psql postgres
# user foo login to postgres db
psql -Ufoo -h localhost -d postgres
What is the difference between Git and GitHub?
Git is a version control system; think of it as a series of snapshots (commits) of your code. You see a path of these snapshots, in which order they where created. You can make branches to experiment and come back to snapshots you took.
GitHub, is a web-page on which you can publish your Git repositories and collaborate with other people.
Is Git saving every repository locally (in the user's machine) and in GitHub?
No, it's only local. You can decide to push (publish) some branches on GitHub.
Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?
Yes, Git runs local if you don't use GitHub. An alternative to using GitHub could be running Git on files hosted on Dropbox, but GitHub is a more streamlined service as it was made especially for Git.
How does Git compare to a backup system such as Time Machine?
It's a different thing, Git lets you track changes and your development process. If you use Git with GitHub, it becomes effectively a backup. However usually you would not push all the time to GitHub, at which point you do not have a full backup if things go wrong. I use git in a folder that is synchronized with Dropbox.
Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?
Yes, committing and pushing are both manual.
If are not collaborating and you are already using a backup system why would you use Git?
If you encounter an error between commits you can use the command git diff
to see the differences between the current code and the last working commit, helping you to locate your error.
You can also just go back to the last working commit.
If you want to try a change, but are not sure that it will work. You create a branch to test you code change. If it works fine, you merge it to the main branch. If it does not you just throw the branch away and go back to the main branch.
You did some debugging. Before you commit you always look at the changes from the last commit. You see your debug print statement that you forgot to delete.
Make sure you check gitimmersion.com.
No one said, but array_push only pushes a element to the END OF THE ARRAY, where $array[index] can insert a value at any given index. Big difference.
Sven said it all, just be very cautious because of automatic type adjustments when append is called.
In [2]: import numpy as np
In [3]: a = np.array([1,2,3])
In [4]: b = np.array([1.,2.,3.])
In [5]: c = np.array(['a','b','c'])
In [6]: np.append(a,b)
Out[6]: array([ 1., 2., 3., 1., 2., 3.])
In [7]: a.dtype
Out[7]: dtype('int64')
In [8]: np.append(a,c)
Out[8]:
array(['1', '2', '3', 'a', 'b', 'c'],
dtype='|S1')
As you see based on the contents the dtype went from int64 to float32, and then to S1
If someone is using @Sceduled this might work for you.
@Scheduled(cron = "${name-of-the-cron:0 0/30 * * * ?}")
This worked for me.
If you have something that's O(f(n)) that means there's are k, g(n) such that f(n) ≤ k g(n).
If you have something that's Ω(f(n)) that means there's are k, g(n) such that f(n) ≥ k g(n).
And if you have a something with O(f(n)) and Ω(f(n)), then it's Θ(f(n).
The Wikipedia article is decent, if a little dense.
Using the following pipeline script:
pipeline {
agent { label "master" }
options { skipDefaultCheckout() }
stages {
stage('CleanWorkspace') {
steps {
cleanWs()
}
}
}
}
Follow these steps:
Silly question. Found that there's a
lsvirtualenv
command which lists all existing virtualenv.
All the plugins listed above have a serious problem - they are using the virtual folders implemented via WordPress Taxonomy API, while X4 Media Library is using the real physical folders located in your wp-content/uploads
directory on the server.
What happens when you put some images to the folder using any plugin listed above? Because of they are using the virtual folders, the destinition folder is represented as a taxonomy tag in the database, so they just assign the folder's tag to moved files.
There are no real modifications happened on your physical disk, in the wp-content/uploads
directory. You can see that images URL didn't change when you move them to another folder.
Alternatively, with X4 Media Library if you put some files to the folder they will really be moved to that physical folder on your disk, in the wp-content/uploads
directory, and the images URL will be changed automatically.
Moreover, this plugin will make sure that all the links associated with these images in all your Posts, Pages and other custom types will be updated automatically.
mkdir -p newDir/subdir{1..8}
ls newDir/
subdir1 subdir2 subdir3 subdir4 subdir5 subdir6 subdir7 subdir8
Following worked in version 1.53.2 on windows 10 ->
People who are still struggling for the simple and best approach, you can use Spread Syntax
for extending object.
var person1 = {_x000D_
name: "Blank",_x000D_
age: 22_x000D_
};_x000D_
_x000D_
var person2 = {_x000D_
name: "Robo",_x000D_
age: 4,_x000D_
height: '6 feet'_x000D_
};_x000D_
// spread syntax_x000D_
let newObj = { ...person1, ...person2 };_x000D_
console.log(newObj.height);
_x000D_
Note: Remember that, the property is farthest to the right will have the priority. In this example, person2
is at right side, so newObj
will have name Robo in it.
The above code not worked for me. I found new solution :
var pdf = new jsPDF();
var img = new Image;
img.onload = function() {
pdf.addImage(this, 10, 10);
pdf.save("test.pdf");
};
img.crossOrigin = "";
img.src = "assets/images/logo.png";
This website is pretty good but not specific to Java: http://bigocheatsheet.com/
If you add this to your meta tags:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
IE8 will render the page like IE7.
Use this:
"$computer, $Speed, $Regcheck" | out-file -filepath C:\temp\scripts\pshell\dump.txt -append -width 200
Use This as the solution
This worked for me perfectly..
<div align="center">
<img src="">
</div>
first, you need to load URL helper like this type or you can upload within autoload.php file:
$this->load->helper('url');
if (!$user_logged_in)
{
redirect('/account/login', 'refresh');
}
You need to use the group(int) of your matcher - group(0) is the entire match, and group(1) is the first group you marked. In the example you specify, group(1) is what comes after "sentence".
place after input
<script type="text/javascript">document.formname.inputname.focus();</script>
for each project in your solution make sure that
Properties > Config. Properties > General > Platform Toolset
is one for all of them, v100 for visual studio 2010, v110 for visual studio 2012
you also may be working on v100 from visual studio 2012
From a child document of different origin you are not allowed access to the top window's location.hash
property, but you are allowed to set the location
property itself.
This means that given that the top windows location is http://example.com/page/
, instead of doing
parent.location.hash = "#foobar";
you do need to know the parents location and do
parent.location = "http://example.com/page/#foobar";
Since the resource is not navigated this will work as expected, only changing the hash part of the url.
If you are using this for cross-domain communication, then I would recommend using easyXDM instead.
-eq
is a mathematical comparison operator. I've never used it for string comparison, relying on ==
and !=
for compares.
if [ 'XYZ' == 'ABC' ]; then # Double equal to will work in Linux but not on HPUX boxes it should be if [ 'XYZ' = 'ABC' ] which will work on both
echo "Match"
else
echo "No Match"
fi
Open eclipse go to Servers panel, right click or press F3 to open Overview window and go to Ports (Modify the server ports). You will get the following:
tomcat adminport
HTTP/1.1
AJP/1.3
You can change the port numbers (e.g. HTTP/1.1 port number 8080 to 8082).
Maybe I've late a bit, but you really should try to use json library from play framework. You could look at documentation. In current 2.1.1 release you could not separately use it without whole play 2, so dependency will looks like this:
val typesaferepo = "TypeSafe Repo" at "http://repo.typesafe.com/typesafe/releases"
val play2 = "play" %% "play" % "2.1.1"
It will bring you whole play framework with all stuff on board.
But as I know guys from Typesafe have a plan to separate it in 2.2 release. So, there is standalone play-json from 2.2-snapshot.
Dictionary<,> is the equivalent. While it doesn't have a Get(...) method, it does have an indexed property called Item which you can access in C# directly using index notation:
class Test {
Dictionary<int,String> entities;
public String getEntity(int code) {
return this.entities[code];
}
}
If you want to use a custom key type then you should consider implementing IEquatable<> and overriding Equals(object) and GetHashCode() unless the default (reference or struct) equality is sufficient for determining equality of keys. You should also make your key type immutable to prevent weird things happening if a key is mutated after it has been inserted into a dictionary (e.g. because the mutation caused its hash code to change).
I found something I did wrong, install the Apache and MySQL services. Click on the WAMP logo, goto Apache -> Service -> Install Service, after that Apache -> Service -> Start/Resume Service. Do the same for MySQL and it will turn green.
Historically, from UNIX v7, the process system has detected orphanity of processes by checking a process' parent id. As I say, historically, the init(8)
system process is a special process by only one reason: It cannot die. It cannot die because the kernel algorithm to deal with assigning a new parent process id, depends on this fact. when a process executes its exit(2)
call (by means of a process system call or by external task as sending it a signal or the like) the kernel reassigns all children of this process the id of the init process as their parent process id. This leads to the most easy test, and most portable way of knowing if a process has got orphan. Just check the result of the getppid(2)
system call and if it is the process id of the init(2)
process then the process got orphan before the system call.
Two issues emerge from this approach that can lead to issues:
init
process to any user process, so How can we assure that the init process will always be parent of all orphan processes? Well, in the exit
system call code there's a explicit check to see if the process executing the call is the init process (the process with pid equal to 1) and if that's the case, the kernel panics (It should not be able anymore to maintain the process hierarchy) so it is not permitted for the init process to do an exit(2)
call.1
, but that's not warranted by the POSIX approach, that states (as exposed in other response) that only a system's process id is reserved for that purpose. Almost no posix implementation does this, and you can assume in original unix derived systems that having 1
as response of getppid(2)
system call is enough to assume the process is orphan. Another way to check is to make a getppid(2)
just after the fork and compare that value with the result of a new call. This simply doesn't work in all cases, as both call are not atomic together, and the parent process can die after the fork(2)
and before the first getppid(2)
system call. The processparent id only changes once, when its parent does an
exit(2)call, so this should be enough to check if the
getppid(2)result changed between calls to see that parent process has exit. This test is not valid for the actual children of the init process, because they are always children of
init(8)`, but you can assume safely these processes as having no parent either (except when you substitute in a system the init process)That's because timer is a local variable to your function.
Try creating it outside of the function.
Try using {}
instead of ()
:
${"file".$i} = file($filelist[$i]);
There are 3 states for boolean in PG: true, false and unknown (null). Explained here: Postgres boolean datatype
Therefore you need only query for NOT TRUE:
SELECT * from table_name WHERE boolean_column IS NOT TRUE;
Thanks Aakash for recommending JIDE MultilineLabel. JIDE's StyledLabel is also enhanced recently to support multiple line. I would recommend it over the MultilineLabel as it has many other great features. You can check out an article on StyledLabel below. It is still free and open source.
You can use List<Y>.ConvertAll<T>([Converter from Y to T]);
List indexes of -x mean the xth item from the end of the list, so n[-1]
means the last item in the list n
. Any good Python tutorial should have told you this.
It's an unusual convention that only a few other languages besides Python have adopted, but it is extraordinarily useful; in any other language you'll spend a lot of time writing n[n.length-1]
to access the last item of a list.
You can also use
./gradlew clean build
(Mac and Linux) -With ./
gradlew clean build
(Windows) -Without ./
it removes build folder, as well configure your modules and then build your project.
i use it before release any new app on playstore.
Simplest way is to save it to temp file and then read it:
import pandas as pd
CSV_FILE_NAME = 'temp_file.csv' # Consider creating temp file, look URL below
with open(CSV_FILE_NAME, 'w') as outfile:
outfile.write(TESTDATA)
df = pd.read_csv(CSV_FILE_NAME, sep=';')
Right way of creating temp file: How can I create a tmp file in Python?
Your code is, I'm sorry to say, very C-like.
A Java String
is not a char[]
. You say you want to remove duplicates from a String
, but you take a char[]
instead.
Is this char[]
\0
-terminated? Doesn't look like it because you take the whole .length
of the array. But then your algorithm tries to \0
-terminate a portion of the array. What happens if the arrays contains no duplicates?
Well, as it is written, your code actually throws an ArrayIndexOutOfBoundsException
on the last line! There is no room for the \0
because all slots are used up!
You can add a check not to add \0
in this exceptional case, but then how are you planning to use this code anyway? Are you planning to have a strlen
-like function to find the first \0
in the array? And what happens if there isn't any? (due to all-unique exceptional case above?).
What happens if the original String
/char[]
contains a \0
? (which is perfectly legal in Java, by the way, see JLS 10.9 An Array of Characters is Not a String)
The result will be a mess, and all because you want to do everything C-like, and in place without any additional buffer. Are you sure you really need to do this? Why not work with String
, indexOf
, lastIndexOf
, replace
, and all the higher-level API of String
? Is it provably too slow, or do you only suspect that it is?
"Premature optimization is the root of all evils". I'm sorry but if you can't even understand what the original code does, then figuring out how it will fit in the bigger (and messier) system will be a nightmare.
My minimal suggestion is to do the following:
String
, i.e. public static String removeDuplicates(String in)
char[] str = in.toCharArray();
return new String(str, 0, tail);
This does use additional buffers, but at least the interface to the rest of the system is much cleaner.
Alternatively, you can use StringBuilder
as such:
static String removeDuplicates(String s) {
StringBuilder noDupes = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
String si = s.substring(i, i + 1);
if (noDupes.indexOf(si) == -1) {
noDupes.append(si);
}
}
return noDupes.toString();
}
Note that this is essentially the same algorithm as what you had, but much cleaner and without as many little corner cases, etc.
You can always try doing it manually from the command prompt. Navigate to the path of the file and type:
gcc filename.c -o filename
You can also do it this way without the need of Linq:
List<int> numbers = new List<int>( Array.ConvertAll(sNumbers.Split(','), int.Parse) );
// Uses Linq
var numbers = Array.ConvertAll(sNumbers.Split(','), int.Parse).ToList();
$ git rev-parse HEAD 273cf91b4057366a560b9ddcee8fe58d4c21e6cb
Update:
Alternatively (if you have tags):
(Good for naming a version, not very good for passing back to git.)
$ git describe v0.1.49-localhost-ag-1-g273cf91
Or (as Mark suggested, listing here for completeness):
$ git show --oneline -s c0235b7 Autorotate uploaded images based on EXIF orientation
Use the LEN
function:
Returns the number of characters of the specified string expression, excluding trailing blanks.
getResourceAsStream
is the right way to do it for web apps (as you already learned).
The reason is that reading from the file system cannot work if you package your web app in a WAR. This is the proper way to package a web app. It's portable that way, because you aren't dependent on an absolute file path or the location where your app server is installed.
import com.google.common.collect.Streams;
and use Streams.stream(iterator)
:
Streams.stream(iterator)
.map(v-> function(v))
.collect(Collectors.toList());
To ignore a field, annotate it with @Transient
so it will not be mapped by hibernate.
but then jackson will not serialize the field when converting to JSON.
If you need mix JPA with JSON(omit by JPA but still include in Jackson) use @JsonInclude
:
@JsonInclude()
@Transient
private String token;
TIP:
You can also use JsonInclude.Include.NON_NULL and hide fields in JSON during deserialization when token == null
:
@JsonInclude(JsonInclude.Include.NON_NULL)
@Transient
private String token;
If you use dplyr
package you can do:
library(dplyr)
filter(df, aged <= laclen)
With the help of this post, I create following function with additional length checks
public string ReplaceStringByIndex(string original, string replaceWith, int replaceIndex)
{
if (original.Length >= (replaceIndex + replaceWith.Length))
{
StringBuilder rev = new StringBuilder(original);
rev.Remove(replaceIndex, replaceWith.Length);
rev.Insert(replaceIndex, replaceWith);
return rev.ToString();
}
else
{
throw new Exception("Wrong lengths for the operation");
}
}
Even better:
DataTable DTable = new DataTable();
BindingSource SBind = new BindingSource();
SBind.DataSource = DTable;
DataGridView ServersTable = new DataGridView();
ServersTable.AutoGenerateColumns = false;
ServersTable.DataSource = DTable;
ServersTable.DataSource = SBind;
ServersTable.Refresh();
You're telling the bindable source that it's bound to the DataTable, in-turn you need to tell your DataGridView not to auto-generate columns, so it will only pull the data in for the columns you've manually input into the control... lastly refresh the control to update the databind.
The simple solution that is working for me:
XmlDocument xmlDoc = new XmlDocument();
StringWriter sw = new StringWriter();
xmlDoc.LoadXml(rawStringXML);
xmlDoc.Save(sw);
String formattedXml = sw.ToString();
docker-compose run myapp sh
should do the deal.
There is some confusion with up
/run
, but docker-compose run
docs have great explanation: https://docs.docker.com/compose/reference/run
I'm one of the developers who helped create Sass.
The difference is UI. Underneath the textual exterior they are identical. This is why sass and scss files can import each other. Actually, Sass has four syntax parsers: scss, sass, CSS, and less. All of these convert a different syntax into an Abstract Syntax Tree which is further processed into CSS output or even onto one of the other formats via the sass-convert tool.
Use the syntax you like the best, both are fully supported and you can change between them later if you change your mind.
You should be able to find your command with a ps
variant like:
ps -ef
ps -fubob # if your job's user ID is bob.
Then, once located, it should be a simple matter to use kill
to kill the process (permissions permitting).
If you're talking about getting rid of jobs in the at
queue (that aren't running yet), you can use atq
to list them and atrm
to get rid of them.
The other answers didn't work for me, but this did:
del /s /q *.svn
rmdir /s /q *.svn
/q disables Yes/No prompting
/s means delete the file(s) from all subdirectories.
In addition to @JBNizet's answer, my general use case for ifPresent
is to combine .isPresent()
and .get()
:
Old way:
Optional opt = getIntOptional();
if(opt.isPresent()) {
Integer value = opt.get();
// do something with value
}
New way:
Optional opt = getIntOptional();
opt.ifPresent(value -> {
// do something with value
})
This, to me, is more intuitive.
No , Both are different . Composition follow "HAS-A" relationship and inheritance follow "IS-A" relationship . Best Example for composition was Strategic pattern .
Here is what worked for me when I deployed to Heroku.
http://flask-cors.readthedocs.org/en/latest/
Install flask-cors by running -
pip install -U flask-cors
from flask import Flask
from flask_cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
@app.route("/")
@cross_origin()
def helloWorld():
return "Hello, cross-origin-world!"
>>> x='$120'
>>> import string
>>> a=string.maketrans('','')
>>> ch=a.translate(a, string.digits)
>>> int(x.translate(a, ch))
120
Here's an implementation that returns fractional seconds (i.e. 1.321 seconds)
/**
* MICROSECOND STOPWATCH FOR PHP
*
* Class FnxStopwatch
*/
class FnxStopwatch
{
/** @var float */
private $start,
$stop;
public function start()
{
$this->start = self::microtime_float();
}
public function stop()
{
$this->stop = self::microtime_float();
}
public function getIntervalSeconds() : float
{
// NOT STARTED
if (empty($this->start))
return 0;
// NOT STOPPED
if (empty($this->stop))
return ($this->stop - self::microtime_float());
return $interval = $this->stop - $this->start;
}
/**
* FOR MORE INFO SEE http://us.php.net/microtime
*
* @return float
*/
private static function microtime_float() : float
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
}
$header3 = @("Field_1","Field_2","Field_3","Field_4","Field_5")
Import-Csv $fileName -Header $header3 -Delimiter "`t" | select -skip 3 | Foreach-Object {
$record = $indexName
foreach ($property in $_.PSObject.Properties){
#doSomething $property.Name, $property.Value
if($property.Name -like '*TextWrittenAsNumber*'){
$record = $record + "," + '"' + $property.Value + '"'
}
else{
$record = $record + "," + $property.Value
}
}
$array.add($record) | out-null
#write-host $record
}
I would add, and also to answer the question find mean bin values using histogram2d python that the scipy also have a function specially designed to compute a bidimensional binned statistic for one or more sets of data
import numpy as np
from scipy.stats import binned_statistic_2d
x = np.random.rand(100)
y = np.random.rand(100)
values = np.random.rand(100)
bin_means = binned_statistic_2d(x, y, values, bins=10).statistic
the function scipy.stats.binned_statistic_dd is a generalization of this funcion for higher dimensions datasets
I also met this problem while using Xshell to connect Linux server.
After seaching for methods, I find Xming + Xshell to solve image imshow problem with matplotlib.
If solutions aboved can't solve your problem, just try to download Xming under the condition you're using Xshell. Then set the attribute in Xshell, SSH->tunnel->X11transfer->choose X DISPLAY localhost:0.0
All too often a new developer asks this simple question which is a common problem specifically with Visual Studio IDE's. Few people answer the specific question and often critique the question or give "guesses" for solutions which don't answer the common problems. The first common problem is the IDE leads you to create new projects rather than add new files (.java, .py, .cpp, .c) to the existing solution (by default it creates a new solution) unless you change the project name and add to the current solution. This problem occurs for Python, java, c#, C++ and C project folders.
The new developer selecting "new>project>project name and changing the solution directory to "use same solution" still creates a new "project" in the same solution space, but not in the same directory space as the current user interface file or command line file which still leads to problems with "package not found" errors when building and running the project or solution. This is why the above coding suggestions to importing packages, classes, methods and functions only work (and thus don't answer the question) when the "library" file or "separate behavior" file is not only in the same solution directory path, but also in the same "user interface" or "command shell" application directory space. This does does not happen when you add another project using the new>project>project type commands of the IDE. The problem here is the new project is stored in a different directory than the existing Client or User interface code files. To create a new "file" in the same project space rather than new project the beginner needs to do the following that Microsoft won't do for you and even misleads you away from the intuitively obvious by default.
NOW the code recommendations to import libraries or using namespaces will work as described in the comments above and you don't have to change path statements or change solutions paths and solution names that Microsoft won't let you change easily (i.e. you can change the filenames or project names but the IDE won't automatically change the project path or the solution path names).
The following is a Python example but works similar for C#, java, or C/C++ using the includes, namespaces or using code commands appropriate to each language to find code in other classes/projects in the SAME DIRECTORY SPACE.
The application file "hello world" importing from other code files in the same directory.
Note the python white space delimiters are not going to space correctly in this stackoverflow comment editor:
print ("test")
from CIXMPythonFacade import ClassA
c1=ClassA
c1.methodA()
from CIXMPythonFacade import functionA
functionA()
class ClassName(object):
def __init__(object, parameter):
object.parameter = value
The library file or "façade" file containing classes, methods or functions you want to import.
class class1(object):
"""description of class"""
class ClassA(object):
print ("test2")
def methodA():
print ("test3")
def functionA ():
print ("test4")
return (0)
pass
NOW how do you actually solve the mess that the IDE leads you into? To import code from another file in the same directory space you add a reference to it.
OK so now that you have this problem solved, how do you really link two separate projects together in the same solution space?
Microsoft really, really needs to fix these problem so you can intuitively create what most people want to create as new files in the same directories and remove solutions by selecting them and deleting them from the IDE. Beginners get so frustrated with directory path statements so flexible for seasoned developers, but so unfair to new developers in their defaults.
Hope this really helps you new guys and stops seasoned developers from giving you the wrong answers that don't work for you. They assume you already understand path statements and just want to type the right code...which is also why the tunnel in on trying to correct your code but does not help you fix the problem. This is probably the most common problem continually described on stackoverflow with wrong answers that don't work for new programmers.
As detailed in the jTDS Frequenlty Asked Questions, the URL format for jTDS is:
jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]
So, to connect to a database called "Blog" hosted by a MS SQL Server running on MYPC
, you may end up with something like this:
jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS;user=sa;password=s3cr3t
Or, if you prefer to use getConnection(url, "sa", "s3cr3t")
:
jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS
EDIT: Regarding your Connection refused
error, double check that you're running SQL Server on port 1433, that the service is running and that you don't have a firewall blocking incoming connections.
Taking for granted that the JSON you posted is actually what you are seeing in the browser, then the problem is the JSON itself.
The JSON snippet you have posted is malformed.
You have posted:
[{
"name" : "shopqwe",
"mobiles" : [],
"address" : {
"town" : "city",
"street" : "streetqwe",
"streetNumber" : "59",
"cordX" : 2.229997,
"cordY" : 1.002539
},
"shoe"[{
"shoeName" : "addidas",
"number" : "631744030",
"producent" : "nike",
"price" : 999.0,
"sizes" : [30.0, 35.0, 38.0]
}]
while the correct JSON would be:
[{
"name" : "shopqwe",
"mobiles" : [],
"address" : {
"town" : "city",
"street" : "streetqwe",
"streetNumber" : "59",
"cordX" : 2.229997,
"cordY" : 1.002539
},
"shoe" : [{
"shoeName" : "addidas",
"number" : "631744030",
"producent" : "nike",
"price" : 999.0,
"sizes" : [30.0, 35.0, 38.0]
}
]
}
]
This is the code I'm using to disable refresh on IE and firefox which works for the following key combinations:
F5 | Ctrl + F5 | Ctrl + R
//this code handles the F5/Ctrl+F5/Ctrl+R
document.onkeydown = checkKeycode
function checkKeycode(e) {
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
// Mozilla firefox
if ($.browser.mozilla) {
if (keycode == 116 ||(e.ctrlKey && keycode == 82)) {
if (e.preventDefault)
{
e.preventDefault();
e.stopPropagation();
}
}
}
// IE
else if ($.browser.msie) {
if (keycode == 116 || (window.event.ctrlKey && keycode == 82)) {
window.event.returnValue = false;
window.event.keyCode = 0;
window.status = "Refresh is disabled";
}
}
}
If you don't want to use useragent to detect what type of browser it is ($.browser
uses navigator.userAgent
to determine the platform), you can use
if('MozBoxSizing' in document.documentElement.style)
which returns true for firefox
:::
works only with lists, while ++
can be used with any traversable. In the current implementation (2.9.0), ++
falls back on :::
if the argument is also a List
.
You can use recursion here to do this. For example:
jQuery(document).ready(checkContainer);
function checkContainer () {
if($('#divIDer').is(':visible'))){ //if the container is visible on the page
createGrid(); //Adds a grid to the html
} else {
setTimeout(checkContainer, 50); //wait 50 ms, then try again
}
}
Basically, this function will check to make sure that the element exists and is visible. If it is, it will run your createGrid()
function. If not, it will wait 50ms and try again.
Note:: Ideally, you would just use the callback function of your AJAX call to know when the container was appended, but this is a brute force, standalone approach. :)
array_key_exists
will definitely tell you if a key exists in an array, whereas isset
will only return true
if the key/variable exists and is not null
.
$a = array('key1' => '????', 'key2' => null);
isset($a['key1']); // true
array_key_exists('key1', $a); // true
isset($a['key2']); // false
array_key_exists('key2', $a); // true
There is another important difference: isset
doesn't complain when $a
does not exist, while array_key_exists
does.
Here is a link that describes how to print permutations of a string. http://nipun-linuxtips.blogspot.in/2012/11/print-all-permutations-of-characters-in.html
In Unix CLI, it's very practical to redirect only errors to a file:
./script 2> errors.log
From your script, either use var_dump()
or equivalent as usual (both STDOUT and STDERR will receive the output), but to write only in the log file:
fwrite(STDERR, "Debug infos\n"); // Write in errors.log^
Then from another shell, for live changes:
tail -f errors.log
or simply
watch cat errors.log
Might as well make this an answer. I had the same issue today and it was more of a non-issue than expected. After adding the CORS functionality, you must restart your Flask server (ctrl + c
-> python manage.py runserver
, or whichever method you use)) in order for the change to take effect, even if the code is correct. Otherwise the CORS will not work in the active instance.
Here's how it looks like for me and it works (Python 3.6.1, Flask 0.12):
factory.py:
from flask import Flask
from flask_cors import CORS # This is the magic
def create_app(register_stuffs=True):
"""Configure the app and views"""
app = Flask(__name__)
CORS(app) # This makes the CORS feature cover all routes in the app
if register_stuffs:
register_views(app)
return app
def register_views(app):
"""Setup the base routes for various features."""
from backend.apps.api.views import ApiView
ApiView.register(app, route_base="/api/v1.0/")
views.py:
from flask import jsonify
from flask_classy import FlaskView, route
class ApiView(FlaskView):
@route("/", methods=["GET"])
def index(self):
return "API v1.0"
@route("/stuff", methods=["GET", "POST"])
def news(self):
return jsonify({
"stuff": "Here be stuff"
})
In my React app console.log:
Sending request:
GET /stuff
With parameters:
null
bundle.js:17316 Received data from Api:
{"stuff": "Here be stuff"}
try this
SELECT group_name, employees, surveys, COUNT( surveys ) AS test1,
concat(round(( surveys/employees * 100 ),2),'%') AS percentage
FROM a_test
GROUP BY employees
try this,
http://seleniumcapsules.blogspot.com/2012/10/design-of-datepicker.html
Many way to Json Parse but i have found most effective way to
@model List<string[]>
<script>
function DataParse() {
var model = '@Html.Raw(Json.Encode(Model))';
var data = JSON.parse(model);
for (i = 0; i < data.length; i++) {
......
}
</script>