The error code 0x800A03EC
(or -2146827284) means NAME_NOT_FOUND; in other words, you've asked for something, and Excel can't find it.
This is a generic code, which can apply to lots of things it can't find e.g. using properties which aren't valid at that time like PivotItem.SourceNameStandard
throws this when a PivotItem doesn't have a filter applied. Worksheets["BLAHBLAH"]
throws this, when the sheet doesn't exist etc. In general, you are asking for something with a specific name and it doesn't exist. As for why, that will taking some digging on your part.
Check your sheet definitely does have the Range you are asking for, or that the .CellName
is definitely giving back the name of the range you are asking for.
Char is a little bit faster, so if you have a column that you KNOW will be a certain length, use char. For example, storing (M)ale/(F)emale/(U)nknown for gender, or 2 characters for a US state.
A more generic approach
To simplify this approach an "id" interface is used
public interface IGuidKey
{
Guid Id { get; set; }
}
The helper method
public static void Modify<T>(this DbSet<T> set, Guid id, Action<T> func)
where T : class, IGuidKey, new()
{
var target = new T
{
Id = id
};
var entry = set.Attach(target);
func(target);
foreach (var property in entry.Properties)
{
var original = property.OriginalValue;
var current = property.CurrentValue;
if (ReferenceEquals(original, current))
{
continue;
}
if (original == null)
{
property.IsModified = true;
continue;
}
var propertyIsModified = !original.Equals(current);
property.IsModified = propertyIsModified;
}
}
Usage
dbContext.Operations.Modify(id, x => { x.Title = "aaa"; });
The main goal of AllowOverride
is for the manager of main configuration files of apache (the one found in /etc/apache2/ mainly) to decide which part of the configuration may be dynamically altered on a per-path basis by applications.
If you are not the administrator of the server, you depend on the AllowOverride Level that theses admins allows for you. So that they can prevent you to alter some important security settings;
If you are the master apache configuration manager you should always use AllowOverride None
and transfer all google_based example you find, based on .htaccess files to Directory
sections on the main configuration files. As a .htaccess content for a .htaccess
file in /my/path/to/a/directory
is the same as a <Directory /my/path/to/a/directory>
instruction, except that the .htaccess
dynamic per-HTTP-request configuration alteration is something slowing down your web server. Always prefer a static configuration without .htaccess
checks (and you will also avoid security attacks by .htaccess
alterations).
By the way in your example you use <Directory>
and this will always be wrong, Directory instructions are always containing a path, like <Directory />
or <Directory C:>
or <Directory /my/path/to/a/directory>
. And of course this cannot be put in a .htaccess
as a .htaccess
is like a Directory instruction but in a file present in this directory. Of course you cannot alter AllowOverride
in a .htaccess
as this instruction is managing the security level of .htaccess
files.
My simple way:
function Timer (callback, delay) {
let callbackStartTime
let remaining = 0
this.timerId = null
this.paused = false
this.pause = () => {
this.clear()
remaining -= Date.now() - callbackStartTime
this.paused = true
}
this.resume = () => {
window.setTimeout(this.setTimeout.bind(this), remaining)
this.paused = false
}
this.setTimeout = () => {
this.clear()
this.timerId = window.setInterval(() => {
callbackStartTime = Date.now()
callback()
}, delay)
}
this.clear = () => {
window.clearInterval(this.timerId)
}
this.setTimeout()
}
How to use:
let seconds = 0_x000D_
const timer = new Timer(() => {_x000D_
seconds++_x000D_
_x000D_
console.log('seconds', seconds)_x000D_
_x000D_
if (seconds === 8) {_x000D_
timer.clear()_x000D_
_x000D_
alert('Game over!')_x000D_
}_x000D_
}, 1000)_x000D_
_x000D_
timer.pause()_x000D_
console.log('isPaused: ', timer.paused)_x000D_
_x000D_
setTimeout(() => {_x000D_
timer.resume()_x000D_
console.log('isPaused: ', timer.paused)_x000D_
}, 2500)_x000D_
_x000D_
_x000D_
function Timer (callback, delay) {_x000D_
let callbackStartTime_x000D_
let remaining = 0_x000D_
_x000D_
this.timerId = null_x000D_
this.paused = false_x000D_
_x000D_
this.pause = () => {_x000D_
this.clear()_x000D_
remaining -= Date.now() - callbackStartTime_x000D_
this.paused = true_x000D_
}_x000D_
this.resume = () => {_x000D_
window.setTimeout(this.setTimeout.bind(this), remaining)_x000D_
this.paused = false_x000D_
}_x000D_
this.setTimeout = () => {_x000D_
this.clear()_x000D_
this.timerId = window.setInterval(() => {_x000D_
callbackStartTime = Date.now()_x000D_
callback()_x000D_
}, delay)_x000D_
}_x000D_
this.clear = () => {_x000D_
window.clearInterval(this.timerId)_x000D_
}_x000D_
_x000D_
this.setTimeout()_x000D_
}
_x000D_
The code is written quickly and did not refactored, raise the rating of my answer if you want me to improve the code and give ES2015 version (classes).
Solution 1 is not great. It does work, but adding hacky random or timestamped query strings to the end of your image files will make the browser re-download and cache every version of every image, every time a page is loaded, regardless of weather the image has changed or not on the server.
Solution 2 is useless. Adding nocache
headers to an image file is not only very difficult to implement, but it's completely impractical because it requires you to predict when it will be needed in advance, the first time you load any image which you think might change at some point in the future.
The absolute best way I've found to solve this is to use ETAGS inside a .htaccess file in your images directory. The following tells Apache to send a unique hash to the browser in the image file headers. This hash only ever changes when time the image file is modified and this change triggers the browser to reload the image the next time it is requested.
<FilesMatch "\.(jpg|jpeg)$">
FileETag MTime Size
</FilesMatch>
What about the mighty IntHolder? I just love any package with omg in the name!
import org.omg.CORBA.IntHolder;
IntHolder a = new IntHolder(p);
IntHolder b = new IntHolder(q);
swap(a, b);
p = a.value;
q = b.value;
void swap(IntHolder a, IntHolder b) {
int temp = a.value;
a.value = b.value;
b.value = temp;
}
<form (submit)="addTodo()">_x000D_
<input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
Use the slicing operator:
list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
list[:10]
Your classes should look like this
[XmlRoot("StepList")]
public class StepList
{
[XmlElement("Step")]
public List<Step> Steps { get; set; }
}
public class Step
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Desc")]
public string Desc { get; set; }
}
Here is my testcode.
string testData = @"<StepList>
<Step>
<Name>Name1</Name>
<Desc>Desc1</Desc>
</Step>
<Step>
<Name>Name2</Name>
<Desc>Desc2</Desc>
</Step>
</StepList>";
XmlSerializer serializer = new XmlSerializer(typeof(StepList));
using (TextReader reader = new StringReader(testData))
{
StepList result = (StepList) serializer.Deserialize(reader);
}
If you want to read a text file you should load the file into a FileStream and deserialize this.
using (FileStream fileStream = new FileStream("<PathToYourFile>", FileMode.Open))
{
StepList result = (StepList) serializer.Deserialize(fileStream);
}
If you're using scikit-learn you can use sklearn.preprocessing.normalize
:
import numpy as np
from sklearn.preprocessing import normalize
x = np.random.rand(1000)*10
norm1 = x / np.linalg.norm(x)
norm2 = normalize(x[:,np.newaxis], axis=0).ravel()
print np.all(norm1 == norm2)
# True
Just enter plt.hold(False)
before the first plt.plot, and you can stick to your original code.
I think that you can make some changes in your data format when you create dictionary, then you can easily convert it to DataFrame:
input:
a={'Dates':['2012-06-08','2012-06-10'],'Date_value':[388,389]}
output:
{'Date_value': [388, 389], 'Dates': ['2012-06-08', '2012-06-10']}
input:
aframe=DataFrame(a)
output: will be your DataFrame
You just need to use some text editing in somewhere like Sublime or maybe Excel.
For people using MacOS:
If you received a file with Windows format and wanted to run on MacOS and seeing this error, run these commands.
brew install dos2unix
sh <file.sh>
Starting in iOS 6, you can use
-tableView:shouldHighlightRowAtIndexPath:
If you return NO
, it disables both the selection highlighting and the storyboard triggered segues connected to that cell.
The method is called when a touch comes down on a row. Returning NO
to that message halts the selection process and does not cause the currently selected row to lose its selected look while the touch is down.
System.err.println("Someone is Restarting me...");
setVisible(false);
try {
Thread.sleep(600);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
setVisible(true);
I guess you don't really want to stop the application, but to "Restart" it. For that, you could use this and add your "Reset" before the sleep and after the invisible window.
Perhaps use information_schema:
SELECT EXISTS(
SELECT *
FROM information_schema.tables
WHERE
table_schema = 'company3' AND
table_name = 'tableincompany3schema'
);
Actually... filter_var($url, FILTER_VALIDATE_URL); doesn't work very well. When you type in a real url, it works but, it only checks for http:// so if you type something like "http://weirtgcyaurbatc", it will still say it's real.
NSString *stringWithoutAsterisk(NSString *string) {
NSRange asterisk = [string rangeOfString:@"*"];
return asterisk.location == 0 ? [string substringFromIndex:1] : string;
}
Use the php's OR (||)
logical operator for php isset()
with multiple operator
e.g
if (isset($_POST['room']) || ($_POST['cottage']) || ($_POST['villa'])) {
}
It depends on your OS, but if you are on Windows XP, you need to go to Systems Properties, then Advanced, then Environment Variables, and include the php binary path to the %PATH% variable.
Locate it by browsing your WAMP directory. It's called php.exe
Your HTML and the way you call the function from the button look correct.
The problem appears to be in the CapacityCount
function. I'm getting this error in my console on Firefox 3.5: "document.all is undefined" on line 759 of bendelcorp.js.
Edit:
Looks like document.all
is an IE-only thing and is a nonstandard way of accessing the DOM. If you use document.getElementById()
, it should probably work. Example: document.getElementById("RUnits").value
instead of document.all.Capacity.RUnits.value
Simple function for removing duplicates from list
private void removeDuplicates(List<?> list)
{
int count = list.size();
for (int i = 0; i < count; i++)
{
for (int j = i + 1; j < count; j++)
{
if (list.get(i).equals(list.get(j)))
{
list.remove(j--);
count--;
}
}
}
}
Example:
Input: [1, 2, 2, 3, 1, 3, 3, 2, 3, 1, 2, 3, 3, 4, 4, 4, 1]
Output: [1, 2, 3, 4]
$(info your_text)
: Information. This doesn't stop the execution.
$(warning your_text)
: Warning. This shows the text as a warning.
$(error your_text)
: Fatal Error. This will stop the execution.
As per this link you may also have to prefix your param with &rp if not using proxy syntax
It is simple. The first thing that you have to understand the design of the Python interpreter. It doesn't allocate memory for all the variables basically if any two or more variable has the same value it just map to that value.
let's go to the code example,
In [6]: a = 10
In [7]: id(a)
Out[7]: 10914656
In [8]: b = 10
In [9]: id(b)
Out[9]: 10914656
In [10]: c = 11
In [11]: id(c)
Out[11]: 10914688
In [12]: d = 21
In [13]: id(d)
Out[13]: 10915008
In [14]: e = 11
In [15]: id(e)
Out[15]: 10914688
In [16]: e = 21
In [17]: id(e)
Out[17]: 10915008
In [18]: e is d
Out[18]: True
In [19]: e = 30
In [20]: id(e)
Out[20]: 10915296
From the above output, variables a and b shares the same memory, c and d has different memory when I create a new variable e and store a value (11) which is already present in the variable c so it mapped to that memory location and doesn't create a new memory when I change the value present in the variable e to 21 which is already present in the variable d so now variables d and e share the same memory location. At last, I change the value in the variable e to 30 which is not stored in any other variable so it creates a new memory for e.
so any variable which is having same value shares the memory.
Not for list and dictionary objects
let's come to your question.
when multiple keys have same value then all shares same memory so the thing that you expect is already there in python.
you can simply use it like this
In [49]: dictionary = {
...: 'k1':1,
...: 'k2':1,
...: 'k3':2,
...: 'k4':2}
...:
...:
In [50]: id(dictionary['k1'])
Out[50]: 10914368
In [51]: id(dictionary['k2'])
Out[51]: 10914368
In [52]: id(dictionary['k3'])
Out[52]: 10914400
In [53]: id(dictionary['k4'])
Out[53]: 10914400
From the above output, the key k1 and k2 mapped to the same address which means value one stored only once in the memory which is multiple key single value dictionary this is the thing you want. :P
total edge case here: I had this issue installing an Arch AUR PKGBUILD file manually. In my case I needed to delete the 'pkg', 'src' and 'node_modules' folders, then it built fine without this npm error.
Aditya,
As you said in your last comment that you are trying to access chrome of some other system so based on that you should keep your chrome driver in that system itself.
for example: if you are trying to access linux chrome from windows then you need to put your chrome driver in linux at some place and give permission as 777 and use below code at your windows system.
System.setProperty("webdriver.chrome.driver", "\\var\\www\\Jar\\chromedriver");
Capability= DesiredCapabilities.chrome(); Capability.setPlatform(org.openqa.selenium.Platform.ANY);
browser=new RemoteWebDriver(new URL(nodeURL),Capability);
This is working code of my system.
string query = "SELECT column_name FROM table_name"; //query the database
SqlCommand queryStatus = new SqlCommand(query, myConnection);
sqlDataReader reader = queryStatus.ExecuteReader();
while (reader.Read()) //loop reader and fill the combobox
{
ComboBox1.Items.Add(reader["column_name"].ToString());
}
As name suggest here memory buffer used to manage how the output of script appears.
Here is one very good tutorial for the topic
Try:
text-align: center;
You may be familiar with the HTML align attribute (which has been discontinued as of HTML 5). The align attribute could be used with tags such as
<table>, <td>, and <img>
to specify the alignment of these elements. This attribute allowed you to align elements horizontally. HTML also has/had a valign attribute for aligning elements vertically. This has also been discontinued from HTML5.
These attributes were discontinued in favor of using CSS to set the alignment of HTML elements.
There isn't actually a CSS align or CSS valign property. Instead, CSS has the text-align which applies to inline content of block-level elements, and vertical-align property which applies to inline level and table cells.
Best way to export database using php script.
Or add 5th parameter(array) of specific tables: array("mytable1","mytable2","mytable3")
for multiple tables
<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlUserName = "Your Username";
$mysqlPassword = "Your Password";
$mysqlHostName = "Your Host";
$DbName = "Your Database Name here";
$backup_name = "mybackup.sql";
$tables = "Your tables";
//or add 5th parameter(array) of specific tables: array("mytable1","mytable2","mytable3") for multiple tables
Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName, $tables=false, $backup_name=false );
function Export_Database($host,$user,$pass,$name, $tables=false, $backup_name=false )
{
$mysqli = new mysqli($host,$user,$pass,$name);
$mysqli->select_db($name);
$mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES');
while($row = $queryTables->fetch_row())
{
$target_tables[] = $row[0];
}
if($tables !== false)
{
$target_tables = array_intersect( $target_tables, $tables);
}
foreach($target_tables as $table)
{
$result = $mysqli->query('SELECT * FROM '.$table);
$fields_amount = $result->field_count;
$rows_num=$mysqli->affected_rows;
$res = $mysqli->query('SHOW CREATE TABLE '.$table);
$TableMLine = $res->fetch_row();
$content = (!isset($content) ? '' : $content) . "\n\n".$TableMLine[1].";\n\n";
for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter=0)
{
while($row = $result->fetch_row())
{ //when started (and every after 100 command cycle):
if ($st_counter%100 == 0 || $st_counter == 0 )
{
$content .= "\nINSERT INTO ".$table." VALUES";
}
$content .= "\n(";
for($j=0; $j<$fields_amount; $j++)
{
$row[$j] = str_replace("\n","\\n", addslashes($row[$j]) );
if (isset($row[$j]))
{
$content .= '"'.$row[$j].'"' ;
}
else
{
$content .= '""';
}
if ($j<($fields_amount-1))
{
$content.= ',';
}
}
$content .=")";
//every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num)
{
$content .= ";";
}
else
{
$content .= ",";
}
$st_counter=$st_counter+1;
}
} $content .="\n\n\n";
}
//$backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";
$backup_name = $backup_name ? $backup_name : $name.".sql";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$backup_name."\"");
echo $content; exit;
}
?>
OS X
If you are using Vim in Mac OS X, unfortunately it comes with older version, and not complied with clipboard options. Luckily, Homebrew can easily solve this problem.
Install Vim:
brew install vim --with-lua --with-override-system-vi
Install the GUI version of Vim:
brew install macvim --with-lua --with-override-system-vi
Restart the terminal for it to take effect.
Append the following line to ~/.vimrc
set clipboard=unnamed
Now you can copy the line in Vim with yy
and paste it system-wide.
You can use a function like this. Complete and modify it to your need :
/**
* Encode URL (except :, /, ?, &, =, ... characters)
* @param url to encode
* @param encodingCharset url encoding charset
* @return encoded URL
* @throws UnsupportedEncodingException
*/
public static String encodeUrl (String url, String encodingCharset) throws UnsupportedEncodingException{
return new URLCodec().encode(url, encodingCharset).replace("%3A", ":").replace("%2F", "/").replace("%3F", "?").replace("%3D", "=").replace("%26", "&");
}
Example of use :
String urlToEncode = ""http://www.growup.com/folder/intérieur-à_vendre?o=4";
Utils.encodeUrl (urlToEncode , "UTF-8")
The result is : http://www.growup.com/folder/int%C3%A9rieur-%C3%A0_vendre?o=4
As previously mentioned, this issue can be seen if you have multiple files with the same name, but in different groups (yellow folders) in the project navigator. In my case, this was intentional as I had multiple subdirectories each with a "preview.jpg" that I wanted copying to the app bundle:
In this situation, you need to ensure that Xcode recognises the directory reference (blue folder icon), not just the groups.
Remove the offending files and choose "Remove Reference" (so we don't delete them entirely):
Re-add them to the project by dragging them back into the project navigator. In the dialog that appears, choose "Create folder references for any added folders":
Notice that the files now have a blue folder icon in the project navigator:
If you now look under the "Copy Bundle Resources" section of the target's build phases, you will notice that there is a single entry for the entire folder, rather than entries for each item contained within the directory. The compiler will not complain about multiple build commands for those files.
Use these properties in ImageView to keep aspect ratio:
android:adjustViewBounds="true"
android:scaleType="fitXY"
About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :
Basically, flatMap
is the equivalent of Promise.then
.
For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay
operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)
buildScript {
...
dependencies {
...
classpath 'com.android.tools.build:gradle:4.0.0-rc01'
}
}
...
distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip
Some libraries require the updated gradle. Such as:
androidTestImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutines"
GL
To take first 5 elements better use expression like this one:
var firstFiveArrivals = myList.Where([EXPRESSION]).Take(5);
or
var firstFiveArrivals = myList.Where([EXPRESSION]).Take(5).OrderBy([ORDER EXPR]);
It will be faster than orderBy variant, because LINQ engine will not scan trough all list due to delayed execution, and will not sort all array.
class MyList : IEnumerable<int>
{
int maxCount = 0;
public int RequestCount
{
get;
private set;
}
public MyList(int maxCount)
{
this.maxCount = maxCount;
}
public void Reset()
{
RequestCount = 0;
}
#region IEnumerable<int> Members
public IEnumerator<int> GetEnumerator()
{
int i = 0;
while (i < maxCount)
{
RequestCount++;
yield return i++;
}
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
#endregion
}
class Program
{
static void Main(string[] args)
{
var list = new MyList(15);
list.Take(5).ToArray();
Console.WriteLine(list.RequestCount); // 5;
list.Reset();
list.OrderBy(q => q).Take(5).ToArray();
Console.WriteLine(list.RequestCount); // 15;
list.Reset();
list.Where(q => (q & 1) == 0).Take(5).ToArray();
Console.WriteLine(list.RequestCount); // 9; (first 5 odd)
list.Reset();
list.Where(q => (q & 1) == 0).Take(5).OrderBy(q => q).ToArray();
Console.WriteLine(list.RequestCount); // 9; (first 5 odd)
}
}
what about
public class CmdExec {
public static Scanner s = null;
public static void main(String[] args) throws InterruptedException, IOException {
s = new Scanner(System.in);
System.out.print("$ ");
String cmd = s.nextLine();
final Process p = Runtime.getRuntime().exec(cmd);
new Thread(new Runnable() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ((line = input.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
p.waitFor();
}
}
It uses the slice
method arrays have and calls it with its this
being the arguments
object. This means it calls it as if you did arguments.slice()
assuming arguments
had such a method.
Creating a slice without any arguments will simply take all elements - so it simply copies the elements from arguments
to an array.
My way of Insert
in SQL Server. Also I usually check if a temporary table exists.
IF OBJECT_ID('tempdb..#MyTable') IS NOT NULL DROP Table #MyTable
SELECT b.Val as 'bVals'
INTO #MyTable
FROM OtherTable as b
update-java-alternatives
The java
executable is not found with your JAVA_HOME
, it only depends on your PATH
.
update-java-alternatives
is a good way to manage it for the entire system is through:
update-java-alternatives -l
Sample output:
java-7-oracle 1 /usr/lib/jvm/java-7-oracle
java-8-oracle 2 /usr/lib/jvm/java-8-oracle
Choose one of the alternatives:
sudo update-java-alternatives -s java-7-oracle
Like update-alternatives
, it works through symlink management. The advantage is that is manages symlinks to all the Java utilities at once: javac
, java
, javap
, etc.
I am yet to see a JAVA_HOME
effect on the JDK. So far, I have only seen it used in third-party tools, e.g. Maven.
I am new in Swift 3, but looking the String
(index) syntax for analogy I think that index is like a "pointer" constrained to string and Int can help as an independent object. Using the base + offset syntax , then we can get the i-th character from string with the code bellow:
let s = "abcdefghi"
let i = 2
print (s[s.index(s.startIndex, offsetBy:i)])
// print c
For a range of characters ( indexes) from string using String (range) syntax we can get from i-th to f-th characters with the code bellow:
let f = 6
print (s[s.index(s.startIndex, offsetBy:i )..<s.index(s.startIndex, offsetBy:f+1 )])
//print cdefg
For a substring (range) from a string using String.substring (range) we can get the substring using the code bellow:
print (s.substring (with:s.index(s.startIndex, offsetBy:i )..<s.index(s.startIndex, offsetBy:f+1 ) ) )
//print cdefg
Notes:
The i-th and f-th begin with 0.
To f-th, I use offsetBY: f + 1, because the range of subscription use ..< (half-open operator), not include the f-th position.
Of course must include validate errors like invalid index.
Here's an extension method for converting a Bitmap to BitmapImage.
public static BitmapImage ToBitmapImage(this Bitmap bitmap)
{
using (var memory = new MemoryStream())
{
bitmap.Save(memory, ImageFormat.Png);
memory.Position = 0;
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze();
return bitmapImage;
}
}
Pandas is based on NumPy arrays. The key to speed with NumPy arrays is to perform your operations on the whole array at once, never row-by-row or item-by-item.
For example, if close
is a 1-d array, and you want the day-over-day percent change,
pct_change = close[1:]/close[:-1]
This computes the entire array of percent changes as one statement, instead of
pct_change = []
for row in close:
pct_change.append(...)
So try to avoid the Python loop for i, row in enumerate(...)
entirely, and
think about how to perform your calculations with operations on the entire array (or dataframe) as a whole, rather than row-by-row.
I know this is an ancient question, but I just thought that I'd weigh in.
I'm using disableScroll. Simple and it works like in a dream.
I have had some trouble disabling scroll on body, but allowing it on child elements (like a modal or a sidebar). It looks like that something can be done using disableScroll.on([element], [options]);
, but I haven't gotten that to work just yet.
The reason that this is prefered compared to overflow: hidden;
on body is that the overflow-hidden can get nasty, since some things might add overflow: hidden;
like this:
... This is good for preloaders and such, since that is rendered before the CSS is finished loading.
But it gives problems, when an open navigation should add a class to the body
-tag (like <body class="body__nav-open">
). And then it turns into one big tug-of-war with overflow: hidden; !important
and all kinds of crap.
Covert .ppk to id_rsa using tool PuttyGen, (http://mydailyfindingsit.blogspot.in/2015/08/create-keys-for-your-linux-machine.html) and
scp -C -i ./id_rsa -r /var/www/* [email protected]:/var/www
it should work !
Study up on multidimensional arrays. This question might help.
You can raise a notice in Postgres
as follows:
raise notice 'Value: %', deletedContactId;
Read here
import networkx as nx
import matplotlib.pyplot as plt
g = nx.DiGraph()
g.add_nodes_from([1,2,3,4,5])
g.add_edge(1,2)
g.add_edge(4,2)
g.add_edge(3,5)
g.add_edge(2,3)
g.add_edge(5,4)
nx.draw(g,with_labels=True)
plt.draw()
plt.show()
This is just simple how to draw directed graph using python 3.x using networkx. just simple representation and can be modified and colored etc. See the generated graph here.
Note: It's just a simple representation. Weighted Edges could be added like
g.add_edges_from([(1,2),(2,5)], weight=2)
and hence plotted again.
=>Create a new table directly with the following query:
CREATE TABLE table_name (Column_1 TEXT,Column_2 TEXT);
=>Now insert the data into table_name from existing_table with the following query:
INSERT INTO table_name (Column_1,Column_2) FROM existing_table;
=>Now drop the existing_table by following query:
DROP TABLE existing_table;
If you did a new or clean install of OS X version 10.3 or more recent, the default user terminal shell is bash.
Bash is essentially an enhanced and GNU freeware version of the original Bourne shell, sh. If you have previous experience with bash (often the default on GNU/Linux installations), this makes the OS X command-line experience familiar, otherwise consider switching your shell either to tcsh or to zsh, as some find these more user-friendly.
If you upgraded from or use OS X version 10.2.x, 10.1.x or 10.0.x, the default user shell is tcsh, an enhanced version of csh('c-shell'). Early implementations were a bit buggy and the programming syntax a bit weird so it developed a bad rap.
There are still some fundamental differences between mac and linux as Gordon Davisson so aptly lists, for example no useradd
on Mac and ifconfig
works differently.
The following table is useful for knowing the various unix shells.
sh The original Bourne shell Present on every unix system
ksh Original Korn shell Richer shell programming environment than sh
csh Original C-shell C-like syntax; early versions buggy
tcsh Enhanced C-shell User-friendly and less buggy csh implementation
bash GNU Bourne-again shell Enhanced and free sh implementation
zsh Z shell Enhanced, user-friendly ksh-like shell
You may also find these guides helpful:
http://homepage.mac.com/rgriff/files/TerminalBasics.pdf
http://guides.macrumors.com/Terminal
http://www.ofb.biz/safari/article/476.html
On a final note, I am on Linux (Ubuntu 11) and Mac osX so I use bash and the thing I like the most is customizing the .bashrc (source'd from .bash_profile
on OSX) file with aliases, some examples below.
I now placed all my aliases in a separate .bash_aliases file and include it with:
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
in the .bashrc or .bash_profile file.
Note that this is an example of a mac-linux difference because on a Mac you can't have the --color=auto
. The first time I did this (without knowing) I redefined ls
to be invalid which was a bit alarming until I removed --auto-color
!
You may also find https://unix.stackexchange.com/q/127799/10043 useful
# ~/.bash_aliases
# ls variants
#alias l='ls -CF'
alias la='ls -A'
alias l='ls -alFtr'
alias lsd='ls -d .*'
# Various
alias h='history | tail'
alias hg='history | grep'
alias mv='mv -i'
alias zap='rm -i'
# One letter quickies:
alias p='pwd'
alias x='exit'
alias {ack,ak}='ack-grep'
# Directories
alias s='cd ..'
alias play='cd ~/play/'
# Rails
alias src='script/rails console'
alias srs='script/rails server'
alias raked='rake db:drop db:create db:migrate db:seed'
alias rvm-restart='source '\''/home/durrantm/.rvm/scripts/rvm'\'''
alias rrg='rake routes | grep '
alias rspecd='rspec --drb '
#
# DropBox - syncd
WORKBASE="~/Dropbox/97_2012/work"
alias work="cd $WORKBASE"
alias code="cd $WORKBASE/ror/code"
#
# DropNot - NOT syncd !
WORKBASE_GIT="~/Dropnot"
alias {dropnot,not}="cd $WORKBASE_GIT"
alias {webs,ww}="cd $WORKBASE_GIT/webs"
alias {setups,docs}="cd $WORKBASE_GIT/setups_and_docs"
alias {linker,lnk}="cd $WORKBASE_GIT/webs/rails_v3/linker"
#
# git
alias {gsta,gst}='git status'
# Warning: gst conflicts with gnu-smalltalk (when used).
alias {gbra,gb}='git branch'
alias {gco,go}='git checkout'
alias {gcob,gob}='git checkout -b '
alias {gadd,ga}='git add '
alias {gcom,gc}='git commit'
alias {gpul,gl}='git pull '
alias {gpus,gh}='git push '
alias glom='git pull origin master'
alias ghom='git push origin master'
alias gg='git grep '
#
# vim
alias v='vim'
#
# tmux
alias {ton,tn}='tmux set -g mode-mouse on'
alias {tof,tf}='tmux set -g mode-mouse off'
#
# dmc
alias {dmc,dm}='cd ~/Dropnot/webs/rails_v3/dmc/'
alias wf='cd ~/Dropnot/webs/rails_v3/dmc/dmWorkflow'
alias ws='cd ~/Dropnot/webs/rails_v3/dmc/dmStaffing'
It looks like the ~ gives the functionality that I need, but I am yet to find any appropriate documentation on it.
df.filter(~col('bar').isin(['a','b'])).show()
+---+---+
| id|bar|
+---+---+
| 4| c|
| 5| d|
+---+---+
I like to use views over stored procedures when I am only running a query. Views can also simplify security, can be used to ease inserts/updates to multiple tables, and can be used to snapshot/materialize data (run a long-running query, and keep the results cached).
I've used materialized views for run longing queries that are not required to be kept accurate in real time.
SELECT *
FROM
(
SELECT rownum rn, empno, ename
FROM emp
) temp
WHERE MOD(temp.rn,2) = 1
Add a shortcut:
$.Shortcuts.add({
type: 'down',
mask: 'Ctrl+A',
handler: function() {
debug('Ctrl+A');
}
});
Start reacting to shortcuts:
$.Shortcuts.start();
Add a shortcut to “another” list:
$.Shortcuts.add({
type: 'hold',
mask: 'Shift+Up',
handler: function() {
debug('Shift+Up');
},
list: 'another'
});
Activate “another” list:
$.Shortcuts.start('another');
Remove a shortcut:
$.Shortcuts.remove({
type: 'hold',
mask: 'Shift+Up',
list: 'another'
});
Stop (unbind event handlers):
$.Shortcuts.stop();
Months in Calendar object start from 0
0 = January = Calendar.JANUARY
1 = february = Calendar.FEBRUARY
Here is the script that I use often. Run it as $ source script_name
#!/bin/bash -x
PWD=`pwd`
/usr/local/bin/virtualenv --python=python3 venv
echo $PWD
activate () {
. $PWD/venv/bin/activate
}
activate
Please take a look at this example here. It is a simple example of a count up! Which I think you could easily modify to create a count down.
http://jsfiddle.net/ganarajpr/LQGE2/
function AlbumCtrl($scope,$timeout) {
$scope.counter = 0;
$scope.onTimeout = function(){
$scope.counter++;
mytimeout = $timeout($scope.onTimeout,1000);
}
var mytimeout = $timeout($scope.onTimeout,1000);
$scope.stop = function(){
$timeout.cancel(mytimeout);
}
}
<!doctype html>
<html ng-app>
<head>
<script src="http://code.angularjs.org/angular-1.0.0rc11.min.js"></script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
</head>
<body>
<div ng-controller="AlbumCtrl">
{{counter}}
<button ng-click="stop()">Stop</button>
</div>
</body>
</html>
It looks that 3.15 offers no satisfying solution: either one uses the old style with Cell.CELL_TYPE_*, or we use the method getCellTypeEnum() which is marked as deprecated. A lot of disturbances for little add value...
It’s just HTML with Server Side Includes.
You can either use:
<button onclick="window.history.back()">Back</button>
or..
<button onclick="window.history.go(-1)">Back</button>
The difference, of course, is back()
only goes back 1 page but go()
goes back/forward the number of pages you pass as a parameter, relative to your current page.
You use it like this to redirect on a particular URL and render component after redirecting from old-router to new-router.
<Route path="/old-router">
<Redirect exact to="/new-router"/>
<Route path="/new-router" component={NewRouterType}/>
</Route>
I'm using these classes to alter top margin:
.margin-top-05 { margin-top: 0.5em; }
.margin-top-10 { margin-top: 1.0em; }
.margin-top-15 { margin-top: 1.5em; }
.margin-top-20 { margin-top: 2.0em; }
.margin-top-25 { margin-top: 2.5em; }
.margin-top-30 { margin-top: 3.0em; }
When I need an element to have 2em spacing from the element above I use it like this:
<div class="row margin-top-20">Something here</div>
If you prefere pixels so change the em to px to have it your way.
Here I post a simple way of solution
CREATE FUNCTION [dbo].[split](
@delimited NVARCHAR(MAX),
@delimiter NVARCHAR(100)
) RETURNS @t TABLE (id INT IDENTITY(1,1), val NVARCHAR(MAX))
AS
BEGIN
DECLARE @xml XML
SET @xml = N'<t>' + REPLACE(@delimited,@delimiter,'</t><t>') + '</t>'
INSERT INTO @t(val)
SELECT r.value('.','varchar(MAX)') as item
FROM @xml.nodes('/t') as records(r)
RETURN
END
Execute the function like this
select * from dbo.split('Hello John Smith',' ')
If you need a drive letter (some applications don't like UNC style paths that start with a machine-name) you can "map a drive" to a UNC path. Right-click on "My Computer" and select Map Network Drive... or use this command line:
NET USE z: \server\c$\folder1\folder2
NET USE y: \server\d$
Note that you can map drive-to-drive or drill down and map to sub-folder.
Another possible cause of this is trying to use the ;x509; module on something that is not X.509.
The server certificate is X.509 format, but the private key is RSA.
So:
openssl rsa -noout -text -in privkey.pem
openssl x509 -noout -text -in servercert.pem
Since there are also macOS folks reading this one (as I did), the following code worked for me (on 10.14)
egrep -rl '<pattern>' <dir> | xargs -I@ sed -i '' 's/<arg1>/<arg2>/g' @
All other answers using -i
and -e
do not work on macOS.
You should declare it with declarations array(meta property) of @NgModule
as shown below (RC5 and later
),
import {CoursesComponent} from './courses.component';
@NgModule({
imports: [ BrowserModule],
declarations: [ AppComponent,CoursesComponent], //<----here
providers: [],
bootstrap: [ AppComponent ]
})
Once you verified the versions, you may need to either:
a: Give administrative privileges for Genymotion via properties
OR
b: Change the location for the deployed devices via Settings/VirtualBox to somewhere more accessbile like D:/GenyMotion VMs/
I had the same problem until I used a 3rd Party tool to generate the Class from the XSD and it worked! I discovered that the tool was adding some extra code at the top of my class. When I added this same code to the top of my original class it worked. Here's what I added...
#pragma warning disable
namespace MyNamespace
{
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.Xml;
using System.Collections.Generic;
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.6.1064.2")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class MyClassName
{
...
The problem is with -3.7(prof[x])
, which looks like a function call (note the parens). Just use a *
like this -3.7*prof[x]
.
EDIT again:
Sorry. Besides missing the nullable I was looking at the wrong function,
Min<(Of <(TSource, TResult>)>)(IEnumerable<(Of <(TSource>)>), Func<(Of <(TSource, TResult>)>)) does return the result type as you said.
I would say one possible solution is to implement IComparable and use Min<(Of <(TSource>)>)(IEnumerable<(Of <(TSource>)>)), which really does return an element from the IEnumerable. Of course, that doesn't help you if you can't modify the element. I find MS's design a bit weird here.
Of course, you can always do a for loop if you need to, or use the MoreLINQ implementation Jon Skeet gave.
So after doing more investigating I ended up going with a slightly revised version of Method 3 (mgechev/angular2-seed).
I basically moved components to be a main level directory and then each feature will be inside of it.
You need to assign the result back to $content
as preg_replace
does not modify the original string.
$content = preg_replace("/<img[^>]+\>/i", "(image) ", $content);
You are missing a parantheses in the denominator of your gaussian() function. As it is right now you divide by 2 and multiply with the variance (sig^2). But that is not true and as you can see of your plots the greater variance the more narrow the gaussian is - which is wrong, it should be opposit.
So just change the gaussian() function to:
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
The problem comes from the fact that np.isnan()
does not handle string values correctly. For example, if you do:
np.isnan("A")
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
However the pandas version pd.isnull()
works for numeric and string values:
pd.isnull("A")
> False
pd.isnull(3)
> False
pd.isnull(np.nan)
> True
pd.isnull(None)
> True
datetime.datetime.fromtimestamp
will do, if you know the time zone, you could produce the same output as with time.gmtime
>>> datetime.datetime.fromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 11, 19, 54)
or
>>> datetime.datetime.utcfromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 10, 19, 54)
Eva M from above, almost had the answer as posted above (Thanks Eva M!):
var validator = $( "#myform" ).validate();
validator.form();
This is almost the answer, but it causes problems, in even the most up to date jquery validation plugin as of 13 DEC 2018. The problem is that if one directly copies that sample, and EVER calls ".validate()" more than once, the focus/key processing of the validation can get broken, and the validation may not show errors properly.
Here is how to use Eva M's answer, and ensure those focus/key/error-hiding issues do not occur:
1) Save your validator to a variable/global.
var oValidator = $("#myform").validate();
2) DO NOT call $("#myform").validate() EVER again.
If you call $("#myform").validate() more than once, it may cause focus/key/error-hiding issues.
3) Use the variable/global and call form.
var bIsValid = oValidator.form();
Pay super close attention to umerk44's solution above. getMimeTypeFromExtension
invokes guessMimeTypeTypeFromExtension
and is CASE SENSITIVE. I spent an afternoon on this then took a closer look - getMimeTypeFromExtension
will return NULL
if you pass it "JPG" whereas it will return "image/jpeg" if you pass it "jpg".
Try using the key
keyword with sorted()
.
sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)], key=lambda x: x[1])
key
should be a function that identifies how to retrieve the comparable element from your data structure. In your case, it is the second element of the tuple, so we access [1]
.
For optimization, see jamylak's response using itemgetter(1)
, which is essentially a faster version of lambda x: x[1]
.
If you're using jQuery, this is a kinda cool way to manipulate elements in javascript without adding them to the DOM:
var myAnchor = $("<a />");
//set href
myAnchor.attr('href', 'http://example.com/path/to/myfile')
//your link's features
var hostname = myAnchor.attr('hostname'); // http://example.com
var pathname = myAnchor.attr('pathname'); // /path/to/my/file
//...etc
Suppose you have less data, I suggest to try 70%, 80% and 90% and test which is giving better result. In case of 90% there are chances that for 10% test you get poor accuracy.
this is variation of Dennis method, looks more elegant in the scripts.
function definition:
define(){ IFS='\n' read -r -d '' ${1} || true; }
usage:
define VAR <<'EOF'
abc'asdf"
$(dont-execute-this)
foo"bar"''
EOF
echo "$VAR"
enjoy
p.s. made a 'read loop' version for shells that do not support read -d
. should work with set -eu
and unpaired backticks, but not tested very well:
define(){ o=; while IFS="\n" read -r a; do o="$o$a"'
'; done; eval "$1=\$o"; }
For me no work i need upgrade pip....
Debian/Ubuntu
install dependencies
sudo apt-get install libpython-dev libssl-dev libffi-dev
upgrade pip and install packages
sudo pip install -U pip
sudo pip install -U pyopenssl ndg-httpsclient pyasn1
If you want remove dependencies
sudo apt-get remove --purge libpython-dev libssl-dev libffi-dev
sudo apt-get autoremove
Although in the particular example of the OP's question, switch
is not appropriate, there is an example where switch is still appropriate/beneficial, but other evaluation expressions are also required. This can be achieved by using the default clause for the expressions:
switch (foo) {
case 'bar':
// do something
break;
case 'foo':
// do something
break;
... // other plain comparison cases
default:
if (foo.length > 16) {
// something specific
} else if (foo.length < 2) {
// maybe error
} else {
// default action for everything else
}
}
Visual Studio should now ask your GitHub credentials and then proceed to upload your solution.
Since I have my Windows account connected to Visual Studio to work with Team Foundation I don't know if it works without an account, Visual Studio will keep track of who commits so if you are not logged in it will probably ask you to first.
Dead-simple and easy to read!
"mrap"
from nicknames
as a String from this JSON response{
"other": {
"nicknames": ["mrap", "Mikee"]
}
It takes your json data NSData
as it is, no need to preprocess.
let parser = JSONParser(jsonData)
if let handle = parser.getString("other.nicknames[0]") {
// that's it!
}
Disclaimer: I made this and I hope it helps everyone. Feel free to improve on it!
Quite simple:
$input = array(
array(
'tag_name' => 'google'
),
array(
'tag_name' => 'technology'
)
);
echo implode(', ', array_map(function ($entry) {
return $entry['tag_name'];
}, $input));
and new in php v5.5.0, array_column
:
echo implode(', ', array_column($input, 'tag_name'));
This demo is returning correctly for me in Chrome 14, FF3 and FF5 (with Firebug):
var mytextvalue = document.getElementById("mytext").value;
console.log(mytextvalue == ''); // true
console.log(mytextvalue == null); // false
and changing the console.log
to alert
, I still get the desired output in IE6.
This is what I used.
$('#foo').popover({
placement : 'bottom',
title : 'Title',
content : '<div id="popOverBox"><img src="http://i.telegraph.co.uk/multimedia/archive/01515/alGore_1515233c.jpg" /></div>'
});
and for the HTML
<b id="foo" rel="popover">text goes here</b>
Output the images in a lossless format such as PNG:
ffmpeg.exe -i 10fps.h264 -r 10 -f image2 10fps.h264_%03d.png
Edit/Update: Not quite sure why I originally gave a strange filename example (with a possibly made-up extension).
I have since found that
-vsync 0
is simpler than-r 10
because it avoids needing to know the frame rate.This is something like what I currently use:
mkdir stills ffmpeg -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png
To extract only the key frames (which are likely to be of higher quality post-edit):
ffmpeg -skip_frame nokey -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png
Then use another program (where you can more precisely specify quality, subsampling and DCT method – e.g. GIMP) to convert the PNGs you want to JPEG.
It is possible to obtain slightly sharper images in JPEG format this way than is possible with -qmin 1 -q:v 1
and outputting as JPEG directly from ffmpeg
.
2 steps solved my problem:
1) Delete "/Library/LaunchDaemons/com.mysql.mysql.plist"
2) Restart Yosemite
this works well for me
arglen=$#
argparam=$*
if [ $arglen -eq '3' ];
then
echo Valid Number of arguments
echo "Arguments are $*"
else
echo only four arguments are allowed
fi
You can access column name specifically like this too if you don't want to loop through all columns:
table.Columns[1].ColumnName
Why is it necessary to maintain the order of insertion? If you use HashMap
, you can get the entry by key
. It does not mean it does not provide classes that do what you want.
Assuming that the DropDownList control in the other table also contains DepartmentName and DepartmentID:
lstDepartment.ClearSelection();
foreach (var item in lstDepartment.Items)
{
if (item.Value == otherDropDownList.SelectedValue)
{
item.Selected = true;
}
}
In addition mysql passwords when not using the IDENTIFIED BY
clause, may be blank values, if non-blank, they may be encrypted. But yes USAGE
is used to modify an account by granting simple resource limiters such as MAX_QUERIES_PER_HOUR
, again this can be specified by also
using the WITH clause, in conjuction with GRANT USAGE
(no privileges added) or GRANT ALL
, you can also specify GRANT USAGE
at the global level, database level, table level,etc....
Random branching of a program or yes/no; 1/0; true/false output:
if [ $RANDOM -gt 16383 ]; then # 16383 = 32767/2
echo var=true/1/yes/go_hither
else
echo var=false/0/no/go_thither
fi
of if you lazy to remember 16383:
if (( RANDOM % 2 )); then
echo "yes"
else
echo "no"
fi
today this kind of thing can be done by using display:flex;
https://jsfiddle.net/suunyz3e/1435/
html:
<div class="container flex-direction">
<div class="div1">
<span>Div One</span>
</div>
<div class="div2">
<span>Div Two</span>
</div>
</div>
css:
.container{
display:inline-flex;
flex-wrap:wrap;
border:1px solid black;
}
.flex-direction{
flex-direction:row;
}
.div1{
border-right:1px solid black;
background-color:#727272;
width:165px;
height:132px;
}
.div2{
background-color:#fff;
width:314px;
height:132px;
}
span{
font-size:16px;
font-weight:bold;
display: block;
line-height: 132px;
text-align: center;
}
@media screen and (max-width: 500px) {
.flex-direction{
flex-direction:column;
}
.div1{
width:202px;
height:131px;
border-right:none;
border-bottom:1px solid black;
}
.div2{
width:202px;
height:107px;
}
.div2 span{
line-height:107px;
}
}
Yes, the order of elements in a python list is persistent.
The most simple and straightforward C/C++ implementation that I found is in a link at the bottom of this page:
Web Page: http://www.barrgroup.com/Embedded-Systems/How-To/CRC-Calculation-C-Code
Code Download Link: https://barrgroup.com/code/crc.zip
It is a simple standalone implementation with one .h and one .c file. There is support for CRC32, CRC16 and CRC_CCITT thru the use of a define. Also, the code lets the user change parameter settings like the CRC polynomial, initial/final XOR value, and reflection options if you so desire.
The license is not explicitly defined ala LGPL or similar. However the site does say that they are placing the code in the public domain for any use. The actual code files also say this.
Hope it helps!
You can do this too:
$ var="myscript"
$ echo $var
myscript
$ var=${var}.sh
$ echo $var
myscript.sh
That query is failing and returning false
.
Put this after mysqli_query()
to see what's going on.
if (!$check1_res) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
For more information:
I know this is an old question, but it is the top google result for "gitbash homedir windows" so figured I'd add my findings.
No matter what I tried I couldn't get git-bash to start in anywhere but my network drive,(U:) in my case making every operation take 15-20 seconds to respond. (Remote employee on VPN, network drive hosted on the other side of the country)
I tried setting HOME and HOMEDIR variables in windows.
I tried setting HOME and HOMEDIR variables in the git installation'setc/profile file.
I tried editing the "Start in" on the git-bash shortcut to be C:/user/myusername.
"env" command inside the git-bash shell would show correct c:/user/myusername. But git-bash would still start in U:
What ultimately fixed it for me was editing the git-bash shortcut and removing the "--cd-to-home" from the Target line.
I'm on Windows 10 running latest version of Git-for-windows 2.22.0.
Create and similar object for comparison works too ex:
from datetime import datetime, date
now = datetime.now()
today = date.today()
# compare now with today
two_month_earlier = date(now.year, now.month - 2, now.day)
if two_month_earlier > today:
print(True)
two_month_earlier = datetime(now.year, now.month - 2, now.day)
if two_month_earlier > now:
print("this will work with datetime too")
VAR=value
sets VAR to value.
After that export VAR
will give it to child processes too.
export VAR=value
is a shorthand doing both.
.query
with Pandas >= 0.25.0:August 2019 updated answer
Since Pandas >= 0.25.0 we can use the query
method to filter dataframes with Pandas methods and even column names which have spaces. Normally the spaces in column names would give an error, but now we can solve that using a backtick (`) - see GitHub:
# Example dataframe
df = pd.DataFrame({'Sender email':['[email protected]', "[email protected]", "[email protected]"]})
Sender email
0 [email protected]
1 [email protected]
2 [email protected]
Using .query
with method str.endswith
:
df.query('`Sender email`.str.endswith("@shop.com")')
Output
Sender email
1 [email protected]
2 [email protected]
Also we can use local variables by prefixing it with an @
in our query:
domain = 'shop.com'
df.query('`Sender email`.str.endswith(@domain)')
Output
Sender email
1 [email protected]
2 [email protected]
For Win7 Acrobat Pro X
Since I did all these without rechecking to see if the problem still existed afterwards, I am not sure which on of these actually fixed the problem, but one of them did. In fact, after doing the #3 and rebooting, it worked perfectly.
FYI: Below is the order in which I stepped through the repair.
Go to Control Panel
> folders options under each of the General
, View
and Search
Tabs
click the Restore Defaults
button and the Reset Folders
button
Go to Internet Explorer
, Tools
> Options
> Advanced
> Reset
( I did not need to delete personal settings)
Open Acrobat Pro X
, under Edit
> Preferences
> General
.
At the bottom of page select Default PDF Handler
. I chose Adobe Pro X
, and click Apply
.
You may be asked to reboot (I did).
Best Wishes
You can animate the position (top, bottom, left, right) and then subtract the element's width or height through a CSS transformation.
Consider:
$('.animate').on('click', function(){
$(this).toggleClass("move");
})
_x000D_
.animate {
height: 100px;
width: 100px;
background-color: #c00;
transition: all 1s ease;
position: absolute;
cursor: pointer;
font: 13px/100px sans-serif;
color: white;
text-align: center;
}
/* ? just to position things */
.animate.left { left: 0; top: 50%; margin-top: -100px;}
.animate.right { right: 0; top: 50%; }
.animate.top { top: 0; left: 50%; }
.animate.bottom { bottom: 0; left: 50%; margin-left: -100px;}
.animate.left.move {
left: 100%;
transform: translate(-100%, 0);
}
.animate.right.move {
right: 100%;
transform: translate(100%, 0);
}
.animate.top.move {
top: 100%;
transform: translate(0, -100%);
}
.animate.bottom.move {
bottom: 100%;
transform: translate(0, 100%);
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Click to animate
<div class="animate left">left</div>
<div class="animate top">top</div>
<div class="animate bottom">bottom</div>
<div class="animate right">right</div>
_x000D_
And then animate depending on the position...
At first choose your API level from the following links:
API Level 17: http://dl-ssl.google.com/android/repository/docs-17_r02.zip
API Level 18: http://dl-ssl.google.com/android/repository/docs-18_r02.zip
API Level 19: http://dl-ssl.google.com/android/repository/docs-19_r02.zip
Android-L API doc: http://dl-ssl.google.com/android/repository/docs-L_r01.zip
API Level 24 doc: https://dl-ssl.google.com/android/repository/docs-24_r01.zip
download and extract it in your sdk driectory.
In your eclipse IDE:
at project -> properties -> java build path -> Libraries -> Android x.x -> android.jar -> javadoc
press edit in right:
javadoc URL -> Browse
select "docs/reference/" in archive extracted directory
press validate
... to validate this javadoc.
In your IntelliJ IDEA
at file -> Project Structure
Select SDKs from left panel -> select your sdk from middle panel -> in right panel go to Documentation Paths
tab so click plus icon and select docs/reference/
in archive extracted directory.
enjoy the offline javadoc...
In case you are still looking for a Windows build of OpenJDK, Azul Systems launched the Zulu product line last fall. The Zulu distribution of OpenJDK is built and tested on Windows and Linux. We posted the OpenJDK 8 version this week, though OpenJDK 7 and 6 are both available too. The following URL leads to you free downloads, the Zulu community forum, and other details: http://www.azulsystems.com/products/zulu These are binary downloads, so you do not need to build OpenJDK from scratch to use them.
I can attest that building OpenJDK 6 for Windows was not a trivial exercise. Of the six different platforms we've built (OpenJDK6, OpenJDK7, and OpenJDK8, each for Windows and Linux) for x64 so far, the Windows OpenJDK6 build took by far the most effort to wring out items that didn't work on Windows, or would not pass the Technical Compatibility Kit test protocol for Java SE 6 "as is."
Disclaimer: I am the Product Manager for Zulu. You can review my Zulu release notices here: https://support.azulsystems.com/hc/communities/public/topics/200063190-Zulu-Releases I hope this helps.
col_Names=["Sequence", "Start", "End", "Coverage"]
my_CSV_File= pd.read_csv("yourCSVFile.csv",names=col_Names)
having done this, just check it with[well obviously I know, u know that. But still...
my_CSV_File.head()
Hope it helps ... Cheers
Here an alternative using SUBSTRING
SELECT
SUBSTRING([Field], LEN([Field]) - 2, 3) [Right3],
SUBSTRING([Field], 0, LEN([Field]) - 2) [TheRest]
FROM
[Fields]
It works in my react project:
import FileSaver from 'file-saver';
// ...
onTestSaveFile() {
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
FileSaver.saveAs(blob, "hello world.txt");
}
String message = URLEncoder.encode("my message", "UTF-8");
try {
// instantiate the URL object with the target URL of the resource to
// request
URL url = new URL("http://www.example.com/comment");
// instantiate the HttpURLConnection with the URL object - A new
// connection is opened every time by calling the openConnection
// method of the protocol handler for this URL.
// 1. This is the point where the connection is opened.
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
// set connection output to true
connection.setDoOutput(true);
// instead of a GET, we're going to send using method="POST"
connection.setRequestMethod("POST");
// instantiate OutputStreamWriter using the output stream, returned
// from getOutputStream, that writes to this connection.
// 2. This is the point where you'll know if the connection was
// successfully established. If an I/O error occurs while creating
// the output stream, you'll see an IOException.
OutputStreamWriter writer = new OutputStreamWriter(
connection.getOutputStream());
// write data to the connection. This is data that you are sending
// to the server
// 3. No. Sending the data is conducted here. We established the
// connection with getOutputStream
writer.write("message=" + message);
// Closes this output stream and releases any system resources
// associated with this stream. At this point, we've sent all the
// data. Only the outputStream is closed at this point, not the
// actual connection
writer.close();
// if there is a response code AND that response code is 200 OK, do
// stuff in the first if block
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// OK
// otherwise, if any other status code is returned, or no status
// code is returned, do stuff in the else block
} else {
// Server returned HTTP error code.
}
} catch (MalformedURLException e) {
// ...
} catch (IOException e) {
// ...
}
The first 3 answers to your questions are listed as inline comments, beside each method, in the example HTTP POST above.
From getOutputStream:
Returns an output stream that writes to this connection.
Basically, I think you have a good understanding of how this works, so let me just reiterate in layman's terms. getOutputStream
basically opens a connection stream, with the intention of writing data to the server. In the above code example "message" could be a comment that we're sending to the server that represents a comment left on a post. When you see getOutputStream
, you're opening the connection stream for writing, but you don't actually write any data until you call writer.write("message=" + message);
.
From getInputStream():
Returns an input stream that reads from this open connection. A SocketTimeoutException can be thrown when reading from the returned input stream if the read timeout expires before data is available for read.
getInputStream
does the opposite. Like getOutputStream
, it also opens a connection stream, but the intent is to read data from the server, not write to it. If the connection or stream-opening fails, you'll see a SocketTimeoutException
.
How about the getInputStream? Since I'm only able to get the response at getInputStream, then does it mean that I didn't send any request at getOutputStream yet but simply establishes a connection?
Keep in mind that sending a request and sending data are two different operations. When you invoke getOutputStream or getInputStream url.openConnection()
, you send a request to the server to establish a connection. There is a handshake that occurs where the server sends back an acknowledgement to you that the connection is established. It is then at that point in time that you're prepared to send or receive data. Thus, you do not need to call getOutputStream to establish a connection open a stream, unless your purpose for making the request is to send data.
In layman's terms, making a getInputStream
request is the equivalent of making a phone call to your friend's house to say "Hey, is it okay if I come over and borrow that pair of vice grips?" and your friend establishes the handshake by saying, "Sure! Come and get it". Then, at that point, the connection is made, you walk to your friend's house, knock on the door, request the vice grips, and walk back to your house.
Using a similar example for getOutputStream
would involve calling your friend and saying "Hey, I have that money I owe you, can I send it to you"? Your friend, needing money and sick inside that you kept it for so long, says "Sure, come on over you cheap bastard". So you walk to your friend's house and "POST" the money to him. He then kicks you out and you walk back to your house.
Now, continuing with the layman's example, let's look at some Exceptions. If you called your friend and he wasn't home, that could be a 500 error. If you called and got a disconnected number message because your friend is tired of you borrowing money all the time, that's a 404 page not found. If your phone is dead because you didn't pay the bill, that could be an IOException. (NOTE: This section may not be 100% correct. It's intended to give you a general idea of what's happening in layman's terms.)
Question #5:
Yes, you are correct that openConnection simply creates a new connection object but does not establish it. The connection is established when you call either getInputStream or getOutputStream.
openConnection
creates a new connection object. From the URL.openConnection javadocs:
A new connection is opened every time by calling the openConnection method of the protocol handler for this URL.
The connection is established when you call openConnection, and the InputStream, OutputStream, or both, are called when you instantiate them.
Question #6:
To measure the overhead, I generally wrap some very simple timing code around the entire connection block, like so:
long start = System.currentTimeMillis();
log.info("Time so far = " + new Long(System.currentTimeMillis() - start) );
// run the above example code here
log.info("Total time to send/receive data = " + new Long(System.currentTimeMillis() - start) );
I'm sure there are more advanced methods for measuring the request time and overhead, but this generally is sufficient for my needs.
For information on closing connections, which you didn't ask about, see In Java when does a URL connection close?.
You can now sync all your settings across devices with VSCode's built-in Settings Sync
. It's found under Code > Preferences > Turn on Settings Sync...
Read more about it in the official docs here
I encountered the same problem. So, I tried representing the JSON
in different Language syntax formats.But all time favorites are Perl
, js
, python
, & elixir
.
This is how it looks.
The following screenshots are from the Gitlab
in a markdown file.
This may vary based on the colors using for syntax in MARKDOWN
files.
I was about to advise to extract all the files at the same level, then to make a jar out of the result, since the package system should keep them neatly separated. That would be the manual way, I suppose the tools indicated by Steve will do that nicely.
If you want the correct answer according to the latest Unicode standard, you should use icu4j.
UCharacter.toTitleCase(Locale.US, "hello world", null, 0);
Note that this is locale sensitive.
Use PREPARE
/EXECUTE
and querying the schema.
The host doesn't need to have permission to create or run procedures :
SET @dbname = DATABASE();
SET @tablename = "tableName";
SET @columnname = "colName";
SET @preparedStatement = (SELECT IF(
(
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE
(table_name = @tablename)
AND (table_schema = @dbname)
AND (column_name = @columnname)
) > 0,
"SELECT 1",
CONCAT("ALTER TABLE ", @tablename, " ADD ", @columnname, " INT(11);")
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;
As a JavaScript fallback (or your sole solution), you can use my jQuery Scalem plugin, which lets you scale relative to the parent element (container) by passing the reference
option.
I know this is old but you could create a custom extension if you needed to create that form over and over:
public static MvcForm BeginMultipartForm(this HtmlHelper htmlHelper)
{
return htmlHelper.BeginForm(null, null, FormMethod.Post,
new Dictionary<string, object>() { { "enctype", "multipart/form-data" } });
}
Usage then just becomes
<% using(Html.BeginMultipartForm()) { %>
My solution (similar to KyleLanser's answer) (on a Unix box):
strings dumpfile.dmp | grep SCHEMA_LIST
Every SQL statement executed by the Oracle database has a cursor associated with it, which is a private work area to store processing information. Implicit cursors are implicitly created by the Oracle server for all DML and SELECT statements.
You can declare and use Explicit cursors to name the private work area, and access its stored information in your program block.
You don't need to explicitly set GOROOT
(Modern versions of Go can figure it out on their own based on the location of the go binary that you run).
Also, got the follow error when trying to work with vgo
:
go: modules disabled inside GOPATH/src by GO111MODULE=auto; see 'go help modules'
Removing GOROOT, updating my GOPATH and export GO111MODULE="on"
resolved the issue.
GOPATH see in here
GOPATH may be set to a colon-separated list of paths inside which Go code, package objects, and executables may be found.
Set a GOPATH to use goinstall to build and install your own code and external libraries outside of the Go tree (and to avoid writing Makefiles).
Use the following:
type file.txt | findstr /v ERROR | findstr /v REFERENCE
This has the advantage of using standard tools in the Windows OS, rather than having to find and install sed/awk/perl and such.
See the following transcript for it in operation:
C:\>type file.txt Good Line of data bad line of C:\Directory\ERROR\myFile.dll Another good line of data bad line: REFERENCE Good line C:\>type file.txt | findstr /v ERROR | findstr /v REFERENCE Good Line of data Another good line of data Good line
I try GET 'http://example.com/?var=value'
Important use '
add >/dev/null 2>&1
for not send email when this activate
Sorry for my English
Even better, use DEFAULT instead of NULL. You want to store the default value, not a NULL that might trigger a default value.
But you'd better name all columns, with a piece of SQL you can create all the INSERT, UPDATE and DELETE's you need. Just check the information_schema and construct the queries you need. There is no need to do it all by hand, SQL can help you out.
Try wrapping the spans in an anchor tag and apply the background image to that.
HTML:
<div class="header">
<a href="/">
<span class="header-title">My gray sea design</span><br />
<span class="header-title-two">A beautiful design</span>
</a>
</div>
CSS:
.header {
border-bottom:1px solid #eaeaea;
}
.header a {
display: block;
background-image: url("./images/embouchure.jpg");
background-repeat: no-repeat;
height:160px;
padding-left:280px;
padding-top:50px;
width:470px;
color: #eaeaea;
}
You could take a look at date-and-time api for easily date manipulation.
let now = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss', true);_x000D_
console.log(now);
_x000D_
<script src="https://cdn.jsdelivr.net/npm/date-and-time/date-and-time.min.js"></script>
_x000D_
Linux
conda env export --no-builds | grep -v "prefix" > environment.yml
Windows
conda env export --no-builds | findstr -v "prefix" > environment.yml
Rationale: By default, conda env export
includes the build information:
$ conda env export
...
dependencies:
- backcall=0.1.0=py37_0
- blas=1.0=mkl
- boto=2.49.0=py_0
...
You can instead export your environment without build info:
$ conda env export --no-builds
...
dependencies:
- backcall=0.1.0
- blas=1.0
- boto=2.49.0
...
Which unties the environment from the Python version and OS.
Using static defaultProps
is correct. You should also be using interfaces, not classes, for the props and state.
Update 2018/12/1: TypeScript has improved the type-checking related to defaultProps
over time. Read on for latest and greatest usage down to older usages and issues.
TypeScript specifically added support for defaultProps
to make type-checking work how you'd expect. Example:
interface PageProps {
foo: string;
bar: string;
}
export class PageComponent extends React.Component<PageProps, {}> {
public static defaultProps = {
foo: "default"
};
public render(): JSX.Element {
return (
<span>Hello, { this.props.foo.toUpperCase() }</span>
);
}
}
Which can be rendered and compile without passing a foo
attribute:
<PageComponent bar={ "hello" } />
Note that:
foo
is not marked optional (ie foo?: string
) even though it's not required as a JSX attribute. Marking as optional would mean that it could be undefined
, but in fact it never will be undefined
because defaultProps
provides a default value. Think of it similar to how you can mark a function parameter optional, or with a default value, but not both, yet both mean the call doesn't need to specify a value. TypeScript 3.0+ treats defaultProps
in a similar way, which is really cool for React users!defaultProps
has no explicit type annotation. Its type is inferred and used by the compiler to determine which JSX attributes are required. You could use defaultProps: Pick<PageProps, "foo">
to ensure defaultProps
matches a sub-set of PageProps
. More on this caveat is explained here.@types/react
version 16.4.11
to work properly.Before TypeScript 3.0 implemented compiler support for defaultProps
you could still make use of it, and it worked 100% with React at runtime, but since TypeScript only considered props when checking for JSX attributes you'd have to mark props that have defaults as optional with ?
. Example:
interface PageProps {
foo?: string;
bar: number;
}
export class PageComponent extends React.Component<PageProps, {}> {
public static defaultProps: Partial<PageProps> = {
foo: "default"
};
public render(): JSX.Element {
return (
<span>Hello, world</span>
);
}
}
Note that:
defaultProps
with Partial<>
so that it type-checks against your props, but you don't have to supply every required property with a default value, which makes no sense since required properties should never need a default.strictNullChecks
the value of this.props.foo
will be possibly undefined
and require a non-null assertion (ie this.props.foo!
) or type-guard (ie if (this.props.foo) ...
) to remove undefined
. This is annoying since the default prop value means it actually will never be undefined, but TS didn't understand this flow. That's one of the main reasons TS 3.0 added explicit support for defaultProps
.This works the same but you don't have Partial
types, so just omit Partial<>
and either supply default values for all required props (even though those defaults will never be used) or omit the explicit type annotation completely.
You can use defaultProps
on function components as well, but you have to type your function to the FunctionComponent
(StatelessComponent
in @types/react
before version 16.7.2
) interface so that TypeScript knows about defaultProps
on the function:
interface PageProps {
foo?: string;
bar: number;
}
const PageComponent: FunctionComponent<PageProps> = (props) => {
return (
<span>Hello, {props.foo}, {props.bar}</span>
);
};
PageComponent.defaultProps = {
foo: "default"
};
Note that you don't have to use Partial<PageProps>
anywhere because FunctionComponent.defaultProps
is already specified as a partial in TS 2.1+.
Another nice alternative (this is what I use) is to destructure your props
parameters and assign default values directly:
const PageComponent: FunctionComponent<PageProps> = ({foo = "default", bar}) => {
return (
<span>Hello, {foo}, {bar}</span>
);
};
Then you don't need the defaultProps
at all! Be aware that if you do provide defaultProps
on a function component it will take precedence over default parameter values, because React will always explicitly pass the defaultProps
values (so the parameters are never undefined, thus the default parameter is never used.) So you'd use one or the other, not both.
As mentioned above, if you use INSERT..IGNORE, errors that occur while executing the INSERT statement are treated as warnings instead.
One thing which is not explicitly mentioned is that INSERT..IGNORE will cause invalid values will be adjusted to the closest values when inserted (whereas invalid values would cause the query to abort if the IGNORE keyword was not used).
You can add a unique index
to group_id
; if you are sure that group_id
is unique.
It can solve your case without modifying the query.
A late answer, but it has not been mentioned yet in the answers. Maybe it should complete the already comprehensive answers available. At least it did solve my case when I had to split a table with too many fields.
Here I did with jQuery using FileReader API.
Html Markup:
<input id="fileUpload" type="file" multiple />
<div id="image-holder"></div>
jQuery:
Here in jQuery code,first I check for file extension. i.e valid image file to be processed, then will check whether the browser support FileReader API is yes then only processed else display respected message
$("#fileUpload").on('change', function () {
//Get count of selected files
var countFiles = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
var image_holder = $("#image-holder");
image_holder.empty();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof (FileReader) != "undefined") {
//loop for each file selected for uploaded.
for (var i = 0; i < countFiles; i++) {
var reader = new FileReader();
reader.onload = function (e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Pls select only images");
}
});
Detailed Article: How to Preview Image before upload it, jQuery, HTML5 FileReader() with Live Demo
The html
data attribute does exactly what it says it does in the docs. Try this little example, no JavaScript necessary (broken into lines for clarification):
<span rel="tooltip"
data-toggle="tooltip"
data-html="true"
data-title="<table><tr><td style='color:red;'>complex</td><td>HTML</td></tr></table>"
>
hover over me to see HTML
</span>
JSFiddle demos:
After reinstalling Android Studio, Is working without adb kill-server
I had the same issue where these fixes didn't work.
I'm on Ubuntu 20.04 using hestiaCP with Nginx.
Today after adding
Include /etc/phpmyadmin/apache.conf
into both Apache and Nginx, Nginx failed to restart. It was having an issue with "proxy_buffers" value.
Yesterday I had to modify the Nginx config to add and increase these values so Magento 2.4 would run. Today I altered "proxy_buffers" again
proxy_buffers 3 64k;
proxy_buffer_size 128k;
proxy_busy_buffers_size 128k;
After the second alteration and the removal of "Include /etc/phpmyadmin/apache.conf" from both Apache and Nginx, Magento 2.4 and PHPMyAdmin are working as expected.
As you have noticed, xscale
and yscale
does not support a simple linear re-scaling (unfortunately). As an alternative to Hooked's answer, instead of messing with the data, you can trick the labels like so:
ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*scale))
ax.xaxis.set_major_formatter(ticks)
A complete example showing both x and y scaling:
import numpy as np
import pylab as plt
import matplotlib.ticker as ticker
# Generate data
x = np.linspace(0, 1e-9)
y = 1e3*np.sin(2*np.pi*x/1e-9) # one period, 1k amplitude
# setup figures
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
# plot two identical plots
ax1.plot(x, y)
ax2.plot(x, y)
# Change only ax2
scale_x = 1e-9
scale_y = 1e3
ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_x))
ax2.xaxis.set_major_formatter(ticks_x)
ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_y))
ax2.yaxis.set_major_formatter(ticks_y)
ax1.set_xlabel("meters")
ax1.set_ylabel('volt')
ax2.set_xlabel("nanometers")
ax2.set_ylabel('kilovolt')
plt.show()
And finally I have the credits for a picture:
Note that, if you have text.usetex: true
as I have, you may want to enclose the labels in $
, like so: '${0:g}$'
.
your div looks like this:
<div id="someId">Some Value</div>
With jquery:
<script type="text/javascript">
$(function(){
var text = $('#someId').html();
//or
var text = $('#someId').text();
};
</script>
There are three standard approaches for importing a JAR file into Android studio. The first one is traditional way, the second one is standard way, and the last one is remote library. I explained these approaches step by step with screenshots in this link:
https://stackoverflow.com/a/35369267/5475941.
I hope it helps.
Let's say you have:
<a></a>
<(.*)>
would match a></a
where as <(.*?)>
would match a
.
The latter stops after the first match of >
. It checks for one
or 0 matches of .*
followed by the next expression.
The first expression <(.*)>
doesn't stop when matching the first >
. It will continue until the last match of >
.
Iterating a list and removing multiple items using a find. Response contains an array of integers. $('#OneSelectList') is a select list.
$.ajax({
url: "Controller/Action",
type: "GET",
success: function (response) {
// Take out excluded years.
$.each(response, function (j, responseYear) {
$('#OneSelectList').find('[value="' + responseYear + '"]').remove();
});
},
error: function (response) {
console.log("Error");
}
});
I realize this is an old thread, but @alex 's answer needs to be marked as the correct answer
element.getBoundingClientRect()
is an exact match to jQuery's $(element).offset()
And it's compatible with IE4+ ... https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect
This works for me using JsonConvert
var result = JsonConvert.DeserializeObject<Class>(responseString);
$('p:contains("dogsss")').text('dollsss');
The typical pattern is to check out the root project folder (=the one containing a file called ".project") from SVN using eclipse's svn integration (SVN repository exploring perspective). The project is then recognized automatically.
button.titleLabel.font = [UIFont systemFontOfSize:size];
should help
The new Android Studio incorporates very significant performance improvements for the AVDs (emulated devices).
But when you initially install the Android Studio (or, when you update to a new version, such as Android Studio 2.0, which was recently released), the most important performance feature (at least if running on a Windows PC) is turned off by default. This is the HAXM emulator accelerator.
Open the Android SDK from the studio by selecting its icon from the top of the display (near the right side of the icons there), then select the SDKTools tab, and then check the box for the Intel x86 Emulator Accelerator (HAXM installer), click OK. Follow instructions to install the accelerator.
Be sure to completely exit Android Studio after installing, and then go to your SDK folder (C:\users\username\AppData\Local\extras\intel\Hardware_Accelerated_Execution_Manager, if you accepted the defaults). In this directory Go to extras\intel\Hardware_Accelerated_Execution_Manager and run the file named "intelhaxm-android.exe".
Then, re-enter the Studio, before running the AVD again.
Also, I found that when I updated from Android Studio 1.5 to version 2.0, I had to create entirely new AVDs, because all of my old ones ran so slowly as to be unusable (e.g., they were still booting up after five minutes - I never got one to completely boot). As soon as I created new ones, they ran quite well.
As far as I can tell after reading the docs for javadoc there is no such feature.
Don't use <code>foo</code>
as recommended in other answers; you can use {@code foo}
. This is especially good to know when you refer to a generic type such as {@code Iterator<String>}
-- sure looks nicer than <code>Iterator<String></code>
, doesn't it!
More oin regards to question part 4 How do you e-mail that error to an email address? The error_log function has email destination too. http://php.net/manual/en/function.error-log.php
Agha, here I found an example that shows a usage. Send errors message via email using error_log()
error_log($this->_errorMsg, 1, ADMIN_MAIL, "Content-Type: text/html; charset=utf8\r\nFrom: ".MAIL_ERR_FROM."\r\nTo: ".ADMIN_MAIL);
Here's a summary of different ways to do it, they will work for all these inputs:
"" => ""
"a b c" => "A B C"
"foO baR" => "FoO BaR"
"foo bar" => "Foo Bar"
"foo's bar" => "Foo's Bar"
"foo's1bar" => "Foo's1bar"
"foo 1bar" => "Foo 1bar"
- The simplest solution is to split the sentence into words and capitalize the first letter then join it back together:
# Be careful with multiple spaces, and empty strings
# for empty words w[0] would cause an index error,
# but with w[:1] we get an empty string as desired
def cap_sentence(s):
return ' '.join(w[:1].upper() + w[1:] for w in s.split(' '))
- If you don't want to split the input string into words first, and using fancy generators:
# Iterate through each of the characters in the string and capitalize
# the first char and any char after a blank space
from itertools import chain
def cap_sentence(s):
return ''.join( (c.upper() if prev == ' ' else c) for c, prev in zip(s, chain(' ', s)) )
- Or without importing itertools:
def cap_sentence(s):
return ''.join( (c.upper() if i == 0 or s[i-1] == ' ' else c) for i, c in enumerate(s) )
- Or you can use regular expressions, from steveha's answer:
# match the beginning of the string or a space, followed by a non-space
import re
def cap_sentence(s):
return re.sub("(^|\s)(\S)", lambda m: m.group(1) + m.group(2).upper(), s)
Now, these are some other answers that were posted, and inputs for which they don't work as expected if we are using the definition of a word being the start of the sentence or anything after a blank space:
return s.title()
# Undesired outputs:
"foO baR" => "Foo Bar"
"foo's bar" => "Foo'S Bar"
"foo's1bar" => "Foo'S1Bar"
"foo 1bar" => "Foo 1Bar"
return ' '.join(w.capitalize() for w in s.split())
# or
import string
return string.capwords(s)
# Undesired outputs:
"foO baR" => "Foo Bar"
"foo bar" => "Foo Bar"
using ' ' for the split will fix the second output, but capwords() still won't work for the first
return ' '.join(w.capitalize() for w in s.split(' '))
# or
import string
return string.capwords(s, ' ')
# Undesired outputs:
"foO baR" => "Foo Bar"
Be careful with multiple blank spaces
return ' '.join(w[0].upper() + w[1:] for w in s.split())
# Undesired outputs:
"foo bar" => "Foo Bar"
I've experimented with typing "exit for" a few times and noticed it worked and VB didn't yell at me. It's an option I guess but it just looked bad.
I think the best option is similar to that shared by Tobias. Just put your code in a function and have it return when you want to break out of your loops. Looks cleaner too.
For Each item In itemlist
For Each item1 In itemlist1
If item1 = item Then
Return item1
End If
Next
Next
<mvc:annotation-driven />
means that you can define spring beans dependencies without actually having to specify a bunch of elements in XML or implement an interface or extend a base class. For example @Repository
to tell spring that a class is a Dao without having to extend JpaDaoSupport
or some other subclass of DaoSupport. Similarly @Controller
tells spring that the class specified contains methods that will handle Http requests without you having to implement the Controller interface or extend a subclass that implements the controller.
When spring starts up it reads its XML configuration file and looks for <bean
elements within it if it sees something like <bean class="com.example.Foo" />
and Foo was marked up with @Controller
it knows that the class is a controller and treats it as such. By default, Spring assumes that all the classes it should manage are explicitly defined in the beans.XML file.
Component scanning with <context:component-scan base-package="com.mycompany.maventestwebapp" />
is telling spring that it should search the classpath for all the classes under com.mycompany.maventestweapp and look at each class to see if it has a @Controller
, or @Repository
, or @Service
, or @Component
and if it does then Spring will register the class with the bean factory as if you had typed <bean class="..." />
in the XML configuration files.
In a typical spring MVC app you will find that there are two spring configuration files, a file that configures the application context usually started with the Spring context listener.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
And a Spring MVC configuration file usually started with the Spring dispatcher servlet. For example.
<servlet>
<servlet-name>main</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Spring has support for hierarchical bean factories, so in the case of the Spring MVC, the dispatcher servlet context is a child of the main application context. If the servlet context was asked for a bean called "abc" it will look in the servlet context first, if it does not find it there it will look in the parent context, which is the application context.
Common beans such as data sources, JPA configuration, business services are defined in the application context while MVC specific configuration goes not the configuration file associated with the servlet.
Hope this helps.
For Windows:
#include "windows.h"
Sleep(10);
For Unix:
#include <unistd.h>
usleep(10)
Click volumes, then explore, and then that should open lampp which has htdocs in it.
If you want to use a function form a package or module in python you have to import and reference them. For example normally you do the following to draw 5 points( [1,5],[2,4],[3,3],[4,2],[5,1]) in the space:
import matplotlib.pyplot
matplotlib.pyplot.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
matplotlib.pyplot.show()
In your solution
from matplotlib import*
This imports the package matplotlib and "plot is not defined" means there is no plot function in matplotlib you can access directly, but instead if you import as
from matplotlib.pyplot import *
plot([1,2,3,4,5],[5,4,3,2,1],"bx")
show()
Now you can use any function in matplotlib.pyplot without referencing them with matplotlib.pyplot.
I would recommend you to name imports you have, in this case you can prevent disambiguation and future problems with the same function names. The last and clean version of above example looks like:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
plt.show()
This is how I do:
$('#my_input').select2('destroy').val('').select2();
git log -S"string_to_search" # options like --source --reverse --all etc
Pay attention not to use spaces between S and "string_to_search". In some setups (git 1.7.1), you'll get an error like:
fatal: ambiguous argument 'string_to_search': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions
Copied from http://technet.microsoft.com/en-us/library/cc750354.aspx
What's FAT?
FAT may sound like a strange name for a file system, but it's actually an acronym for File Allocation Table. Introduced in 1981, FAT is ancient in computer terms. Because of its age, most operating systems, including Microsoft Windows NT®, Windows 98, the Macintosh OS, and some versions of UNIX, offer support for FAT.
The FAT file system limits filenames to the 8.3 naming convention, meaning that a filename can have no more than eight characters before the period and no more than three after. Filenames in a FAT file system must also begin with a letter or number, and they can't contain spaces. Filenames aren't case sensitive.
What About VFAT?
Perhaps you've also heard of a file system called VFAT. VFAT is an extension of the FAT file system and was introduced with Windows 95. VFAT maintains backward compatibility with FAT but relaxes the rules. For example, VFAT filenames can contain up to 255 characters, spaces, and multiple periods. Although VFAT preserves the case of filenames, it's not considered case sensitive.
When you create a long filename (longer than 8.3) with VFAT, the file system actually creates two different filenames. One is the actual long filename. This name is visible to Windows 95, Windows 98, and Windows NT (4.0 and later). The second filename is called an MS-DOS® alias. An MS-DOS alias is an abbreviated form of the long filename. The file system creates the MS-DOS alias by taking the first six characters of the long filename (not counting spaces), followed by the tilde [~] and a numeric trailer. For example, the filename Brien's Document.txt would have an alias of BRIEN'~1.txt.
An interesting side effect results from the way VFAT stores its long filenames. When you create a long filename with VFAT, it uses one directory entry for the MS-DOS alias and another entry for every 13 characters of the long filename. In theory, a single long filename could occupy up to 21 directory entries. The root directory has a limit of 512 files, but if you were to use the maximum length long filenames in the root directory, you could cut this limit to a mere 24 files. Therefore, you should use long filenames very sparingly in the root directory. Other directories aren't affected by this limit.
You may be wondering why we're discussing VFAT. The reason is it's becoming more common than FAT, but aside from the differences I mentioned above, VFAT has the same limitations. When you tell Windows NT to format a partition as FAT, it actually formats the partition as VFAT. The only time you'll have a true FAT partition under Windows NT 4.0 is when you use another operating system, such as MS-DOS, to format the partition.
FAT32
FAT32 is actually an extension of FAT and VFAT, first introduced with Windows 95 OEM Service Release 2 (OSR2). FAT32 greatly enhances the VFAT file system but it does have its drawbacks.
The greatest advantage to FAT32 is that it dramatically increases the amount of free hard disk space. To illustrate this point, consider that a FAT partition (also known as a FAT16 partition) allows only a certain number of clusters per partition. Therefore, as your partition size increases, the cluster size must also increase. For example, a 512-MB FAT partition has a cluster size of 8K, while a 2-GB partition has a cluster size of 32K.
This may not sound like a big deal until you consider that the FAT file system only works in single cluster increments. For example, on a 2-GB partition, a 1-byte file will occupy the entire cluster, thereby consuming 32K, or roughly 32,000 times the amount of space that the file should consume. This rule applies to every file on your hard disk, so you can see how much space can be wasted.
Converting a partition to FAT32 reduces the cluster size (and overcomes the 2-GB partition size limit). For partitions 8 GB and smaller, the cluster size is reduced to a mere 4K. As you can imagine, it's not uncommon to gain back hundreds of megabytes by converting a partition to FAT32, especially if the partition contains a lot of small files.
Note: This section of the quote/ article (1999) is out of date. Updated info quote below.
As I mentioned, FAT32 does have limitations. Unfortunately, it isn't compatible with any operating system other than Windows 98 and the OSR2 version of Windows 95. However, Windows 2000 will be able to read FAT32 partitions.
The other disadvantage is that your disk utilities and antivirus software must be FAT32-aware. Otherwise, they could interpret the new file structure as an error and try to correct it, thus destroying data in the process.
Finally, I should mention that converting to FAT32 is a one-way process. Once you've converted to FAT32, you can't convert the partition back to FAT16. Therefore, before converting to FAT32, you need to consider whether the computer will ever be used in a dual-boot environment. I should also point out that although other operating systems such as Windows NT can't directly read a FAT32 partition, they can read it across the network. Therefore, it's no problem to share information stored on a FAT32 partition with other computers on a network that run older operating systems.
Updated mentioned in comment by Doktor-J (assimilated to update out of date answer in case comment is ever lost):
I'd just like to point out that most modern operating systems (WinXP/Vista/7/8, MacOS X, most if not all Linux variants) can read FAT32, contrary to what the second-to-last paragraph suggests.
The original article was written in 1999, and being posted on a Microsoft website, probably wasn't concerned with non-Microsoft operating systems anyways.
The operating systems "excluded" by that paragraph are probably the original Windows 95, Windows NT 4.0, Windows 3.1, DOS, etc.
There is a small handful of programs that do that... TowerJ is one that comes to mind (I'll let you Google for it) but it costs significant money.
The most useful reference for this topic I found is at: http://mindprod.com/jgloss/nativecompiler.html
it mentions a few other products, and alternatives to achieve the same purpose.
The java.util.Date/Calendar classes are a mess and should be avoided.
Update: The Joda-Time project is in maintenance mode. The team advises migration to the java.time classes.
Here's your answer using the Joda-Time 2.3 library. Very easy.
As noted in the example code, I suggest you use named time zones wherever possible so that your programming can handle Daylight Saving Time (DST) and other anomalies.
If you had placed a T
in the middle of your string instead of a space, you could skip the first two lines of code, dealing with a formatter to parse the string. The DateTime constructor can take a string in ISO 8601 format.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
// Parse string as a date-time in UTC (no time zone offset).
DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern( "yyyy-MM-dd' 'HH:mm:ss" );
DateTime dateTimeInUTC = formatter.withZoneUTC().parseDateTime( "2011-10-06 03:35:05" );
// Adjust for 13 hour offset from UTC/GMT.
DateTimeZone offsetThirteen = DateTimeZone.forOffsetHours( 13 );
DateTime thirteenDateTime = dateTimeInUTC.toDateTime( offsetThirteen );
// Hard-coded offsets should be avoided. Better to use a desired time zone for handling Daylight Saving Time (DST) and other anomalies.
// Time Zone list… http://joda-time.sourceforge.net/timezones.html
DateTimeZone timeZoneTongatapu = DateTimeZone.forID( "Pacific/Tongatapu" );
DateTime tongatapuDateTime = dateTimeInUTC.toDateTime( timeZoneTongatapu );
Dump those values…
System.out.println( "dateTimeInUTC: " + dateTimeInUTC );
System.out.println( "thirteenDateTime: " + thirteenDateTime );
System.out.println( "tongatapuDateTime: " + tongatapuDateTime );
When run…
dateTimeInUTC: 2011-10-06T03:35:05.000Z
thirteenDateTime: 2011-10-06T16:35:05.000+13:00
tongatapuDateTime: 2011-10-06T16:35:05.000+13:00
async
and defer
will download the file during HTML parsing. Both will not interrupt the parser.
The script with async
attribute will be executed once it is downloaded. While the script with defer
attribute will be executed after completing the DOM parsing.
The scripts loaded with async
doesn't guarantee any order. While the scripts loaded with defer
attribute maintains the order in which they appear on the DOM.
Use <script async>
when the script does not rely on anything.
when the script depends use <script defer>
.
Best solution would be add the <script>
at the bottom of the body. There will be no issue with blocking or rendering.
Another way to do that, if you want the result as a List inline, you can do it like this:
Arrays.asList(new String[] { "String1", "string2" });
import java.time.LocalTime;
private String ConvertSecondToHHMMSSString(int nSecondTime) {
return LocalTime.MIN.plusSeconds(nSecondTime).toString();
}
You should use sendfile apis given by popular servers like apache
or nginx
in production. Many years i was using sendfile api of these servers for protecting files. Then created a simple middleware based django app for this purpose suitable for both development & production purpose.You can access the source code here.
UPDATE: in new version python
provider uses django FileResponse
if available and also adds support for many server implementations from lighthttp, caddy to hiawatha
Usage
pip install django-fileprovider
fileprovider
app to INSTALLED_APPS
settings,fileprovider.middleware.FileProviderMiddleware
to MIDDLEWARE_CLASSES
settingsFILEPROVIDER_NAME
settings to nginx
or apache
in production, by default it is python
for development purpose.in your classbased or function views set response header X-File
value to absolute path to the file. For example,
def hello(request):
// code to check or protect the file from unauthorized access
response = HttpResponse()
response['X-File'] = '/absolute/path/to/file'
return response
django-fileprovider
impemented in a way that your code will need only minimum modification.
Nginx configuration
To protect file from direct access you can set the configuration as
location /files/ {
internal;
root /home/sideffect0/secret_files/;
}
Here nginx
sets a location url /files/
only access internaly, if you are using above configuration you can set X-File as,
response['X-File'] = '/files/filename.extension'
By doing this with nginx configuration, the file will be protected & also you can control the file from django views
Use chardet https://github.com/chardet/chardet (documentation is short and easy to read).
Install python, then pip install chardet, at last use the command line command.
I tested under GB2312 and it's pretty accurate. (Make sure you have at least a few characters, sample with only 1 character may fail easily).
file
is not reliable as you can see.
Since Java 8 you can use the argument-less any
method and the type argument will get inferred by the compiler:
verify(bar).doStuff(any());
The new thing in Java 8 is that the target type of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only arguments to methods where used for type parameter inference (most of the time).
In this case the parameter type of doStuff
will be the target type for any()
, and the return value type of any()
will get chosen to match that argument type.
This mechanism was added in Java 8 mainly to be able to compile lambda expressions, but it improves type inferences generally.
This doesn't work with primitive types, unfortunately:
public interface IBar {
void doPrimitiveStuff(int i);
}
verify(bar).doPrimitiveStuff(any()); // Compiles but throws NullPointerException
verify(bar).doPrimitiveStuff(anyInt()); // This is what you have to do instead
The problem is that the compiler will infer Integer
as the return value type of any()
. Mockito will not be aware of this (due to type erasure) and return the default value for reference types, which is null
. The runtime will try to unbox the return value by calling the intValue
method on it before passing it to doStuff
, and the exception gets thrown.
use 'any'
dict = {}
if any(dict) :
# true
# dictionary is not empty
else :
# false
# dictionary is empty
The classList
property ensures that duplicate classes are not unnecessarily added to the element. In order to keep this functionality, if you dislike the longhand versions or jQuery version, I'd suggest adding an addMany
function and removeMany
to DOMTokenList
(the type of classList
):
DOMTokenList.prototype.addMany = function(classes) {
var array = classes.split(' ');
for (var i = 0, length = array.length; i < length; i++) {
this.add(array[i]);
}
}
DOMTokenList.prototype.removeMany = function(classes) {
var array = classes.split(' ');
for (var i = 0, length = array.length; i < length; i++) {
this.remove(array[i]);
}
}
These would then be useable like so:
elem.classList.addMany("first second third");
elem.classList.removeMany("first third");
Update
As per your comments, if you wish to only write a custom method for these in the event they are not defined, try the following:
DOMTokenList.prototype.addMany = DOMTokenList.prototype.addMany || function(classes) {...}
DOMTokenList.prototype.removeMany = DOMTokenList.prototype.removeMany || function(classes) {...}
Try using raw_input
rather than input
if you simply want to read strings.
print("Enter your name: ")
x = raw_input()
print("Hello, "+x)
- Create a Class
with public static final
fields.
- And then you can access these fields from any class using the Class_Name.Field_Name
.
- You can declare the class
as final
, so that the class
can't be extended(Inherited) and modify....
The other answers will break if output of command contains spaces (which is rather frequent) or glob characters like *
, ?
, [...]
.
To get the output of a command in an array, with one line per element, there are essentially 3 ways:
With Bash=4 use mapfile
—it's the most efficient:
mapfile -t my_array < <( my_command )
Otherwise, a loop reading the output (slower, but safe):
my_array=()
while IFS= read -r line; do
my_array+=( "$line" )
done < <( my_command )
As suggested by Charles Duffy in the comments (thanks!), the following might perform better than the loop method in number 2:
IFS=$'\n' read -r -d '' -a my_array < <( my_command && printf '\0' )
Please make sure you use exactly this form, i.e., make sure you have the following:
IFS=$'\n'
on the same line as the read
statement: this will only set the environment variable IFS
for the read
statement only. So it won't affect the rest of your script at all. The purpose of this variable is to tell read
to break the stream at the EOL character \n
.-r
: this is important. It tells read
to not interpret the backslashes as escape sequences.-d ''
: please note the space between the -d
option and its argument ''
. If you don't leave a space here, the ''
will never be seen, as it will disappear in the quote removal step when Bash parses the statement. This tells read
to stop reading at the nil byte. Some people write it as -d $'\0'
, but it is not really necessary. -d ''
is better.-a my_array
tells read
to populate the array my_array
while reading the stream.printf '\0'
statement after my_command
, so that read
returns 0
; it's actually not a big deal if you don't (you'll just get an return code 1
, which is okay if you don't use set -e
– which you shouldn't anyway), but just bear that in mind. It's cleaner and more semantically correct. Note that this is different from printf ''
, which doesn't output anything. printf '\0'
prints a null byte, needed by read
to happily stop reading there (remember the -d ''
option?).If you can, i.e., if you're sure your code will run on Bash=4, use the first method. And you can see it's shorter too.
If you want to use read
, the loop (method 2) might have an advantage over method 3 if you want to do some processing as the lines are read: you have direct access to it (via the $line
variable in the example I gave), and you also have access to the lines already read (via the array ${my_array[@]}
in the example I gave).
Note that mapfile
provides a way to have a callback eval'd on each line read, and in fact you can even tell it to only call this callback every N lines read; have a look at help mapfile
and the options -C
and -c
therein. (My opinion about this is that it's a little bit clunky, but can be used sometimes if you only have simple things to do — I don't really understand why this was even implemented in the first place!).
Now I'm going to tell you why the following method:
my_array=( $( my_command) )
is broken when there are spaces:
$ # I'm using this command to test:
$ echo "one two"; echo "three four"
one two
three four
$ # Now I'm going to use the broken method:
$ my_array=( $( echo "one two"; echo "three four" ) )
$ declare -p my_array
declare -a my_array='([0]="one" [1]="two" [2]="three" [3]="four")'
$ # As you can see, the fields are not the lines
$
$ # Now look at the correct method:
$ mapfile -t my_array < <(echo "one two"; echo "three four")
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # Good!
Then some people will then recommend using IFS=$'\n'
to fix it:
$ IFS=$'\n'
$ my_array=( $(echo "one two"; echo "three four") )
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # It works!
But now let's use another command, with globs:
$ echo "* one two"; echo "[three four]"
* one two
[three four]
$ IFS=$'\n'
$ my_array=( $(echo "* one two"; echo "[three four]") )
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="t")'
$ # What?
That's because I have a file called t
in the current directory… and this filename is matched by the glob [three four]
… at this point some people would recommend using set -f
to disable globbing: but look at it: you have to change IFS
and use set -f
to be able to fix a broken technique (and you're not even fixing it really)! when doing that we're really fighting against the shell, not working with the shell.
$ mapfile -t my_array < <( echo "* one two"; echo "[three four]")
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="[three four]")'
here we're working with the shell!
Just to note,
MixEdit is not completely free.
"This software is currently not licensed to any user and is running in evaluation mode. MIXEDIT may be downloaded and evaluated for free, however a license must be purchased for continued use."
Upon installation and use, a popup redirects to webpage - similar to SublimeText's unlicensed software pop-up message.
I got this message when I drag and dropped some source files from another project. When I deleted them and then added them via the "Add Files..." from the File menu, it built without the error.
In case we want to dump the in memory file to disk. This code can be used
if isinstanceof(obj,SpooledTemporaryFile):
obj.rollover()
ggplot2 is based on grid graphics, which provide a different system for arranging plots on a page. The par(mfrow...)
command doesn't have a direct equivalent, as grid objects (called grobs) aren't necessarily drawn immediately, but can be stored and manipulated as regular R objects before being converted to a graphical output. This enables greater flexibility than the draw this now model of base graphics, but the strategy is necessarily a little different.
I wrote grid.arrange()
to provide a simple interface as close as possible to par(mfrow)
. In its simplest form, the code would look like:
library(ggplot2)
x <- rnorm(100)
eps <- rnorm(100,0,.2)
p1 <- qplot(x,3*x+eps)
p2 <- qplot(x,2*x+eps)
library(gridExtra)
grid.arrange(p1, p2, ncol = 2)
More options are detailed in this vignette.
One common complaint is that plots aren't necessarily aligned e.g. when they have axis labels of different size, but this is by design: grid.arrange
makes no attempt to special-case ggplot2 objects, and treats them equally to other grobs (lattice plots, for instance). It merely places grobs in a rectangular layout.
For the special case of ggplot2 objects, I wrote another function, ggarrange
, with a similar interface, which attempts to align plot panels (including facetted plots) and tries to respect the aspect ratios when defined by the user.
library(egg)
ggarrange(p1, p2, ncol = 2)
Both functions are compatible with ggsave()
. For a general overview of the different options, and some historical context, this vignette offers additional information.
Try replacing apt-get
with yum
as Amazon Linux based AMI uses the yum
command instead of apt-get
.
Watch the Tutorial https://www.youtube.com/watch?v=u92_73vfA8M
or
follow steps :
Go to any browser
type gradle and press enter
you can specify any version you want after the
gradle keyword
i am downloading gradle 3.3
https://services.gradle.org/distributions click on this link which is in description directly if you want
click on gradle 3.3 all.zip
wait for the download to complete
c://user/your pc name /.gradle/wrapper/dists
wait till extraction it takes 5 mins to complete
Now open your project in android studio
9.go to file > settings >bulid ,exec,deployment > gradle
use local gradle distributn
select the location where you had extracted gradle 3.3.zip
C:\Users\your pc name.gradle\wrapper\dists\gradle-3.3
click on OK
Now build starts again and
you can see now the build is successful and error is resolved
NULL
is a value that is valid for any pointer type. It represents the absence of a value.
A void pointer is a type. Any pointer type is convertible to a void pointer hence it can point to any value. This makes it good for general storage but bad for use. By itself it cannot be used to access a value. The program must have extra context to understand the type of value the void pointer refers to before it can access the value.
should call the function properly; like- Fibonacci:input
Notepad++ has a powerful regex engine, capable to search and replace patterns at will.
In your scenario:
Click the menu item Search\Replace...
Fill the 'Find what' field with the search pattern:
^(\d{4})\s+(\w{3})\s+(\w{3})$
Fill the replace pattern:
Insert into tbl (\1, \2) where clm = \3
Click the Replace All
button.
And that's it.
You can use https://grabz.it solution.
It's got a PHP API which is very flexible and can be called in different ways such as from a cronjob or a PHP web page.
In order to implement it you will need to first get an app key and secret and download the (free) SDK.
And an example for implementation. First of all initialization:
include("GrabzItClient.class.php");
// Create the GrabzItClient class
// Replace "APPLICATION KEY", "APPLICATION SECRET" with the values from your account!
$grabzIt = new GrabzItClient("Sign in to view your Application Key", "Sign in to view your Application Secret");
And screenshoting example:
// To take a image screenshot
$grabzIt->URLToImage("http://www.google.com");
// Or to take a PDF screenshot
$grabzIt->URLToPDF("http://www.google.com");
// Or to convert online videos into animated GIF's
$grabzIt->URLToAnimation("http://www.example.com/video.avi");
// Or to capture table(s)
$grabzIt->URLToTable("http://www.google.com");
Next is the saving.You can use one of the two save methods, Save
if publicly accessible callback handle available and SaveTo
if not. Check the documentation for details.
Perhaps something akin to:
bool is_empty(std::ifstream& pFile)
{
return pFile.peek() == std::ifstream::traits_type::eof();
}
Short and sweet.
With concerns to your error, the other answers use C-style file access, where you get a FILE*
with specific functions.
Contrarily, you and I are working with C++ streams, and as such cannot use those functions. The above code works in a simple manner: peek()
will peek at the stream and return, without removing, the next character. If it reaches the end of file, it returns eof()
. Ergo, we just peek()
at the stream and see if it's eof()
, since an empty file has nothing to peek at.
Note, this also returns true if the file never opened in the first place, which should work in your case. If you don't want that:
std::ifstream file("filename");
if (!file)
{
// file is not open
}
if (is_empty(file))
{
// file is empty
}
// file is open and not empty
I confirm that the audio isn't working as described (at least on iPad running 4.3.5). The specific issue is the audio won't load in an asynchronous method (ajax, timer event, etc) but it will play if it was preloaded. The problem is the load has to be on a user-triggered event. So if you can have a button for the user to initiate the playing you can do something like:
function initSounds() {
window.sounds = new Object();
var sound = new Audio('assets/sounds/clap.mp3');
sound.load();
window.sounds['clap.mp3'] = sound;
}
Then to play it, eg in an ajax request, you can do
function doSomething() {
$.post('testReply.php',function(data){
window.sounds['clap.mp3'].play();
});
}
Not the greatest solution, but it may help, especially knowing the culprit is the load function in a non-user-triggered event.
Edit: I found Apple's explanation, and it affects iOS 4+: http://developer.apple.com/library/safari/#documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html
Sub Addrisk()
Dim rActive As Range
Dim Count_Id_Column as long
Set rActive = ActiveCell
Application.ScreenUpdating = False
with thisworkbook.sheets(1) 'change to "sheetname" or sheetindex
for i = 1 to .range("A1045783").end(xlup).row
if 'something' = 'something' then
.range("A" & i).EntireRow.Copy 'add thisworkbook.sheets(index_of_sheet) if you copy from another sheet
.range("A" & i).entirerow.insert shift:= xldown 'insert and shift down, can also use xlup
.range("A" & i + 1).EntireRow.paste 'paste is all, all other defs are less.
'change I to move on to next row (will get + 1 end of iteration)
i = i + 1
end if
On Error Resume Next
.SpecialCells(xlCellTypeConstants).ClearContents
On Error GoTo 0
End With
next i
End With
Application.CutCopyMode = False
Application.ScreenUpdating = True 're-enable screen updates
End Sub
include
folder where you have installed
Codeblocks. int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX,
in that line.This code works well :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
var options = {};
$("#c").hide();
$("#d").hide();
$("#a").click(function(){
$("#c").toggle( "slide", options, 500 );
$("#d").hide();
});
$("#b").click(function(){
$("#d").toggle( "slide", options, 500 );
$("#c").hide();
});
});
</script>
<style>
nav{
float:left;
max-width:300px;
width:300px;
margin-top:100px;
}
article{
margin-top:100px;
height:100px;
}
#c,#d{
padding:10px;
border:1px solid olive;
margin-left:100px;
margin-top:100px;
background-color:blue;
}
button{
border:2px solid blue;
background-color:white;
color:black;
padding:10px;
}
</style>
</head>
<body>
<header>
<center>hi</center>
</header>
<nav>
<button id="a">Register 1</button>
<br>
<br>
<br>
<br>
<button id="b">Register 2</button>
</nav>
<article id="c">
<form>
<label>User name:</label>
<input type="text" name="123" value="something"/>
<br>
<br>
<label>Password:</label>
<input type="text" name="456" value="something"/>
</form>
</article>
<article id="d">
<p>Hi</p>
</article>
</body>
</html>
Reference:W3schools.com and jqueryui.com
Note:This is a example code don't forget to add all the script tags in order to achieve proper functioning of the code.
A couple of things:
new
as a variable name, it's a reserved word.input
elements, you can just use the value
property directly, you don't have to go through getAttribute
. The attribute is "reflected" as a property.name
.So:
var inputs, input, newValue, i;
inputs = document.getElementsByTagName('input');
for (i=0; i<inputs.length; i++) {
input = inputs[i];
if (input.name == "ans") {
newValue = input.value;
alert(newValue);
}
}
Mark the test with the ExpectedExceptionAttribute (this is the term in NUnit or MSTest; users of other unit testing frameworks may need to translate).
Semantically there is no difference between these cases in LDAP.
This is a generic, HTML source ordered solution where:
Fixed/Second Column on Right
#wrapper {_x000D_
margin-right: 200px;_x000D_
}_x000D_
#content {_x000D_
float: left;_x000D_
width: 100%;_x000D_
background-color: powderblue;_x000D_
}_x000D_
#sidebar {_x000D_
float: right;_x000D_
width: 200px;_x000D_
margin-right: -200px;_x000D_
background-color: palevioletred;_x000D_
}_x000D_
#cleared {_x000D_
clear: both;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<div id="content">Column 1 (fluid)</div>_x000D_
<div id="sidebar">Column 2 (fixed)</div>_x000D_
<div id="cleared"></div>_x000D_
</div>
_x000D_
Fixed/Second Column on Left
#wrapper {_x000D_
margin-left: 200px;_x000D_
}_x000D_
#content {_x000D_
float: right;_x000D_
width: 100%;_x000D_
background-color: powderblue;_x000D_
}_x000D_
#sidebar {_x000D_
float: left;_x000D_
width: 200px;_x000D_
margin-left: -200px;_x000D_
background-color: palevioletred;_x000D_
}_x000D_
#cleared {_x000D_
clear: both;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<div id="content">Column 1 (fluid)</div>_x000D_
<div id="sidebar">Column 2 (fixed)</div>_x000D_
<div id="cleared"></div>_x000D_
</div>
_x000D_
Alternate solution is to use display: table-cell; which results in equal height columns.
List<string> empnames = emplist.Select(e => e.Ename).ToList();
This is an example of Projection in Linq. Followed by a ToList
to resolve the IEnumerable<string>
into a List<string>
.
Alternatively in Linq syntax (head compiled):
var empnamesEnum = from emp in emplist
select emp.Ename;
List<string> empnames = empnamesEnum.ToList();
Projection is basically representing the current type of the enumerable as a new type. You can project to anonymous types, another known type by calling constructors etc, or an enumerable of one of the properties (as in your case).
For example, you can project an enumerable of Employee
to an enumerable of Tuple<int, string>
like so:
var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));
update VersionedFields
set Value = replace(replace(value,'<iframe','<a>iframe'), '> </iframe>','</a>')
and you do it in a single pass.
This script exports rows from specified tables to the CSV format in the output window for any tables structure. Hope, the script will be helpful for you -
DECLARE
@TableName SYSNAME
, @ObjectID INT
DECLARE [tables] CURSOR READ_ONLY FAST_FORWARD LOCAL FOR
SELECT
'[' + s.name + '].[' + t.name + ']'
, t.[object_id]
FROM (
SELECT DISTINCT
t.[schema_id]
, t.[object_id]
, t.name
FROM sys.objects t WITH (NOWAIT)
JOIN sys.partitions p WITH (NOWAIT) ON p.[object_id] = t.[object_id]
WHERE p.[rows] > 0
AND t.[type] = 'U'
) t
JOIN sys.schemas s WITH (NOWAIT) ON t.[schema_id] = s.[schema_id]
WHERE t.name IN ('<your table name>')
OPEN [tables]
FETCH NEXT FROM [tables] INTO
@TableName
, @ObjectID
DECLARE
@SQLInsert NVARCHAR(MAX)
, @SQLColumns NVARCHAR(MAX)
, @SQLTinyColumns NVARCHAR(MAX)
WHILE @@FETCH_STATUS = 0 BEGIN
SELECT
@SQLInsert = ''
, @SQLColumns = ''
, @SQLTinyColumns = ''
;WITH cols AS
(
SELECT
c.name
, datetype = t.name
, c.column_id
FROM sys.columns c WITH (NOWAIT)
JOIN sys.types t WITH (NOWAIT) ON c.system_type_id = t.system_type_id AND c.user_type_id = t.user_type_id
WHERE c.[object_id] = @ObjectID
AND c.is_computed = 0
AND t.name NOT IN ('xml', 'geography', 'geometry', 'hierarchyid')
)
SELECT
@SQLTinyColumns = STUFF((
SELECT ', [' + c.name + ']'
FROM cols c
ORDER BY c.column_id
FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
, @SQLColumns = STUFF((SELECT CHAR(13) +
CASE
WHEN c.datetype = 'uniqueidentifier'
THEN ' + '';'' + ISNULL('''' + CAST([' + c.name + '] AS VARCHAR(MAX)) + '''', ''NULL'')'
WHEN c.datetype IN ('nvarchar', 'varchar', 'nchar', 'char', 'varbinary', 'binary')
THEN ' + '';'' + ISNULL('''' + CAST(REPLACE([' + c.name + '], '''', '''''''') AS NVARCHAR(MAX)) + '''', ''NULL'')'
WHEN c.datetype = 'datetime'
THEN ' + '';'' + ISNULL('''' + CONVERT(VARCHAR, [' + c.name + '], 120) + '''', ''NULL'')'
ELSE
' + '';'' + ISNULL(CAST([' + c.name + '] AS NVARCHAR(MAX)), ''NULL'')'
END
FROM cols c
ORDER BY c.column_id
FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 10, 'CHAR(13) + '''' +')
DECLARE @SQL NVARCHAR(MAX) = '
SET NOCOUNT ON;
DECLARE
@SQL NVARCHAR(MAX) = ''''
, @x INT = 1
, @count INT = (SELECT COUNT(1) FROM ' + @TableName + ')
IF EXISTS(
SELECT 1
FROM tempdb.dbo.sysobjects
WHERE ID = OBJECT_ID(''tempdb..#import'')
)
DROP TABLE #import;
SELECT ' + @SQLTinyColumns + ', ''RowNumber'' = ROW_NUMBER() OVER (ORDER BY ' + @SQLTinyColumns + ')
INTO #import
FROM ' + @TableName + '
WHILE @x < @count BEGIN
SELECT @SQL = STUFF((
SELECT ' + @SQLColumns + ' + ''''' + '
FROM #import
WHERE RowNumber BETWEEN @x AND @x + 9
FOR XML PATH, TYPE, ROOT).value(''.'', ''NVARCHAR(MAX)''), 1, 1, '''')
PRINT(@SQL)
SELECT @x = @x + 10
END'
EXEC sys.sp_executesql @SQL
FETCH NEXT FROM [tables] INTO
@TableName
, @ObjectID
END
CLOSE [tables]
DEALLOCATE [tables]
In the output window you'll get something like this (AdventureWorks.Person.Person):
1;EM;0;NULL;Ken;J;Sánchez;NULL;0;92C4279F-1207-48A3-8448-4636514EB7E2;2003-02-08 00:00:00
2;EM;0;NULL;Terri;Lee;Duffy;NULL;1;D8763459-8AA8-47CC-AFF7-C9079AF79033;2002-02-24 00:00:00
3;EM;0;NULL;Roberto;NULL;Tamburello;NULL;0;E1A2555E-0828-434B-A33B-6F38136A37DE;2001-12-05 00:00:00
4;EM;0;NULL;Rob;NULL;Walters;NULL;0;F2D7CE06-38B3-4357-805B-F4B6B71C01FF;2001-12-29 00:00:00
5;EM;0;Ms.;Gail;A;Erickson;NULL;0;F3A3F6B4-AE3B-430C-A754-9F2231BA6FEF;2002-01-30 00:00:00
6;EM;0;Mr.;Jossef;H;Goldberg;NULL;0;0DEA28FD-EFFE-482A-AFD3-B7E8F199D56F;2002-02-17 00:00:00
With the command:
sudo apt-get remove --purge mysql\*
you can delete anything related to packages named mysql. Those commands are only valid on debian / debian-based linux distributions (Ubuntu for example).
You can list all installed mysql packages with the command:
sudo dpkg -l | grep -i mysql
For more cleanup of the package cache, you can use the command:
sudo apt-get clean
Also, remember to use the command:
sudo updatedb
Otherwise the "locate" command will display old data.
To install mysql again, use the following command:
sudo apt-get install libmysqlclient-dev mysql-client
This will install the mysql client, libmysql and its headers files.
To install the mysql server, use the command:
sudo apt-get install mysql-server
HTML:
<div class="form-group">
<label for="pt_date" class="col-2 col-form-label">Date</label>
<input class="form-control" type="date" value=<?php echo date("Y-m-d") ;?> id="pt_date" name="pt_date">
</div>
SQL
$pt_date = $_POST['pt_date'];
$sql = "INSERT INTO `table` ( `pt_date`) VALUES ( '$pt_date')";
If node-soap
doesn't work for you, just use node
request
module and then convert the xml to json if needed.
My request wasn't working with node-soap
and there is no support for that module beyond the paid support, which was beyond my resources. So i did the following:
curl http://192.168.0.28:10005/MainService/WindowsService?wsdl > wsdl_file.xml
File > New Soap project
and uploaded my wsdl_file.xml
.Show Request Editor
.From there I could send a request and make sure it worked and I could also use the Raw
or HTML
data to help me build an external request.
Raw from SoapUI for my request
POST http://192.168.0.28:10005/MainService/WindowsService HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: text/xml;charset=UTF-8
SOAPAction: "http://Main.Service/AUserService/GetUsers"
Content-Length: 303
Host: 192.168.0.28:10005
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
XML from SoapUI
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:qtre="http://Main.Service">
<soapenv:Header/>
<soapenv:Body>
<qtre:GetUsers>
<qtre:sSearchText></qtre:sSearchText>
</qtre:GetUsers>
</soapenv:Body>
</soapenv:Envelope>
I used the above to build the following node
request
:
var request = require('request');
let xml =
`<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:qtre="http://Main.Service">
<soapenv:Header/>
<soapenv:Body>
<qtre:GetUsers>
<qtre:sSearchText></qtre:sSearchText>
</qtre:GetUsers>
</soapenv:Body>
</soapenv:Envelope>`
var options = {
url: 'http://192.168.0.28:10005/MainService/WindowsService?wsdl',
method: 'POST',
body: xml,
headers: {
'Content-Type':'text/xml;charset=utf-8',
'Accept-Encoding': 'gzip,deflate',
'Content-Length':xml.length,
'SOAPAction':"http://Main.Service/AUserService/GetUsers"
}
};
let callback = (error, response, body) => {
if (!error && response.statusCode == 200) {
console.log('Raw result', body);
var xml2js = require('xml2js');
var parser = new xml2js.Parser({explicitArray: false, trim: true});
parser.parseString(body, (err, result) => {
console.log('JSON result', result);
});
};
console.log('E', response.statusCode, response.statusMessage);
};
request(options, callback);