Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium
From your react native folder run:
cd android && gradlew clean
THEN
cd .. && react-native run-android
Notes:
For mac you may need to change
gradlew
to./gradlew
For the command prompt you may need to change the
&&
to&
For powershell you may need to change the
&&
to;
andgradlew
to.\gradlew.bat
Each command can also be run individually like so
cd android
thengradlew clean
thencd ..
thenreact-native run-android
Though there isn't any code equivalent to goto/label
in Python, you could still get such functionality of goto/label
using loops.
Lets take a code sample shown below where goto/label
can be used in a arbitrary language other than python.
String str1 = 'BACK'
label1:
print('Hello, this program contains goto code\n')
print('Now type BACK if you want the program to go back to the above line of code. Or press the ENTER key if you want the program to continue with further lines of code')
str1 = input()
if str1 == 'BACK'
{
GoTo label1
}
print('Program will continue\nBla bla bla...\nBla bla bla...\nBla bla bla...')
Now the same functionality of the above code sample can be achieved in python by using a while
loop as shown below.
str1 = 'BACK'
while str1 == 'BACK':
print('Hello, this is a python program containing python equivalent code for goto code\n')
print('Now type BACK if you want the program to go back to the above line of code. Or press the ENTER key if you want the program to continue with further lines of code')
str1 = input()
print('Program will continue\nBla bla bla...\nBla bla bla...\nBla bla bla...')
You should be able to use:
$('#Edit.myClass, #Create.myClass').plugin({options here});
You use EXECUTENONQUERY()
for INSERT
,UPDATE
and DELETE
.
But for SELECT
you must use EXECUTEREADER()
.........
You have to catch the SIGINT signal (we are talking POSIX right?)
See @Gab Royer´s answer for sigaction.
Example:
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
void my_handler(sig_t s){
printf("Caught signal %d\n",s);
exit(1);
}
int main(int argc,char** argv)
{
signal (SIGINT,my_handler);
while(1);
return 0;
}
You can tell Eclipse to ignore these serialVersionUID warnings:
Window > Preferences > Java > Compiler > Errors / Warnings > Potential Programming Problems
In case you didn't know, there are a lot of other warnings you can enable in this section (or even have some reported as errors), many are very useful:
and many more.
You can toggle the block comment with
Ctrl+Shift+/
Source: http://www.sublimetext.com/forum/viewtopic.php?f=3&t=2967
If you want a really hacky one-liner using regular expressions and interpolated strings...
const splitString = (value, idx) => value.split(new RegExp(`(?<=^.{${idx}})`));
console.log(splitString('abcdefgh', 5));
_x000D_
This code says split the string by replacing the value returned in the regex. The regex returns a position, not a character, so we don't lose in characters in the initial string. The way it does this is finding the position, via a look-behind and the ^
anchor, where there were index
characters from the start of the string.
To solve your proposed problem of adding commas every third position from the end, the regex would be slightly different and we'd use replace rather than split.
const values = [ 8211, 98700, 1234567890 ];
const addCommas = (value, idx) => value.replace(new RegExp(`(?=(.{${idx}})+$)`, 'g'), ',');
console.log(values.map(v => addCommas(v.toString(), 3)));
_x000D_
Here we find the idx
th position from the end by using a look-ahead and the $
anchor, but we also capture any number of those sets of positions from the end. Then we replace the position with a comma. We use the g
flag (global) so it replaces every occurrence, not just the first found.
You're in replace mode. Press the Insert
key on your keyboard to switch back to insert mode. Many applications that handle text have this in common.
The other answers here fail to spell out a full solution for regex versions which don't support non-greedy matching. The greedy quantifiers (.*?
, .+?
etc) are a Perl 5 extension which isn't supported in traditional regular expressions.
If your stopping condition is a single character, the solution is easy; instead of
a(.*?)b
you can match
a[^ab]*b
i.e specify a character class which excludes the starting and ending delimiiters.
In the more general case, you can painstakingly construct an expression like
start(|[^e]|e(|[^n]|n(|[^d])))end
to capture a match between start
and the first occurrence of end
. Notice how the subexpression with nested parentheses spells out a number of alternatives which between them allow e
only if it isn't followed by nd
and so forth, and also take care to cover the empty string as one alternative which doesn't match whatever is disallowed at that particular point.
Of course, the correct approach in most cases is to use a proper parser for the format you are trying to parse, but sometimes, maybe one isn't available, or maybe the specialized tool you are using is insisting on a regular expression and nothing else.
Although it's more verbose than \w
, I personally appreciate the readability of the full POSIX character class names ( http://www.zytrax.com/tech/web/regex.htm#special ), so I'd say:
^[[:alnum:]_]+$
However, while the documentation at the above links states that \w
will "Match any character in the range 0 - 9, A - Z and a - z (equivalent of POSIX [:alnum:])", I have not found this to be true. Not with grep -P
anyway. You need to explicitly include the underscore if you use [:alnum:]
but not if you use \w
. You can't beat the following for short and sweet:
^\w+$
Along with readability, using the POSIX character classes (http://www.regular-expressions.info/posixbrackets.html) means that your regex can work on non ASCII strings, which the range based regexes won't do since they rely on the underlying ordering of the ASCII characters which may be different from other character sets and will therefore exclude some non-ASCII characters (letters such as œ) which you might want to capture.
Updated with the theme()
function, ggsave()
and the code for the legend background:
df <- data.frame(y = d, x = 1, group = rep(c("gr1", "gr2"), 50))
p <- ggplot(df) +
stat_boxplot(aes(x = x, y = y, color = group),
fill = "transparent" # for the inside of the boxplot
)
Fastest way is using using rect
, as all the rectangle elements inherit from rect:
p <- p +
theme(
rect = element_rect(fill = "transparent") # all rectangles
)
p
More controlled way is to use options of theme
:
p <- p +
theme(
panel.background = element_rect(fill = "transparent"), # bg of the panel
plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
panel.grid.major = element_blank(), # get rid of major grid
panel.grid.minor = element_blank(), # get rid of minor grid
legend.background = element_rect(fill = "transparent"), # get rid of legend bg
legend.box.background = element_rect(fill = "transparent") # get rid of legend panel bg
)
p
To save (this last step is important):
ggsave(p, filename = "tr_tst2.png", bg = "transparent")
Please do not reinvent the wheel. There are many open-source & COTS solutions that already exist to solve this problem.
Please take a look at the following JavaScript libraries:
I wrote a one-liner using Moment.js below. You can check out the demo here: JSFiddle.
moment('2014-08-20 15:30:00').format('MM/DD/YYYY h:mm a'); // 08/20/2014 3:30 pm
I am getting this error because log4j2 file got deleted from my src folder
Simply add xml file under src folder
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
</Console>
<RollingFile name="RollingFile" filename="logs/B2CATA-hybrid.log"
filepattern="${logPath}/%d{yyyyMMddHHmmss}-fargo.log">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
<Policies>
<SizeBasedTriggeringPolicy size="100 MB" />
</Policies>
<DefaultRolloverStrategy max="20" />
</RollingFile>
</Appenders>
<Loggers>
<Logger name="com.pragiti." level="trace" />
<Root level="info">
<AppenderRef ref="Console" />
<AppenderRef ref="RollingFile" />
</Root>
</Loggers>
With out knowing exactly what your trying to accomplish here its hard to say but if your spending the time to solve this problem with javascript an AJAX request is going to be your best bet. However if you'd like to do it completely in PHP put this at the end of your script, and you should be set.
if(isset($_SERVER['HTTP_REFERER'])){
header("Location: " . $_SERVER['HTTP_REFERER']);
} else {
echo "An Error";
}
This will still cause the page to change, twice, but the user will end on the page initiating the request. This is not even close to the right way to do this, and I highly recommend using an AJAX request, but it will get the job done.
Steps to convert .py to .exe in Python 3.6
pip install cx_Freeze
.pip install idna
..py
program named myfirstprog.py
.setup.py
on the current directory of your script.setup.py
file, copy the code below and save it.python setup.py build
build
. It has another folder in it. Within that folder you can find your application. Run it. Make yourself happy.See the original script in my blog.
setup.py:
from cx_Freeze import setup, Executable
base = None
executables = [Executable("myfirstprog.py", base=base)]
packages = ["idna"]
options = {
'build_exe': {
'packages':packages,
},
}
setup(
name = "<any name>",
options = options,
version = "<any number>",
description = '<any description>',
executables = executables
)
EDIT:
myfirstprog.py
you should put your .py
extension file name as created in step 4;import
ed package in your .py
into packages
list (ex: packages = ["idna", "os","sys"]
)any name, any number, any description
in setup.py
file should not remain the same, you should change it accordingly (ex:name = "<first_ever>", version = "0.11", description = ''
)import
ed packages must be installed before you start step 8.<?php
//None HttpOnly cookie:
setcookie("abc", "test", NULL, NULL, NULL, NULL, FALSE);
//HttpOnly cookie:
setcookie("abc", "test", NULL, NULL, NULL, NULL, TRUE);
?>
Change it to this:
var email = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
This is a regular expression literal that is passed the i
flag which means to be case insensitive.
Keep in mind that email address validation is hard (there is a 4 or 5 page regular expression at the end of Mastering Regular Expressions demonstrating this) and your expression certainly will not capture all valid e-mail addresses.
If there are duplicate keys then a key may correspond to more than one value. The obvious solution is to map the key to a list of these values.
For example in Python:
map = dict()
map["driver"] = list()
map["driver"].append("john")
map["driver"].append("mike")
print map["driver"] # It shows john and mike
print map["driver"][0] # It shows john
print map["driver"][1] # It shows mike
From this post:
To get the entire PC CPU and Memory usage:
using System.Diagnostics;
Then declare globally:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Processor", "% Processor Time", "_Total");
Then to get the CPU time, simply call the NextValue()
method:
this.theCPUCounter.NextValue();
This will get you the CPU usage
As for memory usage, same thing applies I believe:
private PerformanceCounter theMemCounter =
new PerformanceCounter("Memory", "Available MBytes");
Then to get the memory usage, simply call the NextValue()
method:
this.theMemCounter.NextValue();
For a specific process CPU and Memory usage:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Process", "% Processor Time",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
private PerformanceCounter theMemCounter =
new PerformanceCounter("Process", "Working Set",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
Note that Working Set may not be sufficient in its own right to determine the process' memory footprint -- see What is private bytes, virtual bytes, working set?
To retrieve all Categories, see Walkthrough: Retrieving Categories and Counters
The difference between Processor\% Processor Time
and Process\% Processor Time
is Processor
is from the PC itself and Process
is per individual process. So the processor time of the processor would be usage on the PC. Processor time of a process would be the specified processes usage. For full description of category names: Performance Monitor Counters
An alternative to using the Performance Counter
Use System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties to calculate your processor usage as this article describes.
sudo arduino is the only way I get the Arduino IDE working (serial port and upload) on ubuntu 12.04 (64) Indeed the serial port to use is /dev/ttyACM0 in my case too. The other two (ttyS4 and ttyS0) gave an error when trying to upload to Uno. Have fun
Solution for this issue is:
Create another connection manager for your excel or flat files else you just have to pass variable values in connection string:
Right Click on Connection Manager
>>properties
>>Expression
>>Select "ConnectionString"
from drop down and pass the input variable like path , filename ..
i wrote a simple function for this:
Function (stringVar param)
(
Local stringVar oneChar := '0';
Local numberVar strLen := Length(param);
Local numberVar index := strLen;
oneChar = param[strLen];
while index > 0 and oneChar = '0' do
(
oneChar := param[index];
index := index - 1;
);
Left(param , index + 1);
)
If order is important you can create your own events and bind callbacks to fire when those events are triggered by other callbacks.
$('#mydiv').click(function(e) {
// maniplate #mydiv ...
$('#mydiv').trigger('mydiv-manipulated');
});
$('#mydiv').bind('mydiv-manipulated', function(e) {
// do more stuff now that #mydiv has been manipulated
return;
});
Something like that at least.
I was executing the whole command in one line, as it was mentioned as such
$ docker run --name testproject-agent \
-e TP_API_KEY="REPLACE_WITH_YOUR_KEY" \
-e TP_AGENT_ALIAS="My First Agent" \
testproject/agent:latest
But its supposed to be a multiline command, and I copied the command line by line and pressed enter
after every line and bam! it worked.
Sometimes when you copy off of the web, the new-line
character gets omitted, hence my suggestion to try manually introducing the new line.
For completeness, this is what you would have found in the svn book, had you known what to look for. It's what you've discovered already:
Same thing, from the more recent (and detailed) version of the book:
git stash show -p | git apply
and then git stash drop
if you want to drop the stashed items.
Try to code below,
String[][] shades = new String[4][3];
for(int i = 0; i < 4; i++)
{
for(int y = 0; y < 3; y++)
{
shades[i][y] = value;
}
}
For "English locale" file names, this works nicely. I'm using this for sanitizing uploaded file names. The file name is not meant to be linked to anything on disk, it's for when the file is being downloaded hence there are no path checks.
$file_name = preg_replace('/([^\x20-~]+)|([\\/:?"<>|]+)/g', '_', $client_specified_file_name);
Basically it strips all non-printable and reserved characters for Windows and other OSs. You can easily extend the pattern to support other locales and functionalities.
if all you need is the names, use xpath instead. No need to do the iteration yourself and check for null.
string xml = @"
<root>
<Employee name=""an"" />
<Employee name=""nobyd"" />
<Employee/>
</root>
";
var doc = new XmlDocument();
//doc.Load(path);
doc.LoadXml(xml);
var names = doc.SelectNodes("//Employee/@name");
Well, it partly depends what you want to happen if you're actually in a derived class.
For example, suppose SuperClass
is in A.jar and SubClass
is in B.jar, and you're executing code in an instance method declared in SuperClass
but where this
refers to an instance of SubClass
. If you use this.getClass().getResource()
it will look relative to SubClass
, in B.jar. I suspect that's usually not what's required.
Personally I'd probably use Foo.class.getResourceAsStream(name)
most often - if you already know the name of the resource you're after, and you're sure of where it is relative to Foo
, that's the most robust way of doing it IMO.
Of course there are times when that's not what you want, too: judge each case on its merits. It's just the "I know this resource is bundled with this class" is the most common one I've run into.
Simple way in Java
public void resize(String inputImagePath,
String outputImagePath, int scaledWidth, int scaledHeight)
throws IOException {
// reads input image
File inputFile = new File(inputImagePath);
BufferedImage inputImage = ImageIO.read(inputFile);
// creates output image
BufferedImage outputImage = new BufferedImage(scaledWidth,
scaledHeight, inputImage.getType());
// scales the input image to the output image
Graphics2D g2d = outputImage.createGraphics();
g2d.drawImage(inputImage, 0, 0, scaledWidth, scaledHeight, null);
g2d.dispose();
// extracts extension of output file
String formatName = outputImagePath.substring(outputImagePath
.lastIndexOf(".") + 1);
// writes to output file
ImageIO.write(outputImage, formatName, new File(outputImagePath));
}
If you need the path
and thedomain
for each cookie, which get_dict()
is not exposes, you can parse the cookies manually, for instance:
[
{'name': c.name, 'value': c.value, 'domain': c.domain, 'path': c.path}
for c in session.cookies
]
Browser security prevents making an ajax call from a page hosted on one domain to a page hosted on a different domain; this is called the "same-origin policy".
The problem here is that in your code the program is calling 'null.length()' which is not defined if the argument passed to the function is null. That's why the exception is thrown.
Your css is almost correct. You are just missing display: block;
in image css.
Also one typo in your id. It should be <div id="ImageContainer">
img.Image { max-width: 100%; display: block; }_x000D_
div#ImageContainer { width: 600px; }
_x000D_
<div id="ImageContainer">_x000D_
<img src="http://placehold.it/1000x600" class="Image">_x000D_
</div>
_x000D_
I can confirm this issue is due to pandas 0.23.
Uninstall and then reinstall 0.22.
pip uninstall pandas
pip install pandas==0.22
Hope this could solve the problem.
If you've just added the select option to a form and you wish to trigger the change event, I've found a setTimeout is required otherwise jQuery doesn't pick up the newly added select box:
window.setTimeout(function() { jQuery('.languagedisplay').change();}, 1);
My answer is intended for comment though but since i havent got enough reputation, i think it will still be relevant as an answer and help some one.
I find datatable
in library DT
robust to handle rownames
, and columnames
Library DT
datatable(df, rownames = FALSE) # no row names
refer to https://rstudio.github.io/DT/ for usage scenarios
You can use setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom)
set 0 where you don't want images
Example for Drawable on the left:
TextView textView = (TextView) findViewById(R.id.myTxtView);
textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon, 0, 0, 0);
Alternatively, you can use setCompoundDrawablesRelativeWithIntrinsicBounds to respect RTL/LTR layouts.
Tip: Whenever you know any XML attribute but don't have clue about how to use it at runtime. just go to the description of that property in developer doc. There you will find Related Methods if it's supported at runtime . i.e. For DrawableLeft
Definitely works.
if [[ `pgrep -f $0` != "$$" ]]; then
echo "Exiting ! Exist"
exit
fi
I really did not want to post this as a comment because I would need to comment all answers and the original question.
All of the answers seem to rely on MSVCRT Microsoft Visual C Runtime. If you would like to avoid that dependency :
In case you want cross platform support, using the library here:
https://pypi.org/project/getkey/#files
https://github.com/kcsaff/getkey
Can allow for a more elegant solution.
Code example:
from getkey import getkey, keys
key = getkey()
if key == keys.UP:
... # Handle the UP key
elif key == keys.DOWN:
... # Handle the DOWN key
elif key == 'a':
... # Handle the `a` key
elif key == 'Y':
... # Handle `shift-y`
else:
# Handle other text characters
buffer += key
print(buffer)
I had old MySQL and Centos OS (ver 6 I believe) that was not supported.
One day I couldn't access Plesk.
Using Filezilla, I copied files the database files from var/lib/mysql/databasename/
I then purchased a new server with new Centos 8 OS and MariaDB.
In Plesk, I created a new database with the same name as my old one.
Using Filezilla, I then pasted the old database files into the newly created database folder. I could see the data in phpmyadmin but it was giving errors such as the ones described here. I happened to have an old sql backup dump file. I imported the dump file and it overwrote those files. I then pasted the old files back into var/lib/mysql/databasename/
I then had to do a repair in Plesk. To my suprise. It worked. I had over 6 months of order data restored and I didn't lose anything.
flatMap
transform the items emitted by an Observable into new Observables, then flattens the emissions from those into a single Observable.
Check out the scenario below where get("posts")
returns an Observable that is "flattened" by flatMap
.
myObservable.map(e => get("posts")).subscribe(o => console.log(o));
// this would log Observable objects to console.
myObservable.flatMap(e => get("posts")).subscribe(o => console.log(o));
// this would log posts to console.
Along with the already suggested methods of using a foreach
loop, I thought I'd also mention that any object that implements IEnumerable
also provides an IEnumerator
interface via the GetEnumerator
method. Although this method is usually not necessary, this can be used for manually iterating over collections, and is particularly useful when writing your own extension methods for collections.
IEnumerable<T> mySequence;
using (var sequenceEnum = mySequence.GetEnumerator())
{
while (sequenceEnum.MoveNext())
{
// Do something with sequenceEnum.Current.
}
}
A prime example is when you want to iterate over two sequences concurrently, which is not possible with a foreach
loop.
myCars.Select((v, i) => new {car = v, index = i}).First(myCondition).index;
or the slightly shorter
myCars.Select((car, index) => new {car, index}).First(myCondition).index;
With sdk, you can't write to the root of internal storage. This cause your error.
Edit :
Based on your code, to use internal storage with sdk:
final File dir = new File(context.getFilesDir() + "/nfs/guille/groce/users/nicholsk/workspace3/SQLTest");
dir.mkdirs(); //create folders where write files
final File file = new File(dir, "BlockForTest.txt");
Update
As of 2019 this can be easily achieved using ProgressIndicator
, in Material Components library, used with the Widget.MaterialComponents.ProgressIndicator.Circular.Indeterminate
style.
For more details please check Gabriele Mariotti's answer below.
Old implementation
Here is an awesome implementation of the material design circular intermediate progress bar https://gist.github.com/castorflex/4e46a9dc2c3a4245a28e. The implementation only lacks the ability add various colors like in inbox by android app but this does a pretty great job.
It's a part of ISO-8601 date representation. It's incomplete because a complete date representation in this pattern should also contains the date:
2015-03-04T00:00:00.000Z //Complete ISO-8601 date
If you try to parse this date as it is you will receive an Invalid Date
error:
new Date('T00:00:00.000Z'); // Invalid Date
So, I guess the way to parse a timestamp in this format is to concat with any date
new Date('2015-03-04T00:00:00.000Z'); // Valid Date
Then you can extract only the part you want (timestamp part)
var d = new Date('2015-03-04T00:00:00.000Z');
console.log(d.getUTCHours()); // Hours
console.log(d.getUTCMinutes());
console.log(d.getUTCSeconds());
There is also an another actively developed alternative - JSCS — JavaScript Code Style:
JSCS is a code style linter for programmatically enforcing your style guide. You can configure JSCS for your project in detail using over 150 validation rules, including presets from popular style guides like jQuery, Airbnb, Google, and more.
It comes with multiple presets that you can choose from by simply specifying the preset
in the .jscsrc
configuration file and customize it - override, enable or disable any rules:
{
"preset": "jquery",
"requireCurlyBraces": null
}
There are also plugins and extensions built for popular editors.
Also see:
I don't think you can. You may need to use an Iframe instead.
Please consider using some code like this:
SqlDataReader reader = command.ExecuteReader();
int numRows = 0;
DataTable dt = new DataTable();
dt.Load(reader);
numRows = dt.Rows.Count;
string attended_type = "";
for (int index = 0; index < numRows; index++)
{
attended_type = dt.Rows[indice2]["columnname"].ToString();
}
reader.Close();
I had to use a HTTP connection, because on HTTPS there is default file size limit.
curl -i -X 'POST' -F 'file=@/home/testeincremental.xlsx' 'http://example.com/upload.aspx?user=example&password=example123&type=XLSX'
You could use WITH to define your expressions. Then do a simple Sub-SELECT to access those definitions.
CREATE VIEW MyView
AS
WITH MyVars (SomeVar, Var2)
AS (
SELECT
'something' AS 'SomeVar',
123 AS 'Var2'
)
SELECT *
FROM MyTable
WHERE x = (SELECT SomeVar FROM MyVars)
$.ajax({
type: 'POST',
url: 'test.php',
data:$("#Test-form").serialize(),
dataType:'json',
beforeSend:function(xhr, settings){
settings.data += '&moreinfo=MoreData';
},
success:function(data){
// json response
},
error: function(data) {
// if error occured
}
});
If you want to consider null values equality too, try the following
select column1, column2,
case
when column1 is NULL and column2 is NULL then 'true'
when column1=column2 then 'true'
else 'false'
end
from table;
one more case where this issue can occur,
if(a==b)
double c;
getValue(c);
here, the value is declared in a condition and then used outside it.
My code was broken because I was using a deprecated technique. It used to be this:
video.src = window.URL.createObjectURL(localMediaStream);
video.play();
Then I replaced that with this:
video.srcObject = localMediaStream;
video.play();
That worked beautifully.
EDIT: Recently localMediaStream
has been deprecated and replaced with MediaStream
. The latest code looks like this:
video.srcObject = new MediaStream();
References:
Permission denied simply means the system is not having permission to write the file to that folder. Give permissions to the folder using "sudo chmod 777 " from terminal and try to run it. It worked for me.
Use
set dir="Your Folder Path Here"
rmdir /s %dir%
mkdir %dir%
This version deletes without asking:
set dir="Your Folder Here"
rmdir /s /q %dir%
mkdir %dir%
Example:
set dir="C:\foo1\foo\foo\foo3"
rmdir /s /q %dir%
mkdir %dir%
This will clear C:\foo1\foo\foo\foo3
.
(I would like to mention Abdullah Sabouin's answer. There was a mix up about me copying him. I did not notice his post. I would like to thank you melpomene for pointing out errors!)
Here is a more general generator function that skips any number of items from the beginning and end of an iterable:
def skip(iterable, at_start=0, at_end=0):
it = iter(iterable)
for x in itertools.islice(it, at_start):
pass
queue = collections.deque(itertools.islice(it, at_end))
for x in it:
queue.append(x)
yield queue.popleft()
Example usage:
>>> list(skip(range(10), at_start=2, at_end=2))
[2, 3, 4, 5, 6, 7]
Try the Join-Path cmdlet:
Get-ChildItem c:\code\*\bin\* -Filter *.dll | Foreach-Object {
Join-Path -Path $_.DirectoryName -ChildPath "$buildconfig\$($_.Name)"
}
For the sake of completeness (sometimes problems like this are not as complicated as they might seem):
Having a non-existing remote repository configured can also result in this behavior - I recently found out by accidentally changing my origin's URL to githu.com
.
Easy as pie.
$(document).ready(function() {
var referrer = document.referrer;
});
Hope it helps. It is not always available though.
Sounds like you're looking for the time_ago_in_words
method (or distance_of_time_in_words
), from ActiveSupport. Call it like this:
<%= time_ago_in_words(timestamp) %>
I manually pass the variables to MSBuild on build server.
msbuild.exe MyProject.csproj "/p:TargetFrameworkSDKToolsDirectory=C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools" "/p:AspnetMergePath=C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools"
Simple and Efficient Solution : use Volley
StringRequest stringRequest = new StringRequest(Request.Method.GET, finalUrl ,
new Response.Listener<String>() {
@Override
public void onResponse(String){
try {
JSONObject jsonObject = new JSONObject(response);
HashMap<String, Object> responseHashMap = new HashMap<>(Utility.toMap(jsonObject)) ;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("api", error.getMessage().toString());
}
});
RequestQueue queue = Volley.newRequestQueue(context) ;
queue.add(stringRequest) ;
Make sure you've set your locale settings right before running the script from the shell, e.g.
$ locale -a | grep "^en_.\+UTF-8"
en_GB.UTF-8
en_US.UTF-8
$ export LC_ALL=en_GB.UTF-8
$ export LANG=en_GB.UTF-8
Docs: man locale
, man setlocale
.
Your HTML should include quotes for attributes : http://jsfiddle.net/dKWnb/4/
Not required when using a HTML5 doctype - thanks @bazmegakapa
You create the array each time and add a value to it ... its working as expected ?
Moving the array outside of the live() function works fine :
var myarray = []; // more efficient than new Array()
$("#test").live("click",function() {
myarray.push($("#drop").val());
alert(myarray);
});
Also note that in later versions of jQuery v1.7 -> the live() method is deprecated and replaced by the on() method.
Your quotes only need to surround the value part of the attribute-equals selector, [attr='val']
, like this:
$('a#check_var').click(function() {
alert($("input:radio[name='r']:checked").val()+ ' '+
$("input:radio[name='s']:checked").val());
});?
If you are on Linux, gitg
is way to go to do it very quickly and graphically.
If you insist on command line you can use:
git log --oneline --decorate
To make git log
nicer by default, I typically set these global preferences:
git config --global log.decorate true
git config --global log.abbrevCommit true
if x
is numeric, then add scale_x_continuous()
; if x
is character/factor, then add scale_x_discrete()
. This might solve your problem.
The tail
program can do this:
ls -lart | tail -n +2
The -n +2
means “start passing through on the second line of output”.
CONVERT(DATE, <yourdatetime>) or CONVERT(DATE, GetDate()) or CONVERT(DATE, CURRENT_TIMESTAMP)
WeekMonth = CASE WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 22 THEN '5'
WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 15 THEN '4'
WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 8 THEN '3'
WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 1 THEN '2'
ELSE '1'
END
I ended up in this situation several times with my .NET 4.6.1 web site. I created the problem each time when I added a reference to a separate .NET Core project. Upon building, Visual Studio correctly alerted me that such cross-framework references are invalid, and I quickly deleted the project reference. The project built fine after that, but the System.Runtime error appeared when accessing the web site and refused to go away.
The fix each time was lame but effective: I deleted the project directory and redownloaded it from source control. Even though there was no difference between before and after, I was able to build the project and access the page with no complaints.
Here is the complete C# 7 solution...
switch (value)
{
case var s when new[] { 1,2,3 }.Contains(s):
// Do something
break;
case var s when new[] { 4,5,6 }.Contains(s):
// Do something
break;
default:
// Do the default
break;
}
It works with strings too...
switch (mystring)
{
case var s when new[] { "Alpha","Beta","Gamma" }.Contains(s):
// Do something
break;
...
}
Try the sp_foreachdb procedure.
I tried using the solution By @davy-c but had an Exception "System.FormatException: 'Input string was not in a correct format.'", this was due to there still being text past the line number, I modified the code he posted and came up with:
int line = Convert.ToInt32(objErr.ToString().Substring(objErr.ToString().IndexOf("line")).Substring(0, objErr.ToString().Substring(objErr.ToString().IndexOf("line")).ToString().IndexOf("\r\n")).Replace("line ", ""));
This works for me in VS2017 C#.
A wrapper class is a class that is used to wrap another class to add a layer of indirection and abstraction between the client and the original class being wrapped.
Take a look at the PDOStatement.fetchAll
method. You could also use fetch
in an iterator pattern.
Code sample for fetchAll
, from the PHP documentation:
<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);
Results:
Array
(
[0] => Array
(
[NAME] => pear
[COLOUR] => green
)
[1] => Array
(
[NAME] => watermelon
[COLOUR] => pink
)
)
As no one has mentioned - I would suggest to use great tool for such purpose - swaks
# yum info swaks
Installed Packages
Name : swaks
Arch : noarch
Version : 20130209.0
Release : 3.el6
Size : 287 k
Repo : installed
From repo : epel
Summary : Command-line SMTP transaction tester
URL : http://www.jetmore.org/john/code/swaks
License : GPLv2+
Description : Swiss Army Knife SMTP: A command line SMTP tester. Swaks can test
: various aspects of your SMTP server, including TLS and AUTH.
It has a lot of options and can do almost everything you want.
GMAIL: STARTTLS, SSLv3 (and yes, in 2016 gmail still support sslv3)
$ echo "Hello world" | swaks -4 --server smtp.gmail.com:587 --from [email protected] --to [email protected] -tls --tls-protocol sslv3 --auth PLAIN --auth-user [email protected] --auth-password 7654321 --h-Subject "Test message" --body -
=== Trying smtp.gmail.com:587...
=== Connected to smtp.gmail.com.
<- 220 smtp.gmail.com ESMTP h8sm76342lbd.48 - gsmtp
-> EHLO www.example.net
<- 250-smtp.gmail.com at your service, [193.243.156.26]
<- 250-SIZE 35882577
<- 250-8BITMIME
<- 250-STARTTLS
<- 250-ENHANCEDSTATUSCODES
<- 250-PIPELINING
<- 250-CHUNKING
<- 250 SMTPUTF8
-> STARTTLS
<- 220 2.0.0 Ready to start TLS
=== TLS started with cipher SSLv3:RC4-SHA:128
=== TLS no local certificate set
=== TLS peer DN="/C=US/ST=California/L=Mountain View/O=Google Inc/CN=smtp.gmail.com"
~> EHLO www.example.net
<~ 250-smtp.gmail.com at your service, [193.243.156.26]
<~ 250-SIZE 35882577
<~ 250-8BITMIME
<~ 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
<~ 250-ENHANCEDSTATUSCODES
<~ 250-PIPELINING
<~ 250-CHUNKING
<~ 250 SMTPUTF8
~> AUTH PLAIN AGFhQxsZXguaGhMGdATGV4X2hoYtYWlsLmNvbQBS9TU1MjQ=
<~ 235 2.7.0 Accepted
~> MAIL FROM:<[email protected]>
<~ 250 2.1.0 OK h8sm76342lbd.48 - gsmtp
~> RCPT TO:<[email protected]>
<~ 250 2.1.5 OK h8sm76342lbd.48 - gsmtp
~> DATA
<~ 354 Go ahead h8sm76342lbd.48 - gsmtp
~> Date: Wed, 17 Feb 2016 09:49:03 +0000
~> To: [email protected]
~> From: [email protected]
~> Subject: Test message
~> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
~>
~> Hello world
~>
~>
~> .
<~ 250 2.0.0 OK 1455702544 h8sm76342lbd.48 - gsmtp
~> QUIT
<~ 221 2.0.0 closing connection h8sm76342lbd.48 - gsmtp
=== Connection closed with remote host.
YAHOO: TLS aka SMTPS, tlsv1.2
$ echo "Hello world" | swaks -4 --server smtp.mail.yahoo.com:465 --from [email protected] --to [email protected] --tlsc --tls-protocol tlsv1_2 --auth PLAIN --auth-user [email protected] --auth-password 7654321 --h-Subject "Test message" --body -
=== Trying smtp.mail.yahoo.com:465...
=== Connected to smtp.mail.yahoo.com.
=== TLS started with cipher TLSv1.2:ECDHE-RSA-AES128-GCM-SHA256:128
=== TLS no local certificate set
=== TLS peer DN="/C=US/ST=California/L=Sunnyvale/O=Yahoo Inc./OU=Information Technology/CN=smtp.mail.yahoo.com"
<~ 220 smtp.mail.yahoo.com ESMTP ready
~> EHLO www.example.net
<~ 250-smtp.mail.yahoo.com
<~ 250-PIPELINING
<~ 250-SIZE 41697280
<~ 250-8 BITMIME
<~ 250 AUTH PLAIN LOGIN XOAUTH2 XYMCOOKIE
~> AUTH PLAIN AGFhQxsZXguaGhMGdATGV4X2hoYtYWlsLmNvbQBS9TU1MjQ=
<~ 235 2.0.0 OK
~> MAIL FROM:<[email protected]>
<~ 250 OK , completed
~> RCPT TO:<[email protected]>
<~ 250 OK , completed
~> DATA
<~ 354 Start Mail. End with CRLF.CRLF
~> Date: Wed, 17 Feb 2016 10:08:28 +0000
~> To: [email protected]
~> From: [email protected]
~> Subject: Test message
~> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
~>
~> Hello world
~>
~>
~> .
<~ 250 OK , completed
~> QUIT
<~ 221 Service Closing transmission
=== Connection closed with remote host.
I have been using swaks to send email notifications from nagios via gmail for last 5 years without any problem.
We had this in many other cases, what we decided internally is to always have a wrapper for the controller/directive so that we don't need to think about it. Here is you example with our wrapper.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.min.js"></script>
<script>
function main($scope) {
$scope.thisScope = $scope;
$scope.testa = false;
$scope.testb = false;
$scope.testc = false;
$scope.testd = false;
}
</script>
<div ng-app >
<div ng-controller="main">
Test A: {{testa}}<br />
Test B: {{testb}}<br />
Test C: {{testc}}<br />
Test D: {{testd}}<br />
<div>
testa (without ng-if): <input type="checkbox" ng-model="thisScope.testa" />
</div>
<div ng-if="!testa">
testb (with ng-if): <input type="checkbox" ng-model="thisScope.testb" />
</div>
<div ng-show="!testa">
testc (with ng-show): <input type="checkbox" ng-model="thisScope.testc" />
</div>
<div ng-hide="testa">
testd (with ng-hide): <input type="checkbox" ng-model="thisScope.testd" />
</div>
</div>
</div>
Hopes this helps, Yishay
Code:
List<String> list = new ArrayList<String>();
list.add("a");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
array.put(list.get(i));
}
JSONObject obj = new JSONObject();
try {
obj.put("result", array);
} catch (JSONException e) {
e.printStackTrace();
}
Change ng-disabled="!contractTypeValid"
to [disabled]="!contractTypeValid"
Java 8 introduces the Instant.ofEpochSecond
utility method for creating an Instant
from a Unix timestamp, this can then be converted into a ZonedDateTime
and finally formatted, e.g.:
final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
final long unixTime = 1372339860;
final String formattedDtm = Instant.ofEpochSecond(unixTime)
.atZone(ZoneId.of("GMT-4"))
.format(formatter);
System.out.println(formattedDtm); // => '2013-06-27 09:31:00'
I thought this might be useful for people who are using Java 8.
I got the same issue when i newly installed pycharm in my windows 10 machine.
download python setup
install this solved my problem.
for more help visit goodluck
During the install of python make sure you have "Install for all users" selected. Uninstall python and do a custom install and check "Install for all users"
In windows, if you need the a ${PWD} env variable in your docker-compose.yml you can creat a .env file in the same directory as your docker-compose.yml file then insert manualy the location of your folder.
CMD (pwd_var.bat) :
echo PWD=%cd% >> .env
Powershell (pwd_var.ps1) :
$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'; echo "PWD=$(get-location).path" >> .env
There is more good features hear for docker-compose .env variables:
https://docs.docker.com/compose/reference/envvars/ especially for the COMPOSE_CONVERT_WINDOWS_PATHS
env variable that allow docker compose to accept windows path with baskslash "\"
.
When you want to share a file on windows, the file must exist before sharing it with the container.
Problem is system is not able to find the file tools.jar
So first check that the file is there in the JDK installation of the directory.
Make the below entry in POM.xml as rightly pointed by others
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>C:\Program Files\Java\jdk1.8.0_241\lib\tools.jar</systemPath>
</dependency>
then Follow the below steps also to remove the problem
1) Right Click on your project
2) Click on Build path
As per the below image, select the workspace default JRE and click on finish.
I came up with this CSS only method of rotating the screen using media queries. The queries are based on screen sizes that I found here. 480px seemed to be a good as no/few devices had more than 480px width or less than 480px height.
@media (max-height: 480px) and (min-width: 480px) and (max-width: 600px) {
html{
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
-ms-transform: rotate(-90deg);
-o-transform: rotate(-90deg);
transform: rotate(-90deg);
-webkit-transform-origin: left top;
-moz-transform-origin: left top;
-ms-transform-origin: left top;
-o-transform-origin: left top;
transform-origin: left top;
width: 320px; /*this is the iPhone screen width.*/
position: absolute;
top: 100%;
left: 0
}
}
findViewById(R.id.drawer_layout).setAlpha((float) 0.7);
R.id.drawer_layout
is the id of the layout of which you want to dim the brightness.
You can try this... put parameters as :
http://localhost:8080/WebApplication11/webresources/generic/getText?arg1=hello
in your browser...
package newpackage;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.QueryParam;
@Path("generic")
public class GenericResource {
@Context
private UriInfo context;
/**
* Creates a new instance of GenericResource
*/
public GenericResource() {
}
/**
* Retrieves representation of an instance of newpackage.GenericResource
* @return an instance of java.lang.String
*/
@GET
@Produces("text/plain")
@Consumes("text/plain")
@Path("getText/")
public String getText(@QueryParam("arg1")
@DefaultValue("") String arg1) {
return arg1 ; }
@PUT
@Consumes("text/plain")
public void putText(String content) {
}
}
So I had the same issue, but it was because I was saving the access token but not using it. It could be because I'm super sleepy because of due dates, or maybe I just didn't think about it! But in case anyone else is in the same situation:
When I log in the user I save the access token:
$facebook = new Facebook(array(
'appId' => <insert the app id you get from facebook here>,
'secret' => <insert the app secret you get from facebook here>
));
$accessToken = $facebook->getAccessToken();
//save the access token for later
Now when I make requests to facebook I just do something like this:
$facebook = new Facebook(array(
'appId' => <insert the app id you get from facebook here>,
'secret' => <insert the app secret you get from facebook here>
));
$facebook->setAccessToken($accessToken);
$facebook->api(... insert own code here ...)
The original form is nearly perfect, you just have to omit prereq after CASE:
SELECT
CASE
WHEN prereq IS NULL THEN ' '
ELSE prereq
END AS prereq
FROM test;
I have found a way to use <base>
and anchor based links. You can use JavaScript to keep links like #contact
working as they have to. I used it in some parallax pages and it works for me.
<base href="http://www.mywebsite.com/templates/"><!--[if lte IE 6]></base><![endif]-->
...content...
<script>
var link='',pathname = window.location.href;
$('a').each(function(){
link = $(this).attr('href');
if(link[0]=="#"){
$(this).attr('href', pathname + link);
}
});
</script>
You should use at the end of the page
UPDATE `table_name` SET `test` = `number`
You can also do any mathematical changes in the process or use MySQL functions to modify the values.
By saying "Character array" you mean a string? Like "hello" or "hahaha this is a string of characters"..
Anyway, use strlen(). Read a bit about it, there's plenty of info about it, like here.
There is actually a python library called dataframe_image Just do a
pip install dataframe_image
Do the imports
import pandas as pd
import numpy as np
import dataframe_image as dfi
df = pd.DataFrame(np.random.randn(6, 6), columns=list('ABCDEF'))
and style your table if you want by:
df_styled = df.style.background_gradient() #adding a gradient based on values in cell
and finally:
dfi.export(df_styled,"mytable.png")
SELECT * FROM news WHERE date > DATE_SUB(NOW(), INTERVAL 24 HOUR)
At page translation time, the content of the file given in the include directive is ‘pasted’ as it is, in the place where the JSP include directive is used. Then the source JSP page is converted into a java servlet class. The included file can be a static resource or a JSP page. Generally, JSP include directive is used to include header banners and footers.
Syntax for include a jsp file:
<%@ include file="relative url">
Example
<%@include file="page_name.jsp" %>
Another possibility is that the result is not awaited on the client side. This can happen if any one method on the call stack does not use the await keyword to wait for the call to be completed.
It is impossible for both (?=foo)
and (?=baz)
to match at the same time. It would require the next character to be both f
and b
simultaneously which is impossible.
Perhaps you want this instead:
(?=.*foo)(?=.*baz)
This says that foo
must appear anywhere and baz
must appear anywhere, not necessarily in that order and possibly overlapping (although overlapping is not possible in this specific case because the letters themselves don't overlap).
One more solution:
no toolbar but a segmented control (eyecandy)
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
delegate:nil
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
pickerView.showsSelectionIndicator = YES;
pickerView.dataSource = self;
pickerView.delegate = self;
[actionSheet addSubview:pickerView];
[pickerView release];
UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Close"]];
closeButton.momentary = YES;
closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
closeButton.tintColor = [UIColor blackColor];
[closeButton addTarget:self action:@selector(dismissActionSheet:) forControlEvents:UIControlEventValueChanged];
[actionSheet addSubview:closeButton];
[closeButton release];
[actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
[actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
One way that also works is putting it this way in the first line of the your target:
your-target: $(eval SHELL:=/bin/bash)
@echo "here shell is $$0"
For those of you want to copy the cURL output in the clipboard instead of outputting to a file, you can use pbcopy
by using the pipe |
after the cURL command.
Example: curl https://www.google.com/robots.txt | pbcopy
. This will copy all the content from the given URL to your clipboard.
If you need both words are close each other, for example no more than 3 lines, you can do this:
find . -exec grep -Hn -C 3 "abc" {} \; | grep -C 3 "efg"
Same example but filtering only *.txt files:
find . -name *.txt -exec grep -Hn -C 3 "abc" {} \; | grep -C 3 "efg"
And also you can replace grep
command with egrep
command if you want also find with regular expressions.
Using this solution, you will also be able to put the cursor at the end of newly text.
final TextEditingController _controller = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: TextField(controller: _controller)),
floatingActionButton: FloatingActionButton(
onPressed: () {
_controller.text = "Hello";
// this changes cursor position
_controller.selection = TextSelection.fromPosition(TextPosition(offset: _controller.text.length));
setState(() {});
},
),
);
}
The use of file.exists() to test for the existence of the directory is a problem in the original post. If subDir included the name of an existing file (rather than just a path), file.exists() would return TRUE, but the call to setwd() would fail because you can't set the working directory to point at a file.
I would recommend the use of file_test(op="-d", subDir), which will return "TRUE" if subDir is an existing directory, but FALSE if subDir is an existing file or a non-existent file or directory. Similarly, checking for a file can be accomplished with op="-f".
Additionally, as described in another comment, the working directory is part of the R environment and should be controlled by the user, not a script. Scripts should, ideally, not change the R environment. To address this problem, I might use options() to store a globally available directory where I wanted all of my output.
So, consider the following solution, where someUniqueTag is just a programmer-defined prefix for the option name, which makes it unlikely that an option with the same name already exists. (For instance, if you were developing a package called "filer", you might use filer.mainDir and filer.subDir).
The following code would be used to set options that are available for use later in other scripts (thus avoiding the use of setwd() in a script), and to create the folder if necessary:
mainDir = "c:/path/to/main/dir"
subDir = "outputDirectory"
options(someUniqueTag.mainDir = mainDir)
options(someUniqueTag.subDir = "subDir")
if (!file_test("-d", file.path(mainDir, subDir)){
if(file_test("-f", file.path(mainDir, subDir)) {
stop("Path can't be created because a file with that name already exists.")
} else {
dir.create(file.path(mainDir, subDir))
}
}
Then, in any subsequent script that needed to manipulate a file in subDir, you might use something like:
mainDir = getOption(someUniqueTag.mainDir)
subDir = getOption(someUniqueTag.subDir)
filename = "fileToBeCreated.txt"
file.create(file.path(mainDir, subDir, filename))
This solution leaves the working directory under the control of the user.
He's right. If you want to stay with jQuery you could do this
var ctx = $('#myChart')[0];
ctx.height = 500;
or
var ctx = $('#myChart');
ctx.attr('height',500);
If you are not sure if local db is installed, or not sure which database name you should use to connect to it - try running 'sqllocaldb info' command - it will show you existing localdb databases.
Now, as far as I know, local db should be installed together with Visual Studio 2015. But probably it is not required feature, and if something goes wrong or it cannot be installed for some reason - Visual Studio installation continues still (note that is just my guess). So to be on the safe side don't rely on it will always be installed together with VS.
This way work for me:
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(GApplication.getInstance().getTheme());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Then you want to change a new theme:
GApplication.getInstance().setTheme(R.style.LightTheme);
recreate();
In rails 5, as per the instructions in Rails Guides, you can use:
redirect_back(fallback_location: root_path)
The 'back' location is pulled from the HTTP_REFERER header which is not guaranteed to be set by the browser. Thats why you should provide a 'fallback_location'.
That looks like it might belong in the select statement:
SELECT id, col1, col2, col3, (CASE WHEN table3.col3 IS NULL THEN table2.col3 AS col4 ELSE table3.col3 as col4 END)
FROM table1
LEFT OUTER JOIN table2
ON table1.id = table2.id
LEFT OUTER JOIN table3
ON table1.id = table3.id
Try creating an inline table-valued function. Example:
CREATE FUNCTION dbo.fxnExample (@Parameter1 INTEGER)
RETURNS TABLE
AS
RETURN
(
SELECT Field1, Field2
FROM SomeTable
WHERE Field3 = @Parameter1
)
-- Then call like this, just as if it's a table/view just with a parameter
SELECT * FROM dbo.fxnExample(1)
If you view the execution plan for the SELECT you will not see a mention of the function at all and will actually just show you the underlying tables being queried. This is good as it means statistics on the underlying tables will be used when generating an execution plan for the query.
The thing to avoid would be a multi-statement table valued function as underlying table statistics will not be used and can result in poor performance due to a poor execution plan.
Example of what to avoid:
CREATE FUNCTION dbo.fxnExample (@Parameter1 INTEGER)
RETURNS @Results TABLE(Field1 VARCHAR(10), Field2 VARCHAR(10))
AS
BEGIN
INSERT @Results
SELECT Field1, Field2
FROM SomeTable
WHERE Field3 = @Parameter1
RETURN
END
Subtly different, but with potentially big differences in performance when the function is used in a query.
Just as a note you can also use this for iPads:
activityViewController.popoverPresentationController?.sourceView = sender
So the popover pops from the sender (the button in that case).
Drop multiple columns like this:
cols = [1,2,4,5,12]
df.drop(df.columns[cols],axis=1,inplace=True)
inplace=True
is used to make the changes in the dataframe itself without doing the column dropping on a copy of the data frame. If you need to keep your original intact, use:
df_after_dropping = df.drop(df.columns[cols],axis=1)
I think you want to give Share button, clicking on which the suitable media/website option should be there to share with it. In Android, you need to create createChooser
for the same.
Sharing Text:
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "This is the text that will be shared.");
startActivity(Intent.createChooser(sharingIntent,"Share using"));
Sharing binary objects (Images, videos etc.)
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse(path);
sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));
FYI, above code are referred from Sharing content in Android using ACTION_SEND Intent
This post will go through the following topics:
merge
, join
, concat
There are a few options, some simpler than others depending on the use case.
DataFrame.merge
withleft_index
andright_index
(orleft_on
andright_on
using names indexes)
- supports inner/left/right/full
- can only join two at a time
- supports column-column, index-column, index-index joins
DataFrame.join
(join on index)
- supports inner/left (default)/right/full
- can join multiple DataFrames at a time
- supports index-index joins
pd.concat
(joins on index)
- supports inner/full (default)
- can join multiple DataFrames at a time
- supports index-index joins
Setup & Basics
import pandas as pd
import numpy as np
np.random.seed([3, 14])
left = pd.DataFrame(data={'value': np.random.randn(4)},
index=['A', 'B', 'C', 'D'])
right = pd.DataFrame(data={'value': np.random.randn(4)},
index=['B', 'D', 'E', 'F'])
left.index.name = right.index.name = 'idxkey'
left
value
idxkey
A -0.602923
B -0.402655
C 0.302329
D -0.524349
right
value
idxkey
B 0.543843
D 0.013135
E -0.326498
F 1.385076
Typically, an inner join on index would look like this:
left.merge(right, left_index=True, right_index=True)
value_x value_y
idxkey
B -0.402655 0.543843
D -0.524349 0.013135
Other joins follow similar syntax.
Notable Alternatives
DataFrame.join
defaults to joins on the index. DataFrame.join
does a LEFT OUTER JOIN by default, so how='inner'
is necessary here.
left.join(right, how='inner', lsuffix='_x', rsuffix='_y')
value_x value_y
idxkey
B -0.402655 0.543843
D -0.524349 0.013135
Note that I needed to specify the lsuffix
and rsuffix
arguments since join
would otherwise error out:
left.join(right)
ValueError: columns overlap but no suffix specified: Index(['value'], dtype='object')
Since the column names are the same. This would not be a problem if they were differently named.
left.rename(columns={'value':'leftvalue'}).join(right, how='inner')
leftvalue value
idxkey
B -0.402655 0.543843
D -0.524349 0.013135
pd.concat
joins on the index and can join two or more DataFrames at once. It does a full outer join by default, so how='inner'
is required here..
pd.concat([left, right], axis=1, sort=False, join='inner')
value value
idxkey
B -0.402655 0.543843
D -0.524349 0.013135
For more information on concat
, see this post.
To perform an inner join using index of left, column of right, you will use DataFrame.merge
a combination of left_index=True
and right_on=...
.
right2 = right.reset_index().rename({'idxkey' : 'colkey'}, axis=1)
right2
colkey value
0 B 0.543843
1 D 0.013135
2 E -0.326498
3 F 1.385076
left.merge(right2, left_index=True, right_on='colkey')
value_x colkey value_y
0 -0.402655 B 0.543843
1 -0.524349 D 0.013135
Other joins follow a similar structure. Note that only merge
can perform index to column joins. You can join on multiple columns, provided the number of index levels on the left equals the number of columns on the right.
join
and concat
are not capable of mixed merges. You will need to set the index as a pre-step using DataFrame.set_index
.
If your index is named, then from pandas >= 0.23, DataFrame.merge
allows you to specify the index name to on
(or left_on
and right_on
as necessary).
left.merge(right, on='idxkey')
value_x value_y
idxkey
B -0.402655 0.543843
D -0.524349 0.013135
For the previous example of merging with the index of left, column of right, you can use left_on
with the index name of left:
left.merge(right2, left_on='idxkey', right_on='colkey')
value_x colkey value_y
0 -0.402655 B 0.543843
1 -0.524349 D 0.013135
Jump to other topics in Pandas Merging 101 to continue learning:
* you are here
You can do like below to make setTimeout pausable on server side (Node.js)
const PauseableTimeout = function(callback, delay) {
var timerId, start, remaining = delay;
this.pause = function() {
global.clearTimeout(timerId);
remaining -= Date.now() - start;
};
this.resume = function() {
start = Date.now();
global.clearTimeout(timerId);
timerId = global.setTimeout(callback, remaining);
};
this.resume();
};
and you can check it as below
var timer = new PauseableTimeout(function() {
console.log("Done!");
}, 3000);
setTimeout(()=>{
timer.pause();
console.log("setTimeout paused");
},1000);
setTimeout(()=>{
console.log("setTimeout time complete");
},3000)
setTimeout(()=>{
timer.resume();
console.log("setTimeout resume again");
},5000)
This looks like a Json array list.Therefore its best to use ArrayList
to handle the data. In your api end point add array list like this
@GET("places/")
Call<ArrayList<Place>> getNearbyPlaces(@Query("latitude") String latitude, @Query("longitude") String longitude);
You can use the onChange property. Something like:
<select onChange="window.location.href=this.value">
<option value="www.google.com">A</option>
<option value="www.aol.com">B</option>
</select>
Either one should work OK. In fact, System.Threading.Timer uses System.Timers.Timer internally.
Having said that, it's easy to misuse System.Timers.Timer. If you don't store the Timer object in a variable somewhere, then it is liable to be garbage collected. If that happens, your timer will no longer fire. Call the Dispose method to stop the timer, or use the System.Threading.Timer class, which is a slightly nicer wrapper.
What problems have you seen so far?
In the meantime urllib2 seems to verify server certificates by default. The warning, that was shown in the past disappeared for 2.7.9 and I currently ran into this problem in a test environment with a self signed certificate (and Python 2.7.9).
My evil workaround (don't do this in production!):
import urllib2
import ssl
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
urllib2.urlopen("https://your-test-server.local", context=ctx)
According to docs calling SSLContext constructor directly should work, too. I haven't tried that.
If Git for windows is installed, run Git Bash shell
:
bash
You can run ssh from within Bash shell (Bash is aware of the path of ssh)
To know the exact path of ssh, run "where" command in Bash shell:
$ where ssh
you get:
c:\Program Files\Git\usr\bin\ssh.exe
You can add this to your _Layout.cshtml:
@using MyProj.ViewModels;
...
@if (TempData["UserMessage"] != null)
{
var message = (MessageViewModel)TempData["UserMessage"];
<div class="alert @message.CssClassName" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong>@message.Title</strong>
@message.Message
</div>
}
Then if you want to throw an error message in your controller:
TempData["UserMessage"] = new MessageViewModel() { CssClassName = "alert-danger alert-dismissible", Title = "Error", Message = "This is an error message" };
MessageViewModel.cs:
public class MessageViewModel
{
public string CssClassName { get; set; }
public string Title { get; set; }
public string Message { get; set; }
}
Note: Using Bootstrap 4 classes.
You can also use a dict comprehension like:
with open("infile.txt") as f:
d = {int(k): v for line in f for (k, v) in [line.strip().split(None, 1)]}
Better yet, consider sp_getapplock
which is designed for this. Or use SET LOCK_TIMEOUT
Otherwise, you'd have to do something with sys.dm_tran_locks
which I'd use only for DBA stuff: not for user defined concurrency.
The below should work
describe "#foo"
it "should call 'bar' with appropriate arguments" do
subject.stub(:bar)
subject.foo
expect(subject).to have_received(:bar).with("Invalid number of arguments")
end
end
Documentation: https://github.com/rspec/rspec-mocks#expecting-arguments
Just want to reiterate this will work in pandas >= 0.9.1:
In [2]: read_csv('sample.csv', dtype={'ID': object})
Out[2]:
ID
0 00013007854817840016671868
1 00013007854817840016749251
2 00013007854817840016754630
3 00013007854817840016781876
4 00013007854817840017028824
5 00013007854817840017963235
6 00013007854817840018860166
I'm creating an issue about detecting integer overflows also.
EDIT: See resolution here: https://github.com/pydata/pandas/issues/2247
Update as it helps others:
To have all columns as str, one can do this (from the comment):
pd.read_csv('sample.csv', dtype = str)
To have most or selective columns as str, one can do this:
# lst of column names which needs to be string
lst_str_cols = ['prefix', 'serial']
# use dictionary comprehension to make dict of dtypes
dict_dtypes = {x : 'str' for x in lst_str_cols}
# use dict on dtypes
pd.read_csv('sample.csv', dtype=dict_dtypes)
This will convert an integer to a 2 digit hex string with the 0x prefix:
strHex = "0x%0.2X" % 255
<TouchableHighlight>
element can have only one child inside All answers are correct with sc.textFile
I was just wondering why not wholeTextFiles
For example, in this case...
val minPartitions = 2
val path = "/pathtohdfs"
sc.wholeTextFiles(path,minPartitions)
.flatMap{case (path, text)
...
one limitation is that, we have to load small files otherwise performance will be bad and may lead to OOM.
Note :
Further reference to visit
Case 1:Only two activity A and B:
Here Activity flow is A->B .On clicking backbutton from B we need to close the application then while starting Activity B from A just call finish() this will prevent android from storing Activity A in to the Backstack.eg for activity A is Loding/Splash screen of application.
Intent newIntent = new Intent(A.this, B.class);
startActivity(newIntent);
finish();
Case 2:More than two activitiy:
If there is a flow like A->B->C->D->B and on clicking back button in Activity B while coming from Activity D.In that case we should use.
Intent newIntent = new Intent(D.this,B.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(newIntent);
Here Activity B will be started from the backstack rather than a new instance because of Intent.FLAG_ACTIVITY_CLEAR_TOP and Intent.FLAG_ACTIVITY_NEW_TASK clears the stack and makes it the top one.So when we press back button the whole application will be terminated.
for i in A:
print('\t'.join(map(str, i)))
Since Spring 3.1 the id
attribute is an xsd:string
and permits the same range of characters as the name
attribute.
The only difference between an id
and a name
is that a name
can contain multiple aliases separated by a comma, semicolon or whitespace, whereas an id
must be a single value.
From the Spring 3.2 documentation:
In XML-based configuration metadata, you use the id and/or name attributes to specify the bean identifier(s). The id attribute allows you to specify exactly one id. Conventionally these names are alphanumeric ('myBean', 'fooService', etc), but may special characters as well. If you want to introduce other aliases to the bean, you can also specify them in the name attribute, separated by a comma (,), semicolon (;), or white space. As a historical note, in versions prior to Spring 3.1, the id attribute was typed as an xsd:ID, which constrained possible characters. As of 3.1, it is now xsd:string. Note that bean id uniqueness is still enforced by the container, though no longer by XML parsers.
'[{"event":"inbound","ts":1426249238}]'
is a string, you cannot access any properties there. You will have to parse it to an object, with JSON.parse()
and then handle it like a normal object
for installing multiple packages, i am using a setup.py file with following code:
import sys
import subprocess
import pkg_resources
required = {'numpy','pandas','<etc>'}
installed = {pkg.key for pkg in pkg_resources.working_set}
missing = required - installed
if missing:
# implement pip as a subprocess:
subprocess.check_call([sys.executable, '-m', 'pip', 'install',*missing])
If you want to delete an item from the repository, but keep it locally as an unversioned file/folder, use Extended Context Menu ? Delete (keep local). You have to hold the Shift key while right clicking on the item in the explorer list pane (right pane) in order to see this in the extended context menu.
Delete completely:
right mouse click ? Menu ? Delete
Delete & Keep local:
Shift + right mouse click ? Menu ? Delete
You can access the keys with ${!array[@]}
:
bash-4.0$ echo "${!array[@]}"
foo bar
Then, iterating over the key/value pairs is easy:
for i in "${!array[@]}"
do
echo "key :" $i
echo "value:" ${array[$i]}
done
You should use is as follows:
DECIMAL(m,a)
m
is the number of total digits your decimal can have.
a
is the max number of digits you can have after the decimal point.
http://www.tsqltutorials.com/datatypes.php has descriptions for all the datatypes.
The new cv2
interface for Python integrates numpy arrays into the OpenCV framework, which makes operations much simpler as they are represented with simple multidimensional arrays. For example, your question would be answered with:
import cv2 # Not actually necessary if you just want to create an image.
import numpy as np
blank_image = np.zeros((height,width,3), np.uint8)
This initialises an RGB-image that is just black. Now, for example, if you wanted to set the left half of the image to blue and the right half to green , you could do so easily:
blank_image[:,0:width//2] = (255,0,0) # (B, G, R)
blank_image[:,width//2:width] = (0,255,0)
If you want to save yourself a lot of trouble in future, as well as having to ask questions such as this one, I would strongly recommend using the cv2
interface rather than the older cv
one. I made the change recently and have never looked back. You can read more about cv2
at the OpenCV Change Logs.
If you want to update a single gem to a specific version:
bundle update
> ruby -v
ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-darwin19]
> gem -v
3.0.3
> bundle -v
Bundler version 2.1.4
There's no easy CSS only solution. You could do this:
Find all instances of background-color
and color
in your CSS file and create a class name for each unique color.
.top-header { color: #fff; }
.content-text { color: #f00; }
.bg-leftnav { background-color: #fff; }
.bg-column { background-color: #f00; }
Next go through every single page on your site where color was involved and add the appropriate classes for both color and background color.
Last, remove any references of colors in your CSS other than your newly created color classes.
an easy solution is to install the module using python -m pip install <library-name>
instead of pip install <library-name>
you may use sudo in case of admin restrictions
Is this what you are looking for?
https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant
types is optional
This can done several ways. I usually do it from my class.
From class
.image
{
width:100%;
}
and for this your html would be:
<img class="image" src="images/image_name">
or if you want to style it using inline styling then you would just have:
<img style="width:100%; height:60px" id="image" src="images/image_name">
I however recommend doing it from your external style-sheet because as your project grows you will realize that the entire thing is easier managed with separate files for your html and your css.
if (nfile.eof()) // Prompt data from the Priming read:
nfile >> CODE >> QTY >> PRICE;
else
{
/*used to check that the file is not empty*/
ofile << "empty file!!" << endl;
return 1;
}
I try Ronnie's answer, and my app crashed. Then I check my drawable xml. It looks like this:
<selector >...</selector>
. I changed it to this:(also changed attributes)
<shape> ... </shape>
It works.
For those who encounter the same problem.
It helps to install a python package foo
on your machine (can also be in virtualenv
) so that you can import the package foo
from other projects and also from [I]Python prompts.
It does the similar job of pip
, easy_install
etc.,
Using setup.py
Let's start with some definitions:
Package - A folder/directory that contains __init__.py
file.
Module - A valid python file with .py
extension.
Distribution - How one package relates to other packages and modules.
Let's say you want to install a package named foo
. Then you do,
$ git clone https://github.com/user/foo
$ cd foo
$ python setup.py install
Instead, if you don't want to actually install it but still would like to use it. Then do,
$ python setup.py develop
This command will create symlinks to the source directory within site-packages instead of copying things. Because of this, it is quite fast (particularly for large packages).
Creating setup.py
If you have your package tree like,
foo
+-- foo
¦ +-- data_struct.py
¦ +-- __init__.py
¦ +-- internals.py
+-- README
+-- requirements.txt
+-- setup.py
Then, you do the following in your setup.py
script so that it can be installed on some machine:
from setuptools import setup
setup(
name='foo',
version='1.0',
description='A useful module',
author='Man Foo',
author_email='[email protected]',
packages=['foo'], #same as name
install_requires=['bar', 'greek'], #external packages as dependencies
)
Instead, if your package tree is more complex like the one below:
foo
+-- foo
¦ +-- data_struct.py
¦ +-- __init__.py
¦ +-- internals.py
+-- README
+-- requirements.txt
+-- scripts
¦ +-- cool
¦ +-- skype
+-- setup.py
Then, your setup.py
in this case would be like:
from setuptools import setup
setup(
name='foo',
version='1.0',
description='A useful module',
author='Man Foo',
author_email='[email protected]',
packages=['foo'], #same as name
install_requires=['bar', 'greek'], #external packages as dependencies
scripts=[
'scripts/cool',
'scripts/skype',
]
)
Add more stuff to (setup.py
) & make it decent:
from setuptools import setup
with open("README", 'r') as f:
long_description = f.read()
setup(
name='foo',
version='1.0',
description='A useful module',
license="MIT",
long_description=long_description,
author='Man Foo',
author_email='[email protected]',
url="http://www.foopackage.com/",
packages=['foo'], #same as name
install_requires=['bar', 'greek'], #external packages as dependencies
scripts=[
'scripts/cool',
'scripts/skype',
]
)
The long_description
is used in pypi.org as the README description of your package.
And finally, you're now ready to upload your package to PyPi.org so that others can install your package using pip install yourpackage
.
First step is to claim your package name & space in pypi using:
$ python setup.py register
Once your package name is registered, nobody can claim or use it. After successful registration, you have to upload your package there (to the cloud) by,
$ python setup.py upload
Optionally, you can also sign your package with GPG
by,
$ python setup.py --sign upload
Bonus Reading:
See a sample setup.py
from a real project here: torchvision-setup.py
You need to specify the encoding of the InputStreamReader using the Charset parameter.
Charset inputCharset = Charset.forName("ISO-8859-1");
InputStreamReader isr = new InputStreamReader(fis, inputCharset));
This is work for me. i hope to help you.
Use the bootstrap classes col-xx-#
and col-xx-offset-#
So what is happening here is your screen is getting divided into 12 columns. In col-xx-#
, #
is the number of columns you cover and offset is the number of columns you leave.
For xx
, in a general website, md
is preferred and if you want your layout to look the same in a mobile device, xs
is preferred.
With what I can make of your requirement,
<div class="row">
<div class="col-md-4">First Div</div>
<div class="col-md-8">Second DIV </div>
</div>
Should do the trick.
For someone who needs only Style
way for AppCompat
.
styles.xml
<resources>
...
<style name="Spinner" parent="Widget.AppCompat.Light.DropDownItem.Spinner">
<item name="android:paddingStart">0dp</item>
<item name="android:paddingEnd">0dp</item>
<item name="android:textColor">@color/material_grey_700</item>
<item name="android:textSize">12sp</item>
</style>
</resources>
your_spinner_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" />
...
<android.support.v7.widget.AppCompatSpinner
android:id="@+id/content_spinner"
style="@style/Widget.AppCompat.Spinner.Underlined"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:entries="@array/shipping_tracking_carrier_names"
android:spinnerMode="dropdown"
android:theme="@style/Spinner" />
<EditText
android:id="@+id/content_input"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:inputType="text"
android:maxLines="1"
android:paddingEnd="8dp"
android:paddingStart="8dp"
android:textColor="@color/material_grey_700"
android:textSize="12sp" />
...
</LinearLayout>
Plus
And if you want to set android:entries
programmatically with defined style.
Try this.
AppCompatSpinner spinner = findViewById(R.id.content_spinner);
CharSequence[] entries = getResources().getTextArray(R.array.shipping_tracking_carrier_names);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<>(spinner.getContext(), android.R.layout.simple_spinner_item, entries);
adapter.setDropDownViewResource(android.support.v7.appcompat.R.layout.support_simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
As in the code, using same Context
with the Spinner
is most important thing.
spinner.getContext()
Here is a simple approach which triggers when the video ends.
<html>
<body>
<video id="myVideo" controls="controls">
<source src="video.mp4" type="video/mp4">
etc ...
</video>
</body>
<script type='text/javascript'>
document.getElementById('myVideo').addEventListener('ended', function(e) {
alert('The End');
})
</script>
</html>
In the 'EventListener' line substitute the word 'ended' with 'pause' or 'play' to capture those events as well.
string fileAndPath = @"c:\webserver\public\myCompany\configs\promo.xml";
string currentDirectory = Path.GetDirectoryName(fileAndPath);
string fullPathOnly = Path.GetFullPath(currentDirectory);
currentDirectory: c:\webserver\public\myCompany\configs
fullPathOnly: c:\webserver\public\myCompany\configs
The solution is pretty easy... Searched for it for a while and it turns out that you just have to edit 2 config-files:
/usr/my.cnf
/etc/mysql/my.cnf
in both files you'll have to add:
[mysqld]
...
sql_mode=NO_ENGINE_SUBSTITUTION
At least, that's what's working for 5.6.24-2+deb.sury.org~precise+2
For VS2017 you will need to add the "Microsoft Visual Studio 2017 Installer Projects" VS extension. This will give you additional Visual Studio Installer project templates. https://marketplace.visualstudio.com/items?itemName=VisualStudioProductTeam.MicrosoftVisualStudio2017InstallerProjects#overview
To install the windows service you can add a new setup wizard type project and follow the steps from Kelsey's answer https://stackoverflow.com/a/9021107/1040040
Your part:
$result = mysql_connect("localhost", "******", "*****") or die ("Could not save image name
Error: " . mysql_error());
mysql_select_db("project") or die("Could not select database");
mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");
if($result) { echo "Image name saved into database
";
Doesn't make much sense, your connection shouldn't be named $result but that is a naming issue not a coding one.
What is a coding issue is if($result), your saying if you can connect to the database regardless of the insert query failing or succeeding you will output "Image saved into database".
Try adding do
$realresult = mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");
and change the if($result) to $realresult
I suspect your query is failing, perhaps you have additional columns or something?
Try copy/pasting your query, replacing the ".$_FILES['filep']['name']." with test and running it in your query browser and see if it goes in.
Also worth noting you can use 'em' as well as 'px' - blogs and text based sites do it because then the browser makes layout decisions more relative to the text content.
On Wordpress twentysixteen I wanted my tagline to display on mobiles as well as desktops, so I put this in my child theme style.css
@media screen and (max-width:59em){
p.site-description {
display: block;
}
}
Type info variables
to list "All global and static variable names".
Type info locals
to list "Local variables of current stack frame" (names and values), including static variables in that function.
Type info args
to list "Arguments of the current stack frame" (names and values).
What if your server goes down at 4:59AM and comes back at 5:01AM? I think it will just skip the run. I would recommend persistent scheduler like Quartz, that would store its schedule data somewhere. Then it will see that this run hasn't been performed yet and will do it at 5:01AM.
If we have:
enum Gender
{
M = 0,
F = 1,
U = 2
}
and
enum Gender2
{
Male = 0,
Female = 1,
Unknown = 2
}
We can safely do
var gender = Gender.M;
var gender2 = (Gender2)(int)gender;
Or even
var enumOfGender2Type = (Gender2)0;
If you want to cover the case where an enum on the right side of the '=' sign has more values than the enum on the left side - you will have to write your own method/dictionary to cover that as others suggested.
You seem to be confusing asynchronous IO with asynchronous functions. node.js uses asynchronous non-blocking IO because non blocking IO is better. The best way to understand it is to go watch some videos by ryan dahl.
How do I write asynchronous functions for Node?
Just write normal functions, the only difference is that they are not executed immediately but passed around as callbacks.
How should I implement error event handling correctly
Generally API's give you a callback with an err as the first argument. For example
database.query('something', function(err, result) {
if (err) handle(err);
doSomething(result);
});
Is a common pattern.
Another common pattern is on('error')
. For example
process.on('uncaughtException', function (err) {
console.log('Caught exception: ' + err);
});
Edit:
var async_function = function(val, callback){
process.nextTick(function(){
callback(val);
});
};
The above function when called as
async_function(42, function(val) {
console.log(val)
});
console.log(43);
Will print 42
to the console asynchronously. In particular process.nextTick
fires after the current eventloop callstack is empty. That call stack is empty after async_function
and console.log(43)
have run. So we print 43 followed by 42.
You should probably do some reading on the event loop.
Explanation and working solution here: Howto: div with onclick inside another div with onclick javascript
by executing this script in your inner click handler:
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
Disabling the alert message is not a way to solve the problem. Despite the PHP core is continue to work it makes a dangerous assumptions and actions.
Never ignore the error where PHP should make an assumptions of something!!!!
If the class organized as a singleton you can always use function getInstance() and then use getData()
Likse:
$classObj = MyClass::getInstance();
$classObj->getData();
If the class is not a singleton, use
$classObj = new MyClass();
$classObj->getData();
In addition to options suggested by others I can recommend the fmt library which implements string formatting similar to str.format
in Python and String.Format
in C#. Here's an example:
std::string a = "test";
std::string b = "text.txt";
std::string c = "text1.txt";
std::string result = fmt::format("{0} {1} > {2}", a, b, c);
Disclaimer: I'm the author of this library.
after reading previous examples I came up with this:
protected static $nonce_length = 32;
public static function getNonce()
{
$chars = array();
for ($i = 0; $i < 10; $i++)
$chars = array_merge($chars, range(0, 9), range('A', 'Z'));
shuffle($chars);
$start = mt_rand(0, count($chars) - self::$nonce_length);
return substr(join('', $chars), $start, self::$nonce_length);
}
I duplicate 10 times the array[0-9,A-Z] and shuffle the elements, after I get a random start point for substr() to be more 'creative' :) you can add [a-z] and other elements to array, duplicate more or less, be more creative than me
A MySQL MyISAM table is the combination of three files:
You should be able to restore by copying them in your database folder (In linux, the default location is /var/lib/mysql/
)
You should do it while the server is not running.
You can give your canvas the ff CSS properties:
#myCanvas
{
display: block;
margin: 0 auto;
}
Use Notepad ++ and use the option to Convert the file to UNIX format. That should solve this problem.
you may also like this
var Grp = Model.GroupBy(item => item.Order.Customer)
.Select(group => new
{
Customer = Model.First().Customer,
CustomerId= group.Key,
Orders= group.ToList()
})
.ToList();
Old question but this is a rather simple task that can be solved properly with core JS... without the Class abstraction of ES6. In fact as far as i can tell, the Class abstraction do not even solve this problem.
We can do this job both with the good old constructor function or even better with Object.create()
. Lets go with the constructor first. This will essentially be a similar solution to georgebrock's answer which is criticised because all restaurants created by the Restaurant
constructor will have the same private methods. I will try to overcome that limitation.
function restaurantFactory(name,menu){
function Restaurant(name){
this.name = name;
}
function prototypeFactory(menu){
// This is a private function
function calculateBill(item){
return menu[item] || 0;
}
// This is the prototype to be
return { constructor: Restaurant
, askBill : function(...items){
var cost = items.reduce((total,item) => total + calculateBill(item) ,0)
return "Thank you for dining at " + this.name + ". Total is: " + cost + "\n"
}
, callWaiter : function(){
return "I have just called the waiter at " + this.name + "\n";
}
}
}
Restaurant.prototype = prototypeFactory(menu);
return new Restaurant(name,menu);
}
var menu = { water: 1
, coke : 2
, beer : 3
, beef : 15
, rice : 2
},
name = "Silver Scooop",
rest = restaurantFactory(name,menu);
console.log(rest.callWaiter());
console.log(rest.askBill("beer", "beef"));
_x000D_
Now obviously we can not access menu
from outside but we may easily rename the name
property of a restaurant.
This can also be done with Object.create()
in which case we skip the constructor function and simply do like var rest = Object.create(prototypeFactory(menu))
and add the name property to the rest
object afterwards like rest.name = name
.
I had a similar problem with the SP call returning an error that an expected parameter was not included. My code was as follows.
Stored Procedure:
@Result int OUTPUT
And C#:
SqlParameter result = cmd.Parameters.Add(new SqlParameter("@Result", DbType.Int32)); result.Direction = ParameterDirection.ReturnValue;
In troubleshooting, I realized that the stored procedure was ACTUALLY looking for a direction of "InputOutput" so the following change fixed the problem.
r
Result.Direction = ParameterDirection.InputOutput;
I would like to update on this, because in .NET Core multi-dimensional arrays are faster than jagged arrays. I ran the tests from John Leidegren and these are the results on .NET Core 2.0 preview 2. I increased the dimension value to make any possible influences from background apps less visible.
Debug (code optimalization disabled)
Running jagged
187.232 200.585 219.927 227.765 225.334 222.745 224.036 222.396 219.912 222.737
Running multi-dimensional
130.732 151.398 131.763 129.740 129.572 159.948 145.464 131.930 133.117 129.342
Running single-dimensional
91.153 145.657 111.974 96.436 100.015 97.640 94.581 139.658 108.326 92.931
Release (code optimalization enabled)
Running jagged
108.503 95.409 128.187 121.877 119.295 118.201 102.321 116.393 125.499 116.459
Running multi-dimensional
62.292 60.627 60.611 60.883 61.167 60.923 62.083 60.932 61.444 62.974
Running single-dimensional
34.974 33.901 34.088 34.659 34.064 34.735 34.919 34.694 35.006 34.796
I looked into disassemblies and this is what I found
jagged[i][j][k] = i * j * k;
needed 34 instructions to execute
multi[i, j, k] = i * j * k;
needed 11 instructions to execute
single[i * dim * dim + j * dim + k] = i * j * k;
needed 23 instructions to execute
I wasn't able to identify why single-dimensional arrays were still faster than multi-dimensional but my guess is that it has to do with some optimalization made on the CPU
Imagine that we have 3 buttons for example
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
Button button2 = (Button)findViewById(R.id.corky2);
Button button3 = (Button)findViewById(R.id.corky3);
// Register the onClick listener with the implementation above
button.setOnClickListener(mCorkyListener);
button2.setOnClickListener(mCorkyListener);
button3.setOnClickListener(mCorkyListener);
}
// Create an anonymous implementation of OnClickListener
private View.OnClickListener mCorkyListener = new View.OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
// Yes we will handle click here but which button clicked??? We don't know
}
};
}
So what we will do?
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
Button button2 = (Button)findViewById(R.id.corky2);
Button button3 = (Button)findViewById(R.id.corky3);
// Register the onClick listener with the implementation above
button.setOnClickListener(mCorkyListener);
button2.setOnClickListener(mCorkyListener);
button3.setOnClickListener(mCorkyListener);
}
// Create an anonymous implementation of OnClickListener
private View.OnClickListener mCorkyListener = new View.OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
// Yes we will handle click here but which button clicked??? We don't know
// So we will make
switch (v.getId() /*to get clicked view id**/) {
case R.id.corky:
// do something when the corky is clicked
break;
case R.id.corky2:
// do something when the corky2 is clicked
break;
case R.id.corky3:
// do something when the corky3 is clicked
break;
default:
break;
}
}
};
}
Or we can do this:
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
Button button2 = (Button)findViewById(R.id.corky2);
Button button3 = (Button)findViewById(R.id.corky3);
// Register the onClick listener with the implementation above
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something when the corky is clicked
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something when the corky2 is clicked
}
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something when the corky3 is clicked
}
});
}
}
Or we can implement View.OnClickListener and i think it's the best way:
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
Button button2 = (Button)findViewById(R.id.corky2);
Button button3 = (Button)findViewById(R.id.corky3);
// Register the onClick listener with the implementation above
button.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// do something when the button is clicked
// Yes we will handle click here but which button clicked??? We don't know
// So we will make
switch (v.getId() /*to get clicked view id**/) {
case R.id.corky:
// do something when the corky is clicked
break;
case R.id.corky2:
// do something when the corky2 is clicked
break;
case R.id.corky3:
// do something when the corky3 is clicked
break;
default:
break;
}
}
}
Finally there is no real differences here Just "Way better than the other"
Another deprecated (thanks to @daylight) option, and the easiest for me (this is what I'm using for SpokenToday.info):
The Google Feed API without using JQuery and with only 2 steps:
Import the library:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">google.load("feeds", "1");</script>
Find/Load feeds (documentation):
var feed = new google.feeds.Feed('http://www.google.com/trends/hottrends/atom/feed?pn=p1');
feed.load(function (data) {
// Parse data depending on the specified response format, default is JSON.
console.dir(data);
});
To parse data, check documentation about the response format.
What I found worked was checking the "Use the 64 bit version of IIS Express for Web Sites and Projects" option under the Projects and Solutions => Web Projects section under the Tools=>Options menu.
The nice thing about iterator is that later on if you wanted to switch your vector to a another STD container. Then the forloop will still work.
Why not add a variable for the element's Id and make it a reusable function?
function SelectElement(selectElementId, valueToSelect)
{
var element = document.getElementById(selectElementId);
element.value = valueToSelect;
}
I tried almost all the posted solutions and nothing worked for me. I use Mojave OS (10.14.6) and what finally worked for me (after removing and re-installing Xcode and CLTs and SDK headers):
CC=/usr/local/opt/llvm/bin/clang -fopenmp
CXX=/usr/local/opt/llvm/bin/clang++
with
CC=/usr/local/clang8/bin/clang -fopenmp
CXX=/usr/local/clang8/bin/clang++
Now R packages that rely on C compilers install successfully
While the template approach is clever for various reasons, it is important to remember the lifecycle of the lambda and the captured variables. If any form of a lambda pointer is is going to be used and the lambda is not a downward continuation, then only a copying [=] lambda should used. I.e., even then, capturing a pointer to a variable on the stack is UNSAFE if the lifetime of those captured pointers (stack unwind) is shorter than the lifetime of the lambda.
A simpler solution for capturing a lambda as a pointer is:
auto pLamdba = new std::function<...fn-sig...>([=](...fn-sig...){...});
e.g., new std::function<void()>([=]() -> void {...}
Just remember to later delete pLamdba
so ensure that you don't leak the lambda memory.
Secret to realize here is that lambdas can capture lambdas (ask yourself how that works) and also that in order for std::function
to work generically the lambda implementation needs to contain sufficient internal information to provide access to the size of the lambda (and captured) data (which is why the delete
should work [running destructors of captured types]).
I would do it this way:
try {
txtProt = (EditText) findViewById(R.id.Protein); // Same
p = txtProt.getText().toString(); // Same
protein = Double.parseDouble(p); // Make use of autoboxing. It's also easier to read.
} catch (NumberFormatException e) {
// p did not contain a valid double
}
EDIT: "the program force closes immediately without leaving any info in the logcat"
I don't know bout not leaving information in the logcat output, but a force-close generally means there's an uncaught exception - like a NumberFormatException.
Yes - according to the pandas.read_csv
documentation:
Note: A fast-path exists for iso8601-formatted dates.
So if your csv has a column named datetime
and the dates looks like 2013-01-01T01:01
for example, running this will make pandas (I'm on v0.19.2) pick up the date and time automatically:
df = pd.read_csv('test.csv', parse_dates=['datetime'])
Note that you need to explicitly pass parse_dates
, it doesn't work without.
Verify with:
df.dtypes
You should see the datatype of the column is datetime64[ns]
* "For example, say you'd declared a List at the beginning of a method which grew in size to be very large, but was only required until half-way through the method. You could at this point set the List reference to null to allow the garbage collector to potentially reclaim this object before the method completes (and the reference falls out of scope anyway)." *
This is correct, but this solution may not be generalizable. While setting a List object reference to null -will- make memory available for garbage collection, this is only true for a List object of primitive types. If the List object instead contains reference types, setting the List object = null will not dereference -any- of the reference types contained -in- the list. In this case, setting the List object = null will orphan the contained reference types whose objects will not be available for garbage collection unless the garbage collection algorithm is smart enough to determine that the objects have been orphaned.
Try to disable ModSecurity from your cPanel. Log into your cPanel. Find the category "Security". There you can find ModSecurity link.Click on it and disable it for the domain you are facing the 403 error.
Some 403 errors can be solved by this method too. Go to the wordpress dashboard, settings>permalink and just click save.
Hope this helped. :)
You are creating three lists, instead of using one (you don't use the return value of DirSearch(d)
). You can use a list as a parameter to save the state:
static void Main(string[] args)
{
var list = new List<string>();
DirSearch(list, ".");
foreach (var file in list)
{
Console.WriteLine(file);
}
}
public static void DirSearch(List<string> files, string startDirectory)
{
try
{
foreach (string file in Directory.GetFiles(startDirectory, "*.*"))
{
string extension = Path.GetExtension(file);
if (extension != null)
{
files.Add(file);
}
}
foreach (string directory in Directory.GetDirectories(startDirectory))
{
DirSearch(files, directory);
}
}
catch (System.Exception e)
{
Console.WriteLine(e.Message);
}
}
Try this folks, the cli needs to be updated to the latest version
npm install --save-dev @angular/cli@latest
credit goes go to R.Richards https://stackoverflow.com/a/44526528/1908827
select DateAdded, count(CustID)
from tbl
group by DateAdded
about 7-days interval it's DB-depending question
I found the solution to this. There is a temporary tablespace called TEMP which is used internally by database for operations like distinct, joins,etc. Since my query(which has 4 joins) fetches almost 50 million records the TEMP tablespace does not have that much space to occupy all data. Hence the query fails even though my tablespace has free space.So, after increasing the size of TEMP tablespace the issue was resolved. Hope this helps someone with the same issue. Thanks :)
There is a very easy way:
echo "your header" > headerFile.txt
cat yourFile >> headerFile.txt
You only return a value if the current element is a string
. Perhaps assigning an empty string otherwise will suffice:
var arr = ['a','b',1];
var results = arr.map(function(item){
return (typeof item ==='string') ? item : '';
});
Of course, if you want to filter any non-string elements, you shouldn't use map()
. Rather, you should look into using the filter()
function.
an existing folder will FAIL with FileExists
Function FileExists(strFileName)
' Check if a file exists - returns True or False
use instead or in addition:
Function FolderExists(strFolderPath)
' Check if a path exists
memcpy expects the first two arguments to be void*.
Try:
memcpy( (void*)&RTCclk, (void*)&RTCclkBuffert, sizeof(RTCclk) );
P.S. although not necessary, convention dictates the brackets for the sizeof operator. You can get away with a lot in C that leaves code impossible to maintain, so following convention is the mark of a good (employable) C programmer.
date +%s
This works fine for me on OS X Lion.
This should make life much easier. You can simply use Response.RedirectWithData(...) method in your web application easily.
Imports System.Web
Imports System.Runtime.CompilerServices
Module WebExtensions
<Extension()> _
Public Sub RedirectWithData(ByRef aThis As HttpResponse, ByVal aDestination As String, _
ByVal aData As NameValueCollection)
aThis.Clear()
Dim sb As StringBuilder = New StringBuilder()
sb.Append("<html>")
sb.AppendFormat("<body onload='document.forms[""form""].submit()'>")
sb.AppendFormat("<form name='form' action='{0}' method='post'>", aDestination)
For Each key As String In aData
sb.AppendFormat("<input type='hidden' name='{0}' value='{1}' />", key, aData(key))
Next
sb.Append("</form>")
sb.Append("</body>")
sb.Append("</html>")
aThis.Write(sb.ToString())
aThis.End()
End Sub
End Module
.html
<form [formGroup]="contactForm">
<button [disabled]="contactForm.invalid" (click)="onSubmit()">SEND</button>
.ts
contactForm: FormGroup;
I think using script command might help. Something like,
script -c bash -qf fifo_pid
Using bash features to set after parsing.
Look at the traceback:
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
out = iter(out)
TypeError: 'bool' object is not iterable
Your code isn't iterating the value, but the code receiving it is.
The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)
) or enclose it in a tuple ((False,)
).
Always read the traceback: it's correct, and it's helpful.
edit: Reading the faq a bit longer I like the idea of the << >> operator overloading and adding as a friend of those classes, however I am not sure how this doesn't break encapsulation
How would it break encapsulation?
You break encapsulation when you allow unrestricted access to a data member. Consider the following classes:
class c1 {
public:
int x;
};
class c2 {
public:
int foo();
private:
int x;
};
class c3 {
friend int foo();
private:
int x;
};
c1
is obviously not encapsulated. Anyone can read and modify x
in it. We have no way to enforce any kind of access control.
c2
is obviously encapsulated. There is no public access to x
. All you can do is call the foo
function, which performs some meaningful operation on the class.
c3
? Is that less encapsulated? Does it allow unrestricted access to x
? Does it allow unknown functions access?
No. It allows precisely one function to access the private members of the class. Just like c2
did. And just like c2
, the one function which has access is not "some random, unknown function", but "the function listed in the class definition". Just like c2
, we can see, just by looking at the class definitions, a complete list of who has access.
So how exactly is this less encapsulated? The same amount of code has access to the private members of the class. And everyone who has access is listed in the class definition.
friend
does not break encapsulation. It makes some Java people programmers feel uncomfortable, because when they say "OOP", they actually mean "Java". When they say "Encapsulation", they don't mean "private members must be protected from arbitrary accesses", but "a Java class where the only functions able to access private members, are class members", even though this is complete nonsense for several reasons.
First, as already shown, it is too restricting. There's no reason why friend methods shouldn't be allowed to do the same.
Second, it is not restrictive enough. Consider a fourth class:
class c4 {
public:
int getx();
void setx(int x);
private:
int x;
};
This, according to aforesaid Java mentality, is perfectly encapsulated. And yet, it allows absolutely anyone to read and modify x. How does that even make sense? (hint: It doesn't)
Bottom line: Encapsulation is about being able to control which functions can access private members. It is not about precisely where the definitions of these functions are located.