If you want to use LinearLayout, you can do alignment with layout_weight
with Space
element.
E.g. following layout places textView
and textView2
next to each other and textView3
will be right-aligned
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@+id/textView2" />
<Space
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@+id/textView3" />
</LinearLayout>
you can achieve the same effect without Space
if you would set layout_weight
to textView2
. It's just that I like things more separated, plus to demonstrate Space
element.
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@+id/textView2" />
Note that you should (not must though) set layout_width
explicitly as it will be recalculated according to it's weight anyway (same way you should set height in elements of vertical LinearLayout
). For other layout performance tips see Android Layout Tricks series.
I found some useful information in a forum page, quoted below.
From this, mainly the sentences in bold formatting, my answer is:
Make a bash (shell) script version of your .bat file (like other
answers, with \
changed to /
in file paths). For example:
# File "example.command":
#!/bin/bash
java -cp ".;./supportlibraries/Framework_Core.jar; ...etc.
Then rename it to have the Mac OS file extension .command
.
That should make the script run using the Terminal app.
If the app user is going to use a bash script version of the file on Linux
or run it from the command line, they need to add executable rights
(change mode bits) using this command, in the folder that has the file:
chmod +rx [filename].sh
#or:# chmod +rx [filename].command
The forum page question:
Good day, [...] I wondering if there are some "simple" rules to write an equivalent
of the Windows (DOS) bat file. I would like just to click on a file and let it run.
Info from some answers after the question:
Write a shell script, and give it the extension ".command". For example:
#!/bin/bash printf "Hello World\n"
- Mar 23, 2010, Tony T1.
The DOS .BAT file was an attempt to bring to MS-DOS something like the idea of the UNIX script.
In general, UNIX permits you to make a text file with commands in it and run it by simply flagging
the text file as executable (rather than give it a specific suffix). This is how OS X does it.However, OS X adds the feature that if you give the file the suffix
.command
, Finder
will run Terminal.app to execute it (similar to how BAT files work in Windows).Unlike MS-DOS, however, UNIX (and OS X) permits you to specify what interpreter is used
for the script. An interpreter is a program that reads in text from a file and does something
with it. [...] In UNIX, you can specify which interpreter to use by making the first line in the
text file one that begins with "#!" followed by the path to the interpreter. For example [...]#!/bin/sh echo Hello World
- Mar 23, 2010, J D McIninch.
Also, info from an accepted answer for Equivalent of double-clickable .sh and .bat on Mac?:
On mac, there is a specific extension for executing shell
scripts by double clicking them: this is.command
.
I had the same issue and I used this function to compress individual pages which results in the file size being compressed by upto 1/3 of the original size.
for (int i = 1; i <= theDoc.PageCount; i++)
{
theDoc.PageNumber = i;
theDoc.Flatten();
}
For anyone needs to change the options of the menu dynamically:
private Menu menu;
// ...
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
this.menu = menu;
getMenuInflater().inflate(R.menu.options, menu);
return true;
}
// ...
private void hideOption(int id)
{
MenuItem item = menu.findItem(id);
item.setVisible(false);
}
private void showOption(int id)
{
MenuItem item = menu.findItem(id);
item.setVisible(true);
}
private void setOptionTitle(int id, String title)
{
MenuItem item = menu.findItem(id);
item.setTitle(title);
}
private void setOptionIcon(int id, int iconRes)
{
MenuItem item = menu.findItem(id);
item.setIcon(iconRes);
}
If id
is the first key in the array, this'll do:
$ids = array_map('current', $users);
You should not necessarily rely on this though. :)
With Pandas version 0.17, you can set 'keep = False' in the duplicated function to get all the duplicate items.
In [1]: import pandas as pd
In [2]: df = pd.DataFrame(['a','b','c','d','a','b'])
In [3]: df
Out[3]:
0
0 a
1 b
2 c
3 d
4 a
5 b
In [4]: df[df.duplicated(keep=False)]
Out[4]:
0
0 a
1 b
4 a
5 b
You can do it with pseudo-elements: (demo on dabblet.com)
your markup:
<div class="parent">
<div class="child"> Hello I am child </div>
</div>
css:
.parent{
position: relative;
}
.parent:before {
z-index: -1;
content: '';
position: absolute;
opacity: 0.2;
width: 400px;
height: 200px;
background: url('http://img42.imageshack.us/img42/1893/96c75664f7e94f9198ad113.png') no-repeat 0 0;
}
.child{
Color:black;
}
Unless you really want to keep the dictionary, I think the best solution is to use the csv
Python module to read the file.
Then, you get rows of data and you can change member_phone
or whatever you want ;
finally, you can use the csv
module again to save the file in the same format
as you opened it.
Code for reading:
import csv
with open("my_input_file.txt", "r") as f:
reader = csv.reader(f, delimiter=":")
lines = list(reader)
Code for writing:
with open("my_output_file.txt", "w") as f:
writer = csv.writer(f, delimiter=":")
writer.writerows(lines)
Of course, you need to adapt your change()
function:
def change(lines):
a = input('ID')
for line in lines:
if line[0] == a:
d=str(input("phone"))
line[3]=d
break
else:
print "not"
If you want more datesource configs e.g.
spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis=30000
spring.datasource.validation-query=select 1
you could use below code
@Bean
public DataSource dataSource() {
DataSource dataSource = new DataSource(); // org.apache.tomcat.jdbc.pool.DataSource;
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setTestWhileIdle(testWhileIdle);
dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMills);
dataSource.setValidationQuery(validationQuery);
return dataSource;
}
refer: Spring boot jdbc Connection
Any script tags posted on an ASP.NET web form will cause your site to throw and unhandled exception.
You can use a asp regex validator to confirm input, just ensure you wrap your code behind method with a if(IsValid) clause in case your javascript is bypassed. If your client javascript is bypassed and script tags are posted to your asp.net form, asp.net will throw a unhandled exception.
You can use something like:
<asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbEmail" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>
publish date: 06/26/2018
https://docs.microsoft.com/en-us/dotnet/framework/network-programming/how-to-upload-files-with-ftp
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main ()
{
// Get the object used to communicate with the server.
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("anonymous",
"[email protected]");
// Copy the contents of the file to the request stream.
byte[] fileContents;
using (StreamReader sourceStream = new StreamReader("testfile.txt"))
{
fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
}
request.ContentLength = fileContents.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
Console.WriteLine($"Upload File Complete, status
{response.StatusDescription}");
}
}
}
}
if you want to change the only icon of radio button then you can only add android:button="@drawable/ic_launcher"
to your radio button and for making sensitive on click then you have to use the selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/image_what_you_want_on_select_state" android:state_checked="true"/>
<item android:drawable="@drawable/image_what_you_want_on_un_select_state" android:state_checked="false"/>
</selector>
and set to your radio android:background="@drawable/name_of_selector"
Without JS, I am doing it like this:
My HTML:
<div class="container">
<div class="sometext">Some text here</div>
<div class="someothertext">Some other text here</div>
<a href="#" class="mylink">text of my link</a>
</div>
My CSS:
.container{
position: relative;
}
.container.a{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
text-indent: -9999px; //these two lines are to hide my actual link text.
overflow: hidden; //these two lines are to hide my actual link text.
}
I made an extension so now I can just load a collection with a list by doing:
MyObservableCollection.Load(MyList);
The extension is:
public static class ObservableCollectionExtension
{
public static ObservableCollection<T> Load<T>(this ObservableCollection<T> Collection, List<T> Source)
{
Collection.Clear();
Source.ForEach(x => Collection.Add(x));
return Collection;
}
}
According to HTML living standard specification, the load
event is
Fired at the Window when the document has finished loading; fired at an element containing a resource (e.g. img, embed) when its resource has finished loading
I.e. load
event is not fired on document
object.
Credit: Why does document.addEventListener(‘load’, handler) not work?
You can use setattr
name = 'varname'
value = 'something'
setattr(self, name, value) #equivalent to: self.varname= 'something'
print (self.varname)
#will print 'something'
But, since you should inform an object to receive the new variable, this only works inside classes or modules.
To get the list of stashes that are still in your repository, but not reachable any more:
git fsck --unreachable | grep commit | cut -d" " -f3 | xargs git log --merges --no-walk --grep=WIP
If you gave a title to your stash, replace "WIP" in -grep=WIP
at the end of the command with a part of your message, e.g. -grep=Tesselation
.
The command is grepping for "WIP" because the default commit message for a stash is in the form WIP on mybranch: [previous-commit-hash] Message of the previous commit.
$('#OvernightOnshore').click(function () {
if ($('#OvernightOnshore').prop("checked") == true) {
if ($('#OvernightOffshore').prop("checked") == true) {
$('#OvernightOffshore').attr('checked', false)
}
}
})
$('#OvernightOffshore').click(function () {
if ($('#OvernightOffshore').prop("checked") == true) {
if ($('#OvernightOnshore').prop("checked") == true) {
$('#OvernightOnshore').attr('checked', false);
}
}
})
This above code snippet will allow you to use checkboxes over radio buttons, but have the same functionality of radio buttons where you can only have one selected.
Use this
var theForm = document.forms['formname']
[].slice.call(theForm).forEach(function (el, i) {
console.log(el.value);
});
The el stands for the particular form element. It is better to use this than the foreach loop, as the foreach loop also returns a function as one of the element. However this only returns the DOM elements of the form.
normaly when selenium open a new page from a click or submit or get methods, it will wait untell the page is loaded but the probleme is when the page have a xhr call (ajax) he will never wait of the xhr to be loaded, so creating a new methode to monitor a xhr and wait for them it will be the good.
public boolean waitForJSandJQueryToLoad() {
WebDriverWait wait = new WebDriverWait(webDriver, 30);
// wait for jQuery to load
ExpectedCondition<Boolean> jQueryLoad = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
try {
Long r = (Long)((JavascriptExecutor)driver).executeScript("return $.active");
return r == 0;
} catch (Exception e) {
LOG.info("no jquery present");
return true;
}
}
};
// wait for Javascript to load
ExpectedCondition<Boolean> jsLoad = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript("return document.readyState")
.toString().equals("complete");
}
};
return wait.until(jQueryLoad) && wait.until(jsLoad);
}
if $.active == 0
so the is no active xhrs call (that work only with jQuery).
for javascript ajax call you have to create a variable in your project and simulate it.
If it's a deeper key/value you're after and you're not dealing with arrays of keys/values at each level, you could recursively search the tree:
public static String recurseKeys(JSONObject jObj, String findKey) throws JSONException {
String finalValue = "";
if (jObj == null) {
return "";
}
Iterator<String> keyItr = jObj.keys();
Map<String, String> map = new HashMap<>();
while(keyItr.hasNext()) {
String key = keyItr.next();
map.put(key, jObj.getString(key));
}
for (Map.Entry<String, String> e : (map).entrySet()) {
String key = e.getKey();
if (key.equalsIgnoreCase(findKey)) {
return jObj.getString(key);
}
// read value
Object value = jObj.get(key);
if (value instanceof JSONObject) {
finalValue = recurseKeys((JSONObject)value, findKey);
}
}
// key is not found
return finalValue;
}
Usage:
JSONObject jObj = new JSONObject(jsonString);
String extract = recurseKeys(jObj, "extract");
Using Map code from https://stackoverflow.com/a/4149555/2301224
String strOut = str.substring(0, 8) + "...";
Use chocolatey in PowerShell
choco install ruby -y
refreshenv
gem install bundler
If you already have the data "for (Parcelable currentHeadline : allHeadlines)," then why are you doing that in a separate thread?
You should poll the data in a separate thread, and when it's finished gathering it, then call your populateTables method on the UI thread:
private void populateTable() {
runOnUiThread(new Runnable(){
public void run() {
//If there are stories, add them to the table
for (Parcelable currentHeadline : allHeadlines) {
addHeadlineToTable(currentHeadline);
}
try {
dialog.dismiss();
} catch (final Exception ex) {
Log.i("---","Exception in thread");
}
}
});
}
In addition to the above answers, $
has no special meaning in javascript,it is free to be used in object naming. In jQuery, it is simply used as an alias for the jQuery object and jQuery() function.
However, you may encounter situations where you want to use it in conjunction with another JS library that also uses $, which would result a naming conflict. There is a method in JQuery just for this reason, jQuery.noConflict()
.
Here is a sample from jQuery doc's:
<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
$.noConflict();
// Code that uses other library's $ can follow here.
</script>
Alternatively, you can also use a like this
(function ($) {
// Code in which we know exactly what the meaning of $ is
} (jQuery));
In cmd
, you can do this:
copy one.txt+two.txt+three.txt four.txt
In PowerShell this would be:
cmd /c copy one.txt+two.txt+three.txt four.txt
While the PowerShell way would be to use gc, the above will be pretty fast, especially for large files. And it can be used on on non-ASCII files too using the /B
switch.
You can easily access the SQL parameters using the following approach.
$result = $qb->getQuery()->getSQL();
$param_values = '';
$col_names = '';
foreach ($result->getParameters() as $index => $param){
$param_values .= $param->getValue().',';
$col_names .= $param->getName().',';
}
//echo rtrim($param_values,',');
//echo rtrim($col_names,',');
So if you printed out the $param_values
and $col_names
, you can get the parameter values passing through the sql and respective column names.
Note : If $param
returns an array, you need to re iterate, as parameters inside IN (:?)
usually comes is as a nested array.
Meantime if you found another approach, please be kind enough to share with us :)
Thank you!
The <center>
element was deprecated because it defines the presentation of its contents — it does not describe its contents.
One method of centering is to set the margin-left
and margin-right
properties of the element to auto
, and then set the parent element’s text-align
property to center
. This guarantees that the element will be centered in all modern browsers.
The default System.Net.ServicePointManager.SecurityProtocol
in both .NET 4.0/4.5
is SecurityProtocolType.Tls|SecurityProtocolType.Ssl3
.
.NET 4.0
supports up to TLS 1.0
while .NET 4.5
supports up to TLS 1.2
However, an application targeting .NET 4.0
can still support up to TLS 1.2
if .NET 4.5
is installed in the same environment. .NET 4.5
installs on top of .NET 4.0
, replacing System.dll
.
I've verified this by observing the correct security protocol set in traffic with fiddler4
and by manually setting the enumerated values in a .NET 4.0
project:
ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 |
(SecurityProtocolType)768 | (SecurityProtocolType)3072;
Reference:
namespace System.Net
{
[System.Flags]
public enum SecurityProtocolType
{
Ssl3 = 48,
Tls = 192,
Tls11 = 768,
Tls12 = 3072,
}
}
If you attempt the hack on an environment with ONLY .NET 4.0
installed, you will get the exception:
Unhandled Exception: System.NotSupportedException: The requested security protocol is not supported. at System.Net.ServicePointManager.set_SecurityProtocol(SecurityProtocolType v alue)
However, I wouldn't recommend this "hack" since a future patch, etc. may break it.*
Therefore, I've decided the best route to remove support for SSLv3
is to:
.NET 4.5
Add the following to boostrapping code to override the default and future proof it:
System.Net.ServicePointManager.SecurityProtocol =
SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
*Someone correct me if this hack is wrong, but initial tests I see it works
Tell PDO your charset
initially.... something like
PDO("mysql:host=$host;dbname=$DB_name;charset=utf8;", $username, $password);
Notice the: charset=utf8;
part.
hope it helps!
The first preserves the original stack trace of the exception, the second one replaces it with the current location.
Therefore the first is BY FAR the better.
In eclipse click on window>show view>console. Thats it. You are set to use console. Happy codding.
There is a way to do key listeners in python. This functionality is available through pynput.
Command line:
$ pip install pynput
Python code:
from pynput import keyboard
# your code here
Do the build job on Jenkins first without Sonar configured. Then add Sonar, and run a build job again. Should fix the problem
There is a way to get count of runes without any packages by converting string to []rune as len([]rune(YOUR_STRING))
:
package main
import "fmt"
func main() {
russian := "??????? ? ??????"
english := "Sputnik & pogrom"
fmt.Println("count of bytes:",
len(russian),
len(english))
fmt.Println("count of runes:",
len([]rune(russian)),
len([]rune(english)))
}
count of bytes 30 16
count of runes 16 16
Both kinds of enclosed characters are strings. One type of quote is conveniently used to enclose the other type of quote. "'"
and '"'
. The biggest difference between the types of quotes is that enclosed identifier references are substituted for inside double quotes, but not inside single quotes.
To save to a file on Windows, OSX and Linux
adb exec-out screencap -p > screen.png
To copy to clipboard on Linux use
adb exec-out screencap -p | xclip -t image/png
Although ANSI C does not have this mechanism, it is possible to use itoa() as a shortcut:
char buffer [33];
itoa (i,buffer,2);
printf ("binary: %s\n",buffer);
Here's the origin:
It is non-standard C, but K&R mentioned the implementation in the C book, so it should be quite common. It should be in stdlib.h.
I faced the same problem, and resolved it by changing the BodyStyle attribut value to "WebMessageBodyStyle.Bare" :
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetProjectWithGeocodings/{projectId}")]
GeoCod_Project GetProjectWithGeocodings(string projectId);
The returned object will no longer be wrapped.
Create 2 apps and
In /initializers/env_variables.rb
if Rails.env == 'development'
ENV['FB_APP_ID'] = "HERE"
ENV["FB_SECRET"] = "HERE"
else
ENV['FB_APP_ID'] = "HERE"
ENV["FB_SECRET"] = "HERE"
end
you could use the last-child psuedo class
table tr td:last-child {
border: none;
}
This will style the last td only. It's not fully supported yet so it may be unsuitable
yes = | head -n$(($(tput lines) * $COLUMNS)) | tr -d '\n'
If the "many" model does not justify the creation of a model per-se (not the case here, but it might benefits other people), another alternative would be to rely on specific PostgreSQL data types, via the Django Contrib package
Postgres can deal with Array or JSON data types, and this may be a nice workaround to handle One-To-Many when the many-ies can only be tied to a single entity of the one.
Postgres allows you to access single elements of the array, which means that queries can be really fast, and avoid application-level overheads. And of course, Django implements a cool API to leverage this feature.
It obviously has the disadvantage of not being portable to others database backend, but I thougt it still worth mentionning.
Hope it may help some people looking for ideas.
try this out let me know what happens.
Form:
<form action="form.php" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" value="Submit" />
</form>
Form.php:
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo 'Primary key: ' .$row['PRIMARYKEY'];
echo '<br /> Code: ' .$row['Code'];
echo '<br /> Description: '.$row['Description'];
echo '<br /> Category: '.$row['Category'];
echo '<br /> Cut Size: '.$row['CutSize'];
}
Edit: Cleaned it up a little more.
Final Cut (my test file):
<?php
$db_hostname = 'localhost';
$db_username = 'demo';
$db_password = 'demo';
$db_database = 'demo';
// Database Connection String
$con = mysql_connect($db_hostname,$db_username,$db_password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_database, $con);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" value="Submit" />
</form>
<?php
if (!empty($_REQUEST['term'])) {
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo 'Primary key: ' .$row['PRIMARYKEY'];
echo '<br /> Code: ' .$row['Code'];
echo '<br /> Description: '.$row['Description'];
echo '<br /> Category: '.$row['Category'];
echo '<br /> Cut Size: '.$row['CutSize'];
}
}
?>
</body>
</html>
See below image...
I've added --local-infile=1
to normal mysql command mysql -u root -p
So total line would be :
mysql --local-infile=1 -u root -p
If you have user specific credentials ( i.e each developer might have different username/password ) then I would recommend using the gradle-properties-plugin.
gradle.properties
gradle-local.properties
( this should be git ignored ).This is better than overriding using $USER_HOME/.gradle/gradle.properties
because different projects might have same property names.
Try using reduce
or inject
.
[1, 2, 3].reduce([]) { |memo, i|
if i % 2 == 0
memo << i
end
memo
}
I agree with the accepted answer that we shouldn't map
and compact
, but not for the same reasons.
I feel deep inside that map
then compact
is equivalent to select
then map
. Consider: map
is a one-to-one function. If you are mapping from some set of values, and you map
, then you want one value in the output set for each value in the input set. If you are having to select
before-hand, then you probably don't want a map
on the set. If you are having to select
afterwards (or compact
) then you probably don't want a map
on the set. In either case you are iterating twice over the entire set, when a reduce
only needs to go once.
Also, in English, you are trying to "reduce a set of integers into a set of even integers".
A temporary table can have 3 kinds, the #
is the most used. This is a temp table that only exists in the current session.
An equivalent of this is @
, a declared table variable. This has a little less "functions" (like indexes etc) and is also only used for the current session.
The ##
is one that is the same as the #
, however, the scope is wider, so you can use it within the same session, within other stored procedures.
You can create a temp table in various ways:
declare @table table (id int)
create table #table (id int)
create table ##table (id int)
select * into #table from xyz
EDIT: Although, this solution works, I would recommend you try MvanGeest's solution below which uses the placeholder
-attribute and a javascript fallback for browsers which don't support it yet.
If you are looking for a Mootools equivalent to the JQuery fallback in MvanGeest's reply, here is one.
--
You should probably use onfocus
and onblur
events in order to support keyboard users who tab through forms.
Here's an example:
<input type="text" value="[email protected]" name="Email" id="Email"
onblur="if (this.value == '') {this.value = '[email protected]';}"
onfocus="if (this.value == '[email protected]') {this.value = '';}" />
I have written an extended function, so the chunk length can also be an array of numbers, like [1,3]
String.prototype.chunkString = function(len) {
var _ret;
if (this.length < 1) {
return [];
}
if (typeof len === 'number' && len > 0) {
var _size = Math.ceil(this.length / len), _offset = 0;
_ret = new Array(_size);
for (var _i = 0; _i < _size; _i++) {
_ret[_i] = this.substring(_offset, _offset = _offset + len);
}
}
else if (typeof len === 'object' && len.length) {
var n = 0, l = this.length, chunk, that = this;
_ret = [];
do {
len.forEach(function(o) {
chunk = that.substring(n, n + o);
if (chunk !== '') {
_ret.push(chunk);
n += chunk.length;
}
});
if (n === 0) {
return undefined; // prevent an endless loop when len = [0]
}
} while (n < l);
}
return _ret;
};
The code
"1234567890123".chunkString([1,3])
will return:
[ '1', '234', '5', '678', '9', '012', '3' ]
Add a <version>
element after the <plugin>
<artifactId>
in your pom.xml
file. Find the following text:
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
Add the version tag to it:
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
The warning should be resolved.
Regarding this:
'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing
Many people have mentioned why the issue is happening, but fail to suggest a fix. All I needed to do was to go into my POM file for my project, and add the <version>
tag as shown above.
To discover the version number, one way is to look in Maven's output after it finishes running. Where you are missing version numbers, Maven will display its default version:
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ entities ---
Take that version number (as in the 2.3.2
above) and add it to your POM, as shown.
You can use a regular expression: window.location.href.match(/^[^\#\?]+/)[0]
I just tried with this code, and it worked for me: <link rel="icon" type="image/jpg" href="C:\Users\nrm05\Pictures\logo.jpg" />
Be sure to type type="image/jpg"
for jpg files, and type="image/png"
for PNG files. If you haven't downloaded the image, but you know the image URL, then you can type it in like this: href="image_url"
Hope this answered your question :-)
Try:
System.getProperty("os.name");
http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#getProperties%28%29
Wrap the "set" statement to mean "set if not set" and put it naked above the while loop.
You are correct, the language does not provide what you're looking for in exactly that syntax, but that's because there are programming paradigms like the one I just suggested so you don't need the syntax you are proposing.
Regular expressions might be the best tool here. If you are not famililar with them, I recommend you install Expresso - a great little regex tool.
Something like:
Regex regex = new Regex("\\((?<TextInsideBrackets>\\w+)\\)");
string incomingValue = "Username (sales)";
string insideBrackets = null;
Match match = regex.Match(incomingValue);
if(match.Success)
{
insideBrackets = match.Groups["TextInsideBrackets"].Value;
}
I think of it as a large array of binary data. The usability of BLOB follows immediately from the limited bandwidth of the DB interface, it is not determined by the DB storage mechanisms. No matter how you store the large piece of data, the only way to store and retrieve is the narrow database interface. The database is a bottleneck of the system. Why to use it as a file server, which can easily be distributed? Normally you do not want to download the BLOB. You just want the DB to store your BLOB urls. Deposite the BLOBs on a separate file server. Then, you reliefe the precious DB connection and provide unlimited bandwidth for large objects. This creates some issue of coherence though.
To extend answers above, you cannot use Guid default value with Guid.Empty
as an optional argument in method, indexer or delegate definition, because it will give you compile time error. Use default(Guid)
or new Guid()
instead.
You control how a row or column aligns its children using the mainAxisAlignment and crossAxisAlignment properties. For a row, the main axis runs horizontally and the cross axis runs vertically. For a column, the main axis runs vertically and the cross axis runs horizontally.
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
As mentioned originally in this answer by SoBeRich, and in my own answer, as of git 2.4.x
git push --atomic origin <branch name> <tag>
(Note: this actually work with HTTPS only with Git 2.24)
As of git 2.4.1, you can do
git config --global push.followTags true
If set to true enable --follow-tags option by default.
You may override this configuration at time of push by specifying --no-follow-tags.
As noted in this thread by Matt Rogers answering Wes Hurd:
--follow-tags
only pushes annotated tags.
git tag -a -m "I'm an annotation" <tagname>
That would be pushed (as opposed to git tag <tagname>
, a lightweight tag, which would not be pushed, as I mentioned here)
Since git 1.8.3 (April 22d, 2013), you no longer have to do 2 commands to push branches, and then to push tags:
The new "
--follow-tags
" option tells "git push
" to push relevant annotated tags when pushing branches out.
You can now try, when pushing new commits:
git push --follow-tags
That won't push all the local tags though, only the one referenced by commits which are pushed with the git push
.
Git 2.4.1+ (Q2 2015) will introduce the option push.followTags
: see "How to make “git push
” include tags within a branch?".
The nuclear option would be git push --mirror
, which will push all refs under refs/
.
You can also push just one tag with your current branch commit:
git push origin : v1.0.0
You can combine the --tags
option with a refspec like:
git push origin --tags :
(since --tags
means: All refs under refs/tags
are pushed, in addition to refspecs explicitly listed on the command line)
You also have this entry "Pushing branches and tags with a single "git push" invocation"
A handy tip was just posted to the Git mailing list by Zoltán Füzesi:
I use
.git/config
to solve this:
[remote "origin"]
url = ...
fetch = +refs/heads/*:refs/remotes/origin/*
push = +refs/heads/*
push = +refs/tags/*
With these lines added
git push origin
will upload all your branches and tags. If you want to upload only some of them, you can enumerate them.
Haven't tried it myself yet, but it looks like it might be useful until some other way of pushing branches and tags at the same time is added to git push.
On the other hand, I don't mind typing:
$ git push && git push --tags
Beware, as commented by Aseem Kishore
push = +refs/heads/*
will force-pushes all your branches.
This bit me just now, so FYI.
René Scheibe adds this interesting comment:
The
--follow-tags
parameter is misleading as only tags under.git/refs/tags
are considered.
Ifgit gc
is run, tags are moved from.git/refs/tags
to.git/packed-refs
. Afterwardsgit push --follow-tags ...
does not work as expected anymore.
I am just building on Abdennour TOUMI's answer. here are the reasons why:
1.) I agree with Brad, I do not think it is a good idea to extend object that we did not create.
2.) array.length
is exactly reliable in javascript, I prefer Array.reduce
beacuse a=[1,3];a[1000]=5;
, now a.length
would return 1001
.
function getAverage(arry){
// check if array
if(!(Object.prototype.toString.call(arry) === '[object Array]')){
return 0;
}
var sum = 0, count = 0;
sum = arry.reduce(function(previousValue, currentValue, index, array) {
if(isFinite(currentValue)){
count++;
return previousValue+ parseFloat(currentValue);
}
return previousValue;
}, sum);
return count ? sum / count : 0;
};
If I understood your problem correctly, $(this).parents('.box').children('.something1')
Is this what you are looking for?
How to import huge amount of Data in Xampp
It’s the best solution to open new, clean database, and import the file in phpMyAdmin. Choose file from local folder and leave all settings as is. That should be it.
But if your file exceeded file size of 2MB (that is default value in xampp installation) than you need to tweak some out. Basically we will just increase the maximum upload file size.
Open your xampp install folder and go to php folder. With some text editor file (notepad++) open the file called php.ini (by type windows describe it as configuration settings) and edit the line (cca. 770, or press ctrl+f in notepad++ to find it):
post_max_size = 2M
instead 2M, put wanted maximum file size (16MB for example but not higher than 128M),
after that go to this line: max_execution_time = 30 instead 30, increase execution time that’s in seconds (90 for example), also you need to change this line:
max_input_time = 60
instead 60, increase input time in seconds (120 for example) and top of all you have to change this line:
upload_max_filesize = 2M
instead of 2M, increase to 16M for example. Save the file, restart apache and mysql in xampp and try to upload again, if you follow correctly you should be able to import files through 16MB (example)
Swift 4
While the previous saying to prepare for segue is correct and its true the back button belongs to the previous VC, its just adding a bunch more unnecessary code.
The best thing to do is set the title of the current VC in viewDidLoad and it'll automatically set the back button title correctly on the next VC. This line worked for me
navigationController?.navigationBar.topItem?.title = "Title"
You can use filterfalse function from itertools module
Example
import random
from itertools import filterfalse
random.seed(42)
data = [random.randrange(5) for _ in range(10)]
clean = [*filterfalse(lambda i: i == 0, data)]
print(f"Remove 0s\n{data=}\n{clean=}\n")
clean = [*filterfalse(lambda i: i in (0, 1), data)]
print(f"Remove 0s and 1s\n{data=}\n{clean=}")
Output:
Remove 0s
data=[0, 0, 2, 1, 1, 1, 0, 4, 0, 4]
clean=[2, 1, 1, 1, 4, 4]
Remove 0s and 1s
data=[0, 0, 2, 1, 1, 1, 0, 4, 0, 4]
clean=[2, 4, 4]
You can find some resources related to developing web services client using Apache axis2 here.
http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html
Below posts gives good explanations about developing web services using Apache axis2.
http://www.ibm.com/developerworks/opensource/library/ws-webaxis1/
select inet_server_addr( ), inet_server_port( );
inputs[5].addEventListener('keydown', enterNumbers);
function enterNumbers(event) {
if ((event.code == 'ArrowLeft') || (event.code == 'ArrowRight') ||
(event.code == 'ArrowUp') || (event.code == 'ArrowDown') ||
(event.code == 'Delete') || (event.code == 'Backspace')) {
return;
} else if (event.key.search(/\d/) == -1) {
event.preventDefault();
}
}
in this case, the value of the input field stays intact when a non-number button is pressed, and still delete, backspace, arrowup-down-left-right work properly and can be used for modifying the digital input.
You can DROP
a unique constraint from a table using phpMyAdmin as requested as shown in the table below. A unique constraint has been placed on the Wingspan field. The name of the constraint is the same as the field name, in this instance.
HTML
<input type="checkbox" id="checkme"/><input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />
JS
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
checker.onchange = function() {
sendbtn.disabled = !!this.checked;
};
No, you cannot insert a div directly inside of a table. It is not correct html, and will result in unexpected output.
I would be happy to be more insightful, but you haven't said what you are attempting, so I can't really offer an alternative.
Check out the range
documentation, you have to define a negative step:
>>> range(10, 0, -1)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
You just rebuilt your project
compile fileTree(dir: 'libs', include: ['*.jar'])
You need convert list
to numpy array
and then reshape
:
df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
a b c
0 1 2 3
1 4 5 6
2 7 8 9
this worked for me
$ gcc dbconnect.c -o dbconnect -lmysqlclient
$ ./dbconnect
-lmysqlclient is must.
and i would personally recommend to use following notation instead of using -I compilation flag.
#include <mysql/mysql.h>
In my case, clearing caché didn't work.
On SDK Manager, be sure to check the box on "show package descriptions"; then you should also select the "Google APIs" for the version you are willing to install.
Install it and then you should be ok
Just add position:absolute; top:0; right:0;
to the CSS for your button.
#button {
line-height: 12px;
width: 18px;
font-size: 8pt;
font-family: tahoma;
margin-top: 1px;
margin-right: 2px;
position:absolute;
top:0;
right:0;
}
Most of the other solutions count duplicates. If you really need to group key value pairs, try this:
Here is my example data:
find . | xargs md5sum
fe4ab8e15432161f452e345ff30c68b0 a.txt
30c68b02161e15435ff52e34f4fe4ab8 b.txt
30c68b02161e15435ff52e34f4fe4ab8 c.txt
fe4ab8e15432161f452e345ff30c68b0 d.txt
fe4ab8e15432161f452e345ff30c68b0 e.txt
This will print the key value pairs grouped by the md5 checksum.
cat table.txt | awk '{print $1}' | sort | uniq | xargs -i grep {} table.txt
30c68b02161e15435ff52e34f4fe4ab8 b.txt
30c68b02161e15435ff52e34f4fe4ab8 c.txt
fe4ab8e15432161f452e345ff30c68b0 a.txt
fe4ab8e15432161f452e345ff30c68b0 d.txt
fe4ab8e15432161f452e345ff30c68b0 e.txt
As long and your input
and label
elements are associated by their id
and for
attributes, you should be able to do something like this:
$('.input').each(function() {
$this = $(this);
$label = $('label[for="'+ $this.attr('id') +'"]');
if ($label.length > 0 ) {
//this input has a label associated with it, lets do something!
}
});
If for
is not set then the elements have no semantic relation to each other anyway, and there is no benefit to using the label tag in that instance, so hopefully you will always have that relationship defined.
UPDATED
DEMO: http://jsbin.com/uneti3/3
your code is wrong, it should be something like this:
$(bla).click(function() {
var disable = $target.toggleClass('open').hasClass('open');
$target.prev().prop("disabled", disable);
});
you are using the toggleClass function in wrong way
Here's how you would do it in Kotlin
fun <T> myMethod(item: T) where T : ClassA, T : InterfaceB {
//your code here
}
Reason for this is explained in the Inheritance article of the Java Platform which says:
"A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass."
I was going through the textbook:Computer System: a programmer's perspective, and there is a problem to determine which endian is this by C program.
I used the feature of the pointer to do that as following:
#include <stdio.h>
int main(void){
int i=1;
unsigned char* ii = &i;
printf("This computer is %s endian.\n", ((ii[0]==1) ? "little" : "big"));
return 0;
}
As the int takes up 4 bytes, and char takes up only 1 bytes. We could use a char pointer to point to the int with value 1. Thus if the computer is little endian, the char that char pointer points to is with value 1, otherwise, its value should be 0.
In python there is no difference between modules and scripts; You can execute both scripts and modules. The file must be on the pythonpath AFAIK because python must be able to find the file in question. If python is executed from a directory, then the directory is automatically added to the pythonpath.
Refer to What is the best way to call a Python script from another Python script? for more information about modules vs scripts
There is also a builtin function execfile(filename) that will do what you want
You can Change the speed by adding scrolldelay
<marquee style="font-family: lato; color: #FFFFFF" bgcolor="#00224f" scrolldelay="400">Now the Speed is Delay to 400 Milliseconds</marquee>
_x000D_
Adding another version based on example above by @ricky89 and @mklement0 with few improvements:
Script to process:
LF-to-CRLF.ps1:
# get current dir
$currentDirectory = Split-Path $MyInvocation.MyCommand.Path -Parent
# create subdir CR-to-CRLF for new files
$outDir = $(Join-Path $currentDirectory "CR-to-CRLF")
New-Item -ItemType Directory -Force -Path $outDir | Out-Null
# get all .txt files
Get-ChildItem $currentDirectory -Force | Where-Object {$_.extension -eq ".txt"} | ForEach-Object {
$file = New-Object System.IO.StreamReader -Arg $_.FullName
# Resulting file will be in CR-to-CRLF subdir
$outstream = [System.IO.StreamWriter] $(Join-Path $outDir $($_.BaseName + $_.Extension))
$count = 0
# read line by line, replace CR with CRLF in each by saving it with $outstream.WriteLine
while ($line = $file.ReadLine()) {
$count += 1
$outstream.WriteLine($line)
}
$file.close()
$outstream.close()
Write-Host ("$_`: " + $count + ' lines processed.')
}
Try this:
$fruits = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );_x000D_
echo reset($fruits)."\n";
_x000D_
char c = '5'
A char
(1 byte) is allocated on stack at address 0x12345678
.
char *d = &c;
You obtain the address of c
and store it in d
, so d = 0x12345678
.
int *e = (int*)d;
You force the compiler to assume that 0x12345678
points to an int
, but an int is not just one byte (sizeof(char) != sizeof(int)
). It may be 4 or 8 bytes according to the architecture or even other values.
So when you print the value of the pointer, the integer is considered by taking the first byte (that was c
) and other consecutive bytes which are on stack and that are just garbage for your intent.
And it's maybe also handy to know that BigTable is not a relational database (like MySQL) but a huge (distributed) hash table which has very different characteristics. You can play around with (a limited version) of BigTable yourself on the Google AppEngine platform.
Next to Hadoop mentioned above there are many other implementations that try to solve the same problems as BigTable (scalability, availability). I saw a nice blog post yesterday listing most of them here.
If the list is in random order, you can just take the first 50.
Otherwise, use
import random
random.sample(the_list, 50)
random.sample
help text:
sample(self, population, k) method of random.Random instance
Chooses k unique random elements from a population sequence.
Returns a new list containing elements from the population while
leaving the original population unchanged. The resulting list is
in selection order so that all sub-slices will also be valid random
samples. This allows raffle winners (the sample) to be partitioned
into grand prize and second place winners (the subslices).
Members of the population need not be hashable or unique. If the
population contains repeats, then each occurrence is a possible
selection in the sample.
To choose a sample in a range of integers, use xrange as an argument.
This is especially fast and space efficient for sampling from a
large population: sample(xrange(10000000), 60)
If you need a custom string sort, you can create a function that returns a number based on the order you specify.
For example, I had pictures that I wanted to sort based on being front side or clasp. So I did the following:
Private Function sortpictures(s As String) As Integer
If Regex.IsMatch(s, "FRONT") Then
Return 0
ElseIf Regex.IsMatch(s, "SIDE") Then
Return 1
ElseIf Regex.IsMatch(s, "CLASP") Then
Return 2
Else
Return 3
End If
End Function
Then I call the sort function like this:
list.Sort(Function(elA As String, elB As String)
Return sortpictures(elA).CompareTo(sortpictures(elB))
End Function)
Use a no-break space directly
(not the same as !).
(You could insert HTML or some esoteric markdown code, but I can think of better reasons to break compatibility with standard markdown.)
If you are working with SourceTree, this will help you.
Right click on the commit then select "Reset (current branch)/master to this commit" and last select "Soft" reset.
Here is my solution. It replicates the behavior of var_dump
well, and allows for nested objects/arrays. Note that it does not support multiple arguments.
function var_dump(variable) {
let out = "";
let type = typeof variable;
if(type == "object") {
var realType;
var length;
if(variable instanceof Array) {
realType = "array";
length = variable.length;
} else {
realType = "object";
length = Object.keys(variable).length;
}
out = `${realType}(${length}) {`;
for (const [key, value] of Object.entries(variable)) {
out += `\n [${key}]=>\n ${var_dump(value).replace(/\n/g, "\n ")}\n`;
}
out += "}";
} else if(type == "string") {
out = `${type}(${type.length}) "${variable}"`;
} else {
out = `${type}(${variable.toString()})`;
}
return out;
}
console.log(var_dump(1.5));
console.log(var_dump("Hello!"));
console.log(var_dump([]));
console.log(var_dump([1,2,3,[1,2]]));
console.log(var_dump({"a":"b"}));
_x000D_
import MySQLdb
class Database:
host = 'localhost'
user = 'root'
password = '123'
db = 'test'
def __init__(self):
self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
self.cursor = self.connection.cursor()
def insert(self, query):
try:
self.cursor.execute(query)
self.connection.commit()
except:
self.connection.rollback()
def query(self, query):
cursor = self.connection.cursor( MySQLdb.cursors.DictCursor )
cursor.execute(query)
return cursor.fetchall()
def __del__(self):
self.connection.close()
if __name__ == "__main__":
db = Database()
#CleanUp Operation
del_query = "DELETE FROM basic_python_database"
db.insert(del_query)
# Data Insert into the table
query = """
INSERT INTO basic_python_database
(`name`, `age`)
VALUES
('Mike', 21),
('Michael', 21),
('Imran', 21)
"""
# db.query(query)
db.insert(query)
# Data retrieved from the table
select_query = """
SELECT * FROM basic_python_database
WHERE age = 21
"""
people = db.query(select_query)
for person in people:
print "Found %s " % person['name']
You need to specify an access modifier for your variable. In this case you want it public.
public class Variables
{
public static string name = "";
}
After this you can use the variable like this.
Variables.name
You have two ways to fix this. The preferred way is to use:
string answer;
(instead of char
). The other possible way to fix it is:
if (answer == 'y') ...
(note single quotes instead of double, representing a char
constant).
form_for @user, :url => url_for(:controller => 'mycontroller', :action => 'myaction')
or
form_for @user, :url => whatever_path
It allows servlets to have multiple servlet mappings:
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/bill</url-pattern>
</servlet-mapping>
It allows filters to be mapped on the particular servlet:
<filter-mapping>
<filter-name>Filter1</filter-name>
<servlet-name>Servlet1</servlet-name>
</filter-mapping>
Your proposal would support neither of them. Note that the web.xml
is read and parsed only once during application's startup, not on every HTTP request as you seem to think.
Since Servlet 3.0, there's the @WebServlet
annotation which minimizes this boilerplate:
@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {
Using Blob
as a source for an img
:
template:
<img [src]="url">
component:
public url : SafeResourceUrl;
constructor(private http: HttpClient, private sanitizer: DomSanitizer) {
this.getImage('/api/image.jpg').subscribe(x => this.url = x)
}
public getImage(url: string): Observable<SafeResourceUrl> {
return this.http
.get(url, { responseType: 'blob' })
.pipe(
map(x => {
const urlToBlob = window.URL.createObjectURL(x) // get a URL for the blob
return this.sanitizer.bypassSecurityTrustResourceUrl(urlToBlob); // tell Anuglar to trust this value
}),
);
}
Further reference about trusting save values
First include the file in head tag of html , then call the function in script tags under body tags e.g.
Js file function to be called
function tryMe(arg) {
document.write(arg);
}
HTML FILE
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src='object.js'> </script>
<title>abc</title><meta charset="utf-8"/>
</head>
<body>
<script>
tryMe('This is me vishal bhasin signing in');
</script>
</body>
</html>
finish
if(values >= 0) {
// as zero is more likely positive than negative
} else {
}
There is nothing wrong with the example you have given. But i must say i believe it's not efficient to store function definitions in a cpp file. I only understand the need to separate the function's declaration and definition.
When used together with explicit class instantiation, the Boost Concept Check Library (BCCL) can help you generate template function code in cpp files.
this works June 2018, even after the HTTPS requirement. It appears a test app does not require https:
create a test app: https://developers.facebook.com/docs/apps/test-apps/
then within the test app, follow the simple steps in this video: https://www.youtube.com/watch?v=7DuRvf7Jtkg
Your query ($myQuery) is failing and therefore not producing a query resource, but instead producing FALSE.
To reveal what your dynamically generated query looks like and reveal the errors, try this:
$result2 = mysql_query($myQuery) or die($myQuery."<br/><br/>".mysql_error());
The error message will guide you to the solution, which from your comment below is related to using ORDER BY on a field that doesn't exist in the table you're SELECTing from.
Here using Hive warehouse dir you can export data instead of Hive table. first give hive warehouse path and after local path where you want to store the .csv file For this command is bellow :-
hadoop fs -cat /user/hdusr/warehouse/HiveDb/tableName/* > /users/hadoop/test/nilesh/sample.csv
You could make use of the Javascript DOM API. In particular, look at the createElement() method.
You could create a re-usable function that will create an image like so...
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
// This next line will just add it to the <body> tag
document.body.appendChild(img);
}
Then you could use it like this...
<button onclick=
"show_image('http://google.com/images/logo.gif',
276,
110,
'Google Logo');">Add Google Logo</button>
If you want to do it in java code just use this line to disable it:
editText.setEnabled(false);
And this to enable it:
editText.setEnabled(true);
With Swift you don't need anymore to check the equality with isEqualToString
You can now use ==
Example:
let x = "hello"
let y = "hello"
let isEqual = (x == y)
now isEqual is true
.
To answer the question in your subject line,* yes, there are closures in Python, except they only apply inside a function, and also (in Python 2.x) they are read-only; you can't re-bind the name to a different object (though if the object is mutable, you can modify its contents). In Python 3.x, you can use the nonlocal
keyword to modify a closure variable.
def incrementer():
counter = 0
def increment():
nonlocal counter
counter += 1
return counter
return increment
increment = incrementer()
increment() # 1
increment() # 2
* The question origially asked about closures in Python.
Clean, safe solution in pure standard C:
#include <stdio.h>
#define STRF(x) #x
#define STRINGIFY(x) STRF(x)
/* list of enum constants */
#define TEST_0 hello
#define TEST_1 world
typedef enum
{
TEST_0,
TEST_1,
TEST_N
} test_t;
const char* test_str[]=
{
STRINGIFY(TEST_0),
STRINGIFY(TEST_1),
};
int main()
{
_Static_assert(sizeof test_str / sizeof *test_str == TEST_N,
"Incorrect number of items in enum or look-up table");
printf("%d %s\n", hello, test_str[hello]);
printf("%d %s\n", world, test_str[world]);
test_t x = world;
printf("%d %s\n", x, test_str[x]);
return 0;
}
Output
0 hello
1 world
1 world
Rationale
When solving the core problem "have enum constants with corresponding strings", a sensible programmer will come up with the following requirements:
The first requirement, and maybe also the second, can be fulfilled with various messy macro solutions such as the infamous "x macro" trick, or other forms of macro magic. The problem with such solutions is that they leave you with a completely unreadable mess of mysterious macros - they don't meet the third requirement above.
The only thing needed here is actually to have a string look-up table, which we can access by using the enum variable as index. Such a table must naturally correspond directly to the enum and vice versa. When one of them is updated, the other has to be updated too, or it will not work.
Explanation of the code
Suppose we have an enum like
typedef enum
{
hello,
world
} test_t;
This can be changed to
#define TEST_0 hello
#define TEST_1 world
typedef enum
{
TEST_0,
TEST_1,
} test_t;
With the advantage that these macro constants can now be used elsewhere, to for example generate a string look-up table. Converting a pre-processor constant to a string can be done with a "stringify" macro:
#define STRF(x) #x
#define STRINGIFY(x) STRF(x)
const char* test_str[]=
{
STRINGIFY(TEST_0),
STRINGIFY(TEST_1),
};
And that's it. By using hello
, we get the enum constant with value 0. By using test_str[hello]
we get the string "hello".
To make the enum and look-up table correspond directly, we have to ensure that they contain the very same amount of items. If someone would maintain the code and only change the enum, and not the look-up table, or vice versa, this method won't work.
The solution is to have the enum to tell you how many items it contains. There is a commonly-used C trick for this, simply add an item at the end, which only fills the purpose of telling how many items the enum has:
typedef enum
{
TEST_0,
TEST_1,
TEST_N // will have value 2, there are 2 enum constants in this enum
} test_t;
Now we can check at compile time that the number of items in the enum is as many as the number of items in the look-up table, preferably with a C11 static assert:
_Static_assert(sizeof test_str / sizeof *test_str == TEST_N,
"Incorrect number of items in enum or look-up table");
(There are ugly but fully-functional ways to create static asserts in older versions of the C standard too, if someone insists on using dinosaur compilers. As for C++, it supports static asserts too.)
As a side note, in C11 we can also achieve higher type safety by changing the stringify macro:
#define STRINGIFY(x) _Generic((x), int : STRF(x))
(int
because enumeration constants are actually of type int
, not test_t
)
This will prevent code like STRINGIFY(random_stuff)
from compiling.
Just setting json
option to true
, the body will contain the parsed json:
request({
url: 'http://...',
json: true
}, function(error, response, body) {
console.log(body);
});
You have to look to official ReactiveX documentation: https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md.
This is a good article about piping in RxJS: https://blog.hackages.io/rxjs-5-5-piping-all-the-things-9d469d1b3f44.
In short .pipe() allows chaining multiple pipeable operators.
Starting in version 5.5 RxJS has shipped "pipeable operators" and renamed some operators:
do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize
You need to use Arrow function ()=>
ES6 feature to preserve this
context within setTimeout
.
// var that = this; // no need of this line
this.messageSuccess = true;
setTimeout(()=>{ //<<<---using ()=> syntax
this.messageSuccess = false;
}, 3000);
The first case will fail when JS is off. It's also a little bit slower since JS must be parsed first (DOM must be loaded). However JS is safer since the destination doesn't know the referer and your redirect might be tracked (referers aren't reliable in general yet this is something).
You can also use meta refresh tag. It also requires DOM to be loaded.
This may be useful for who want to use dateformater.dateformat
;
if you want 12.09.18
you use dateformater.dateformat = "dd.MM.yy"
Wednesday, Sep 12, 2018 --> EEEE, MMM d, yyyy
09/12/2018 --> MM/dd/yyyy
09-12-2018 14:11 --> MM-dd-yyyy HH:mm
Sep 12, 2:11 PM --> MMM d, h:mm a
September 2018 --> MMMM yyyy
Sep 12, 2018 --> MMM d, yyyy
Wed, 12 Sep 2018 14:11:54 +0000 --> E, d MMM yyyy HH:mm:ss Z
2018-09-12T14:11:54+0000 --> yyyy-MM-dd'T'HH:mm:ssZ
12.09.18 --> dd.MM.yy
10:41:02.112 --> HH:mm:ss.SSS
Do this:
First, yy to copy the current line, and then p to paste.
The proper way is to do a Time.now.getutc.to_i
to get the proper timestamp amount as simply displaying the integer need not always be same as the utc timestamp due to time zone differences.
I had the error:
An invalid form control with name='telefono' is not focusable.
This was happening because I was not using the required field correctly, which enabled and disabled when clicking on a checkbok. The solution was to remove the required
attribute whenever the checkbok was not marked and mark it as required when the checkbox was marked.
var telefono = document.getElementById("telefono");
telefono.removeAttribute("required");
In SQL you may only use table type which is defined at schema level (not at package or procedure level), and index-by table (associative array) cannot be defined at schema level. So - you have to define nested table like this
create type exch_row as object (
currency_cd VARCHAR2(9),
exch_rt_eur NUMBER,
exch_rt_usd NUMBER);
create type exch_tbl as table of exch_row;
And then you can use it in SQL with TABLE operator, for example:
declare
l_row exch_row;
exch_rt exch_tbl;
begin
l_row := exch_row('PLN', 100, 100);
exch_rt := exch_tbl(l_row);
for r in (select i.*
from item i, TABLE(exch_rt) rt
where i.currency = rt.currency_cd) loop
-- your code here
end loop;
end;
/
Artisan comes with Laravel by default, if your php
command works fine, then the only thing you need to do is to navigate to the project's root folder. The root folder is the parent folder of the app
folder. For example:
cd c:\Program Files\xampp\htdocs\your-project-name
Now the php artisan list
command should work fine, because PHP runs the file called artisan
in the project's folder.
Keep in mind that Artisan runs scripts stored in the vendor
folder, so if you installed Laravel without Composer, like downloading and extracting the Laravel GitHub repo, then you don't have the framework itself and you may get the following error when you try to use Artisan:
Could not open input file: artisan
To solve this you have to install the framework itself by running composer install
in your project's root folder.
As we read in this answer, HTML5 will solve this for you if you're open to that route. HTML5 audio is supported in all modern browsers.
Here's a copy of the example:
var snd = new Audio("file.wav"); // buffers automatically when created
snd.play();
On the side note, here is how the various plyr
functions correspond to the base *apply
functions (from the intro to plyr document from the plyr webpage http://had.co.nz/plyr/)
Base function Input Output plyr function
---------------------------------------
aggregate d d ddply + colwise
apply a a/l aaply / alply
by d l dlply
lapply l l llply
mapply a a/l maply / mlply
replicate r a/l raply / rlply
sapply l a laply
One of the goals of plyr
is to provide consistent naming conventions for each of the functions, encoding the input and output data types in the function name. It also provides consistency in output, in that output from dlply()
is easily passable to ldply()
to produce useful output, etc.
Conceptually, learning plyr
is no more difficult than understanding the base *apply
functions.
plyr
and reshape
functions have replaced almost all of these functions in my every day use. But, also from the Intro to Plyr document:
Related functions
tapply
andsweep
have no corresponding function inplyr
, and remain useful.merge
is useful for combining summaries with the original data.
Most of the editors take some kind of shortcut to comment out blocks of code. The default editors use something like command or control and single quote to comment out selected lines of code. In RStudio it's Command or Control+/. Check in your editor.
It's still commenting line by line, but they also uncomment selected lines as well. For the Mac RGUI it's command-option ' (I'm imagining windows is control option). For Rstudio it's just Command or Control + Shift + C again.
These shortcuts will likely change over time as editors get updated and different software becomes the most popular R editors. You'll have to look it up for whatever software you have.
We recently started using Gatling for load testing. I would highly recommend to try out this tool for load testing. We had used SOASTA and JMETER in past. Our main reason to consider Gatling is following:
Let me give you simple example to write the code using Gatling Code:
// your code starts here
val scn = scenario("Scenario")
.exec(http("Page")
.get("http://example.com"))
// injecting 100 user enter code here's on above scenario.
setUp(scn.inject(atOnceUsers(100)))
However you can make it as complicated as possible. One of the feature which stand out for Gatling is reporting which is very detail.
Here are some links:
Gatling
Gatling Tutorial
I recently gave talk on it, you can go through the talk here:
https://docs.google.com/viewer?url=http%3A%2F%2Ffiles.meetup.com%2F3872152%2FExploring-Load-Testing-with-Gatling.pdf
A functional way can be achieved using filter
and lambda
operator.
list1 = [1,2,3,4,5,6]
list2 = [2,4,6,9,10]
>>> list(filter(lambda x:x in list1, list2))
[2, 4, 6]
Edit: It filters out x that exists in both list1 and list, set difference can also be achieved using:
>>> list(filter(lambda x:x not in list1, list2))
[9,10]
Edit2: python3 filter
returns a filter object, encapsulating it with list
returns the output list.
Use DATE()
function:
select * from follow_queue group by DATE(follow_date)
I am using 'ImportJS' plugin by Devin Abbott for auto import and you can install this using below code
npm install --global import-js
If you need to check whether the elements of one vector are in another, the best solution is ismember
as mentioned in the other answers.
ismember([15 17],primes(20))
However when you are dealing with floating point numbers, or just want to have close matches (+- 1000 is also possible), the best solution I found is the fairly efficient File Exchange Submission: ismemberf
It gives a very practical example:
[tf, loc]=ismember(0.3, 0:0.1:1) % returns false
[tf, loc]=ismemberf(0.3, 0:0.1:1) % returns true
Though the default tolerance should normally be sufficient, it gives you more flexibility
ismemberf(9.99, 0:10:100) % returns false
ismemberf(9.99, 0:10:100,'tol',0.05) % returns true
Why not just generate a whitespace string dynamically to insert into the statement.
So if you want them all to start on the 50th character...
String key = "Name =";
String space = "";
for(int i; i<(50-key.length); i++)
{space = space + " ";}
String value = "Bob\n";
System.out.println(key+space+value);
Put all of that in a loop and initialize/set the "key" and "value" variables before each iteration and you're golden. I would also use the StringBuilder
class too which is more efficient.
Yeah, your own answer was right. You could also use Cocoa methods:
- (void)drawRect:(NSRect)dirtyRect {
// set any NSColor for filling, say white:
[[NSColor whiteColor] setFill];
NSRectFill(dirtyRect);
[super drawRect:dirtyRect];
}
In Swift:
class MyView: NSView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// #1d161d
NSColor(red: 0x1d/255, green: 0x16/255, blue: 0x1d/255, alpha: 1).setFill()
dirtyRect.fill()
}
}
I think you want to make objects from array and combine it with an old object (BODY.recipients.values), if it's then you may do it using $.extent
(because you are using jQuery
/tagged) method after prepare the object from array
var BODY = {
"recipients": {
"values": []
},
"subject": 'TitleOfSubject',
"body": 'This is the message body.'
}
var values = [],
names = ['sheikh', 'muhammed', 'Answer', 'Uddin', 'Heera']; // for testing
for (var ln = 0; ln < names.length; ln++) {
var item1 = {
"person": { "_path": "/people/"+names[ln] }
};
values.push(item1);
}
// Now merge with BODY
$.extend(BODY.recipients.values, values);
This problem appears when you have a path or a property containing a space and that is not quoted.
All your properties and path have quote around them, it's strange. The error message indicates Education
as a switch, try to remove /p:ProductName="Total Education TEST"
to see if it works.
The problem with your code is that the your script is executed prior to the html element being available. Because of the that var comment
is an empty array.
So you should move your script after the html element is available.
Also, getElementsByClassName
returns html collection, so if you need to add event Listener to an element, you will need to do something like following
comment[0].addEventListener('click' , showComment , false ) ;
If you want to add event listener to all the elements, then you will need to loop through them
for (var i = 0 ; i < comment.length; i++) {
comment[i].addEventListener('click' , showComment , false ) ;
}
When you do
$array_x = $array_y;
PHP copies the array, so I'm not sure how you would have gotten burned. For your case,
global $foo;
$foo = $obj->bar;
should work fine.
In order to get burned, I would think you'd either have to have been using references or expecting objects inside the arrays to be cloned.
I had similar issue when I had to install from github repo, but did not want to install git , etc.
The simple way to do it is using zip archive of the package. Add /zipball/master
to the repo URL:
$ pip install https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Downloading/unpacking https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Downloading master
Running setup.py egg_info for package from https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Installing collected packages: django-debug-toolbar-mongo
Running setup.py install for django-debug-toolbar-mongo
Successfully installed django-debug-toolbar-mongo
Cleaning up...
This way you will make pip work with github source repositories.
If you program is using threads (concurrent programming), it's not necessarily going to be executed as such (parallel execution), since it depends on whether the machine can handle several threads.
Here's a visual example. Threads on a non-threaded machine:
-- -- --
/ \
>---- -- -- -- -- ---->>
Threads on a threaded machine:
------
/ \
>-------------->>
The dashes represent executed code. As you can see, they both split up and execute separately, but the threaded machine can execute several separate pieces at once.
I always just convert a matrix:
x <- as.data.frame(matrix(nrow = 100, ncol = 10))
If you are using Action, Actionforward way to process business logic and next page to show, check out if redirect is called. As many others pointed out, redirecting doesn't keep your original request since it is basically forcing you to make a new request to designated path. So the value set in original request will be vanished if you use redirection instead of requestdispatch.
Java 8:
String[] strArray = {"eins", "zwei", "drei", "vier"};
Set<String> strSet = Arrays.stream(strArray).collect(Collectors.toSet());
System.out.println(strSet);
// [eins, vier, zwei, drei]
Swift:
let fetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(entityName, inManagedObjectContext: context)
fetchRequest.includesPropertyValues = false
var error:NSError?
if let results = context.executeFetchRequest(fetchRequest, error: &error) as? [NSManagedObject] {
for result in results {
context.deleteObject(result)
}
var error:NSError?
if context.save(&error) {
// do something after save
} else if let error = error {
println(error.userInfo)
}
} else if let error = error {
println("error: \(error)")
}
PHP sample:
$string = "A man, a plan, a canal, Panama";
function is_palindrome($string)
{
$a = strtolower(preg_replace("/[^A-Za-z0-9]/","",$string));
return $a==strrev($a);
}
Removes any non-alphanumeric characters (spaces, commas, exclamation points, etc.) to allow for full sentences as above, as well as simple words.
I know a bit late to the party, however I feel the answers could do with some more investigation/input. I have managed to create the situation without using the fieldset tag - that is wrong anyway as if I'm not in a form then that isn't really what I should be doing.
/* Styles go here */
#info-block section {
border: 2px solid black;
}
.file-marker > div {
padding: 0 3px;
height: 100px;
margin-top: -0.8em;
}
.box-title {
background: white none repeat scroll 0 0;
display: inline-block;
padding: 0 2px;
margin-left: 8em;
}
_x000D_
<aside id="info-block">
<section class="file-marker">
<div>
<div class="box-title">
Audit Trail
</div>
<div class="box-contents">
<div id="audit-trail">
</div>
</div>
</div>
</section>
</aside>
_x000D_
This can be viewed in this plunk:
What this achieves is the following:
no use of fieldsets.
minimal use if CSS to create effect with just some paddings.
Use of "em" margin top to create font relative title.
use of display inline-block to achieve natural width around the text.
Anyway I hope that helps future stylers, you never know.
Dim result2 = From s In mySession.Query(Of CSucursal)()
Where (From c In mySession.Query(Of CCiudad)()
From cs In mySession.Query(Of CCiudadSucursal)()
Where cs.id_ciudad Is c
Where cs.id_sucursal Is s
Where c.id = IdCiudad
Where s.accion <> "E" AndAlso s.accion <> Nothing
Where cs.accion <> "E" AndAlso cs.accion <> Nothing
Select c.descripcion).Single() Is Nothing
Where s.accion <> "E" AndAlso s.accion <> Nothing
Select s.id, s.Descripcion
ByteArrayInputStream also does the trick:
InputStream is = new ByteArrayInputStream( myString.getBytes( charset ) );
Then convert to reader:
InputStreamReader reader = new InputStreamReader(is);
Use count(*)
declare
cnt integer;
begin
SELECT count(*) INTO cnt
FROM people
WHERE person_id = my_person_id;
IF cnt > 0 THEN
-- Do something
END IF;
Edit (for the downvoter who didn't read the statement and others who might be doing something similar)
The solution is only effective because there is a where clause on a column (and the name of the column suggests that its the primary key - so the where clause is highly effective)
Because of that where
clause there is no need to use a LIMIT or something else to test the presence of a row that is identified by its primary key. It is an effective way to test this.
Make (or rather a Makefile) is a buildsystem - it drives the compiler and other build tools to build your code.
CMake is a generator of buildsystems. It can produce Makefiles, it can produce Ninja build files, it can produce KDEvelop or Xcode projects, it can produce Visual Studio solutions. From the same starting point, the same CMakeLists.txt file. So if you have a platform-independent project, CMake is a way to make it buildsystem-independent as well.
If you have Windows developers used to Visual Studio and Unix developers who swear by GNU Make, CMake is (one of) the way(s) to go.
I would always recommend using CMake (or another buildsystem generator, but CMake is my personal preference) if you intend your project to be multi-platform or widely usable. CMake itself also provides some nice features like dependency detection, library interface management, or integration with CTest, CDash and CPack.
Using a buildsystem generator makes your project more future-proof. Even if you're GNU-Make-only now, what if you later decide to expand to other platforms (be it Windows or something embedded), or just want to use an IDE?
To extract without conversion I use a context menu entry - as file manager custom action in Linux - to run the following (after having checked what audio type the video contains; example for video containing ogg
audio):
bash -c 'ffmpeg -i "$0" -map 0:a -c:a copy "${0%%.*}".ogg' %f
which is based on the ffmpeg command ffmpeg -i INPUT -map 0:a -c:a copy OUTPUT
.
I have used -map 0:1
in that without problems, but, as said in a comment by @LordNeckbeard, "Stream 0:1
is not guaranteed to always be audio. Using -map 0:a
instead of -map 0:1
will avoid ambiguity."
Here is a pure JavaScript solution I tested working in Firefox and Chrome but not in Internet Explorer:
function downloadDataUrlFromJavascript(filename, dataUrl) {
// Construct the 'a' element
var link = document.createElement("a");
link.download = filename;
link.target = "_blank";
// Construct the URI
link.href = dataUrl;
document.body.appendChild(link);
link.click();
// Cleanup the DOM
document.body.removeChild(link);
delete link;
}
Cross-browser solutions found up until now:
downloadify -> Requires Flash
databounce -> Tested in IE 10 and 11, and doesn't work for me. Requires a servlet and some customization. (Incorrectly detects navigator. I had to set IE in compatibility mode to test, default charset in servlet, JavaScript options object with correct servlet path for absolute paths...) For non-IE browsers, it opens the file in the same window.
download.js -> http://danml.com/download.html Another library similar but not tested. Claims to be pure JavaScript, not requiring servlet nor Flash, but doesn't work on IE <= 9.
Automatically fill all form fields from an array
http://jsfiddle.net/brynner/wf0rk7tz/2/
JS
function fill(a){
for(var k in a){
$('[name="'+k+'"]').val(a[k]);
}
}
array_example = {"God":"Jesus","Holy":"Spirit"};
fill(array_example);
HTML
<form>
<input name="God">
<input name="Holy">
</form>
for ($s=65; $s<=90; $s++) {
//echo chr($s);
$objPHPExcel->getActiveSheet()->getColumnDimension(chr($s))->setAutoSize(true);
}
It sounds like it's just a compiler warning.
Usage of scanf_s
prevents possible buffer overflow.
See: http://code.wikia.com/wiki/Scanf_s
Good explanation as to why scanf
can be dangerous: Disadvantages of scanf
So as suggested, you can try replacing scanf
with scanf_s
or disable the compiler warning.
Additional to the above - the QEMU website has good documentation about setting up an ARM based emulator: http://qemu.weilnetz.de/qemu-doc.html#ARM-System-emulator
I had a similar problem and was able to solve it by addressing my mysql with 127.0.0.1
instead of localhost
.
This probably means I've got something wrong in my hosts setup, but this quick fix get's me going for right now.
Unfortunately, "shallow copy", "deep copy" and "clone" are all rather ill-defined terms.
In the Java context, we first need to make a distinction between "copying a value" and "copying an object".
int a = 1;
int b = a; // copying a value
int[] s = new int[]{42};
int[] t = s; // copying a value (the object reference for the array above)
StringBuffer sb = new StringBuffer("Hi mom");
// copying an object.
StringBuffer sb2 = new StringBuffer(sb);
In short, an assignment of a reference to a variable whose type is a reference type is "copying a value" where the value is the object reference. To copy an object, something needs to use new
, either explicitly or under the hood.
Now for "shallow" versus "deep" copying of objects. Shallow copying generally means copying only one level of an object, while deep copying generally means copying more than one level. The problem is in deciding what we mean by a level. Consider this:
public class Example {
public int foo;
public int[] bar;
public Example() { };
public Example(int foo, int[] bar) { this.foo = foo; this.bar = bar; };
}
Example eg1 = new Example(1, new int[]{1, 2});
Example eg2 = ...
The normal interpretation is that a "shallow" copy of eg1
would be a new Example
object whose foo
equals 1 and whose bar
field refers to the same array as in the original; e.g.
Example eg2 = new Example(eg1.foo, eg1.bar);
The normal interpretation of a "deep" copy of eg1
would be a new Example
object whose foo
equals 1 and whose bar
field refers to a copy of the original array; e.g.
Example eg2 = new Example(eg1.foo, Arrays.copy(eg1.bar));
(People coming from a C / C++ background might say that a reference assignment produces a shallow copy. However, that's not what we normally mean by shallow copying in the Java context ...)
Two more questions / areas of uncertainty exist:
How deep is deep? Does it stop at two levels? Three levels? Does it mean the whole graph of connected objects?
What about encapsulated data types; e.g. a String? A String is actually not just one object. In fact, it is an "object" with some scalar fields, and a reference to an array of characters. However, the array of characters is completely hidden by the API. So, when we talk about copying a String, does it make sense to call it a "shallow" copy or a "deep" copy? Or should we just call it a copy?
Finally, clone. Clone is a method that exists on all classes (and arrays) that is generally thought to produce a copy of the target object. However:
The specification of this method deliberately does not say whether this is a shallow or deep copy (assuming that is a meaningful distinction).
In fact, the specification does not even specifically state that clone produces a new object.
Here's what the javadoc says:
"Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression
x.clone() != x
will be true, and that the expressionx.clone().getClass() == x.getClass()
will be true, but these are not absolute requirements. While it is typically the case thatx.clone().equals(x)
will be true, this is not an absolute requirement."
Note, that this is saying that at one extreme the clone might be the target object, and at the other extreme the clone might not equal the original. And this assumes that clone is even supported.
In short, clone potentially means something different for every Java class.
Some people argue (as @supercat does in comments) that the Java clone()
method is broken. But I think the correct conclusion is that the concept of clone is broken in the context of OO. AFAIK, it is impossible to develop a unified model of cloning that is consistent and usable across all object types.
In my opinion, the issue is because the environment variable is not set up to recognize pip as a valid command.
In general, the pip in Python is at this location:
C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts > pip
So all we need to do is go to Computer Name> Right Click > Advanced System Settings > Select Env Variable then under system variables > reach to Path> Edit path and add the Path by separating this path by putting a semicolon after the last path already was in the Env Variable.
Now run Python shell, and this should work.
2019 Update:
Summary - Java NIO (or NIO.2 for async) is still the most comprehensive file processing solution supported in Scala. The following code creates and writes some text to a new file:
import java.io.{BufferedOutputStream, OutputStream}
import java.nio.file.{Files, Paths}
val testFile1 = Paths.get("yourNewFile.txt")
val s1 = "text to insert in file".getBytes()
val out1: OutputStream = new BufferedOutputStream(
Files.newOutputStream(testFile1))
try {
out1.write(s1, 0, s1.length)
} catch {
case _ => println("Exception thrown during file writing")
} finally {
out1.close()
}
Path
object with your chosen file name OutputStream
write
functionThere is an online tool that lets you upload an APK It decompiles it and finally lets you to download a zip with all sources, manifest XML file and so on decompiled, all of that without having to install any program on your computer: http://www.javadecompilers.com/apk
Also if you wish just to check on some params you can, by their UI
To remove first Character of string in PHP,
$string = "abcdef";
$new_string = substr($string, 1);
echo $new_string;
Generates: "bcdef"
Another possible solution that works for me is something like -
cat a.txt | xargs bash -c 'command1 $@; command2 $@' bash
Note the 'bash' at the end - I assume it is passed as argv[0] to bash. Without it in this syntax the first parameter to each command is lost. It may be any word.
Example:
cat a.txt | xargs -n 5 bash -c 'echo -n `date +%Y%m%d-%H%M%S:` ; echo " data: " $@; echo "data again: " $@' bash
alternative to stdbuf is awk '{print} END {fflush()}'
I wish there were a bash builtin to do this.
Normally it shouldn't be necessary, but with older versions there might be bash synchronization bugs on file descriptors.
you could use things like display: inline-block
but I think you would need to set up another div to move it over, if there is nothing going to the left of the button you could use margins to move it into place.
Alternatively but not a good solution, you could position tags; put the encompassing div as position: relative
and then the div of the button as position: absolute; right: 0
, but like I said this is probably not the best solution
HTML
<div class="parent">
<div>Left Div</div>
<div class="right">Right Div</div>
</div>
CSS
.parent {
position: relative;
}
.right {
position: absolute;
right: 0;
}
Test e = static_cast<Test>(1);
Here's some code that I ended up writing, based upon @Andrei's answer but without the elegancy/simplicity. The advantage is that it allows a more complex recursive merge and also differs between elements that should be connected with rbind
and those that are just connected with c
:
# Decided to move this outside the mapply, not sure this is
# that important for speed but I imagine redefining the function
# might be somewhat time-consuming
mergeLists_internal <- function(o_element, n_element){
if (is.list(n_element)){
# Fill in non-existant element with NA elements
if (length(n_element) != length(o_element)){
n_unique <- names(n_element)[! names(n_element) %in% names(o_element)]
if (length(n_unique) > 0){
for (n in n_unique){
if (is.matrix(n_element[[n]])){
o_element[[n]] <- matrix(NA,
nrow=nrow(n_element[[n]]),
ncol=ncol(n_element[[n]]))
}else{
o_element[[n]] <- rep(NA,
times=length(n_element[[n]]))
}
}
}
o_unique <- names(o_element)[! names(o_element) %in% names(n_element)]
if (length(o_unique) > 0){
for (n in o_unique){
if (is.matrix(n_element[[n]])){
n_element[[n]] <- matrix(NA,
nrow=nrow(o_element[[n]]),
ncol=ncol(o_element[[n]]))
}else{
n_element[[n]] <- rep(NA,
times=length(o_element[[n]]))
}
}
}
}
# Now merge the two lists
return(mergeLists(o_element,
n_element))
}
if(length(n_element)>1){
new_cols <- ifelse(is.matrix(n_element), ncol(n_element), length(n_element))
old_cols <- ifelse(is.matrix(o_element), ncol(o_element), length(o_element))
if (new_cols != old_cols)
stop("Your length doesn't match on the elements,",
" new element (", new_cols , ") !=",
" old element (", old_cols , ")")
}
return(rbind(o_element,
n_element,
deparse.level=0))
return(c(o_element,
n_element))
}
mergeLists <- function(old, new){
if (is.null(old))
return (new)
m <- mapply(mergeLists_internal, old, new, SIMPLIFY=FALSE)
return(m)
}
Here's my example:
v1 <- list("a"=c(1,2), b="test 1", sublist=list(one=20:21, two=21:22))
v2 <- list("a"=c(3,4), b="test 2", sublist=list(one=10:11, two=11:12, three=1:2))
mergeLists(v1, v2)
This results in:
$a
[,1] [,2]
[1,] 1 2
[2,] 3 4
$b
[1] "test 1" "test 2"
$sublist
$sublist$one
[,1] [,2]
[1,] 20 21
[2,] 10 11
$sublist$two
[,1] [,2]
[1,] 21 22
[2,] 11 12
$sublist$three
[,1] [,2]
[1,] NA NA
[2,] 1 2
Yeah, I know - perhaps not the most logical merge but I have a complex parallel loop that I had to generate a more customized .combine
function for, and therefore I wrote this monster :-)
Make the outer div position="relative"
and the inner div position="absolute"
and set it's bottom="0"
.
Additionally,this error may occurs in you are using any proxy in command line.
if you export any proxy before , unset it .
$ unset all_proxy && unset ALL_PROXY
Use the std::vector
class from the standard library.
Use .get()
, which if the key is not found, returns None
.
for i in keySet:
temp = myDict.get(i)
if temp is not None:
print temp
break
Create an IBOutlet of NSLayoutConstraint of yourView and update the constant value accordingly the condition specifies.
//Connect them from Interface
@IBOutlet viewHeight: NSLayoutConstraint!
@IBOutlet view: UIView!
private func updateViewHeight(height:Int){
guard let aView = view, aViewHeight = viewHeight else{
return
}
aViewHeight.constant = height
aView.layoutIfNeeded()
}
There should be a ReceiveTimeout property in the Socket class.
As stats on iOS usage, indicating that iOS 9.0-9.2.x usage is currently at 0.17%. If these numbers are truly indicative of global use of these versions, then it’s even more likely to be safe to remove shrink-to-fit from your viewport meta tag.
After 9.2.x. IOS remove this tag check on its' browser.
You can check this page https://www.scottohara.me/blog/2018/12/11/shrink-to-fit.html
I always stick this as one line. Now params has the vars:
params={};location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){params[k]=v})
multi-lined:
var params={};
window.location.search
.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str,key,value) {
params[key] = value;
}
);
as a function
function getSearchParams(k){
var p={};
location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){p[k]=v})
return k?p[k]:p;
}
which you could use as:
getSearchParams() //returns {key1:val1, key2:val2}
or
getSearchParams("key1") //returns val1
The following link presents a simple way of doing it with just 3 lines in your CSS:
Vertical align anything with just 3 lines of CSS.
Credits to: Sebastian Ekström.
I know the question has already an answer however I saw utility in the link for its simplicity.
@Patrik’s code has a nice idea but with a lot of bugs. @Zac and @Anthony B ( negative numbers solutions) have solve some of them, but @Zac’s code still have 3 mayor bugs:
1. If user deletes all entries in the EditText, it’s impossible to type any number again.. Of course this can be controlled using a EditText changed listener on each field, but it will erase out the beauty of using a common InputFilter class for each EditText in your app.
2. Has @Guernee4 says, if for example min = 3, it’s impossible to type any number starting with 1.
3. If for example min = 0, you can type has many zeros you wish, that it’s not elegant the result. Or also, if no matter what is the min value, user can place the cursor in the left size of the first number, an place a bunch of leading zeros to the left, also not elegant.
I came up whit these little changes of @Zac’s code to solve this 3 bugs. Regarding bug # 3, I still haven't been able to completely remove all leading zeros at the left; It always can be one, but a 00, 01, 0100 etc in that case, is more elegant an valid that an 000000, 001, 000100, etc.etc. Etc.
Here is the code:
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
// Using @Zac's initial solution
String lastVal = dest.toString().substring(0, dstart) + dest.toString().substring(dend);
String newVal = lastVal.substring(0, dstart) + source.toString() + lastVal.substring(dstart);
int input = Integer.parseInt(newVal);
// To avoid deleting all numbers and avoid @Guerneen4's case
if (input < min && lastVal.equals("")) return String.valueOf(min);
// Normal min, max check
if (isInRange(min, max, input)) {
// To avoid more than two leading zeros to the left
String lastDest = dest.toString();
String checkStr = lastDest.replaceFirst("^0+(?!$)", "");
if (checkStr.length() < lastDest.length()) return "";
return null;
}
} catch (NumberFormatException ignored) {}
return "";
}
Have a nice day!
JDO is dead
JDO is not dead actually so please check your facts. JDO 2.2 was released in Oct 2008 JDO 2.3 is under development.
This is developed openly, under Apache. More releases than JPA has had, and its ORM specification is still in advance of even the JPA2 proposed features
I have a similar issue, and this is what I'm doing:
insert into Preguntas (`EncuestaID`, `Tipo` , `Seccion` , `RespuestaID` , `Texto` ) select '23', `Tipo`, `Seccion`, `RespuestaID`, `Texto` from Preguntas where `EncuestaID`= 18
Been Preguntas:
CREATE TABLE IF NOT EXISTS `Preguntas` (
`ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`EncuestaID` int(11) DEFAULT NULL,
`Tipo` char(5) COLLATE utf8_unicode_ci DEFAULT NULL,
`Seccion` int(11) DEFAULT NULL,
`RespuestaID` bigint(11) DEFAULT NULL,
`Texto` text COLLATE utf8_unicode_ci ,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=522 ;
So, the ID
is automatically incremented and also I'm using a fixed value ('23') for EncuestaID
.
Assertions are disabled by default. To enable them we must run the program with -ea
options (granularity can be varied). For example, java -ea AssertionsDemo
.
There are two formats for using assertions:
assert 1==2; // This will raise an AssertionError
.assert 1==2: "no way.. 1 is not equal to 2";
This will raise an AssertionError with the message given displayed too and is thus better. Although the actual syntax is assert expr1:expr2
where expr2 can be any expression returning a value, I have used it more often just to print a message.Here is the simple solution with StreamEx
EntryStream.of(countByType).sortedBy(e -> e.getValue()).keys().toList();
Consider if instead it was:
class RectangularRoom(object):
def __init__(self, width, height):
pass
def cleanTileAtPosition(self, pos):
pass
def isTileCleaned(self, m, n):
pass
and you subclass and forget to tell it how to isTileCleaned()
or, perhaps more likely, typo it as isTileCLeaned()
. Then in your code, you'll get a None
when you call it.
None
valid output? Who knows. raise NotImplmentedError
forces you to implement it, as it will throw an exception when you try to run it until you do so. This removes a lot of silent errors. It's similar to why a bare except is almost never a good idea: because people make mistakes and this makes sure they aren't swept under the rug.
Note: Using an abstract base class, as other answers have mentioned, is better still, as then the errors are frontloaded and the program won't run until you implement them (with NotImplementedError, it will only throw an exception if actually called).
If you don't want to go down the VBA path, there is this trick from a previous question.
Excel 2010: how to use autocomplete in validation list
It does add some annoying bulk to the top of your sheets, and potential maintenance (should you need more options, adding names of people from a staff list, new projects etc.) but works all the same.
You can call the stat() function and use the S_ISREG()
macro on the st_mode
field of the stat structure in order to determine if your path points to a regular file:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int is_regular_file(const char *path)
{
struct stat path_stat;
stat(path, &path_stat);
return S_ISREG(path_stat.st_mode);
}
Note that there are other file types besides regular and directory, like devices, pipes, symbolic links, sockets, etc. You might want to take those into account.
Very simple method:
.create:before {
content: url(image.png);
}
Works in all modern browsers and IE8+.
Edit
Don't use this on large sites though. The :before pseudo-element is horrible in terms of performance.
You cannot concatenate multiple fields with a string. You need to select a field instand of all (*
).
Just wanted to let you know that up until today I was first obtaining an app access token (via GET request to Facebook), and then using the received token as the app-token-or-admin-token
in:
GET graph.facebook.com/debug_token?
input_token={token-to-inspect}
&access_token={app-token-or-admin-token}
However, I just realized a better way of doing this (with the added benefit of requiring one less GET request):
GET graph.facebook.com/debug_token?
input_token={token-to-inspect}
&access_token={app_id}|{app_secret}
As described in Facebook's documentation for Access Tokens here.
<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'ar', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
class="mb-0"
m - sets margin
b - sets bottom margin or padding
0 - sets 0 margin or padding
CSS class
.mb-0{
margin-bottom: 0
}
You can use something like following:
Matrix matrix = new Matrix();
matrix.setRotate(mRotation,source.getWidth()/2,source.getHeight()/2);
RectF rectF = new RectF(0, 0, source.getWidth(), source.getHeight());
matrix.mapRect(rectF);
Bitmap targetBitmap = Bitmap.createBitmap(rectF.width(), rectF.height(), config);
Canvas canvas = new Canvas(targetBitmap);
canvas.drawBitmap(source, matrix, new Paint());
Best Firefox Addon to disable CORS as of September 2016: https://github.com/fredericlb/Force-CORS/releases
You can even configure it by Referrers (Website).
You might want to check that library
**org.eclipse.equinox.launcher_(version).dist.jar**
and
**plugins/org.eclipse.equinox.launcher.gtk.linux.x86_(version).dist**
exists on your system.
Make sure that the version of libraries mentioned in eclipse.ini and the version that exists on your system is same. Usually after upgrade this mismatch occurs and eclipse fails to locate the required jar. Please take a look at this blog post here
I just got this error and it turns out my AD administrator deleted the service account used by EVERY SQL Server instance in the entire company. Thank goodness AD has its own recycle bin.
See if you can run the Active Directory Users and Computers utility (%SystemRoot%\system32\dsa.msc), and check to make sure the account you are relying on still exists.
"Subscript out of range" indicates that you've tried to access an element from a collection that doesn't exist. Is there a "Sheet1" in your workbook? If not, you'll need to change that to the name of the worksheet you want to protect.
The most efficient, but not the C++ way would be:
FILE* f = fopen(filename, "r");
// Determine file size
fseek(f, 0, SEEK_END);
size_t size = ftell(f);
char* where = new char[size];
rewind(f);
fread(where, sizeof(char), size, f);
delete[] where;
#
EDIT - 2Just tested the std::filebuf
variant also. Looks like it can be called the best C++ approach, even though it's not quite a C++ approach, but more a wrapper. Anyway, here is the chunk of code that works almost as fast as plain C does.
std::ifstream file(filename, std::ios::binary);
std::streambuf* raw_buffer = file.rdbuf();
char* block = new char[size];
raw_buffer->sgetn(block, size);
delete[] block;
I've done a quick benchmark here and the results are following. Test was done on reading a 65536K binary file with appropriate (std::ios:binary
and rb
) modes.
[==========] Running 3 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 4 tests from IO
[ RUN ] IO.C_Kotti
[ OK ] IO.C_Kotti (78 ms)
[ RUN ] IO.CPP_Nikko
[ OK ] IO.CPP_Nikko (106 ms)
[ RUN ] IO.CPP_Beckmann
[ OK ] IO.CPP_Beckmann (1891 ms)
[ RUN ] IO.CPP_Neil
[ OK ] IO.CPP_Neil (234 ms)
[----------] 4 tests from IO (2309 ms total)
[----------] Global test environment tear-down
[==========] 4 tests from 1 test case ran. (2309 ms total)
[ PASSED ] 4 tests.
Each tablespace has one or more datafiles that it uses to store data.
The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.
To find out if the actual limit is 32gb, run the following:
select value from v$parameter where name = 'db_block_size';
Compare the result you get with the first column below, and that will indicate what your max datafile size is.
I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).
Block Sz Max Datafile Sz (Gb) Max DB Sz (Tb)
-------- -------------------- --------------
2,048 8,192 524,264
4,096 16,384 1,048,528
8,192 32,768 2,097,056
16,384 65,536 4,194,112
32,768 131,072 8,388,224
You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):
select bytes/1024/1024 as mb_size,
maxbytes/1024/1024 as maxsize_set,
x.*
from dba_data_files x
MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).
If your datafile has a low max size or autoextend is not on you could simply run:
alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;
However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:
alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;
Along the lines of erik's response, you should also be able to calculate the ROC directly by comparing all possible pairs of values from pos.scores and neg.scores:
score.pairs <- merge(pos.scores, neg.scores)
names(score.pairs) <- c("pos.score", "neg.score")
sum(score.pairs$pos.score > score.pairs$neg.score) / nrow(score.pairs)
Certainly less efficient than the sample approach or the pROC::auc, but more stable than the former and requiring less installation than the latter.
Related: when I tried this it gave similar results to pROC's value, but not exactly the same (off by 0.02 or so); the result was closer to the sample approach with very high N. If anyone has ideas why that might be I'd be interested.
A nice way of marking just the first character going out of the specified bounds:
highlight ColorColumn ctermbg=magenta "set to whatever you like
call matchadd('ColorColumn', '\%81v', 100) "set column nr
From Damian Conway's talk.
This is the format of /etc/crontab:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
I recommend copy & pasting that into the top of your crontab file so that you always have the reference handy. RedHat systems are setup that way by default.
To run something every minute:
* * * * * username /var/www/html/a.php
To run something at midnight of every day:
0 0 * * * username /var/www/html/reset.php
You can either include /usr/bin/php in the command to run, or you can make the php scripts directly executable:
chmod +x file.php
Start your php file with a shebang so that your shell knows which interpreter to use:
#!/usr/bin/php
<?php
// your code here
Simple code for command line in java:
class CMDLineArgument
{
public static void main(String args[])
{
String name=args[0];
System.out.println(name);
}
}