It depends on what you want to do. For example you could stick in some conditionals like this in your comprehensions:
# get the squares of each number from 1 to 9, excluding 2
myList = [i**2 for i in range(10) if i != 2]
print(myList)
# --> [0, 1, 9, 16, 25, 36, 49, 64, 81]
Why you shouldn't and when you should use regular expressions?
First off, a common misnomer: Regexps are not for "parsing" HTML. Regexes can however "extract" data. Extracting is what they're made for. The major drawback of regex HTML extraction over proper SGML toolkits or baseline XML parsers are their syntactic effort and varying reliability.
Consider that making a somewhat dependable HTML extraction regex:
<a\s+class="?playbutton\d?[^>]+id="(\d+)".+? <a\s+class="[\w\s]*title
[\w\s]*"[^>]+href="(http://[^">]+)"[^>]*>([^<>]+)</a>.+?
is way less readable than a simple phpQuery or QueryPath equivalent:
$div->find(".stationcool a")->attr("title");
There are however specific use cases where they can help.
<!--
, which however are sometimes the more useful anchors for extraction. In particular pseudo-HTML variations <$var>
or SGML residues are easy to tame with regexps.It's sometimes even advisable to pre-extract a snippet of HTML using regular expressions /<!--CONTENT-->(.+?)<!--END-->/
and process the remainder using the simpler HTML parser frontends.
Note: I actually have this app, where I employ XML parsing and regular expressions alternatively. Just last week the PyQuery parsing broke, and the regex still worked. Yes weird, and I can't explain it myself. But so it happened.
So please don't vote real-world considerations down, just because it doesn't match the regex=evil meme. But let's also not vote this up too much. It's just a sidenote for this topic.
This error occurs if you are trying to set variable of type DateTime to null. Declare the variable as nullable, i.e. DateTime? . This will solve the problem.
You can check checkbox in the commit dialog.
You can use settings to automatically optimize imports since 11.1 and above.
og:title
is one of the open graph meta tags. og:...
properties define objects in a social graph. They are used for example by Facebook.
og:title
stands for the title of your object as it should appear within the graph (see here for more http://ogp.me/ )
Quite frankly I would say use a library that does what you need (like platform.js for example). At some point things will change and the library will be equipped for those changes and manual parsing using regular expressions will fail.
Thank god IE goes away...
I think every process you make start executing the line you create so something like this...
pid=fork() at line 6. fork function returns 2 values
you have 2 pids, first pid=0 for child and pid>0 for parent
so you can use if to separate
.
/*
sleep(int time) to see clearly
<0 fail
=0 child
>0 parent
*/
int main(int argc, char** argv) {
pid_t childpid1, childpid2;
printf("pid = process identification\n");
printf("ppid = parent process identification\n");
childpid1 = fork();
if (childpid1 == -1) {
printf("Fork error !\n");
}
if (childpid1 == 0) {
sleep(1);
printf("child[1] --> pid = %d and ppid = %d\n",
getpid(), getppid());
} else {
childpid2 = fork();
if (childpid2 == 0) {
sleep(2);
printf("child[2] --> pid = %d and ppid = %d\n",
getpid(), getppid());
} else {
sleep(3);
printf("parent --> pid = %d\n", getpid());
}
}
return 0;
}
//pid = process identification
//ppid = parent process identification
//child[1] --> pid = 2399 and ppid = 2398
//child[2] --> pid = 2400 and ppid = 2398
//parent --> pid = 2398
If you have an object and wish to become JObject you can use:
JObject o = (JObject)JToken.FromObject(miObjetoEspecial);
like this :
Pocion pocionDeVida = new Pocion{
tipo = "vida",
duracion = 32,
};
JObject o = (JObject)JToken.FromObject(pocionDeVida);
Console.WriteLine(o.ToString());
// {"tipo": "vida", "duracion": 32,}
You should add return statement while you are forwarding or redirecting the flow.
Example:
if forwardind,
request.getRequestDispatcher("/abs.jsp").forward(request, response);
return;
if redirecting,
response.sendRedirect(roundTripURI);
return;
.video {
width: 100%;
position: relative;
padding-bottom: 56.25%; /* ratio 16/9 */
}
.video iframe {
border: none;
position: absolute;
width: 100%;
height: 100%;
}
16:9
padding-bottom = 9/16 * 100 = 56.25
You can do it this way using INSTR:
SELECT * FROM users WHERE INSTR(LOWER(last_name), 'z') > 0;
INSTR returns zero if the substring is not in the string.
Out of interest, why don't you want to use like?
Edit: I took the liberty of making the search case insensitive so you don't miss Bob Zebidee. :-)
Version check helped me OpenSSL. OpenSSL_1_0_1f not supported TSLv.1_2 ! Check version and compatibility with TSLv.1_2 on github openssl/openssl . And regenerate your certificate with new openssl
openssl pkcs12 -in path.p12 -out newfile.pem
P.S I don’t know what they were minus, but this solution will really help.
Today I had this same problem with another jar. I tried multiple things people said on Stackoverflow, but nothing worked. Eventually I did this:
Now it works again for me. Perhaps this solves the problem for someone else too.
Changing a constant type will lead to an Undefined Behavior.
However, if you have an originally non-const object which is pointed to by a pointer-to-const or referenced by a reference-to-const then you can use const_cast to get rid of that const-ness.
Casting away constness is considered evil and should not be avoided. You should consider changing the type of the pointers you use in vector to non-const if you want to modify the data through it.
Do below steps :
Check the version of chrome browser.
download chromedriver of same version from https://sites.google.com/a/chromium.org/chromedriver/
Give correct path in the pycharm and run the code.
You can use the ATL text conversion macros to convert a narrow (char) string to a wide (wchar_t) one. For example, to convert a std::string:
#include <atlconv.h>
...
std::string str = "Hello, world!";
CA2W pszWide(str.c_str());
loadU(pszWide);
You can also specify a code page, so if your std::string contains UTF-8 chars you can use:
CA2W pszWide(str.c_str(), CP_UTF8);
Very useful but Windows only.
I found a solution after days of search. My comment is going to be buried but anyway...
I get the corrupted data with php.
I don't use set names UTF8
I use utf8_decode() on my data
I update my database with my new decoded data, still not using set names UTF8
and voilà :)
Here, you could use cv2.bitwise_and
function if you already have the mask image.
For check the below code:
img = cv2.imread('lena.jpg')
mask = cv2.imread('mask.png',0)
res = cv2.bitwise_and(img,img,mask = mask)
The output will be as follows for a lena image, and for rectangular mask.
PHP version > 5.0 has a nice SoapClient integrated. Which doesn't require to parse response xml. Here's a quick example
$client = new SoapClient("http://path.to/wsdl?WSDL");
$res = $client->SoapFunction(array('param1'=>'value','param2'=>'value'));
echo $res->PaymentNotification->payment;
You can try 'onbeforeunload
' event.
Also take a look at this-
Double is a wrapper class,
The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double.
In addition, this class provides several methods for converting a double to a String and a String to a double, as well as other constants and methods useful when dealing with a double.
The double data type,
The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
Check each datatype with their ranges : Java's Primitive Data Types.
Important Note : If you'r thinking to use double for precise values, you need to re-think before using it. Java Traps: double
I know the OP was very old, at that time in-app-update was not available. But from API 21, you can use in-app-update checking. You may need to keep your eyes on some points which are nicely written up here:
the complete information one that I got from askTom-Oracle. I hope it helps you
select *
from v$sql
where buffer_gets > 1000000
or disk_reads > 100000
or executions > 50000
I opened "Passwords and Keys" application in my Unity and removed unwanted keys from Secure Keys -> OpenSSH keys And they automatically had been removed from ssh-agent -l as well.
I got this on WatchOS Sim. The issue persisted even after:
...and was finally fixed by "Erase all Content and Settings" in the simulator.
Since ES9, there's now a simpler, better way of getting all the matches, together with information about the capture groups, and their index:
const string = 'Mice like to dice rice';
const regex = /.ice/gu;
for(const match of string.matchAll(regex)) {
console.log(match);
}
// ["mice", index: 0, input: "mice like to dice rice", groups: undefined]
// ["dice", index: 13, input: "mice like to dice rice", groups: undefined]
// ["rice", index: 18, input: "mice like to dice rice", groups: undefined]
It is currently supported in Chrome, Firefox, Opera. Depending on when you read this, check this link to see its current support.
When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).
Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle
message because you asked for some nonexistent data.
When you perform a cd
operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.
While loop is a bit faster than for loop.
var len = arr.length;
while (len--) {
// blah blah
}
Use while loop instead
There are three method to pass value in php.
These three method are used for different purpose.For example if we want to receive our value on next page then we can use 'post' ($_POST) method as:-
$a=$_POST['field-name'];
If we require the value of variable on more than one page than we can use session variable as:-
$a=$_SESSION['field-name];
Before using this Syntax for creating SESSION variable we first have to add this tag at the very beginning of our php page
session_start();
GET method are generally used to print data on same page which used to take input from user. Its syntax is as:
$a=$_GET['field-name'];
POST method are generally consume more secure than GET because when we use Get method than it can display the data in URL bar.If the data is more sensitive data like password then it can be inggeris.
You can make the pagebreak conditional on knitting to PDF. This worked for me.
```{r, results='asis', eval=(opts_knit$get('rmarkdown.pandoc.to') == 'latex')}
cat('\\pagebreak')
```
I agree with Erroid, you must add PHP directory into PATH environment.
PATH=%PATH%;<Your_PHP_Path>
Example
PATH=%PATH%;C:\php
It worked for me. Thank you.
Oh, dear. A few little problems...
As pointed out by others, you need to quote to protect against empty/space-containing entries, and use the !delayed_expansion! facility.
Two other matters of which you should be aware:
First, set/p
will assign a user-input value to a variable. That's not news - but the gotcha is that pressing enter
in response will leave the variable UNCHANGED - it will not ASSIGN a zero-length string to the variable (hence deleting the variable from the environment.) The safe method is:
set "var="
set /p var=
That is, of course, if you don't WANT enter
to repeat the existing value.
Another useful form is
set "var=default"
set /p var=
or
set "var=default"
set /p "var=[%var%]"
(which prompts with the default value; !var!
if in a block statement with delayedexpansion)
Second issue is that on some Windows versions (although W7 appears to "fix" this issue) ANY label - including a :: comment
(which is a broken-label) will terminate any 'block' - that is, parenthesised compound statement)
You just need to add proper path of the haarcascade_frontalface_default.xml
file i.e. you only have to add prefix (cv2.data.haarcascades
)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')
using a switch case
switch ($num){
case ($num>= $value1 && $num<= $value2):
echo "within range 1";
break;
case ($num>= $value3 && $num<= $value4):
echo "within range 2";
break;
.
.
.
.
.
default: //default
echo "within no range";
break;
}
JLRishe's answer is correct, so I simply use this in my event handler:
if (event.target instanceof Element) { /*...*/ }
first need to get actual constrain name by this query
SHOW CREATE TABLE TABLE_NAME
This query will result constrain name of the foreign key, now below query will drop it.
ALTER TABLE TABLE_NAME DROP FOREIGN KEY COLUMN_NAME_ibfk_1
last number in above constrain name depends how many foreign keys you have in table
Try this as root (maybe you can use sudo
or su
):
/etc/init.d/postgresql restart
Without any argument the script also gives you a hint on how to restart a specific version
[Uqbar@Feynman ~] /etc/init.d/postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force-reload|status} [version ...]
Similarly, in case you have it, you can also use the service
tool:
[Uqbar@Feynman ~] service postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force reload|status} [version ...]
Please, pay attention to the optional [version ...]
trailing argument.
That's meant to allow you, the user, to act on a specific version, in case you were running multiple ones. So you can restart version X while keeping version Y and Z untouched and running.
Finally, in case you are running systemd, then you can use systemctl
like this:
[support@Feynman ~] systemctl status postgresql
? postgresql.service - PostgreSQL database server
Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; vendor preset: disabled)
Active: active (running) since Wed 2017-11-14 12:33:35 CET; 7min ago
...
You can replace status
with stop
, start
or restart
as well as other actions. Please refer to the documentation for full details.
In order to operate on multiple concurrent versions, the syntax is slightly different. For example to stop v12
and reload v13
you can run:
systemctl stop postgresql-12.service
systemctl reload postgresql-13.service
Thanks to @Jojo for pointing me to this very one.
Finally Keep in mind that root
permissions may be needed for non-informative tasks as in the other cases seen earlier.
Same but in a JBoss WildFly AS.
Solved with properties in my META-INF/persistence.xml
<properties>
<property name="hibernate.transaction.jta.platform"
value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform" />
<property name="spring.jpa.database-platform" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="spring.jpa.show-sql" value="false" />
</properties>
You can use the code below to solve the problem or download demo here
Create two functions to handle each.
First, the canvas is drawn and the images are drawn on top of each other from point (0,0)
On button click
public void buttonMerge(View view) {
Bitmap bigImage = BitmapFactory.decodeResource(getResources(), R.drawable.img1);
Bitmap smallImage = BitmapFactory.decodeResource(getResources(), R.drawable.img2);
Bitmap mergedImages = createSingleImageFromMultipleImages(bigImage, smallImage);
img.setImageBitmap(mergedImages);
}
Function to create an overlay.
private Bitmap createSingleImageFromMultipleImages(Bitmap firstImage, Bitmap secondImage){
Bitmap result = Bitmap.createBitmap(firstImage.getWidth(), firstImage.getHeight(), firstImage.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(firstImage, 0f, 0f, null);
canvas.drawBitmap(secondImage, 10, 10, null);
return result;
}
You may want to take a look at those pages : http://developer.android.com/reference/android/os/Build.html and http://developer.android.com/reference/java/lang/System.html (the getProperty() method might do the job).
For instance :
System.getProperty("os.version"); // OS version
android.os.Build.VERSION.SDK // API Level
android.os.Build.DEVICE // Device
android.os.Build.MODEL // Model
android.os.Build.PRODUCT // Product
Etc...
Hope below helps!
PS C:\Users\aameer>$invoice = $object.'Invoice Month'
$invoice = "01-" + $invoice
[datetime]$Format_date =$invoice
Now type is converted. You can use method or can access any property.
Example :$Format_date.AddDays(5)
I was having the same problem here. Found out that the problem was with an Advanced Property of the file. There is there an option with the name 'Compilation Action' (may be not with the exact words, I am translating - my VS is in Portuguese).
My Class1.cs file was there as "Content" and I just had to change it to "Compile" to make it work, and have the classes recognized by the others files in the same project.
This will not only validate your email, but also sanitize it for unexpected characters:
$email = $_POST['email'];
$emailB = filter_var($email, FILTER_SANITIZE_EMAIL);
if (filter_var($emailB, FILTER_VALIDATE_EMAIL) === false ||
$emailB != $email
) {
echo "This email adress isn't valid!";
exit(0);
}
xargs --arg-file inputfile cat
This will output the filename followed by the file's contents:
xargs --arg-file inputfile -I % sh -c "echo %; cat %"
My answer here
As I read on the official document, I think this is the best answer, just pass the View to parameter such as your EditText, but showSoftKeyboard seems like not working on landscape
private fun showSoftKeyboard(view: View) {
if (view.requestFocus()) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
}
private fun closeSoftKeyboard(view: View) {
if (view.requestFocus()) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
}
3 answers, which you can combine:
Set implicit wait immediately after creating the web driver instance:
_ = driver.Manage().Timeouts().ImplicitWait;
This will try to wait until the page is fully loaded on every page navigation or page reload.
After page navigation, call JavaScript return document.readyState
until "complete"
is returned. The web driver instance can serve as JavaScript executor. Sample code:
C#
new WebDriverWait(driver, MyDefaultTimeout).Until(
d => ((IJavaScriptExecutor) d).ExecuteScript("return document.readyState").Equals("complete"));
Java
new WebDriverWait(firefoxDriver, pageLoadTimeout).until(
webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
Check if the URL matches the pattern you expect.
If you want to do this the C++ way, do it like this:
#include <fstream>
#include <iterator>
#include <algorithm>
int main()
{
std::ifstream input( "C:\\Final.gif", std::ios::binary );
std::ofstream output( "C:\\myfile.gif", std::ios::binary );
std::copy(
std::istreambuf_iterator<char>(input),
std::istreambuf_iterator<char>( ),
std::ostreambuf_iterator<char>(output));
}
If you need that data in a buffer to modify it or something, do this:
#include <fstream>
#include <iterator>
#include <vector>
int main()
{
std::ifstream input( "C:\\Final.gif", std::ios::binary );
// copies all data into buffer
std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(input), {});
}
generateRandomComplementaryColor = function(r, g, b){
//--- JavaScript code
var red = Math.floor((Math.random() * 256));
var green = Math.floor((Math.random() * 256));
var blue = Math.floor((Math.random() * 256));
//---
//--- Extra check for Internet Explorers, its Math.random is not random enough.
if(!/MSIE 9/i.test(navigator.userAgent) && !/MSIE 10/i.test(navigator.userAgent) && !/rv:11.0/i.test(navigator.userAgent)){
red = Math.floor((('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]) * 256));
green = Math.floor((('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]) * 256));
blue = Math.floor((('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]) * 256));
};
//---
//--- nodejs code
/*
crypto = Npm.require('crypto');
red = Math.floor((parseInt(crypto.randomBytes(8).toString('hex'), 16)) * 1.0e-19 * 256);
green = Math.floor((parseInt(crypto.randomBytes(8).toString('hex'), 16)) * 1.0e-19 * 256);
blue = Math.floor((parseInt(crypto.randomBytes(8).toString('hex'), 16)) * 1.0e-19 * 256);
*/
//---
red = (red + r)/2;
green = (green + g)/2;
blue = (blue + b)/2;
return 'rgb(' + Math.floor(red) + ', ' + Math.floor(green) + ', ' + Math.floor(blue) + ')';
}
Run the function using:
generateRandomComplementaryColor(240, 240, 240);
Try rewriting your success handler to:
success : handleData
The success property of the ajax method only requires a reference to a function.
In your handleData function you can take up to 3 parameters:
object data
string textStatus
jqXHR jqXHR
I had the same problem and I had solved it with:
1.Right click to solution and click 'Clean Solution'
2.Click 'References'
folder in solution explorer and select the problem reference (in your case it seems System.Web.Mvc) and then right click and click 'Properties'
.
3.In the properties window, make sure that the 'Copy Local'
property is set to 'True'
This worked for me. Hope it works for someone else
Helpful Note: As it has mentioned in comments by @Vlad:
If it is already set to True:
I would recommend %20
.
Are you hard-coding them?
This is not very consistent across languages, though.
If I'm not mistaken, in PHP urlencode()
treats spaces as +
whereas Python's urlencode()
treats them as %20
.
EDIT:
It seems I'm mistaken. Python's urlencode()
(at least in 2.7.2) uses quote_plus()
instead of quote()
and thus encodes spaces as "+".
It seems also that the W3C recommendation is the "+" as per here: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
And in fact, you can follow this interesting debate on Python's own issue tracker about what to use to encode spaces: http://bugs.python.org/issue13866.
EDIT #2:
I understand that the most common way of encoding " " is as "+", but just a note, it may be just me, but I find this a bit confusing:
import urllib
print(urllib.urlencode({' ' : '+ '})
>>> '+=%2B+'
Using some of the above recommendations, the following function and code is working for search a date range:
Set date with the time component set to 00:00:00
public static DateTime GetDateZeroTime(DateTime date)
{
return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0);
}
Usage
var modifieddatebegin = Tools.Utilities.GetDateZeroTime(form.modifieddatebegin);
var modifieddateend = Tools.Utilities.GetDateZeroTime(form.modifieddateend.AddDays(1));
Your action method considers model type asList<string>
. But, in your view you are waiting for IEnumerable<Standings.Models.Teams>
.
You can solve this problem with changing the model in your view to List<string>
.
But, the best approach would be to return IEnumerable<Standings.Models.Teams>
as a model from your action method. Then you haven't to change model type in your view.
But, in my opinion your models are not correctly implemented. I suggest you to change it as:
public class Team
{
public int Position { get; set; }
public string HomeGround {get; set;}
public string NickName {get; set;}
public int Founded { get; set; }
public string Name { get; set; }
}
Then you must change your action method as:
public ActionResult Index()
{
var model = new List<Team>();
model.Add(new Team { Name = "MU"});
model.Add(new Team { Name = "Chelsea"});
...
return View(model);
}
And, your view:
@model IEnumerable<Standings.Models.Team>
@{
ViewBag.Title = "Standings";
}
@foreach (var item in Model)
{
<div>
@item.Name
<hr />
</div>
}
Find parameters
The parameters find function takes are as follows:
«Object»
.«Object|String»
optional fields to return, see Query.prototype.select()«Object»
optional see Query.prototype.setOptions()«Function»
How to limit
const Post = require('./models/Post');
Post.find(
{ published: true },
null,
{ sort: { 'date': 'asc' }, limit: 20 },
function(error, posts) {
if (error) return `${error} while finding from post collection`;
return posts; // posts with sorted length of 20
}
);
Extra Info
Mongoose allows you to query your collections in different ways like: Official Documentation
// named john and at least 18
MyModel.find({ name: 'john', age: { $gte: 18 }});
// executes, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});
// executes, name LIKE john and only selecting the "name" and "friends" fields
MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })
// passing options
MyModel.find({ name: /john/i }, null, { skip: 10 })
// passing options and executes
MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});
// executing a query explicitly
var query = MyModel.find({ name: /john/i }, null, { skip: 10 })
query.exec(function (err, docs) {});
// using the promise returned from executing a query
var query = MyModel.find({ name: /john/i }, null, { skip: 10 });
var promise = query.exec();
promise.addBack(function (err, docs) {});
NetBeans IDE automatically defines the structure which is almost similar to one suggested by Patrick Garner. For NetBeans users
File->New Project ->In left side select Maven and In right side select Maven Enterprise Application and press Next -> Asks for project names for both war,ejb and settings.
The IDE will automatically create the structure for you.
You can use one and more echo statement inside href
<a href="profile.php?usr=<?php echo $_SESSION['firstname']."&email=". $_SESSION['email']; ?> ">Link</a>
link : "/profile.php?usr=firstname&email=email"
It doesn't matter at all, but class makes it look like T can only be a class, while it can of course be any type. So typename is more accurate. On the other hand, most people use class, so that is probably easier to read generally.
The CSS solution for Angular Bootstrap is
::ng-deep .tooltip-inner {
white-space: pre-wrap;
}
No need to use a parent element or class selector if you don't need to restrict it's use. Copy/Pasta, and this rule will apply to all sub-components
v. community 5.0.4 (linux): File -> Settings -> Editor -> General -> Appearance -> now check 'Show line numbers', confirm w. OK an voila :)
<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>
Easy as that.
Or without JS
<a href="http://yahoo.com" target="_blank">test</a>
because u have to have jquery set-up to enable the toggling functionality of the toggler button. So, all u have to do is to add bootstrap.bundle.js before bootstrap.css:
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
For Your JSON response you should parse that response for expected results
For Instance: parsed_response = JSON.parse(response.body)
You can check other variables which is included in response like
expect(parsed_response["success"]).to eq(true)
expect(parsed_response["flashcard"]).to eq("flashcard expected value")
expect(parsed_response["lesson"]).to eq("lesson expected value")
expect(subject["status_code"]).to eq(201)
I prefer also check keys of JSON response, For Example:
expect(body_as_json.keys).to match_array(["success", "lesson","status_code", "flashcard"])
Here, We can use should matchers For expected results in Rspec
If the server doesn't have enough memory also will cause this problem. This is my personal experience with Godaddy VPS.
Well, as I didn't have the seq
command installed on my system (Mac OS X v10.6.1 (Snow Leopard)), I ended up using a while
loop instead:
max=5
i=1
while [ $max -gt $i ]
do
(stuff)
done
*Shrugs* Whatever works.
Your solution is correct, but there is some redundancy in your regex.
The similar result can also be obtained from the following regex:
^([A-Z]{3})$
The {3}
indicates that the [A-Z]
must appear exactly 3 times.
I'm using this lib to access nested dict keys
https://github.com/mewwts/addict
import requests
from addict import Dict
r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = Dict(r.json())
print j.state
print j.places[1]['post code'] # only work with keys without '-', space, or starting with number
Try this
SELECT *
FROM categories
LEFT JOIN user_category_subscriptions
ON user_category_subscriptions.category_id = categories.category_id
WHERE user_category_subscriptions.user_id = 1
or user_category_subscriptions.user_id is null
Actually, for the configuration of the machine, just open the .vmx file with a text editor (e.g. notepad, gedit, etc.). You will be able to see the OS type, memsize, ethernet.connectionType, and other settings. Then when you make your machine, just look in the text editor for the corresponding settings. When it asks for the disk, select the .vmdk disk as mentioned above.
Set your editor to point to this program:
/Applications/TextEdit.app/Contents/MacOS/TextEdit
With SVN, you should set SVN_EDITOR
environment variable to:
$ export SVN_EDITOR=/Applications/TextEdit.app/Contents/MacOS/TextEdit
And then, when you try committing something, TextEdit will launch.
For Folder Copy You can Use
robocopy C:\Source D:\Destination /E
For File Copy
copy D:\Sourcefile.txt D:\backup\Destinationfile.txt /Y
Delete file in some folder last modify date more than some day
forfiles -p "D:\FolderPath" -s -m *.[Filetype eg-->.txt] -d -[Numberof dates] -c "cmd /c del @PATH"
And you can Shedule task in windows perform this task automatically in specific time.
I found the problem that was causing the HTTP error.
In the setFalse()
function that is triggered by the Save button my code was trying to submit the form that contained the button.
function setFalse(){
document.getElementById("hasId").value ="false";
document.deliveryForm.submit();
document.submitForm.submit();
when I remove the document.submitForm.submit();
it works:
function setFalse(){
document.getElementById("hasId").value ="false";
document.deliveryForm.submit()
@Roger Lindsjö Thank you for spotting my error where I wasn't passing on the right parameter!
You should follow the guidelines on Add a secondary horizontal axis:
To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.
Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.
On the Layout tab, in the Axes group, click Axes.
Click Secondary Horizontal Axis, and then click the display option that you want.
You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.
In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:
Click the chart.
This displays the Chart Tools, adding the Design, Layout, and Format tabs.
On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.
On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.
Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.
On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.
A secondary vertical axis is displayed in the chart.
To change the display of the secondary vertical axis, do the following:
On the Layout tab, in the Axes group, click Axes.
Click Secondary Vertical Axis, and then click the display option that you want.
To change the axis options of the secondary vertical axis, do the following:
Right-click the secondary vertical axis, and then click Format Axis.
Under Axis Options, select the options that you want to use.
since the data ex1221new was not given, so I have created a dummy data and added it to a data frame. Also, the question which was asked has few changes in codes like then ggplot package has deprecated the use of
"scale_area()" and nows uses scale_size_area()
"opts()" has changed to theme()
In my answer,I have stored the plot in mygraph variable and then I have used
mygraph$labels$x="Discharge of materials" #changes x axis title
mygraph$labels$y="Area Affected" # changes y axis title
And the work is done. Below is the complete answer.
install.packages("Sleuth2")
library(Sleuth2)
library(ggplot2)
ex1221new<-data.frame(Discharge<-c(100:109),Area<-c(120:129),NO3<-seq(2,5,length.out = 10))
discharge<-ex1221new$Discharge
area<-ex1221new$Area
nitrogen<-ex1221new$NO3
p <- ggplot(ex1221new, aes(discharge, area), main="Point")
mygraph<-p + geom_point(aes(size= nitrogen)) +
scale_size_area() + ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")+
theme(
plot.title = element_text(color="Blue", size=30, hjust = 0.5),
# change the styling of both the axis simultaneously from this-
axis.title = element_text(color = "Green", size = 20, family="Courier",)
# you can change the axis title from the code below
mygraph$labels$x="Discharge of materials" #changes x axis title
mygraph$labels$y="Area Affected" # changes y axis title
mygraph
Also, you can change the labels title from the same formula used above -
mygraph$labels$size= "N2" #size contains the nitrogen level
You could try something like this:
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
double[] numbers = new double[5];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextDouble();
}
}
It seems pretty basic stuff unless I am misunderstanding you
If you are looking for sending color data from backend
def color():
color = "#{:06x}".format(random.randint(0, 0xFFFFFF))
return color
To backup all files in all directories to a remote Synology NAS using a different remote port:
scp -P 10022 -r /media/data/somedata/* [email protected]:/var/services/homes/user/directory/
Note that you can also use the C99 fixed-width types perfectly well in Objective-C:
#import <stdint.h>
...
int32_t x; // guaranteed to be 32 bits on any platform
The wikipedia page has a decent description of what's available in this header if you don't have a copy of the C standard (you should, though, since Objective-C is just a tiny extension of C). You may also find the headers limits.h
and inttypes.h
to be useful.
Try using jQuery
<script type="text/javascript">
$("form").submit(function() {
$("form").attr('target', '_blank');
return true;
});
</script>
Here is a full answer - http://ftutorials.com/open-html-form-in-new-tab/
First, install the HTMLAgilityPack nuget package into your project.
Then, as an example:
HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
// There are various options, set as needed
htmlDoc.OptionFixNestedTags=true;
// filePath is a path to a file containing the html
htmlDoc.Load(filePath);
// Use: htmlDoc.LoadHtml(xmlString); to load from a string (was htmlDoc.LoadXML(xmlString)
// ParseErrors is an ArrayList containing any errors from the Load statement
if (htmlDoc.ParseErrors != null && htmlDoc.ParseErrors.Count() > 0)
{
// Handle any parse errors as required
}
else
{
if (htmlDoc.DocumentNode != null)
{
HtmlAgilityPack.HtmlNode bodyNode = htmlDoc.DocumentNode.SelectSingleNode("//body");
if (bodyNode != null)
{
// Do something with bodyNode
}
}
}
(NB: This code is an example only and not necessarily the best/only approach. Do not use it blindly in your own application.)
The HtmlDocument.Load()
method also accepts a stream which is very useful in integrating with other stream oriented classes in the .NET framework. While HtmlEntity.DeEntitize()
is another useful method for processing html entities correctly. (thanks Matthew)
HtmlDocument
and HtmlNode
are the classes you'll use most. Similar to an XML parser, it provides the selectSingleNode and selectNodes methods that accept XPath expressions.
Pay attention to the HtmlDocument.Option??????
boolean properties. These control how the Load
and LoadXML
methods will process your HTML/XHTML.
There is also a compiled help file called HtmlAgilityPack.chm that has a complete reference for each of the objects. This is normally in the base folder of the solution.
If you want PHP to treat $_GET['select2']
as an array of options just add square brackets to the name of the select element like this: <select name="select2[]" multiple …
Then you can acces the array in your PHP script
<?php
header("Content-Type: text/plain");
foreach ($_GET['select2'] as $selectedOption)
echo $selectedOption."\n";
$_GET
may be substituted by $_POST
depending on the <form method="…"
value.
MethodHandles.lookup().lookupClass().getEnclosingMethod().getName();
This could be one solution.
public class RegisterActivity extends AppCompatActivity {
private static final String TAG = "RegisterActivity";
private static final String URL_FOR_REGISTRATION = "http://192.168.10.4/android_login_example/register.php";
ProgressDialog progressDialog;
private EditText signupInputName, signupInputEmail, signupInputPassword, signupInputAge;
private Button btnSignUp;
private Button btnLinkLogin;
private RadioGroup genderRadioGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
// Progress dialog
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
signupInputName = (EditText) findViewById(R.id.signup_input_name);
signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
signupInputAge = (EditText) findViewById(R.id.signup_input_age);
btnSignUp = (Button) findViewById(R.id.btn_signup);
btnLinkLogin = (Button) findViewById(R.id.btn_link_login);
genderRadioGroup = (RadioGroup) findViewById(R.id.gender_radio_group);
btnSignUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
submitForm();
}
});
btnLinkLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
}
});
}
private void submitForm() {
int selectedId = genderRadioGroup.getCheckedRadioButtonId();
String gender;
if(selectedId == R.id.female_radio_btn)
gender = "Female";
else
gender = "Male";
registerUser(signupInputName.getText().toString(),
signupInputEmail.getText().toString(),
signupInputPassword.getText().toString(),
gender,
signupInputAge.getText().toString());
}
private void registerUser(final String name, final String email, final String password,
final String gender, final String dob) {
// Tag used to cancel the request
String cancel_req_tag = "register";
progressDialog.setMessage("Adding you ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_REGISTRATION, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
String user = jObj.getJSONObject("user").getString("name");
Toast.makeText(getApplicationContext(), "Hi " + user +", You are successfully Added!", Toast.LENGTH_SHORT).show();
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
params.put("gender", gender);
params.put("age", dob);
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
It is possible to get a web application running in full screen in both iOS and Android, it is called a PWA and after mucha hard work, it was the only way around this issue.
PWAs open a number of interesting options for development that should not be missed. I've made a couple already, check out this Public and Private Tender Manual For Designers (Spanish). And here is an English explanation from the CosmicJS site
Use a column to let each date be shown as month number; another column for day number:
A B C D
----- ----- ----------- --------
1 8 6 8/6/2010 12.70
2 8 7 8/7/2010 10.50
3 8 7 8/7/2010 7.10
4 8 9 8/9/2010 10.50
5 8 10 8/10/2010 15.00
The formula for A1
is =Month(C1)
The formula for B1
is =Day(C1)
For Month sums, put the month number next to each month:
E F G
----- ----- -------------
1 7 July $1,000,010
2 8 Aug $1,200,300
The formula for G1
is =SumIf($A$1:$A$100, E1, $D$1:$D$100)
. This is a portable formula; just copy it down.
Total for the day will be be a bit more complicated, but you can probably see how to do it.
I believe the part regarding how to span rows has been answered thoroughly (i.e. by nesting rows), but I also ran into the issue of my nested rows not filling their container. While flexbox and negative margins are an option, a much easier solution is to use the predefined h-50
class on the row
containing boxes 2, 3, 4, and 5.
Note: I am using
Bootstrap-4
, I just wanted to share because I ran into the same problem and found this to be a more elegant solution :)
@OP it doesn't matter, you can just split on a space with explode. Until you want to use those values, iterate over the exploded values and discard blanks.
$str = "A B C D";
$s = explode(" ",$str);
foreach ($s as $a=>$b){
if ( trim($b) ) {
print "using $b\n";
}
}
From iOS 7 there is an API and you can get (and set) the tint color with:
self.view.tintColor
Or if you need the CGColor:
self.view.tintColor.CGColor
These are Unicode property shortcuts (\p{L}
for Unicode letters, \p{N}
for Unicode digits). They are supported by .NET, Perl, Java, PCRE, XML, XPath, JGSoft, Ruby (1.9 and higher) and PHP (since 5.1.0)
At any rate, that's a very strange regex. You should not be using alternation when a character class would suffice:
[\p{L}\p{N}_.-]*
The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5
. From the comment you put this needed to be declared elsewhere in your code
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
The error was because you are trying to execute a method that does not exist.
PS C:\Users\Matt> $md5 | gm
TypeName: System.Security.Cryptography.MD5CryptoServiceProvider
Name MemberType Definition
---- ---------- ----------
Clear Method void Clear()
ComputeHash Method byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...
The .ComputeHash()
of $md5.ComputeHash()
was the null valued expression. Typing in gibberish would create the same effect.
PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PowerShell by default allows this to happen as defined its StrictMode
When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.
grep -r -e string directory
-r
is for recursive; -e
is optional but its argument specifies the regex to search for. Interestingly, POSIX grep
is not required to support -r
(or -R
), but I'm practically certain that System V in practice they (almost) all do. Some versions of grep
did, sogrep
support -R
as well as (or conceivably instead of) -r
; AFAICT, it means the same thing.
#include?
should work, it works for general objects, not only strings. Your problem in example code is this test:
unless @suggested_horses.exists?(horse.id)
@suggested_horses<< horse
end
(even assuming using #include?
). You try to search for specific object, not for id. So it should be like this:
unless @suggested_horses.include?(horse)
@suggested_horses << horse
end
ActiveRecord has redefined comparision operator for objects to take a look only for its state (new/created) and id
Use the synchronisation context if you want to send a result to the UI thread. I needed to change the thread priority so I changed from using thread pool threads (commented out code) and created a new thread of my own. I was still able to use the synchronisation context to return whether the database cancel succeeded or not.
#region SyncContextCancel
private SynchronizationContext _syncContextCancel;
/// <summary>
/// Gets the synchronization context used for UI-related operations.
/// </summary>
/// <value>The synchronization context.</value>
protected SynchronizationContext SyncContextCancel
{
get { return _syncContextCancel; }
}
#endregion //SyncContextCancel
public void CancelCurrentDbCommand()
{
_syncContextCancel = SynchronizationContext.Current;
//ThreadPool.QueueUserWorkItem(CancelWork, null);
Thread worker = new Thread(new ThreadStart(CancelWork));
worker.Priority = ThreadPriority.Highest;
worker.Start();
}
SQLiteConnection _connection;
private void CancelWork()//object state
{
bool success = false;
try
{
if (_connection != null)
{
log.Debug("call cancel");
_connection.Cancel();
log.Debug("cancel complete");
_connection.Close();
log.Debug("close complete");
success = true;
log.Debug("long running query cancelled" + DateTime.Now.ToLongTimeString());
}
}
catch (Exception ex)
{
log.Error(ex.Message, ex);
}
SyncContextCancel.Send(CancelCompleted, new object[] { success });
}
public void CancelCompleted(object state)
{
object[] args = (object[])state;
bool success = (bool)args[0];
if (success)
{
log.Debug("long running query cancelled" + DateTime.Now.ToLongTimeString());
}
}
Are you using C# 3.0? You can use object initializers like so:
static MyStruct[] myArray =
new MyStruct[]{
new MyStruct() { id = 1, label = "1" },
new MyStruct() { id = 2, label = "2" },
new MyStruct() { id = 3, label = "3" }
};
I put this function in a util file in one of the apps in my project:
import logging
import re
from django.db import connection
logger = logging.getLogger(__name__)
def sql_logger():
logger.debug('TOTAL QUERIES: ' + str(len(connection.queries)))
logger.debug('TOTAL TIME: ' + str(sum([float(q['time']) for q in connection.queries])))
logger.debug('INDIVIDUAL QUERIES:')
for i, query in enumerate(connection.queries):
sql = re.split(r'(SELECT|FROM|WHERE|GROUP BY|ORDER BY|INNER JOIN|LIMIT)', query['sql'])
if not sql[0]: sql = sql[1:]
sql = [(' ' if i % 2 else '') + x for i, x in enumerate(sql)]
logger.debug('\n### {} ({} seconds)\n\n{};\n'.format(i, query['time'], '\n'.join(sql)))
Then, when needed, I just import it and call it from whatever context (usually a view) is necessary, e.g.:
# ... other imports
from .utils import sql_logger
class IngredientListApiView(generics.ListAPIView):
# ... class variables and such
# Main function that gets called when view is accessed
def list(self, request, *args, **kwargs):
response = super(IngredientListApiView, self).list(request, *args, **kwargs)
# Call our function
sql_logger()
return response
It's nice to do this outside the template because then if you have API views (usually Django Rest Framework), it's applicable there too.
You can use this function (the comments explain how it works):
void strreplace(char *string, const char *find, const char *replaceWith){
if(strstr(string, replaceWith) != NULL){
char *temporaryString = malloc(strlen(strstr(string, find) + strlen(find)) + 1);
strcpy(temporaryString, strstr(string, find) + strlen(find)); //Create a string with what's after the replaced part
*strstr(string, find) = '\0'; //Take away the part to replace and the part after it in the initial string
strcat(string, replaceWith); //Concat the first part of the string with the part to replace with
strcat(string, temporaryString); //Concat the first part of the string with the part after the replaced part
free(temporaryString); //Free the memory to avoid memory leaks
}
}
In Visual Studio 2012, switching between releases still causes problems.
We added a pre-build event to delete the obj
folder: del /s /f /q $(ProjectDir)\obj
and it fixed the issue of publishing. Cleaning works sometimes, but not always.
Public Function GetRange(ByVal sListName As String) As String
Dim oListObject As ListObject
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ThisWorkbook
For Each ws In wb.Sheets
For Each oListObject In ws.ListObjects
If oListObject.Name = sListName Then
GetRange = "[" & ws.Name & "$" & Replace(oListObject.Range.Address, "$", "") & "]"
Exit Function
End If
Next oListObject
Next ws
End Function
In your SQL use it like this
sSQL = "Select * from " & GetRange("NameOfTable") & ""
Another easy way to do so:
import org.mockito.BDDMockito;
import static org.mockito.Matchers.argThat;
import org.mockito.ArgumentMatcher;
BDDMockito.verify(mockedObject)
.someMethodOnMockedObject(argThat(new ArgumentMatcher<TypeOfMethodArg>() {
@Override
public boolean matches(Object argument) {
final TypeOfMethodArg castedArg = (TypeOfMethodArg) argument;
// Make your verifications and return a boolean to say if it matches or not
boolean isArgMarching = true;
return isArgMarching;
}
}));
The data
variable contains a Buffer
object. Convert it into ASCII encoding using the following syntax:
data.toString('ascii', 0, data.length)
Asynchronously:
fs.readFile('test.txt', 'utf8', function (error, data) {
if (error) throw error;
console.log(data.toString());
});
def count_letter(word, char):
count = 0
for char in word:
if char == word:
count += 1
return count #Your return is inside your for loop
r = count_word("banana", "a")
print r
3
It also posible string replacement with stringByReplacingCharactersInRange:withString:
for (int i = 0; i < card.length - 4; i++) {
if (![[card substringWithRange:NSMakeRange(i, 1)] isEqual:@" "]) {
NSRange range = NSMakeRange(i, 1);
card = [card stringByReplacingCharactersInRange:range withString:@"*"];
}
} //out: **** **** **** 1234
by using Listbuffer we can save data into single file:
import java.io.FileWriter
import org.apache.spark.sql.SparkSession
import scala.collection.mutable.ListBuffer
val text = spark.read.textFile("filepath")
var data = ListBuffer[String]()
for(line:String <- text.collect()){
data += line
}
val writer = new FileWriter("filepath")
data.foreach(line => writer.write(line.toString+"\n"))
writer.close()
You can use HTML,
foreach(...)
echo $data1 . ' ' . $data2 . ' ' . $data3 . '<br/>';
If you just want to compute (column a) % (column b), you don't need apply
, just do it directly:
In [7]: df['a'] % df['c']
Out[7]:
0 -1.132022
1 -0.939493
2 0.201931
3 0.511374
4 -0.694647
5 -0.023486
Name: a
I had the same problem when tried to copy an object with some UTF8 characters. Below is a JS example:
var s3 = new AWS.S3();
s3.copyObject({
Bucket: 'somebucket',
CopySource: 'path/to/Weird_file_name_ðO´pi´u.jpg',
Key: 'destination/key.jpg',
ACL: 'authenticated-read'
}, cb);
Solved by encoding the CopySource with encodeURIComponent()
I think the strictSSL: false
should (should have worked, even in 2013) work. So in short are three possible ways:
request
object: const myRequest = require('request').defaults({strictSSL: false})
node-request
internally also allow a request
-object to be injected, so you can make them use your modified instance.NODE_TLS_REJECT_UNAUTHORIZED=0
for the Node.js process.I think that all the answers missed a crucial point:
If you use the Ajax form so that it needs to update itself (and NOT another div outside of the form) then you need to put the containing div OUTSIDE of the form. For example:
<div id="target">
@using (Ajax.BeginForm("MyAction", "MyController",
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "target"
}))
{
<!-- whatever -->
}
</div>
Otherwise you will end like @David where the result is displayed in a new page.
You could use this recursive function for generate necessary T-SQL script.
CREATE FUNCTION dbo.Update_Delete_PrimaryKey
(
@TableName NVARCHAR(255),
@ColumnName NVARCHAR(255),
@OldValue NVARCHAR(MAX),
@NewValue NVARCHAR(MAX),
@Del BIT
)
RETURNS NVARCHAR
(
MAX
)
AS
BEGIN
DECLARE @fks TABLE
(
constraint_name NVARCHAR(255),
table_name NVARCHAR(255),
col NVARCHAR(255)
);
DECLARE @Sql NVARCHAR(MAX),
@EnableConstraints NVARCHAR(MAX);
SET @Sql = '';
SET @EnableConstraints = '';
INSERT INTO @fks
(
constraint_name,
table_name,
col
)
SELECT oConstraint.name constraint_name,
oParent.name table_name,
oParentCol.name col
FROM sys.foreign_key_columns sfkc
--INNER JOIN sys.foreign_keys sfk
-- ON sfk.[object_id] = sfkc.constraint_object_id
INNER JOIN sys.sysobjects oConstraint
ON sfkc.constraint_object_id = oConstraint.id
INNER JOIN sys.sysobjects oParent
ON sfkc.parent_object_id = oParent.id
INNER JOIN sys.all_columns oParentCol
ON sfkc.parent_object_id = oParentCol.object_id
AND sfkc.parent_column_id = oParentCol.column_id
INNER JOIN sys.sysobjects oReference
ON sfkc.referenced_object_id = oReference.id
INNER JOIN sys.all_columns oReferenceCol
ON sfkc.referenced_object_id = oReferenceCol.object_id
AND sfkc.referenced_column_id = oReferenceCol.column_id
WHERE oReference.name = @TableName
AND oReferenceCol.name = @ColumnName
--AND (@Del <> 1 OR sfk.delete_referential_action = 0)
--AND (@Del = 1 OR sfk.update_referential_action = 0)
IF EXISTS(
SELECT 1
FROM @fks
)
BEGIN
DECLARE @Constraint NVARCHAR(255),
@Table NVARCHAR(255),
@Col NVARCHAR(255)
DECLARE Table_Cursor CURSOR LOCAL
FOR
SELECT f.constraint_name,
f.table_name,
f.col
FROM @fks AS f
OPEN Table_Cursor FETCH NEXT FROM Table_Cursor INTO @Constraint, @Table,@Col
WHILE (@@FETCH_STATUS = 0)
BEGIN
IF @Del <> 1
BEGIN
SET @Sql = @Sql + 'ALTER TABLE ' + @Table + ' NOCHECK CONSTRAINT ' + @Constraint + CHAR(13) + CHAR(10);
SET @EnableConstraints = @EnableConstraints + 'ALTER TABLE ' + @Table + ' CHECK CONSTRAINT ' + @Constraint
+ CHAR(13) + CHAR(10);
END
SET @Sql = @Sql + dbo.Update_Delete_PrimaryKey(@Table, @Col, @OldValue, @NewValue, @Del);
FETCH NEXT FROM Table_Cursor INTO @Constraint, @Table,@Col
END
CLOSE Table_Cursor DEALLOCATE Table_Cursor
END
DECLARE @DataType NVARCHAR(30);
SELECT @DataType = t.name +
CASE
WHEN t.name IN ('char', 'varchar', 'nchar', 'nvarchar') THEN '(' +
CASE
WHEN c.max_length = -1 THEN 'MAX'
ELSE CONVERT(
VARCHAR(4),
CASE
WHEN t.name IN ('nchar', 'nvarchar') THEN c.max_length / 2
ELSE c.max_length
END
)
END + ')'
WHEN t.name IN ('decimal', 'numeric') THEN '(' + CONVERT(VARCHAR(4), c.precision) + ','
+ CONVERT(VARCHAR(4), c.Scale) + ')'
ELSE ''
END
FROM sys.columns c
INNER JOIN sys.types t
ON c.user_type_id = t.user_type_id
WHERE c.object_id = OBJECT_ID(@TableName)
AND c.name = @ColumnName
IF @Del <> 1
BEGIN
SET @Sql = @Sql + 'UPDATE [' + @TableName + '] SET [' + @ColumnName + '] = CONVERT(' + @DataType + ', ' + ISNULL('N''' + @NewValue + '''', 'NULL')
+ ') WHERE [' + @ColumnName + '] = CONVERT(' + @DataType + ', ' + ISNULL('N''' + @OldValue + '''', 'NULL') +
');' + CHAR(13) + CHAR(10);
SET @Sql = @Sql + @EnableConstraints;
END
ELSE
SET @Sql = @Sql + 'DELETE [' + @TableName + '] WHERE [' + @ColumnName + '] = CONVERT(' + @DataType + ', N''' + @OldValue
+ ''');' + CHAR(13) + CHAR(10);
RETURN @Sql;
END
GO
DECLARE @Result NVARCHAR(MAX);
SET @Result = dbo.Update_Delete_PrimaryKey('@TableName', '@ColumnName', '@OldValue', '@NewValue', 0);/*Update*/
EXEC (@Result)
SET @Result = dbo.Update_Delete_PrimaryKey('@TableName', '@ColumnName', '@OldValue', NULL, 1);/*Delete*/
EXEC (@Result)
GO
DROP FUNCTION Update_Delete_PrimaryKey;
I'm working on the app that validates International Passports (ICAO). We support only english characters. While most foreign national characters can be represented by a character in the Latin alphabet e.g. è by e, there are several national characters that require an extra letter to represent them such as the German umlaut which requires an ‘e’ to be added to the letter e.g. ä by ae.
This is the JavaScript Regex for the first and last names we use:
/^[a-zA-Z '.-]*$/
The max number of characters on the international passport is up to 31. We use maxlength="31" to better word error messages instead of including it in the regex.
Here is a snippet from our code in AngularJS 1.6 with form and error handling:
class PassportController {_x000D_
constructor() {_x000D_
this.details = {};_x000D_
// English letters, spaces and the following symbols ' - . are allowed_x000D_
// Max length determined by ng-maxlength for better error messaging_x000D_
this.nameRegex = /^[a-zA-Z '.-]*$/;_x000D_
}_x000D_
}_x000D_
_x000D_
angular.module('akyc', ['ngMessages'])_x000D_
.controller('PassportController', PassportController);
_x000D_
_x000D_
.has-error p[ng-message] {_x000D_
color: #bc111e;_x000D_
}_x000D_
_x000D_
.tip {_x000D_
color: #535f67;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>_x000D_
<script src="https://code.angularjs.org/1.6.6/angular-messages.min.js"></script>_x000D_
_x000D_
<main ng-app="akyc" ng-controller="PassportController as $ctrl">_x000D_
<form name="$ctrl.form">_x000D_
_x000D_
<div name="lastName" ng-class="{ 'has-error': $ctrl.form.lastName.$invalid} ">_x000D_
<label for="pp-last-name">Surname</label>_x000D_
<div class="tip">Exactly as it appears on your passport</div>_x000D_
<div ng-messages="$ctrl.form.lastName.$error" ng-if="$ctrl.form.$submitted" id="last-name-error">_x000D_
<p ng-message="required">Please enter your last name</p>_x000D_
<p ng-message="maxlength">This field can be at most 31 characters long</p>_x000D_
<p ng-message="pattern">Only English letters, spaces and the following symbols ' - . are allowed</p>_x000D_
</div>_x000D_
_x000D_
<input type="text" id="pp-last-name" ng-model="$ctrl.details.lastName" name="lastName"_x000D_
class="form-control" required ng-pattern="$ctrl.nameRegex" ng-maxlength="31" aria-describedby="last-name-error" />_x000D_
</div>_x000D_
_x000D_
<button type="submit" class="btn btn-primary">Test</button>_x000D_
_x000D_
</form>_x000D_
</main>
_x000D_
I use This in page.`
public void DTToExcel(DataTable dt)
{
// dosya isimleri ileride ayni anda birden fazla kullanici ayni dosya üzerinde islem yapmak ister düsüncesiyle guid yapildi.
string FileName = Guid.NewGuid().ToString();
FileInfo f = new FileInfo(Server.MapPath("Downloads") + string.Format("\\{0}.xlsx", FileName));
if (f.Exists)
f.Delete(); // delete the file if it already exist.
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.Charset = Encoding.UTF8.WebName;
response.AddHeader("content-disposition", "attachment; filename=" + FileName + ".xls");
response.AddHeader("Content-Type", "application/Excel");
response.ContentType = "application/vnd.xlsx";
//response.AddHeader("Content-Length", file.Length.ToString());
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw)) //datatable'a aldigimiz sorguyu bir datagrid'e atayip html'e çevir.
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
dg.Dispose();
dt.Dispose();
response.End();
}
}
}
Also you can use Android Debug Bridge (adb) to copy your file from Android device to folder on your PC:
adb pull /storage/emulated/0/AudioRecorder/1436854479696.mp4 <folder_on_your_PC_e.g. c:/temp>
And you can copy from device whole AudioRecorder
folder:
adb pull /storage/emulated/0/AudioRecorder <folder_on_your_PC_e.g. c:/temp>
I would create a variable to store the input like this:
var input = document.getElementById("input_id").value;
And then I would just use the variable to add the input value to the string.
= "Your string" + input;
$scope.toggleRightDelayed = function(){
var myInterval = $interval(function(){
$scope.toggleRight();
},1000,1)
.then(function(){
$interval.cancel(myInterval);
});
};
Another option to run multiple Node scripts is with a single Node script, which can fork many others. Forking is supported natively in Node, so it adds no dependencies and is cross-platform.
This would just run the scripts as-is and assume they're located in the parent script's directory.
// fork-minimal.js - run with: node fork-minimal.js
const childProcess = require('child_process');
let scripts = ['some-script.js', 'some-other-script.js'];
scripts.forEach(script => childProcess.fork(script));
This would run the scripts with arguments and configured by the many available options.
// fork-verbose.js - run with: node fork-verbose.js
const childProcess = require('child_process');
let scripts = [
{
path: 'some-script.js',
args: ['-some_arg', '/some_other_arg'],
options: {cwd: './', env: {NODE_ENV: 'development'}}
},
{
path: 'some-other-script.js',
args: ['-another_arg', '/yet_other_arg'],
options: {cwd: '/some/where/else', env: {NODE_ENV: 'development'}}
}
];
let runningScripts= [];
scripts.forEach(script => {
let runningScript = childProcess.fork(script.path, script.args, script.options);
// Optionally attach event listeners to the script
runningScript.on('close', () => console.log('Time to die...'))
runningScripts.push(runningScript); // Keep a reference to the script for later use
});
Forking also has the added benefit that the parent script can receive events from the forked child processes as well as send back. A common example is for the parent script to kill its forked children.
runningScripts.forEach(runningScript => runningScript.kill());
For more available events and methods see the ChildProcess
documentation
I agree with some of the others' answers. The <head>
and <header>
tags have two unique and very unrelated functions. The <header>
tag, if I'm not mistaken, was introduced in HTML5 and was created for increased accessibility, namely for screen readers. It's generally used to indicate the heading of your document and, in order to work appropriately and effectively, should be placed inside the <body>
tag. The <head>
tag, since it's origin, is used for SEO in that it constructs all of the necessary meta data and such. A valid HTML structure for your page with both tags included would be like something like this:
<!DOCTYPE html/>
<html lang="es">
<head>
<!--crazy meta stuff here-->
</head>
<body>
<header>
<!--Optional nav tag-->
<nav>
</nav>
</header>
<!--Body content-->
</body>
</html>
var $list = $('#divname input[id^="q17_"]'); // get all input controls with id q17_
// once you have $list you can do whatever you want
var ControlCnt = $list.length;
// Now loop through list of controls
$list.each( function() {
var id = $(this).prop("id"); // get id
var cbx = '';
if ($(this).is(':checkbox') || $(this).is(':radio')) {
// Need to see if this control is checked
}
else {
// Nope, not a checked control - so do something else
}
});
Free unless noted
Bindings:
Fantasy Consoles:
Editor and games run in an emulated computer system
Inactive/Discontinued:
The ARM is like an Italian sports car:
The x86 is like an American muscle car:
In summary: the x86 is based on a design from 1974 and is good in a straight line (but uses a lot of fuel). The arm uses little fuel, does not slowdown for corners (branches).
Metaphor over, here are some real differences.
There is no reliable way to do this in pure Java. Setting the user.dir
property via System.setProperty()
or java -Duser.dir=...
does seem to affect subsequent creations of Files
, but not e.g. FileOutputStreams
.
The File(String parent, String child)
constructor can help if you build up your directory path separately from your file path, allowing easier swapping.
An alternative is to set up a script to run Java from a different directory, or use JNI native code as suggested below.
The relevant Sun bug was closed in 2008 as "will not fix".
I faced the error "TypeError: 'NoneType' object is not callable " but for a different issue. With the above clues, i was able to debug and got it right! The issue that i faced was : I had the custome Library written and my file wasnt recognizing it although i had mentioned it
example:
Library ../../../libraries/customlibraries/ExtendedWaitKeywords.py
the keywords from my custom library were recognized and that error was resolved only after specifying the complete path, as it was not getting the callable function.
I think this is enough to get you on a nice path:
Sub a()
Dim btn As Button
Application.ScreenUpdating = False
ActiveSheet.Buttons.Delete
Dim t As Range
For i = 2 To 6 Step 2
Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
With btn
.OnAction = "btnS"
.Caption = "Btn " & i
.Name = "Btn" & i
End With
Next i
Application.ScreenUpdating = True
End Sub
Sub btnS()
MsgBox Application.Caller
End Sub
It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.
You can also use
cd %localhost%
to set the directory to the folder the batch file was opened from. Your script would look like this:
@echo off
cd %localhost%
echo .> dblank.txt
Make sure you set the directory before you use the command to create the text file.
If there is other content not being shown inside the outer-div (the green box), why not have that content wrapped inside another div, let's call it "content"
. Have overflow hidden on this new inner-div, but keep overflow visible on the green box.
The only catch is that you will then have to mess around to make sure that the content div doesn't interfere with the positioning of the red box, but it sounds like you should be able to fix that with little headache.
<div id="1" background: #efe; padding: 5px; width: 125px">
<div id="content" style="overflow: hidden;">
</div>
<div id="2" style="position: relative; background: #fee; padding: 2px; width: 100px; height: 100px">
<div id="3" style="position: absolute; top: 10px; background: #eef; padding: 2px; width: 75px; height: 150px"/>
</div>
</div>
Import jquery first before bootstrap:
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/bootstrap.bundle.js"></script>
If you can't get text parsing to work using the accepted answer (e.g if your text file contains non uniform rows) then it's worth trying with Python's csv library - here's an example using a user defined Dialect:
import csv
csv.register_dialect('skip_space', skipinitialspace=True)
with open(my_file, 'r') as f:
reader=csv.reader(f , delimiter=' ', dialect='skip_space')
for item in reader:
print(item)
String name = "\"john\"";
You have to escape the second pair of quotation marks using the \ character in front. It might be worth looking at this link, which explains in some detail.
Other scenario where you set variable:
String name2 = "\""+name+"\"";
Sequence in console:
> String name = "\"john\"";
> name
""john""
> String name2 = "\""+name+"\"";
> name2
"""john"""
You can extract the href from the a tag:
window.open(document.getElementById('redirect').href);
$results = DB::table('rooms')
->distinct()
->leftJoin('bookings', function($join)
{
$join->on('rooms.id', '=', 'bookings.room_type_id');
$join->on('arrival','>=',DB::raw("'2012-05-01'"));
$join->on('arrival','<=',DB::raw("'2012-05-10'"));
$join->on('departure','>=',DB::raw("'2012-05-01'"));
$join->on('departure','<=',DB::raw("'2012-05-10'"));
})
->where('bookings.room_type_id', '=', NULL)
->get();
Not quite sure if the between clause can be added to the join in laravel.
Notes:
DB::raw()
instructs Laravel not to put back quotes.on()
will add AND
condition and orOn()
will add OR
condition.This is simple if you only use Selenium WebDriver, and forget the usage of Selenium-RC. I'd go like this.
WebDriver driver = new FirefoxDriver();
WebElement email = driver.findElement(By.id("email"));
email.sendKeys("[email protected]");
The reason for NullPointerException
however is that your variable driver
has never been started, you start FirefoxDriver
in a variable wb
thas is never being used.
You can query the data dictionary/catalog views to find out when an object was created as well as the time of last DDL involving the object (example: alter table)
select *
from all_objects
where owner = '<name of schema owner>'
and object_name = '<name of table>'
The column "CREATED" tells you when the object was created. The column "LAST_DDL_TIME" tells you when the last DDL was performed against the object.
As for when a particular row was inserted/updated, you can use audit columns like an "insert_timestamp" column or use a trigger and populate an audit table
WebRequest being abstract (and since any inheriting class must override the Headers property).. which concrete WebRequest are you using ? In other words, how do you get that WebRequest object to beign with ?
ehr.. mnour answer made me realize that the error message you were getting is actually spot on: it's telling you that the header you are trying to add already exist and you should then modify its value using the appropriate property (the indexer, for instance), instead of trying to add it again. That's probably all you were looking for.
Other classes inheriting from WebRequest might have even better properties wrapping certain headers; See this post for instance.
If you don't want to go down the VBA path, there is this trick from a previous question.
Excel 2010: how to use autocomplete in validation list
It does add some annoying bulk to the top of your sheets, and potential maintenance (should you need more options, adding names of people from a staff list, new projects etc.) but works all the same.
Yes you right and I just want to make it understandable for complete beginners.
<link rel="shortcut icon" href="images/favicon.ico" />
and past it without any changes in between <head>
opening and </head>
closing tag.Filtering an array to contain unique values can be achieved using the JavaScript Set and Array.from method, as shown below:
Array.from(new Set(arrayOfNonUniqueValues));
The Set object lets you store unique values of any type, whether primitive values or object references.
Return value A new Set object.
The Array.from() method creates a new Array instance from an array-like or iterable object.
Return value A new Array instance.
Example Code:
const array = ["X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11"]_x000D_
_x000D_
const uniqueArray = Array.from(new Set(array));_x000D_
_x000D_
console.log("uniqueArray: ", uniqueArray);
_x000D_
A linear search starts at the beginning of a list of values, and checks 1 by 1 in order for the result you are looking for.
A binary search starts in the middle of a sorted array, and determines which side (if any) the value you are looking for is on. That "half" of the array is then searched again in the same fashion, dividing the results in half by two each time.
My lightweight implementation of ParallelForEach async.
Features:
public static class AsyncEx
{
public static async Task ParallelForEachAsync<T>(this IEnumerable<T> source, Func<T, Task> asyncAction, int maxDegreeOfParallelism = 10)
{
var semaphoreSlim = new SemaphoreSlim(maxDegreeOfParallelism);
var tcs = new TaskCompletionSource<object>();
var exceptions = new ConcurrentBag<Exception>();
bool addingCompleted = false;
foreach (T item in source)
{
await semaphoreSlim.WaitAsync();
asyncAction(item).ContinueWith(t =>
{
semaphoreSlim.Release();
if (t.Exception != null)
{
exceptions.Add(t.Exception);
}
if (Volatile.Read(ref addingCompleted) && semaphoreSlim.CurrentCount == maxDegreeOfParallelism)
{
tcs.TrySetResult(null);
}
});
}
Volatile.Write(ref addingCompleted, true);
await tcs.Task;
if (exceptions.Count > 0)
{
throw new AggregateException(exceptions);
}
}
}
Usage example:
await Enumerable.Range(1, 10000).ParallelForEachAsync(async (i) =>
{
var data = await GetData(i);
}, maxDegreeOfParallelism: 100);
You could also disable it and at the moment that you make the submit call enable it. I think is the easiest way :)
Do note that PostgreSQL 9.0 (today in beta testing) will have a simple way to do that:
test=> GRANT SELECT ON ALL TABLES IN SCHEMA public TO joeuser;
For Eclipse Mars the following worked
real life example, notify Airbrake API about new deployment via NetHttps
require 'uri'
require 'net/https'
require 'json'
class MakeHttpsRequest
def call(url, hash_json)
uri = URI.parse(url)
req = Net::HTTP::Post.new(uri.to_s)
req.body = hash_json.to_json
req['Content-Type'] = 'application/json'
# ... set more request headers
response = https(uri).request(req)
response.body
end
private
def https(uri)
Net::HTTP.new(uri.host, uri.port).tap do |http|
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
end
end
project_id = 'yyyyyy'
project_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
url = "https://airbrake.io/api/v4/projects/#{project_id}/deploys?key=#{project_key}"
body_hash = {
"environment":"production",
"username":"tomas",
"repository":"https://github.com/equivalent/scrapbook2",
"revision":"live-20160905_0001",
"version":"v2.0"
}
puts MakeHttpsRequest.new.call(url, body_hash)
Notes:
in case you doing authentication via Authorisation header set header req['Authorization'] = "Token xxxxxxxxxxxx"
or http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html
You can use slice notation with steps:
>>> x = "abcdefghijklm"
>>> x[0::2] #0. 2. 4...
'acegikm'
>>> x[1::2] #1. 3. 5 ..
'bdfhjl'
>>> [i+j for i,j in zip(x[::2], x[1::2])] # zip makes (0,1),(2,3) ...
['ab', 'cd', 'ef', 'gh', 'ij', 'kl']
Same logic applies for lists too. String lenght doesn't matter, because you're simply adding two strings together.
In Eclipse using Subversive:
Right click your project > Team > Merge
In the merge window, select the revisions you want to revert as normally but also enable checkbox "Reversed merge".
Merge as normally.
The best practice for this sort of situation is to create a method that hold all the logics, and call the method in both events, rather than calling an event from another event;
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
LogicMethod()
End Sub
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
LogicMethod()
End Sub
Private Sub LogicMethod()
// All your logic goes here
End Sub
In case you need the properties of the EventArgs (e), you can easily pass it through parameters in your method, that will avoid errors if ever the sender is of different types. But that won't be a problem in your case, as both senders are of type Button.
This answer should be more of a comment against Dawn Song's comment earlier, but since I don't have enough reputation, I'm going to write it as an answer.
According to the forum page
https://forums.developer.apple.com/thread/11313
"In general, you should never just delete the CoreSimulator/Devices directory yourself. If you really absolutely must, you need to make sure that the service is not runnign while you do that. eg:"
# Quit Xcode.app, Simulator.app, etc
sudo killall -9 com.apple.CoreSimulator.CoreSimulatorService
rm -rf ~/Library/*/CoreSimulator
I definitely ran into this issue after deleting and reinstalling Xcode.
You might encounter a problem trying to connect the build to a simulator device. The thread also answers what to do in that case,
gem install snapshot
fastlane snapshot reset_simulators
Replace spaces in URL with + like If url contains dimension1=Incontinence Liners then replace it with dimension1=Incontinence+Liners.
The clearInterval() method can be used to clear a timer set with the setInterval() method.
setInterval always returns a ID value. This value can be passed in clearInterval() to stop the timer. Here is an example of timer starting from 30 and stops when it becomes 0.
let time = 30;
const timeValue = setInterval((interval) => {
time = this.time - 1;
if (time <= 0) {
clearInterval(timeValue);
}
}, 1000);
Here's a chunk of code that will write values to a log file. If the file doesn't exist, it creates it, otherwise it just appends to the existing file. You need to add "using System.IO;" at the top of your code, if it's not already there.
string strLogText = "Some details you want to log.";
// Create a writer and open the file:
StreamWriter log;
if (!File.Exists("logfile.txt"))
{
log = new StreamWriter("logfile.txt");
}
else
{
log = File.AppendText("logfile.txt");
}
// Write to the file:
log.WriteLine(DateTime.Now);
log.WriteLine(strLogText);
log.WriteLine();
// Close the stream:
log.Close();
If you want more than just direct table grants (e.g., grants via roles, system privileges such as select any table, etc.), here are some additional queries:
System privileges for a user:
SELECT PRIVILEGE
FROM sys.dba_sys_privs
WHERE grantee = <theUser>
UNION
SELECT PRIVILEGE
FROM dba_role_privs rp JOIN role_sys_privs rsp ON (rp.granted_role = rsp.role)
WHERE rp.grantee = <theUser>
ORDER BY 1;
Direct grants to tables/views:
SELECT owner, table_name, select_priv, insert_priv, delete_priv, update_priv, references_priv, alter_priv, index_priv
FROM table_privileges
WHERE grantee = <theUser>
ORDER BY owner, table_name;
Indirect grants to tables/views:
SELECT DISTINCT owner, table_name, PRIVILEGE
FROM dba_role_privs rp JOIN role_tab_privs rtp ON (rp.granted_role = rtp.role)
WHERE rp.grantee = <theUser>
ORDER BY owner, table_name;
git pull origin master
this will sync your master to the central repo and if new branches are pushed to the central repo it will also update your clone copy.
It's best if you worked with DataSet
s and/or DataTable
s. Once you have that, ideally straight from your stored procedure with proper column names for headers, you can use the following method:
ws.Cells.LoadFromDataTable(<DATATABLE HERE>, true, OfficeOpenXml.Table.TableStyles.Light8);
.. which will produce a beautiful excelsheet with a nice table!
Now to serve your file, assuming you have an ExcelPackage
object as in your code above called pck
..
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=" + sFilename);
Response.BinaryWrite(pck.GetAsByteArray());
Response.End();
The response provided by Trevor is correct.
But here is what you can directly add in your .gitconfig
:
# Enforce SSH
[url "ssh://[email protected]/"]
insteadOf = https://github.com/
[url "ssh://[email protected]/"]
insteadOf = https://gitlab.com/
[url "ssh://[email protected]/"]
insteadOf = https://bitbucket.org/
You're accessing the latitude and longitude incorrectly.
Try
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
var address = "new york";
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
alert(latitude);
}
});
</script>
I've been using Typescript in my current angular project for about a year and a half and while there are a few issues with definitions every now and then the DefinitelyTyped project does an amazing job at keeping up with the latest versions of most popular libraries.
Having said that there is a definite learning curve when transitioning from vanilla JavaScript to TS and you should take into account the ability of you and your team to make that transition. Also if you are going to be using angular 1.x most of the examples you will find online will require you to translate them from JS to TS and overall there are not a lot of resources on using TS and angular 1.x together right now.
If you plan on using angular 2 there are a lot of examples using TS and I think the team will continue to provide most of the documentation in TS, but you certainly don't have to use TS to use angular 2.
ES6 does have some nice features and I personally plan on getting more familiar with it but I would not consider it a production-ready language at this point. Mainly due to a lack of support by current browsers. Of course, you can write your code in ES6 and use a transpiler to get it to ES5, which seems to be the popular thing to do right now.
Overall I think the answer would come down to what you and your team are comfortable learning. I personally think both TS and ES6 will have good support and long futures, I prefer TS though because you tend to get language features quicker and right now the tooling support (in my opinion) is a little better.
go to FileZilla and select which folder you will be give 777 permission, then right click set permission 777 and select check box, then ok.
On Linux you should be looking at using epoll for async I/O. It might also be worth fine-tuning socket-buffers to not waste too much kernel space per connection.
I would guess that you should be able to reach 100k connections on a reasonable machine.
With Centos 7, I have found that only JDK has tools.jar
, while JRE has not. I have installed the Java 8 JRE(yum install java-1.8.0-openjdk
), but not the JDK(yum install java-1.8.0-openjdk-devel
).
Installing the latter solves the problem. Also, remember to set JAVA_HOME
.
In swift 4 or swift 5, you can use like bellow:
let date = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: date)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let yesterday_date = dateFormatter.string(from: yesterday!)
print("yesterday->",yesterday_date)
output:
Current date: 2020-03-02
yesterday date: 2020-03-01
If working on EJB client library:
You need to mention the argument for getting the initial context.
InitialContext ctx = new InitialContext();
If you do not, it will look in the project folder for properties file. Also you can include the properties credentials or values in your class file itself as follows:
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
props.put(Context.PROVIDER_URL, "jnp://localhost:1099");
InitialContext ctx = new InitialContext(props);
URL_PKG_PREFIXES: Constant that holds the name of the environment property for specifying the list of package prefixes to use when loading in URL context factories.
The EJB client library is the primary library to invoke remote EJB components.
This library can be used through the InitialContext. To invoke EJB components the library creates an EJB client context via a URL context factory. The only necessary configuration is to parse the value org.jboss.ejb.client.naming for the java.naming.factory.url.pkgs property to instantiate an InitialContext.
If you want to know if a string is a number, you could always try parsing it:
var numberString = "123";
int number;
int.TryParse(numberString , out number);
Note that TryParse
returns a bool
, which you can use to check if your parsing succeeded.
You could [potentially] do a rewrite of the URL, but yes: you have to have control of your DNS settings so that when a user is added it gets its own subdomain.
I see that a lot of people answered the question about overflow, but I wanted to address his original problem. He said the problem was to find ab=c such that all digits are used without repeating. Ok, that's not what he asked in this post, but I'm still think that it was necessary to study the upper bound of the problem and conclude that he would never need to calculate or detect an overflow (note: I'm not proficient in math so I did this step by step, but the end result was so simple that this might have a simple formula).
The main point is that the upper bound that the problem requires for either a, b or c is 98.765.432. Anyway, starting by splitting the problem in the trivial and non trivial parts:
Now we just need to show that no other solution is possible and only the permutations are valid (and then the code to print them is trivial). We go back to the upper bound. Actually the upper bound is c = 98.765.432. It's the upper bound because it's the largest number with 8 digits (10 digits total minus 1 for each a and b). This upper bound is only for c because the bounds for a and b must be much lower because of the exponential growth, as we can calculate, varying b from 2 to the upper bound:
9938.08^2 == 98765432
462.241^3 == 98765432
99.6899^4 == 98765432
39.7119^5 == 98765432
21.4998^6 == 98765432
13.8703^7 == 98765432
9.98448^8 == 98765432
7.73196^9 == 98765432
6.30174^10 == 98765432
5.33068^11 == 98765432
4.63679^12 == 98765432
4.12069^13 == 98765432
3.72429^14 == 98765432
3.41172^15 == 98765432
3.15982^16 == 98765432
2.95305^17 == 98765432
2.78064^18 == 98765432
2.63493^19 == 98765432
2.51033^20 == 98765432
2.40268^21 == 98765432
2.30883^22 == 98765432
2.22634^23 == 98765432
2.15332^24 == 98765432
2.08826^25 == 98765432
2.02995^26 == 98765432
1.97741^27 == 98765432
Notice, for example the last line: it says that 1.97^27 ~98M. So, for example, 1^27 == 1 and 2^27 == 134.217.728 and that's not a solution because it has 9 digits (2 > 1.97 so it's actually bigger than what should be tested). As it can be seen, the combinations available for testing a and b are really small. For b == 14, we need to try 2 and 3. For b == 3, we start at 2 and stop at 462. All the results are granted to be less than ~98M.
Now just test all the combinations above and look for the ones that do not repeat any digits:
['0', '2', '4', '5', '6', '7', '8'] 84^2 = 7056
['1', '2', '3', '4', '5', '8', '9'] 59^2 = 3481
['0', '1', '2', '3', '4', '5', '8', '9'] 59^2 = 3481 (+leading zero)
['1', '2', '3', '5', '8'] 8^3 = 512
['0', '1', '2', '3', '5', '8'] 8^3 = 512 (+leading zero)
['1', '2', '4', '6'] 4^2 = 16
['0', '1', '2', '4', '6'] 4^2 = 16 (+leading zero)
['1', '2', '4', '6'] 2^4 = 16
['0', '1', '2', '4', '6'] 2^4 = 16 (+leading zero)
['1', '2', '8', '9'] 9^2 = 81
['0', '1', '2', '8', '9'] 9^2 = 81 (+leading zero)
['1', '3', '4', '8'] 3^4 = 81
['0', '1', '3', '4', '8'] 3^4 = 81 (+leading zero)
['2', '3', '6', '7', '9'] 3^6 = 729
['0', '2', '3', '6', '7', '9'] 3^6 = 729 (+leading zero)
['2', '3', '8'] 2^3 = 8
['0', '2', '3', '8'] 2^3 = 8 (+leading zero)
['2', '3', '9'] 3^2 = 9
['0', '2', '3', '9'] 3^2 = 9 (+leading zero)
['2', '4', '6', '8'] 8^2 = 64
['0', '2', '4', '6', '8'] 8^2 = 64 (+leading zero)
['2', '4', '7', '9'] 7^2 = 49
['0', '2', '4', '7', '9'] 7^2 = 49 (+leading zero)
None of them matches the problem (which can also be seen by the absence of '0', '1', ..., '9').
The example code that solves it follows. Also note that's written in Python, not because it needs arbitrary precision integers (the code doesn't calculate anything bigger than 98 million), but because we found out that the amount of tests is so small that we should use a high level language to make use of its built-in containers and libraries (also note: the code has 28 lines).
import math
m = 98765432
l = []
for i in xrange(2, 98765432):
inv = 1.0/i
r = m**inv
if (r < 2.0): break
top = int(math.floor(r))
assert(top <= m)
for j in xrange(2, top+1):
s = str(i) + str(j) + str(j**i)
l.append((sorted(s), i, j, j**i))
assert(j**i <= m)
l.sort()
for s, i, j, ji in l:
assert(ji <= m)
ss = sorted(set(s))
if s == ss:
print '%s %d^%d = %d' % (s, i, j, ji)
# Try with non significant zero somewhere
s = ['0'] + s
ss = sorted(set(s))
if s == ss:
print '%s %d^%d = %d (+leading zero)' % (s, i, j, ji)
If you are using Laravel as your Backend, then edit your .htaccess file by just pasting this code, to solve problem CROS in your Angular or IONIC project
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
This is somewhat tricky since PHP gets evaluated server-side and javascript gets evaluated client side.
I would call your PHP file using an AJAX call from inside javascript and then use JS to insert the returned HTML somewhere on your page.
simplify2array
is a base function that is fairly intuitive. However, since R's default is to fill in data by columns first, you will need to transpose the output. (sapply
uses simplify2array
, as documented in help(sapply)
.)
> t(simplify2array(a))
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 1 2 3 4 5
[2,] 2 1 2 3 4 5
[3,] 3 1 2 3 4 5
[4,] 4 1 2 3 4 5
[5,] 5 1 2 3 4 5
[6,] 6 1 2 3 4 5
[7,] 7 1 2 3 4 5
[8,] 8 1 2 3 4 5
[9,] 9 1 2 3 4 5
[10,] 10 1 2 3 4 5
You can also add underscore.js to your project and will be able to do it in one line:
_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})
Shef's answer doesn't compile for me. It looks like he's using RegEx in String.contains()
. If you want to use RegEx use this:
String strWithNumber = "This string has a 1 number";
String strWithoutNumber = "This string has a number";
System.out.println(strWithNumber.matches(".*\\d.*"));
System.out.println(strWithoutNumber.matches(".*\\d.*"));
And if you are using python 3.X, you may apply the sorted
function on the mylist. This is just an addition to the answer that @Sven Marnach has given above.
# using *sort method*
mylist.sort(lambda x: x[1])
# using *sorted function*
sorted(mylist, key = lambda x: x[1])
I had a similar problem.
Issue was there was a trigger on the table that would write changes to an audit log table. Columns were missing in audit log table.
Android includes a process management system which handles the creation and destruction of activities which largely negates any benefit you'd see from manually restarting an activity. You can see more information about it at Application Fundamentals
What is good practice though is to ensure that your onPause and onStop methods release any resources which you don't need to hold on to and use onLowMemory to reduce your activities needs to the absolute minimum.
If you want to ignore lines with only whitespace:
if not line.strip():
... do something
The empty string is a False value.
Or if you really want only empty lines:
if line in ['\n', '\r\n']:
... do something
You can try http://snad.ncsl.nist.gov/nistnet/ https://www-x.antd.nist.gov/nistnet/
It's quite old NIST project (last release 2005), but it works for me.
using :<line number>
you can navigate to any line, thus :1
takes you to the first line.
On limited version of Linux (like a QNAP (nas) I was working on):
grep -f file1 file2
can cause some problems as said by @ChristopherSchultz and using grep -F -f file1 file2
was really slow (more than 5 minutes - not finished it - over 2-3 seconds with the method below on files over 20MB)So here is what I did :
sort file1 > file1.sorted
sort file2 > file2.sorted
diff file1.sorted file2.sorted | grep "<" | sed 's/^< *//' > files.diff
diff file1.sorted files.diff | grep "<" | sed 's/^< *//' > files.same.sorted
If files.same.sorted
shall have been in same order than the original ones, than add this line for same order than file1 :
awk 'FNR==NR {a[$0]=$0; next}; $0 in a {print a[$0]}' files.same.sorted file1 > files.same
or, for same order than file2 :
awk 'FNR==NR {a[$0]=$0; next}; $0 in a {print a[$0]}' files.same.sorted file2 > files.same
I second the top voted answer, but feel like adding little more details here if anyone finds it useful.
short version:
IIS runs any website you configure in a process named w3wp.exe. IIS Application pool is feature in IIS which allows each website or a part of it to run under a corresponding w3wp.exe process. So you can run 100 websites all in a single w3wp.exe or 100 different w3wp.exe. E.g. run 3 websites in same application pool(same w3wp.exe) to save memory usage. ,run 2 different websites in two different application pools so that each can run under separate user account(called application pool identity). run a website in one application pool and a subsite 'website/app' under a different application pool.
Longer version:
Every website or a part of the website,you can run under an application pool.You can control some basic settings of the website using an application pool.
var json = {
"people": {
"person": [{
"name": "Peter",
"age": 43,
"sex": "male"},
{
"name": "Zara",
"age": 65,
"sex": "female"}]
}
};
$.each(json.people.person, function(i, v) {
if (v.name == "Peter") {
alert(v.age);
return;
}
});
Based on this answer, you could use something like:
$(function() {
var json = {
"people": {
"person": [{
"name": "Peter",
"age": 43,
"sex": "male"},
{
"name": "Zara",
"age": 65,
"sex": "female"}]
}
};
$.each(json.people.person, function(i, v) {
if (v.name.search(new RegExp(/peter/i)) != -1) {
alert(v.age);
return;
}
});
});
Add more columns when you have variable loops that repeat at different rates. I'm not sure explicitly what you're trying to do, but I think I've done something that could apply.
Creating a single loop in Excel is prettty simple. It actually does the work for you. Try this on a new workbook
A3 will automatically be "=A2+1" as you drag down. The first steps don't have to be that explicit. Excel will automatically recognize the pattern and count if you just put "2" in A2, but if we want B1-B5 to be "100" and B5-B10 to be "200" (counting up the same way) you can see why knowing how to do it explicitly matters. In this scenario, You just enter:
B7 will automatically be "=B2+100" etc. as you drag down, so basically it increases every 5 rows infinitely. To make a loop of numbers 1-5 in column A:
So, now we have column A repeating numbers 1-5 while column B is increasing by 100 every 5 cells.You could make column B repeat, for instance, the numbers 100-900 in using the same method as you did with column A as a way to produce, for instance, each possible combination with multiple variables. Drag down the columns and they'll do it infinitely. I'm not explicitly addressing the scenario given, but if you follow the steps and understand them, the concept should give you an answer to the problem that involves adding more columns and concactinating or using them as your variables.
There is no such syntax in SQL Server, though CREATE TABLE AS ... SELECT
does exist in PDW. In SQL Server you can use this query to create an empty table:
SELECT * INTO schema.newtable FROM schema.oldtable WHERE 1 = 0;
(If you want to make a copy of the table including all of the data, then leave out the WHERE
clause.)
Note that this creates the same column structure (including an IDENTITY column if one exists) but it does not copy any indexes, constraints, triggers, etc.
It seems that using mongoose there is a limit of more than 1000 documents, when using
Potato.collection.insert(potatoBag, onInsert);
You can use:
var bulk = Model.collection.initializeOrderedBulkOp();
async.each(users, function (user, callback) {
bulk.insert(hash);
}, function (err) {
var bulkStart = Date.now();
bulk.execute(function(err, res){
if (err) console.log (" gameResult.js > err " , err);
console.log (" gameResult.js > BULK TIME " , Date.now() - bulkStart );
console.log (" gameResult.js > BULK INSERT " , res.nInserted)
});
});
But this is almost twice as fast when testing with 10000 documents:
function fastInsert(arrOfResults) {
var startTime = Date.now();
var count = 0;
var c = Math.round( arrOfResults.length / 990);
var fakeArr = [];
fakeArr.length = c;
var docsSaved = 0
async.each(fakeArr, function (item, callback) {
var sliced = arrOfResults.slice(count, count+999);
sliced.length)
count = count +999;
if(sliced.length != 0 ){
GameResultModel.collection.insert(sliced, function (err, docs) {
docsSaved += docs.ops.length
callback();
});
}else {
callback()
}
}, function (err) {
console.log (" gameResult.js > BULK INSERT AMOUNT: ", arrOfResults.length, "docsSaved " , docsSaved, " DIFF TIME:",Date.now() - startTime);
});
}
As the message error says, you need to Increase the length of your column to fit the length of the data you are trying to insert (0000-00-00)
EDIT 1:
Following your comment, I run a test table:
mysql> create table testDate(id int(2) not null auto_increment, pdd date default null, primary key(id));
Query OK, 0 rows affected (0.20 sec)
Insertion:
mysql> insert into testDate values(1,'0000-00-00');
Query OK, 1 row affected (0.06 sec)
EDIT 2:
So, aparently you want to insert a NULL value to pdd
field as your comment states ?
You can do that in 2 ways like this:
Method 1:
mysql> insert into testDate values(2,'');
Query OK, 1 row affected, 1 warning (0.06 sec)
Method 2:
mysql> insert into testDate values(3,NULL);
Query OK, 1 row affected (0.07 sec)
EDIT 3:
You failed to change the default value of pdd
field. Here is the syntax how to do it (in my case, I set it to NULL in the start, now I will change it to NOT NULL)
mysql> alter table testDate modify pdd date not null;
Query OK, 3 rows affected, 1 warning (0.60 sec)
Records: 3 Duplicates: 0 Warnings: 1
If you want to catch the focus event dynamiclly on every input on your component :
import { AfterViewInit, Component, ElementRef } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
constructor(private el: ElementRef) {
}
ngAfterViewInit() {
// document.getElementsByTagName('input') : to gell all Docuement imputs
const inputList = [].slice.call((<HTMLElement>this.el.nativeElement).getElementsByTagName('input'));
inputList.forEach((input: HTMLElement) => {
input.addEventListener('focus', () => {
input.setAttribute('placeholder', 'focused');
});
input.addEventListener('blur', () => {
input.removeAttribute('placeholder');
});
});
}
}
Checkout the full code here : https://stackblitz.com/edit/angular-93jdir
I ran across a Main process exited, code=exited, status=203/EXEC
today as well and my bug was that I forgot to add the executable bit to the file.
The error message you are receiving is telling you that the application failed to connect to the sqlexpress db, and not sql server. I will just change the name of the db in sql server and then update the connectionstring accordingly and try it again.
Your error message states the following:
Cannot open database "Phaeton.mdf" requested by the login. The login failed.
It looks to me you are still trying to connect to the file based database, the name "Phaeton.mdf" does not match with your new sql database name "Phaeton".
Hope this helps.
I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery.
E.X -
1) Run On load to get checkbox value if the age checkbox is checked, then I need to show a text box to enter age, else hide the text box.
2) if the age checkbox is checked, then I need to show a text box to enter age, else hide the text box using click event of checkbox.
so code not returns false by default:
Try the following:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h1>Jquery Demo</h1>
<input type="checkbox" name="isAge" checked id="isAge"> isAge <br/>
<div id="Age" style="display:none">
<label>Enter your age</label>
<input type="number" name="age">
</div>
<script type="text/javascript">
if(document.getElementById('isAge').checked) {
$('#Age').show();
} else {
$('#Age').hide();
}
$('#isAge').click(function() {
if(document.getElementById('isAge').checked) {
$('#Age').show();
} else {
$('#Age').hide();
}
});
</script>
</body>
</html>
Here is a modified version : https://jsfiddle.net/sedhal/0hygLtrz/7/
I am assuming Basic authentication here.
$cred = Get-Credential
Invoke-WebRequest -Uri 'https://whatever' -Credential $cred
You can get your credential through other means (Import-Clixml
, etc.), but it does have to be a [PSCredential]
object.
GitHub is breaking RFC as they explain in the link you provided:
The API supports Basic Authentication as defined in RFC2617 with a few slight differences. The main difference is that the RFC requires unauthenticated requests to be answered with 401 Unauthorized responses. In many places, this would disclose the existence of user data. Instead, the GitHub API responds with 404 Not Found. This may cause problems for HTTP libraries that assume a 401 Unauthorized response. The solution is to manually craft the Authorization header.
Powershell's Invoke-WebRequest
does to my knowledge wait for a 401 response before sending the credentials, and since GitHub never provides one, your credentials will never be sent.
Instead you'll have to create the basic auth headers yourself.
Basic authentication takes a string that consists of the username and password separated by a colon user:pass
and then sends the Base64 encoded result of that.
Code like this should work:
$user = 'user'
$pass = 'pass'
$pair = "$($user):$($pass)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"
$Headers = @{
Authorization = $basicAuthValue
}
Invoke-WebRequest -Uri 'https://whatever' -Headers $Headers
You could combine some of the string concatenation but I wanted to break it out to make it clearer.
You could simply do:
Select Req_ID, (avg(R1)+avg(R2)+avg(R3)+avg(R4)+avg(R5))/5 as Average
from Request
Group by Req_ID
Right?
I'm assuming that you may have multiple rows with the same Req_ID and in these cases you want to calculate the average across all columns and rows for those rows with the same Req_ID
you are in a situation where you cannot set a certain program as the default program to use when opening a certain type of file, I've found using a .bat file handy. In my case, Textpad runs on my machine via Microsoft Application Virtualization ("AppV"). The path to Textpad is in an "AppV directory" so to speak. My Textpad AppV shortcut has this as a target...
%ALLUSERSPROFILE%\Microsoft\AppV\Client\Integration\
12345ABC-A1BC-1A23-1A23-1234567E1234\Root\TextPad.exe
To associate the textpad.exe with 'txt' files via a 'bat' file:
1) In Explorer, create a new ('txt') file and save as opentextpad.bat in an "appropriate" location
2) In the opentextpad.bat file, type this line:
textpad.exe %1
3) Save and Close
4) In explorer, perform windows file association by right-clicking on a 'txt' file (e.g. 'dummy.txt') and choose 'Open with > Choose default program...' from the menu. In the 'Open with' window, click 'Browse...', then navigate to and select your textpad.bat file. Click 'Open'. You'll return to the 'Open with' window. Make sure to check the 'Always use the selected program to open this type of file' checkbox. Click 'OK' and the window will close.
When you open a 'txt' file now, it will open the file with 'textpad.exe'.
Hope this is useful.
my issue was the one having most of the votes
*{
font-family: xxxxx
}
changing it to this solved the problem
body{
font-family: xxxx
}
In the earlier versions of MySQL ( < 5.7.5 ) the only way to set
'innodb_buffer_pool_size'
variable was by writing it to my.cnf (for linux) and my.ini (for windows) under [mysqld] section :
[mysqld]
innodb_buffer_pool_size = 2147483648
You need to restart your mysql server to have it's effect in action.
As of MySQL 5.7.5, the innodb_buffer_pool_size configuration option can be set dynamically using a SET statement, allowing you to resize the buffer pool without restarting the server. For example:
mysql> SET GLOBAL innodb_buffer_pool_size=402653184;
Reference : https://dev.mysql.com/doc/refman/5.7/en/innodb-buffer-pool-resize.html
Another trick for getting sequential pieces (beyond the seq solution already mentioned) is to use a short logical vector and use vector recycling:
foo[ c( rep(FALSE, 5), TRUE ) ]
In your code you aren't using jquery, so, if you want to use it, yo need something like...
$('#foo').css({'background-color' : 'red', 'color' : 'white', 'font-size' : '44px'});
Other way, if you are not using jquery, you need to do ...
document.getElementById('foo').style = 'background-color: red; color: white; font-size: 44px';
I hosted my Flask Application on Google Cloud Platform Virtual Machine.
I started the app using python main.py
But the problem was ctrl+c did not work to stop the server.
This command $ sudo netstat -tulnp | grep :5000
terminates the server.
My Flask app runs on port 5000 by default.
It works for this. Haven't tested for other platforms. Feel free to update or comment if it works for other versions too.
While ("run as SYSTEM") works, people should be advised this means going from a minimum-permissions type account to an account which has all permissions in the world. Which is very much not a recommended setup best practices or security-wise.
If you know what you are doing and know your SQL Server will always be run in an isolated environment (i.e. not on hotel or airport wifi) it's probably fine, but this creates a very real attack vector which can completely compromise a machine if on open internets.
This seems to be an error on Microsoft's part and people should be aware of the implications of the workaround posted.
You could do it with jQuery.
$('.myClass').click(function() {
alert('hohoho');
});
You can also use numpy assuming if you are using python3.x here is an example
import numpy as np
x = 2.3
print(np.rint(x))
>>> 2.0