Try this:
int selectedIndex = comboBox1.SelectedIndex;
comboBox1.SelectedItem.ToString();
int selectedValue = (int)comboBox1.Items[selectedIndex];
Well I will put similar solution that is working fine for me.
private void DataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
if (DataGrid1.SelectedItem != null)
{
if (DataGrid1.SelectedItem is YouCustomClass)
{
var row = (YouCustomClass)DataGrid1.SelectedItem;
if (row != null)
{
// Do something...
// ButtonSaveData.IsEnabled = true;
// LabelName.Content = row.Name;
}
}
}
}
catch (Exception)
{
}
}
You don't need to iterate through the DataGrid
rows, you can achieve your goal with a more simple solution.
In order to match your row you can iterate through you collection that was bound to your DataGrid.ItemsSource
property then assign this item to you DataGrid.SelectedItem
property programmatically, alternatively you can add it to your DataGrid.SelectedItems
collection if you want to allow the user to select more than one row. See the code below:
<Window x:Class="ProgGridSelection.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="OnWindowLoaded">
<StackPanel>
<DataGrid Name="empDataGrid" ItemsSource="{Binding}" Height="200"/>
<TextBox Name="empNameTextBox"/>
<Button Content="Click" Click="OnSelectionButtonClick" />
</StackPanel>
public partial class MainWindow : Window
{
public class Employee
{
public string Code { get; set; }
public string Name { get; set; }
}
private ObservableCollection<Employee> _empCollection;
public MainWindow()
{
InitializeComponent();
}
private void OnWindowLoaded(object sender, RoutedEventArgs e)
{
// Generate test data
_empCollection =
new ObservableCollection<Employee>
{
new Employee {Code = "E001", Name = "Mohammed A. Fadil"},
new Employee {Code = "E013", Name = "Ahmed Yousif"},
new Employee {Code = "E431", Name = "Jasmin Kamal"},
};
/* Set the Window.DataContext, alternatively you can set your
* DataGrid DataContext property to the employees collection.
* on the other hand, you you have to bind your DataGrid
* DataContext property to the DataContext (see the XAML code)
*/
DataContext = _empCollection;
}
private void OnSelectionButtonClick(object sender, RoutedEventArgs e)
{
/* select the employee that his name matches the
* name on the TextBox
*/
var emp = (from i in _empCollection
where i.Name == empNameTextBox.Text.Trim()
select i).FirstOrDefault();
/* Now, to set the selected item on the DataGrid you just need
* assign the matched employee to your DataGrid SeletedItem
* property, alternatively you can add it to your DataGrid
* SelectedItems collection if you want to allow the user
* to select more than one row, e.g.:
* empDataGrid.SelectedItems.Add(emp);
*/
if (emp != null)
empDataGrid.SelectedItem = emp;
}
}
final ListView lv = (ListView) findViewById(R.id.ListView01);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));
}
});
I hope this fixes your problem.
Their names can be a bit confusing :). Here's a summary:
The SelectedItem property returns the entire object that your list is bound to. So say you've bound a list to a collection of Category
objects (with each Category object having Name and ID properties). eg. ObservableCollection<Category>
. The SelectedItem
property will return you the currently selected Category
object. For binding purposes however, this is not always what you want, as this only enables you to bind an entire Category object to the property that the list is bound to, not the value of a single property on that Category object (such as its ID
property).
Therefore we have the SelectedValuePath property and the SelectedValue property as an alternative means of binding (you use them in conjunction with one another). Let's say you have a Product
object, that your view is bound to (with properties for things like ProductName, Weight, etc). Let's also say you have a CategoryID
property on that Product object, and you want the user to be able to select a category for the product from a list of categories. You need the ID property of the Category object to be assigned to the CategoryID
property on the Product object. This is where the SelectedValuePath
and the SelectedValue
properties come in. You specify that the ID property on the Category object should be assigned to the property on the Product object that the list is bound to using SelectedValuePath='ID'
, and then bind the SelectedValue
property to the property on the DataContext (ie. the Product).
The example below demonstrates this. We have a ComboBox bound to a list of Categories (via ItemsSource). We're binding the CategoryID property on the Product as the selected value (using the SelectedValue property). We're relating this to the Category's ID property via the SelectedValuePath property. And we're saying only display the Name property in the ComboBox, with the DisplayMemberPath property).
<ComboBox ItemsSource="{Binding Categories}"
SelectedValue="{Binding CategoryID, Mode=TwoWay}"
SelectedValuePath="ID"
DisplayMemberPath="Name" />
public class Category
{
public int ID { get; set; }
public string Name { get; set; }
}
public class Product
{
public int CategoryID { get; set; }
}
It's a little confusing initially, but hopefully this makes it a bit clearer... :)
Chris
Yocoder is right,
Inside the DataTemplate
, your DataContext
is set to the Rule
its currently handling..
To access the parents DataContext
, you can also consider using a RelativeSource
in your binding:
<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ____Your Parent control here___ }}, Path=DataContext.SelectedRule.Name}" />
More info on RelativeSource
can be found here:
http://msdn.microsoft.com/en-us/library/system.windows.data.relativesource.aspx
I realise this has already had an answer accepted, but I put this together to solve the problem. It uses a similar idea to Delta's solution, but without the need to subclass the TreeView:
public class BindableSelectedItemBehavior : Behavior<TreeView>
{
#region SelectedItem Property
public object SelectedItem
{
get { return (object)GetValue(SelectedItemProperty); }
set { SetValue(SelectedItemProperty, value); }
}
public static readonly DependencyProperty SelectedItemProperty =
DependencyProperty.Register("SelectedItem", typeof(object), typeof(BindableSelectedItemBehavior), new UIPropertyMetadata(null, OnSelectedItemChanged));
private static void OnSelectedItemChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var item = e.NewValue as TreeViewItem;
if (item != null)
{
item.SetValue(TreeViewItem.IsSelectedProperty, true);
}
}
#endregion
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
if (this.AssociatedObject != null)
{
this.AssociatedObject.SelectedItemChanged -= OnTreeViewSelectedItemChanged;
}
}
private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
this.SelectedItem = e.NewValue;
}
}
You can then use this in your XAML as:
<TreeView>
<e:Interaction.Behaviors>
<behaviours:BindableSelectedItemBehavior SelectedItem="{Binding SelectedItem, Mode=TwoWay}" />
</e:Interaction.Behaviors>
</TreeView>
Hopefully it will help someone!
Combine Dynamic SQL with OpenQuery. (This goes to a Teradata server)
DECLARE
@dayOfWk TINYINT = DATEPART(DW, GETDATE()),
@qSQL NVARCHAR(MAX) = '';
SET @qSQL = '
SELECT
*
FROM
OPENQUERY(TERASERVER,''
SELECT DISTINCT
CASE
WHEN ' + CAST(@dayOfWk AS NCHAR(1)) + ' = 2
THEN ''''Monday''''
ELSE ''''Not Monday''''
END
'');';
EXEC sp_executesql @qSQL;
Running nginx -t
through your commandline will issue out a test and append the output with the filepath to the configuration file (with either an error or success message).
To add another esoteric way, this works aswell:
var obj = {a: 1, b:2, c:3}
var newobj = {a,c}=obj && {a,c}
// {a: 1, c:3}
but you have to write the prop names twice.
Jerryf's answer is fine, except for one flaw.
The onload event should be set before the src. Sometimes the src can be loaded instantly and never fire the onload event.
(Like Totty.js pointed out.)
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
var image = new Image();
image.onload = function() {
ctx.drawImage(image, 0, 0);
};
image.src = "data:image/ png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
Long answer: it is possible!
In xampp directory comment line apache/conf/httpd.conf:458
#Include "conf/extra/httpd-perl.conf"
In xampp directory do next replaces in files:
from
"C:\xampp\php\.\php.exe" -f "\xampp\php\pci" -- %*
to
set XAMPPPHPDIR=C:\xampp\php
"%XAMPPPHPDIR%\php.exe" -f "%XAMPPPHPDIR%\pci" -- %*
from
"C:\xampp\php\.\php.exe" -f "\xampp\php\pciconf" -- %*
to
set XAMPPPHPDIR=C:\xampp\php
"%XAMPPPHPDIR%\.\php.exe" -f "%XAMPPPHPDIR%\pciconf" -- %*
from
IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"
to
IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"
from
IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"
to
IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"
from
IF "%PHP_PEAR_BIN_DIR%"=="" SET "PHP_PEAR_BIN_DIR=C:\xampp\php"
IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"
to
IF "%PHP_PEAR_BIN_DIR%"=="" SET "PHP_PEAR_BIN_DIR=C:\xampp\php\"
IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"
from
%~dp0php.exe %~dp0pharcommand.phar %*
to
"%~dp0php.exe" "%~dp0pharcommand.phar" %*
Enjoy new XAMPP with PHP 5.3
Checked by myself in XAMPP 5.6.31, 7.0.15 & 7.1.1 with XAMPP Control Panel v3.2.2
Aside from the fact that you are modifying the String prototype, there is nothing wrong with the function you provided. The way you would use it is this way:
"Hello {0},".format(["Bob"]);
If you wanted it as a stand-alone function, you could alter it slightly to this:
function format(string, object) {
return string.replace(/{([^{}]*)}/g,
function(match, group_match)
{
var data = object[group_match];
return typeof data === 'string' ? data : match;
}
);
}
Vittore's method is also good; his function is called with each additional formating option being passed in as an argument, while yours expects an object.
What this actually looks like is John Resig's micro-templating engine.
In addition, you can build the binary package using the --binary option.
R CMD build --binary RJSONIO_0.2-3.tar.gz
Buffers can be used for taking a string or piece of data and doing base64 encoding of the result. For example:
> console.log(Buffer.from("Hello World").toString('base64'));
SGVsbG8gV29ybGQ=
> console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'))
Hello World
Buffers are a global object, so no require is needed. Buffers created with strings can take an optional encoding parameter to specify what encoding the string is in. The available toString
and Buffer
constructor encodings are as follows:
'ascii' - for 7 bit ASCII data only. This encoding method is very fast, and will strip the high bit if set.
'utf8' - Multi byte encoded Unicode characters. Many web pages and other document formats use UTF-8.
'ucs2' - 2-bytes, little endian encoded Unicode characters. It can encode only BMP(Basic Multilingual Plane, U+0000 - U+FFFF).
'base64' - Base64 string encoding.
'binary' - A way of encoding raw binary data into strings by using only the first 8 bits of each character. This encoding method is deprecated and should be avoided in favor of Buffer objects where possible. This encoding will be removed in future versions of Node.
The line function implementation should be:
void addStudent(struct student person) {
}
person
is not a type but a variable, you cannot use it as the type of a function parameter.
Also, make sure your struct is defined before the prototype of the function addStudent
as the prototype uses it.
If you just want to use AWT, then use Graphics.getFontMetrics
(optionally specifying the font, for a non-default one) to get a FontMetrics
and then FontMetrics.stringWidth
to find the width for the specified string.
For example, if you have a Graphics
variable called g
, you'd use:
int width = g.getFontMetrics().stringWidth(text);
For other toolkits, you'll need to give us more information - it's always going to be toolkit-dependent.
This is a problem with your remote. When you do git push origin master
, origin
is the remote and master
is the branch you're pushing.
When you do this:
git remote
I bet the list does not include origin
. To re-add the origin remote:
git remote add origin [email protected]:your_github_username/your_github_app.git
Or, if it exists but is formatted incorrectly:
git remote rm origin
git remote add origin [email protected]:your_github_username/your_github_app.git
Just to summarize, here's a complete answer, that worked for me.
My problem was that when I used
[NSString stringWithUTF8String:(char *)data.bytes];
The string I got was unpredictable: Around 70% it did contain the expected value, but too often it resulted with Null
or even worse: garbaged at the end of the string.
After some digging I switched to
[[NSString alloc] initWithBytes:(char *)data.bytes length:data.length encoding:NSUTF8StringEncoding];
And got the expected result every time.
It took me a while to locate why the sample application works but mine don't.
The library (Foundation.Framework) that the author refer to is the system library (from OS) where the iphone sdk (I am using 3.0) is not support any more.
Therefore the sample application (from about.com, http://www.appsamuck.com/day1.html) works but ours don't.
in php with function chr(13) :
echo '<textarea class="form-control" rows="5" style="width:100%;" name="responsable" placeholder="NOM prénom du responsable légal'.chr(13).'Adresse'.chr(13).'CP VILLE'.chr(13).'Téléphone'.chr(13).'Adresse de messagerie" id="responsable"></textarea>';
The ASCII character code 13 chr(13) is called a Carriage Return or CR
Its just a 2 line of code.
import org.springframework.web.client.RestTemplate;
RestTemplate restTemplate = new RestTemplate();
YourBean obj = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", YourBean.class);
If you are passing data to a DOM element from the server, you should set the data on the element:
<a id="foo" data-foo="bar" href="#">foo!</a>
The data can then be accessed using .data()
in jQuery:
console.log( $('#foo').data('foo') );
//outputs "bar"
However when you store data on a DOM node in jQuery using data, the variables are stored on the node object. This is to accommodate complex objects and references as storing the data on the node element as an attribute will only accommodate string values.
Continuing my example from above:$('#foo').data('foo', 'baz');
console.log( $('#foo').attr('data-foo') );
//outputs "bar" as the attribute was never changed
console.log( $('#foo').data('foo') );
//outputs "baz" as the value has been updated on the object
Also, the naming convention for data attributes has a bit of a hidden "gotcha":
HTML:<a id="bar" data-foo-bar-baz="fizz-buzz" href="#">fizz buzz!</a>
JS:
console.log( $('#bar').data('fooBarBaz') );
//outputs "fizz-buzz" as hyphens are automatically camelCase'd
The hyphenated key will still work:
HTML:<a id="bar" data-foo-bar-baz="fizz-buzz" href="#">fizz buzz!</a>
JS:
console.log( $('#bar').data('foo-bar-baz') );
//still outputs "fizz-buzz"
However the object returned by .data()
will not have the hyphenated key set:
$('#bar').data().fooBarBaz; //works
$('#bar').data()['fooBarBaz']; //works
$('#bar').data()['foo-bar-baz']; //does not work
It's for this reason I suggest avoiding the hyphenated key in javascript.
For HTML, keep using the hyphenated form. HTML attributes are supposed to get ASCII-lowercased automatically, so <div data-foobar></div>
, <DIV DATA-FOOBAR></DIV>
, and <dIv DaTa-FoObAr></DiV>
are supposed to be treated as identical, but for the best compatibility the lower case form should be preferred.
The .data()
method will also perform some basic auto-casting if the value matches a recognized pattern:
<a id="foo"
href="#"
data-str="bar"
data-bool="true"
data-num="15"
data-json='{"fizz":["buzz"]}'>foo!</a>
JS:
$('#foo').data('str'); //`"bar"`
$('#foo').data('bool'); //`true`
$('#foo').data('num'); //`15`
$('#foo').data('json'); //`{fizz:['buzz']}`
This auto-casting ability is very convenient for instantiating widgets & plugins:
$('.widget').each(function () {
$(this).widget($(this).data());
//-or-
$(this).widget($(this).data('widget'));
});
If you absolutely must have the original value as a string, then you'll need to use .attr()
:
<a id="foo" href="#" data-color="ABC123"></a>
<a id="bar" href="#" data-color="654321"></a>
JS:
$('#foo').data('color').length; //6
$('#bar').data('color').length; //undefined, length isn't a property of numbers
$('#foo').attr('data-color').length; //6
$('#bar').attr('data-color').length; //6
This was a contrived example. For storing color values, I used to use numeric hex notation (i.e. 0xABC123), but it's worth noting that hex was parsed incorrectly in jQuery versions before 1.7.2, and is no longer parsed into a Number
as of jQuery 1.8 rc 1.
jQuery 1.8 rc 1 changed the behavior of auto-casting. Before, any format that was a valid representation of a Number
would be cast to Number
. Now, values that are numeric are only auto-cast if their representation stays the same. This is best illustrated with an example.
<a id="foo"
href="#"
data-int="1000"
data-decimal="1000.00"
data-scientific="1e3"
data-hex="0x03e8">foo!</a>
JS:
// pre 1.8 post 1.8
$('#foo').data('int'); // 1000 1000
$('#foo').data('decimal'); // 1000 "1000.00"
$('#foo').data('scientific'); // 1000 "1e3"
$('#foo').data('hex'); // 1000 "0x03e8"
If you plan on using alternative numeric syntaxes to access numeric values, be sure to cast the value to a Number
first, such as with a unary +
operator.
+$('#foo').data('hex'); // 1000
I know I am posting this answer little late, but I felt it is worth using Google's fuse location provider service to get the current location.
Main features of this api are :
1.Simple APIs: Lets you choose your accuracy level as well as power consumption.
2.Immediately available: Gives your apps immediate access to the best, most recent location.
3.Power-efficiency: It chooses the most efficient way to get the location with less power consumptions
4.Versatility: Meets a wide range of needs, from foreground uses that need highly accurate location to background uses that need periodic location updates with negligible power impact.
It is flexible in while updating in location also.
If you want current location only when your app starts then you can use getLastLocation(GoogleApiClient)
method.
If you want to update your location continuously then you can use requestLocationUpdates(GoogleApiClient,LocationRequest, LocationListener)
You can find a very nice blog about fuse location here and google doc for fuse location also can be found here.
Update
According to developer docs starting from Android O they have added new limits on background location.
If your app is running in the background, the location system service computes a new location for your app only a few times each hour. This is the case even when your app is requesting more frequent location updates. However if your app is running in the foreground, there is no change in location sampling rates compared to Android 7.1.1 (API level 25).
when you create an object using predefine class, at first you want to create a variable for storing that object. Then you can create object and store variable that you created.
class Student:
def __init__(self):
# creating an object....
student1=Student()
Actually this init method is the constructor of class.you can initialize that method using some attributes.. In that point , when you creating an object , you will have to pass some values for particular attributes..
class Student:
def __init__(self,name,age):
self.name=value
self.age=value
# creating an object.......
student2=Student("smith",25)
This is yet another reason to use Joda Time
new DateMidnight(2010, 3, 5)
DateMidnight is now deprecated but the same effect can be achieved with Joda Time DateTime
DateTime dt = new DateTime(2010, 3, 5, 0, 0);
While it looks like your setup is correct, there are a few things to check:
env
- specifically PATH
.command -v java
tells you what?java
executable in $JAVA_HOME\bin
and does it have the execute bit set? If not chmod a+x java
it.I trust you have source
'd your .profile
after adding/changing the JAVA_HOME
and PATH
?
Also, you can help yourself in future maintenance of your JDK installation by writing this instead:
export JAVA_HOME=/home/aqeel/development/jdk/jdk1.6.0_35
export PATH=$JAVA_HOME/bin:$PATH
Then you only need to update one env variable when you setup the JDK installation.
Finally, you may need to run hash -r
to clear the Bash program cache. Other shells may need a similar command.
Cheers,
I ran task manager and looked for httpd.exe in process. Their were two of them running. I stopped one of them gone back to xampp control pannel and started apache. It worked.
I've an object (basically a VO) in Java and I don't know its type. I need to get values which are not null in that object.
Maybe you don't necessary need reflection for that -- here is a plain OO design that might solve your problem:
Validation
which expose a method validate
which checks the fields and return whatever is appropriate. Validation
and check that easily.I guess that you need the field that are null to display an error message in a generic way, so that should be enough. Let me know if this doesn't work for you for some reason.
I figured it out, and it's actually pretty straight forward.
Set your variable:
$image1 = "img/products/image1.jpg";
Then ceate a cell, position it, then rather than setting where the image is, use the variable you created above with the following:
$this->Cell( 40, 40, $pdf->Image($image1, $pdf->GetX(), $pdf->GetY(), 33.78), 0, 0, 'L', false );
Now the cell will move up and down with content if other cells around it move.
Hope this helps others in the same boat.
It is possible. Have a look at JSch.addIdentity(...)
This allows you to use key either as byte array or to read it from file.
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UserAuthPubKey {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
String user = "tjill";
String host = "192.18.0.246";
int port = 10022;
String privateKey = ".ssh/id_rsa";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
// disabling StrictHostKeyChecking may help to make connection but makes it insecure
// see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
//
// java.util.Properties config = new java.util.Properties();
// config.put("StrictHostKeyChecking", "no");
// session.setConfig(config);
session.connect();
System.out.println("session connected.....");
Channel channel = session.openChannel("sftp");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
System.out.println("shell channel connected....");
ChannelSftp c = (ChannelSftp) channel;
String fileName = "test.txt";
c.put(fileName, "./in/");
c.exit();
System.out.println("done");
} catch (Exception e) {
System.err.println(e);
}
}
}
click here in settings, one pop up window will get open. There we have switcher to make SSL verification certificate (Off)
You can also compare with double value
BigDecimal a= new BigDecimal("1.1"); BigDecimal b =new BigDecimal("1.1");
System.out.println(a.doubleValue()==b.doubleValue());
If you don't care too much about performance and want to use the straightforward way, you can use either DIV
or IDIV
.
DIV
or IDIV
takes only one operand where it divides
a certain register with this operand, the operand can
be register or memory location only.
When operand is a byte: AL = AL / operand, AH = remainder (modulus).
Ex:
MOV AL,31h ; Al = 31h
DIV BL ; Al (quotient)= 08h, Ah(remainder)= 01h
when operand is a word: AX = (AX) / operand, DX = remainder (modulus).
Ex:
MOV AX,9031h ; Ax = 9031h
DIV BX ; Ax=1808h & Dx(remainder)= 01h
It could be some un-initialized function pointer, in particular if you have corrupted memory (then the bogus vtable of C++ bad pointers to invalid objects might give that).
BTW gdb
watchpoints & tracepoints, and also valgrind might be useful (if available) to debug such issues. Or some address sanitizer.
Here, give this a shot (this is just a pseudocode)
using System;
using System.Data;
using System.Data.SqlClient;
public class PullDataTest
{
// your data table
private DataTable dataTable = new DataTable();
public PullDataTest()
{
}
// your method to pull data from database to datatable
public void PullData()
{
string connString = @"your connection string here";
string query = "select * from table";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dataTable);
conn.Close();
da.Dispose();
}
}
In Python 2, raw_input()
returns a string, and input()
tries to run the input as a Python expression.
Since getting a string was almost always what you wanted, Python 3 does that with input()
. As Sven says, if you ever want the old behaviour, eval(input())
works.
You could get the full path as a string then split it into a list using your operating system's separator character. Then you get the program name, folder name etc by accessing the elements from the end of the list using negative indices.
Like this:
import os
strPath = os.path.realpath(__file__)
print( f"Full Path :{strPath}" )
nmFolders = strPath.split( os.path.sep )
print( "List of Folders:", nmFolders )
print( f"Program Name :{nmFolders[-1]}" )
print( f"Folder Name :{nmFolders[-2]}" )
print( f"Folder Parent:{nmFolders[-3]}" )
The output of the above was this:
Full Path :C:\Users\terry\Documents\apps\environments\dev\app_02\app_02.py
List of Folders: ['C:', 'Users', 'terry', 'Documents', 'apps', 'environments', 'dev', 'app_02', 'app_02.py']
Program Name :app_02.py
Folder Name :app_02
Folder Parent:dev
Full combo of build/ clean project + build/ rebuild project + file/ Invalidate caches / restart works for me!
RUN /bin/sh -c "apk add --no-cache bash"
worked for me.
margin
to align images:Since we wanted the image
to be left-aligned
, we added:
img {
margin-right: auto;
}
Similarly for image
to be right-aligned
, we can add margin-right: auto;
. The snippet shows a demo for both types of alignment.
Good Luck...
div {_x000D_
display:flex; _x000D_
flex-direction:column;_x000D_
border: 2px black solid;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
text-align: center;_x000D_
}_x000D_
hr {_x000D_
border: 1px black solid;_x000D_
width: 100%_x000D_
}_x000D_
img.one {_x000D_
margin-right: auto;_x000D_
}_x000D_
_x000D_
img.two {_x000D_
margin-left: auto;_x000D_
}
_x000D_
<div>_x000D_
<h1>Flex Box</h1>_x000D_
_x000D_
<hr />_x000D_
_x000D_
<img src="https://via.placeholder.com/80x80" class="one" _x000D_
/>_x000D_
_x000D_
_x000D_
<img src="https://via.placeholder.com/80x80" class="two" _x000D_
/>_x000D_
_x000D_
<hr />_x000D_
</div>
_x000D_
A little verbose, but self documenting...
Dim strEmpty() As String = Enumerable.Empty(Of String).ToArray
You can use TIMESTAMPDIFF(unit, datetime_expr1, datetime_expr2)
function:
SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age
From the fine manual.
You must own the table to use ALTER TABLE.
Or be a database superuser.
ERROR: must be owner of relation contact
PostgreSQL error messages are usually spot on. This one is spot on.
Please check that you are running the android device over same network. This will solve the problem. have fun!!!
There actually doesn't seem to be a lot of explanation on this subject apparently but the exit codes are supposed to be used to give an indication on how the thread exited, 0
tends to mean that it exited safely whilst anything else tends to mean it didn't exit as expected. But then this exit code can be set in code by yourself to completely overlook this.
The closest link I could find to be useful for more information is this
Quote from above link:
What ever the method of exiting, the integer that you return from your process or thread must be values from 0-255(8bits). A zero value indicates success, while a non zero value indicates failure. Although, you can attempt to return any integer value as an exit code, only the lowest byte of the integer is returned from your process or thread as part of an exit code. The higher order bytes are used by the operating system to convey special information about the process. The exit code is very useful in batch/shell programs which conditionally execute other programs depending on the success or failure of one.
From the Documentation for GetEXitCodeThread
Important The GetExitCodeThread function returns a valid error code defined by the application only after the thread terminates. Therefore, an application should not use STILL_ACTIVE (259) as an error code. If a thread returns STILL_ACTIVE (259) as an error code, applications that test for this value could interpret it to mean that the thread is still running and continue to test for the completion of the thread after the thread has terminated, which could put the application into an infinite loop.
My understanding of all this is that the exit code doesn't matter all that much if you are using threads within your own application for your own application. The exception to this is possibly if you are running a couple of threads at the same time that have a dependency on each other. If there is a requirement for an outside source to read this error code, then you can set it to let other applications know the status of your thread.
in your example you could use strip but you have to provide the space
string = '"" " " ""\\1" " "" ""'
string.strip('" ') # output '\\1'
note the \' in the output is the standard python quotes for string output
the value of your variable is '\\1'
I came up with a slightly different solution. It's a bit hack-ish, but here is the mapping:
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>myAppServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
This basically just maps all content files by extension to the default servlet, and everything else to "myAppServlet".
It works in both Jetty and Tomcat.
The issue of erroneous leftover entries in the .csproj file still occurs with VS2015update3 and can also occur if you try to change the signing certificate for a different one (even if that is one generated using the 'new' option in the certificate selection dropdown). The advice in the accepted answer (mark as not signed, save, unload project, edit .csproj, remove the properties relating to the old certificates/thumbprints/keys & reload project, set certificate) is reliable.
Make a text using notepad or any text editor of you choice. Open notepad, write this short command "cmd.exe" without the quote aand save it as cmd.bat.
Click cmd.bat and choose "run as administrator".
How about disabled=disabled
:
<input id="price_from" value="price from " disabled="disabled">????????????
Problem is if you don't want user to edit them, why display them in input? You can hide them even if you want to submit a form. And to display information, just use other tag instead.
The most important part is the concepts. Once you understand how the building blocks work, differences in syntax amount to little more than mild dialects. A layer on top of your regular expression engine's syntax is the syntax of the programming language you're using. Languages such as Perl remove most of this complication, but you'll have to keep in mind other considerations if you're using regular expressions in a C program.
If you think of regular expressions as building blocks that you can mix and match as you please, it helps you learn how to write and debug your own patterns but also how to understand patterns written by others.
Conceptually, the simplest regular expressions are literal characters. The pattern N
matches the character 'N'.
Regular expressions next to each other match sequences. For example, the pattern Nick
matches the sequence 'N' followed by 'i' followed by 'c' followed by 'k'.
If you've ever used grep
on Unix—even if only to search for ordinary looking strings—you've already been using regular expressions! (The re
in grep
refers to regular expressions.)
Adding just a little complexity, you can match either 'Nick' or 'nick' with the pattern [Nn]ick
. The part in square brackets is a character class, which means it matches exactly one of the enclosed characters. You can also use ranges in character classes, so [a-c]
matches either 'a' or 'b' or 'c'.
The pattern .
is special: rather than matching a literal dot only, it matches any character†. It's the same conceptually as the really big character class [-.?+%$A-Za-z0-9...]
.
Think of character classes as menus: pick just one.
Using .
can save you lots of typing, and there are other shortcuts for common patterns. Say you want to match a digit: one way to write that is [0-9]
. Digits are a frequent match target, so you could instead use the shortcut \d
. Others are \s
(whitespace) and \w
(word characters: alphanumerics or underscore).
The uppercased variants are their complements, so \S
matches any non-whitespace character, for example.
From there, you can repeat parts of your pattern with quantifiers. For example, the pattern ab?c
matches 'abc' or 'ac' because the ?
quantifier makes the subpattern it modifies optional. Other quantifiers are
*
(zero or more times)+
(one or more times){n}
(exactly n times){n,}
(at least n times){n,m}
(at least n times but no more than m times)Putting some of these blocks together, the pattern [Nn]*ick
matches all of
The first match demonstrates an important lesson: *
always succeeds! Any pattern can match zero times.
A few other useful examples:
[0-9]+
(and its equivalent \d+
) matches any non-negative integer\d{4}-\d{2}-\d{2}
matches dates formatted like 2019-01-01A quantifier modifies the pattern to its immediate left. You might expect 0abc+0
to match '0abc0', '0abcabc0', and so forth, but the pattern immediately to the left of the plus quantifier is c
. This means 0abc+0
matches '0abc0', '0abcc0', '0abccc0', and so on.
To match one or more sequences of 'abc' with zeros on the ends, use 0(abc)+0
. The parentheses denote a subpattern that can be quantified as a unit. It's also common for regular expression engines to save or "capture" the portion of the input text that matches a parenthesized group. Extracting bits this way is much more flexible and less error-prone than counting indices and substr
.
Earlier, we saw one way to match either 'Nick' or 'nick'. Another is with alternation as in Nick|nick
. Remember that alternation includes everything to its left and everything to its right. Use grouping parentheses to limit the scope of |
, e.g., (Nick|nick)
.
For another example, you could equivalently write [a-c]
as a|b|c
, but this is likely to be suboptimal because many implementations assume alternatives will have lengths greater than 1.
Although some characters match themselves, others have special meanings. The pattern \d+
doesn't match backslash followed by lowercase D followed by a plus sign: to get that, we'd use \\d\+
. A backslash removes the special meaning from the following character.
Regular expression quantifiers are greedy. This means they match as much text as they possibly can while allowing the entire pattern to match successfully.
For example, say the input is
"Hello," she said, "How are you?"
You might expect ".+"
to match only 'Hello,' and will then be surprised when you see that it matched from 'Hello' all the way through 'you?'.
To switch from greedy to what you might think of as cautious, add an extra ?
to the quantifier. Now you understand how \((.+?)\)
, the example from your question works. It matches the sequence of a literal left-parenthesis, followed by one or more characters, and terminated by a right-parenthesis.
If your input is '(123) (456)', then the first capture will be '123'. Non-greedy quantifiers want to allow the rest of the pattern to start matching as soon as possible.
(As to your confusion, I don't know of any regular-expression dialect where ((.+?))
would do the same thing. I suspect something got lost in transmission somewhere along the way.)
Use the special pattern ^
to match only at the beginning of your input and $
to match only at the end. Making "bookends" with your patterns where you say, "I know what's at the front and back, but give me everything between" is a useful technique.
Say you want to match comments of the form
-- This is a comment --
you'd write ^--\s+(.+)\s+--$
.
Regular expressions are recursive, so now that you understand these basic rules, you can combine them however you like.
†: The statement above that .
matches any character is a simplification for pedagogical purposes that is not strictly true. Dot matches any character except newline, "\n"
, but in practice you rarely expect a pattern such as .+
to cross a newline boundary. Perl regexes have a /s
switch and Java Pattern.DOTALL
, for example, to make .
match any character at all. For languages that don't have such a feature, you can use something like [\s\S]
to match "any whitespace or any non-whitespace", in other words anything.
@Zags solution was gorgeous!
I would add, though, a condition for datefields in order to make it JSON friendly.
If you want a django model that has a better python command-line display, have your models child class the following:
from django.db import models
from django.db.models.fields.related import ManyToManyField
class PrintableModel(models.Model):
def __repr__(self):
return str(self.to_dict())
def to_dict(self):
opts = self._meta
data = {}
for f in opts.concrete_fields + opts.many_to_many:
if isinstance(f, ManyToManyField):
if self.pk is None:
data[f.name] = []
else:
data[f.name] = list(f.value_from_object(self).values_list('pk', flat=True))
elif isinstance(f, DateTimeField):
if f.value_from_object(self) is not None:
data[f.name] = f.value_from_object(self).timestamp()
else:
data[f.name] = None
else:
data[f.name] = f.value_from_object(self)
return data
class Meta:
abstract = True
So, for example, if we define our models as such:
class OtherModel(PrintableModel): pass
class SomeModel(PrintableModel):
value = models.IntegerField()
value2 = models.IntegerField(editable=False)
created = models.DateTimeField(auto_now_add=True)
reference1 = models.ForeignKey(OtherModel, related_name="ref1")
reference2 = models.ManyToManyField(OtherModel, related_name="ref2")
Calling SomeModel.objects.first()
now gives output like this:
{'created': 1426552454.926738,
'value': 1, 'value2': 2, 'reference1': 1, u'id': 1, 'reference2': [1]}
NERDcommenter is an excellent plugin for commenting which automatically detects a number of filetypes and their associated comment characters. Ridiculously easy to install using Pathogen.
Comment with <leader>cc
. Uncomment with <leader>cu
. And toggle comments with <leader>c<space>
.
(The default <leader>
key in vim is \
)
<p>tetxetextex</p>
<ol><li>first element</li></ol>
<p>other textetxeettx</p>
Because both <p>
and <ol>
are element rendered as block.
Disclaimer: I am the author of Jsonix, a powerful open-source XML<->JSON JavaScript mapping library.
Today I've released the new version of the Jsonix Schema Compiler, with the new JSON Schema generation feature.
Let's take the Purchase Order schema for example. Here's a fragment:
<xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
<xsd:complexType name="PurchaseOrderType">
<xsd:sequence>
<xsd:element name="shipTo" type="USAddress"/>
<xsd:element name="billTo" type="USAddress"/>
<xsd:element ref="comment" minOccurs="0"/>
<xsd:element name="items" type="Items"/>
</xsd:sequence>
<xsd:attribute name="orderDate" type="xsd:date"/>
</xsd:complexType>
You can compile this schema using the provided command-line tool:
java -jar jsonix-schema-compiler-full.jar
-generateJsonSchema
-p PO
schemas/purchaseorder.xsd
The compiler generates Jsonix mappings as well the matching JSON Schema.
Here's what the result looks like (edited for brevity):
{
"id":"PurchaseOrder.jsonschema#",
"definitions":{
"PurchaseOrderType":{
"type":"object",
"title":"PurchaseOrderType",
"properties":{
"shipTo":{
"title":"shipTo",
"allOf":[
{
"$ref":"#/definitions/USAddress"
}
]
},
"billTo":{
"title":"billTo",
"allOf":[
{
"$ref":"#/definitions/USAddress"
}
]
}, ...
}
},
"USAddress":{ ... }, ...
},
"anyOf":[
{
"type":"object",
"properties":{
"name":{
"$ref":"http://www.jsonix.org/jsonschemas/w3c/2001/XMLSchema.jsonschema#/definitions/QName"
},
"value":{
"$ref":"#/definitions/PurchaseOrderType"
}
},
"elementName":{
"localPart":"purchaseOrder",
"namespaceURI":""
}
}
]
}
Now this JSON Schema is derived from the original XML Schema. It is not exactly 1:1 transformation, but very very close.
The generated JSON Schema matches the generatd Jsonix mappings. So if you use Jsonix for XML<->JSON conversion, you should be able to validate JSON with the generated JSON Schema. It also contains all the required metadata from the originating XML Schema (like element, attribute and type names).
Disclaimer: At the moment this is a new and experimental feature. There are certain known limitations and missing functionality. But I'm expecting this to manifest and mature very fast.
Links:
npm install
HTML forms support GET and POST. (HTML5 at one point added PUT/DELETE, but those were dropped.)
XMLHttpRequest supports every method, including CHICKEN, though some method names are matched against case-insensitively (methods are case-sensitive per HTTP) and some method names are not supported at all for security reasons (e.g. CONNECT).
Browsers are slowly converging on the rules specified by XMLHttpRequest, but as the other comment pointed out there are still some differences.
If you want the accepted answer to work in JQuery 3 change the code like this:
var scrollItems = menuItems.map(function () {
var id = $(this).attr("href");
try {
var item = $(id);
if (item.length) {
return item;
}
} catch {}
});
I also added a try-catch to prevent javascript from crashing if there is no element by that id. Feel free to improve it even more ;)
I have used an html template. In this template's custom.js file, there was a function like this:
jQuery(document).ready(function($) {
$(window).on('load', function() {
//...
});
});
But this function was not working when I go to back after go to other page.
So, I tried this and it has worked:
jQuery(document).ready(function($) {
//...
});
//Window Load Start
window.addEventListener('load', function() {
jQuery(document).ready(function($) {
//...
});
});
Now, I have 2 "ready" function but it doesn't give any error and the page is working very well.
Nevertheless, I have to declare that it has tested on Windows 10 - Opera v53 and Edge v42 but no other browsers. Keep in mind this...
Note: jquery version was 3.3.1 and migrate version was 3.0.0
In any case, you can override height
with max-height
.
One hackish way to define an exit
method in context:
class Bar; def exit; end; end
This works because exit
in the initializer will be resolved as self.exit
1. In addition, this approach allows using the object after it has been created, as in: b = B.new
.
But really, one shouldn't be doing this: don't have exit
(or even puts
) there to begin with.
(And why is there an "infinite" loop and/or user input in an intiailizer? This entire problem is primarily the result of poorly structured code.)
1 Remember Kernel#exit is only a method. Since Kernel is included in every Object, then it's merely the case that exit
normally resolves to Object#exit
. However, this can be changed by introducing an overridden method as shown - nothing fancy.
Node.js is a server side JS platform build on V8 which is chrome java-script runtime.
It leverages the use of java-script on servers too.
You can use JS Date() function or Date class.
As already mentioned by several people, eq
is the right operator here.
If you use warnings;
in your script, you'll get warnings about this (and many other useful things); I'd recommend use strict;
as well.
You can do it with:
dotnet ef migrations remove
Take care not to remove any migrations which are already applied to production databases. Not doing so will prevent you from being able to revert it, and may break the assumptions made by subsequent migrations.
I would recommend using Glazed Lists for this. It makes it very easy to map a data structure to a table model.
To react to the mouseclick on the JTable, use an ActionListener: ActionListener on JLabel or JTable cell
From the Graph API documentation.
/OBJECT_ID/picture
returns a redirect to the object's picture (in this case the users)/OBJECT_ID/?fields=picture
returns the picture's URLExamples:
<img src="https://graph.facebook.com/4/picture"/>
uses a HTTP 301 redirect to Zuck's profile picture
https://graph.facebook.com/4?fields=picture
returns the URL itself
I'm sure the original poster's issue has long since been resolved. However, I had this same issue, so I thought I'd explain what was causing this problem for me.
I was doing a union query with two tables -- 'foo' and 'foo_bar'. However, in my SQL statement, I had a typo: 'foo.bar'
So, instead of telling me that the 'foo.bar' table doesn't exist, the error message indicates that the command was denied -- as though I don't have permissions.
Hope this helps someone.
ES6 of the day here;
const json_getAllKeys = data => (
data.reduce((keys, obj) => (
keys.concat(Object.keys(obj).filter(key => (
keys.indexOf(key) === -1))
)
), [])
)
And yes it can be written in very long one line;
const json_getAllKeys = data => data.reduce((keys, obj) => keys.concat(Object.keys(obj).filter(key => keys.indexOf(key) === -1)), [])
EDIT: Returns all first order keys if the input is of type array of objects
Mine was a name spacing issue. I had two files with the same name. Just renamed them and it resolved.
Always gotta check the 'stupid me' box first before looking elsewhere. : )
Yes, there are a number of ways that you can do this. The "fastest" way would be to add CSS to the div similar to the following
#term-defs {
height: 300px;
overflow: scroll; }
This will force the div to be scrollable, but this might not get the best effect. Another route would be to absolute fix the position of the items at the top, you can play with this by doing something like this.
#top {
position: fixed;
top: 0;
left: 0;
z-index: 999;
width: 100%;
height: 23px;
}
This will fix it to the top, on top of other content with a height of 23px.
The final implementation will depend on what effect you really want.
The solution below works in Firefox also, without any JavaScript:
option[default] {_x000D_
display: none;_x000D_
}
_x000D_
<select>_x000D_
<option value="" default selected>Select Your Age</option>_x000D_
<option value="1">1</option>_x000D_
<option value="2">2</option>_x000D_
<option value="3">3</option>_x000D_
<option value="4">4</option>_x000D_
</select>
_x000D_
By lines I assume you mean rows in the table person
. What you're looking for is:
select p.name
from person p
where p.name LIKE '%A%'; --contains the character 'A'
The above is case sensitive. For a case insensitive search, you can do:
select p.name
from person p
where UPPER(p.name) LIKE '%A%'; --contains the character 'A' or 'a'
For the special character, you can do:
select p.name
from person p
where p.name LIKE '%'||chr(8211)||'%'; --contains the character chr(8211)
The LIKE
operator matches a pattern. The syntax of this command is described in detail in the Oracle documentation. You will mostly use the %
sign as it means match zero or more characters.
As mentioned in the error, the official manual and the comments:
Replace
public function TSStatus($host, $queryPort)
with
public function __construct($host, $queryPort)
Incremental development means that different parts of a software project are continuously integrated into the whole, instead of a monolithic approach where all the different parts are assembled in one or a few milestones of the project.
Iterative means that once a first version of a component is complete it is tested, reviewed and the results are almost immediately transformed into a new version (iteration) of this component.
So as a first result: iterative development doesn't need to be incremental and vice versa, but these methods are a good fit.
Agile development aims to reduce massive planing overhead in software projects to allow fast reactions to change e.g. in customer wishes. Incremental and iterative development are almost always part of an agile development strategy. There are several approaches to Agile development (e.g. scrum).
CONCAT with a null value returns null, so the easiest solution is:
UPDATE myTable SET spares = IFNULL (CONCAT( spares , "string" ), "string")
I used
View.inflate(getContext(), R.layout.whatever, null)
The using of View.inflate
prevents the warning of using null
at getLayoutInflater().inflate()
.
Swift 3:
if let data = text.data(using: String.Encoding.utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any]
print(json)
} catch {
print("Something went wrong")
}
}
Just install apt-get install php5-mysqlnd Restart Apache service apache2 restart
I had this exact issue, and created a GitHub project for testing and figuring out the correct settings.
It contains a working Dockerfile
with supporting scripts, and a simple docker-compose.yml
for quick testing.
Call HttpURLConnection.setRequestMethod("POST")
and HttpURLConnection.setDoOutput(true);
Actually only the latter is needed as POST then becomes the default method.
I've been using keyup on a number field, but today I noticed in chrome the input has up/down buttons to increase/decrease the value which aren't recognized by keyup.
My solution is to use keyup and change together:
(keyup)="unitsChanged[i] = true" (change)="unitsChanged[i] = true"
Initial tests indicate this works fine, will post back if any bugs found after further testing.
As you see, that's actually a natural error ..
A typical construct for reading from an Unpickler object would be like this ..
try:
data = unpickler.load()
except EOFError:
data = list() # or whatever you want
EOFError is simply raised, because it was reading an empty file, it just meant End of File ..
In some cases (blocks without any content, but with background) it can be overridden using borders, individually for every block.
For example:
.colored {
background: #000;
border: 1px solid #ccc;
width: 8px;
height: 8px;
}
@media print {
.colored div {
border: 4px solid #000;
width: 0;
height: 0;
}
}
You can also use Java's implicit conversion:
BigInteger m = new BigInteger(bytemsg);
String mStr = "" + m; // mStr now contains string representation of m.
In case you
add the following to your .bash_profile
:
export GEM_HOME=/Users/‹your_user›/.gem
export PATH="$GEM_HOME/bin:$PATH"
Open a new tab in Terminal OR source ~/.bash_profile
and you're good to go!
The guide you linked now has a Tear Down section:
Talking to the master with the appropriate credentials, run:
kubectl drain <node name> --delete-local-data --force --ignore-daemonsets
kubectl delete node <node name>
Then, on the node being removed, reset all kubeadm installed state:
kubeadm reset
e.which doesn't work in IE try e.keyCode, also you probably want to use keydown() instead of keypress() if you are targeting IE.
See http://unixpapa.com/js/key.html for more information.
Edited for clarity:
This will work to to get the value if the remote.origin.url is in the form protocol://auth_info@git_host:port/project/repo.git. If you find it doesn't work, adjust the -f5 option that is part of the first cut command.
For the example remote.origin.url of protocol://auth_info@git_host:port/project/repo.git the output created by the cut command would contain the following:
-f1: protocol: -f2: (blank) -f3: auth_info@git_host:port -f4: project -f5: repo.git
If you are having problems, look at the output of the git config --get remote.origin.url
command to see which field contains the original repository. If the remote.origin.url does not contain the .git string then omit the pipe to the second cut command.
#!/usr/bin/env bash
repoSlug="$(git config --get remote.origin.url | cut -d/ -f5 | cut -d. -f1)"
echo ${repoSlug}
Use type = "button"
instead of "submit"
, then add an onClick
handler for it.
For example:
<input type="button" value="Increment" onClick="myVar++;" />
If you want to do some high-powered debugging, you can subscribe to every change of the state and pause the app to see what's going on in detail as follows.
store.jsstore.subscribe( () => {
console.log('state\n', store.getState());
debugger;
});
Place that in the file where you do createStore
.
To copy the state
object from the console to the clipboard, follow these steps:
Right-click an object in Chrome's console and select Store as Global Variable from the context menu. It will return something like temp1 as the variable name.
Chrome also has a copy()
method, so copy(temp1)
in the console should copy that object to your clipboard.
https://stackoverflow.com/a/25140576
https://scottwhittaker.net/chrome-devtools/2016/02/29/chrome-devtools-copy-object.html
You can view the object in a json viewer like this one: http://jsonviewer.stack.hu/
You can compare two json objects here: http://www.jsondiff.com/
WARNING:
git clean -f
will remove untracked files, meaning they're gone for good since they aren't stored in the repository. Make sure you really want to remove all untracked files before doing this.
Try this and see git clean -f
.
git reset --hard
will not remove untracked files, where as git-clean
will remove any files from the tracked root directory that are not under Git tracking.
Alternatively, as @Paul Betts said, you can do this (beware though - that removes all ignored files too)
git clean -df
git clean -xdf
CAUTION! This will also delete ignored filesWell, your code is not reproducible so we will never know for sure, but this is what help('break')
says:
break breaks out of a for, while or repeat loop; control is transferred to the first statement outside the inner-most loop.
So yes, break
only breaks the current loop. You can also see it in action with e.g.:
for (i in 1:10)
{
for (j in 1:10)
{
for (k in 1:10)
{
cat(i," ",j," ",k,"\n")
if (k ==5) break
}
}
}
If need to find nested in some dirs:
find / -type f -wholename "*dirname/filename"
Or connected dirs:
find / -type d -wholename "*foo/bar"
The general belief is that you shouldn't be using background images for things with meaningful semantic value so there isn't really a proper way to store alt data with those images. The important question is what are you going to be doing with that alt data? Do you want it to display if the images don't load? Do you need it for some programmatic function on the page? You could store the data arbitrarily using made up css properties that have no meaning (might cause errors?) OR by adding in hidden images that have the image and the alt tag, and then when you need a background images alt you can compare the image paths and then handle the data however you want using some custom script to simulate what you need. There's no way I know of to make the browser automatically handle some sort of alt attribute for background images though.
I got this error because the user account that TFS Build Service was running under did not have permissions to write to the destination folder. Right-click on the folder-->Properties-->Security
.
$('html,body').animate({
scrollTop: $('#answer-<%= @answer.id %>').offset().top - 50
}, 700);
This is from : Script to change password on linux servers over ssh
The script below will need to be saved as a file (eg ./passwdWrapper
) and made executable (chmod u+x ./passwdWrapper)
#!/usr/bin/expect -f
#wrapper to make passwd(1) be non-interactive
#username is passed as 1st arg, passwd as 2nd
set username [lindex $argv 0]
set password [lindex $argv 1]
set serverid [lindex $argv 2]
set newpassword [lindex $argv 3]
spawn ssh $serverid passwd
expect "assword:"
send "$password\r"
expect "UNIX password:"
send "$password\r"
expect "password:"
send "$newpassword\r"
expect "password:"
send "$newpassword\r"
expect eof
Then you can run ./passwdWrapper $user $password $server $newpassword
which will actually change the password.
Note: This requires that you install expect
on the machine from which you will be running the command. (sudo apt-get install expect
) The script works on CentOS 5/6 and Ubuntu 14.04, but if the prompts in passwd
change, you may have to tweak the expect
lines.
AJAX is simply Asyncronous JSON or XML (in most newer situations JSON). Because we are doing an ASYNC task we will likely be providing our users with a more enjoyable UI experience. In this specific case we are doing a FORM submission using AJAX.
Really quickly there are 4 general web actions GET
, POST
, PUT
, and DELETE
; these directly correspond with SELECT/Retreiving DATA
, INSERTING DATA
, UPDATING/UPSERTING DATA
, and DELETING DATA
. A default HTML/ASP.Net webform/PHP/Python or any other form
action is to "submit" which is a POST action. Because of this the below will all describe doing a POST. Sometimes however with http you might want a different action and would likely want to utilitize .ajax
.
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get the action attribute from the <form action=""> element */
var $form = $(this),
url = $form.attr('action');
/* Send the data using post with element id name and name2*/
var posting = $.post(url, {
name: $('#name').val(),
name2: $('#name2').val()
});
/* Alerts the results */
posting.done(function(data) {
$('#result').text('success');
});
posting.fail(function() {
$('#result').text('failed');
});
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formoid" action="studentFormInsert.php" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name">
</div>
<div>
<label class="title">Last Name</label>
<input type="text" id="name2" name="name2">
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<div id="result"></div>
_x000D_
From jQuery website $.post
documentation.
Example: Send form data using ajax requests
$.post("test.php", $("#testform").serialize());
Example: Post a form using ajax and put results in a div
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form action="/" id="searchForm">
<input type="text" name="s" placeholder="Search..." />
<input type="submit" value="Search" />
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
/* attach a submit handler to the form */
$("#searchForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $(this),
term = $form.find('input[name="s"]').val(),
url = $form.attr('action');
/* Send the data using post */
var posting = $.post(url, {
s: term
});
/* Put the results in a div */
posting.done(function(data) {
var content = $(data).find('#content');
$("#result").empty().append(content);
});
});
</script>
</body>
</html>
Without using OAuth or at minimum HTTPS (TLS/SSL) please don't use this method for secure data (credit card numbers, SSN, anything that is PCI, HIPAA, or login related)
@Override
public void onBackPressed() {
super.onBackPressed();
}
and if you want on button click go back then simply put
bbsubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
I ran into the same problem. My fix was changing
<parameter value="v12.0" />
to
<parameter value="mssqllocaldb" />
into the "app.config" file.
I had a similar problems, till I got it working. Below is the full listing of the integration:
ssh-keygen -t rsa
Copy the public key (~/.ssh/id_rsa.pub) and paste it in Bitbucket SSH keys, in user’s account management console:
Copy the private key (~/.ssh/id_rsa) to new user (or even existing one) with private key credentials, in this case, username will not make a difference, so username can be anything:
run this command to test if you can get access to Bitbucket account:
ssh -T [email protected]
git clone [email protected]:username/repo_name.git
Now you can enable Bitbucket hooks for Jenkins push notifications and automatic builds, you will do that in 2 steps:
Add an authentication token inside the job/project you configure, it can be anything:
In Bitbucket hooks: choose jenkins hooks, and fill the fields as below:
Where:
**End point**: username:usertoken@jenkins_domain_or_ip
**Project name**: is the name of job you created on Jenkins
**Token**: Is the authorization token you added in the above steps in your Jenkins' job/project
Recommendation: I usually add the usertoken as the authorization Token (in both Jenkins Auth Token job configuration and Bitbucket hooks), making them one variable to ease things on myself.
In theory, yes, as long as you don't exceed the maximum url and/oor query string length for the client or server.
In practice, things can get a bit trickier. For example, it can trigger an HttpRequestValidationException on ASP.NET if the value happens to contain an "on" and you leave in the trailing "==".
I just put SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
as first line of my Job.execute(JobExecutionContext context)
method.
I just wrote a Cli helper to deal with Unix/windows easily.
Javascript:
define(["require", "exports"], function (require, exports) {
/**
* Helper to use the Command Line Interface (CLI) easily with both Windows and Unix environments.
* Requires underscore or lodash as global through "_".
*/
var Cli = (function () {
function Cli() {}
/**
* Execute a CLI command.
* Manage Windows and Unix environment and try to execute the command on both env if fails.
* Order: Windows -> Unix.
*
* @param command Command to execute. ('grunt')
* @param args Args of the command. ('watch')
* @param callback Success.
* @param callbackErrorWindows Failure on Windows env.
* @param callbackErrorUnix Failure on Unix env.
*/
Cli.execute = function (command, args, callback, callbackErrorWindows, callbackErrorUnix) {
if (typeof args === "undefined") {
args = [];
}
Cli.windows(command, args, callback, function () {
callbackErrorWindows();
try {
Cli.unix(command, args, callback, callbackErrorUnix);
} catch (e) {
console.log('------------- Failed to perform the command: "' + command + '" on all environments. -------------');
}
});
};
/**
* Execute a command on Windows environment.
*
* @param command Command to execute. ('grunt')
* @param args Args of the command. ('watch')
* @param callback Success callback.
* @param callbackError Failure callback.
*/
Cli.windows = function (command, args, callback, callbackError) {
if (typeof args === "undefined") {
args = [];
}
try {
Cli._execute(process.env.comspec, _.union(['/c', command], args));
callback(command, args, 'Windows');
} catch (e) {
callbackError(command, args, 'Windows');
}
};
/**
* Execute a command on Unix environment.
*
* @param command Command to execute. ('grunt')
* @param args Args of the command. ('watch')
* @param callback Success callback.
* @param callbackError Failure callback.
*/
Cli.unix = function (command, args, callback, callbackError) {
if (typeof args === "undefined") {
args = [];
}
try {
Cli._execute(command, args);
callback(command, args, 'Unix');
} catch (e) {
callbackError(command, args, 'Unix');
}
};
/**
* Execute a command no matters what's the environment.
*
* @param command Command to execute. ('grunt')
* @param args Args of the command. ('watch')
* @private
*/
Cli._execute = function (command, args) {
var spawn = require('child_process').spawn;
var childProcess = spawn(command, args);
childProcess.stdout.on("data", function (data) {
console.log(data.toString());
});
childProcess.stderr.on("data", function (data) {
console.error(data.toString());
});
};
return Cli;
})();
exports.Cli = Cli;
});
Typescript original source file:
/**
* Helper to use the Command Line Interface (CLI) easily with both Windows and Unix environments.
* Requires underscore or lodash as global through "_".
*/
export class Cli {
/**
* Execute a CLI command.
* Manage Windows and Unix environment and try to execute the command on both env if fails.
* Order: Windows -> Unix.
*
* @param command Command to execute. ('grunt')
* @param args Args of the command. ('watch')
* @param callback Success.
* @param callbackErrorWindows Failure on Windows env.
* @param callbackErrorUnix Failure on Unix env.
*/
public static execute(command: string, args: string[] = [], callback ? : any, callbackErrorWindows ? : any, callbackErrorUnix ? : any) {
Cli.windows(command, args, callback, function () {
callbackErrorWindows();
try {
Cli.unix(command, args, callback, callbackErrorUnix);
} catch (e) {
console.log('------------- Failed to perform the command: "' + command + '" on all environments. -------------');
}
});
}
/**
* Execute a command on Windows environment.
*
* @param command Command to execute. ('grunt')
* @param args Args of the command. ('watch')
* @param callback Success callback.
* @param callbackError Failure callback.
*/
public static windows(command: string, args: string[] = [], callback ? : any, callbackError ? : any) {
try {
Cli._execute(process.env.comspec, _.union(['/c', command], args));
callback(command, args, 'Windows');
} catch (e) {
callbackError(command, args, 'Windows');
}
}
/**
* Execute a command on Unix environment.
*
* @param command Command to execute. ('grunt')
* @param args Args of the command. ('watch')
* @param callback Success callback.
* @param callbackError Failure callback.
*/
public static unix(command: string, args: string[] = [], callback ? : any, callbackError ? : any) {
try {
Cli._execute(command, args);
callback(command, args, 'Unix');
} catch (e) {
callbackError(command, args, 'Unix');
}
}
/**
* Execute a command no matters what's the environment.
*
* @param command Command to execute. ('grunt')
* @param args Args of the command. ('watch')
* @private
*/
private static _execute(command, args) {
var spawn = require('child_process').spawn;
var childProcess = spawn(command, args);
childProcess.stdout.on("data", function (data) {
console.log(data.toString());
});
childProcess.stderr.on("data", function (data) {
console.error(data.toString());
});
}
}
Example of use:
Cli.execute(Grunt._command, args, function (command, args, env) {
console.log('Grunt has been automatically executed. (' + env + ')');
}, function (command, args, env) {
console.error('------------- Windows "' + command + '" command failed, trying Unix... ---------------');
}, function (command, args, env) {
console.error('------------- Unix "' + command + '" command failed too. ---------------');
});
Here some basic explanation of hibernate cache...
First level cache is associated with “session” object.
The scope of cache objects is of session. Once session is closed, cached objects are gone forever.
First level cache is enabled by default and you can not disable it.
When we query an entity first time, it is retrieved from database and stored in first level cache associated with hibernate session.
If we query same object again with same session object, it will be loaded from cache and no sql query will be executed.
The loaded entity can be removed from session using evict()
method. The next loading of this entity will again make a database call if it has been removed using evict()
method.
The whole session cache can be removed using clear()
method. It will remove all the entities stored in cache.
Second level cache is apart from first level cache which is available to be used globally in session factory scope.
second level cache is created in session factory scope and is available to be used in all sessions which are created using that particular session factory.
It also means that once session factory is closed, all cache associated with it die and cache manager also closed down.
Whenever hibernate session try to load an entity, the very first place it look for cached copy of entity in first level cache (associated with particular hibernate session).
If cached copy of entity is present in first level cache, it is returned as result of load method.
If there is no cached entity in first level cache, then second level cache is looked up for cached entity.
If second level cache has cached entity, it is returned as result of load method. But, before returning the entity, it is stored in first level cache also so that next invocation to load method for entity will return the entity from first level cache itself, and there will not be need to go to second level cache again.
If entity is not found in first level cache and second level cache also, then database query is executed and entity is stored in both cache levels, before returning as response of load()
method.
What you're asking is not possible. There is no mechanism in .Net that would set all references to some object to null
.
And I think that the fact that you're trying to do this indicates some sort of design problem. You should probably think about the underlying problem and solve it in another way (the other answers here suggest some options).
If the input value gets populated by a script that has some latency involved (e.g. AJAX call) then you need to wait until the input has been populated. E.g.
var w = new WebDriverWait(WebBrowser, TimeSpan.FromSeconds(10));
w.Until((d) => {
// Wait until the input has a value...
var elements = d.FindElements(By.Name(name));
var ele = elements.SingleOrDefault();
if (ele != null)
{
// Found a single element
if (ele.GetAttribute("value") != "")
{
// We have a value now
return true;
}
}
return false;
});
var e = WebBrowser.Current.FindElement(By.Name(name));
if (e.GetAttribute("value") != value)
{
Assert.Fail("Result contains a field named '{0}', but its value is '{1}', not '{2}' as expected", name, e.GetAttribute("value"), value);
}
Character set conversion is done implicitly on the database connection level. You can force automatic conversion off in the ODBC or ADODB connection string with the parameter "Auto Translate=False". This is NOT recommended. See: https://msdn.microsoft.com/en-us/library/ms130822.aspx
There has been a codepage incompatibility in SQL Server 2005 when Database and Client codepage did not match. https://support.microsoft.com/kb/KbView/904803
SQL-Management Console 2008 and upwards is a UNICODE application. All values entered or requested are interpreted as such on the application level. Conversation to and from the column collation is done implicitly. You can verify this with:
SELECT CAST(N'±' as varbinary(10)) AS Result
This will return 0xB100
which is the Unicode character U+00B1 (as entered in the Management Console window). You cannot turn off "Auto Translate" for Management Studio.
If you specify a different collation in the select, you eventually end up in a double conversion (with possible data loss) as long as "Auto Translate" is still active. The original character is first transformed to the new collation during the select, which in turn gets "Auto Translated" to the "proper" application codepage. That's why your various COLLATION tests still show all the same result.
You can verify that specifying the collation DOES have an effect in the select, if you cast the result as VARBINARY
instead of VARCHAR
so the SQL Server transformation is not invalidated by the client before it is presented:
SELECT cast(columnName COLLATE SQL_Latin1_General_CP850_BIN2 as varbinary(10)) from tableName
SELECT cast(columnName COLLATE SQL_Latin1_General_CP1_CI_AS as varbinary(10)) from tableName
This will get you 0xF1
or 0xB1
respectively if columnName
contains just the character '±'
You still might get the correct result and yet a wrong character, if the font you are using does not provide the proper glyph.
Please double check the actual internal representation of your character by casting the query to VARBINARY
on a proper sample and verify whether this code indeed corresponds to the defined database collation SQL_Latin1_General_CP850_BIN2
SELECT CAST(columnName as varbinary(10)) from tableName
Differences in application collation and database collation might go unnoticed as long as the conversion is always done the same way in and out. Troubles emerge as soon as you add a client with a different collation. Then you might find that the internal conversion is unable to match the characters correctly.
All that said, you should keep in mind that Management Studio usually is not the final reference when interpreting result sets. Even if it looks gibberish in MS, it still might be the correct output. The question is whether the records show up correctly in your applications.
The location is in the following registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps
Source: http://msdn.microsoft.com/en-us/library/windows/desktop/bb787181%28v=vs.85%29.aspx
This solution does not need any extra lib and it also fires things up when the user presses enter:
const debounce = (fn, delay) => {
let timer = null;
return function() {
const context = this,
args = arguments;
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(context, args);
}, delay);
};
}
const [search, setSearch] = useState('');
const [searchFor, setSearchFor] = useState(search);
useEffect(() => {
console.log("Search:", searchFor);
}, [searchFor]);
const fireChange = event => {
const { keyCode } = event;
if (keyCode === 13) {
event.preventDefault();
setSearchFor(search);
}
}
const changeSearch = event => {
const { value } = event.target;
setSearch(value);
debounceSetSearchFor(value);
};
const debounceSetSearchFor = useCallback(debounce(function(value) {
setSearchFor(value);
}, 250), []);
and the input could be like:
<input value={search} onKeyDown={fireChange} onChange={changeSearch} />
I used this a little example and it worked.
$('#date').datetimepicker({
defaultDate: new Date()
});
if you are on linux, edit the /etc/php/php.ini
(or you will have to create a new extension import file at /etc/php5/cli/conf.d) file so that you add the imap shared object file and then, restart the apache server. Uncomment
;extension=imap.so
so that it becomes like this:
extension=imap.so
Then, restart the apache by
# /etc/rc.d/httpd restart
Test with a setTimeout, that worked for me and I could submit my form, refers to this answer https://stackoverflow.com/a/779785/5510314
$(document).ready(function () {
$("#btnSubmit").click(function () {
setTimeout(function () { disableButton(); }, 0);
});
function disableButton() {
$("#btnSubmit").prop('disabled', true);
}
});
if anyone else need the solution
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
I wasn't completely happy by the --allow-file-access-from-files
solution, because I'm using Chrome as my primary browser, and wasn't really happy with this breach I was opening.
Now I'm using Canary ( the chrome beta version ) for my development with the flag on. And the mere Chrome version for my real blogging : the two browser don't share the flag !
create a batch-file with the following code:
dir %1 /b /a-d > list.txt
Then drag & drop a directory on it and the files inside the directory will be listed in list.txt
Try this
<div class="home-component"
[style.width.px]="width"
[style.height.px]="height">Some stuff in this div</div>
[Updated]: To set in % use
[style.height.%]="height">Some stuff in this div</div>
Don't use $(document).ready() just put the script directly in the head section of the page. Pages are processed top to bottom so things at the top are processed first.
Answering myself as the FAQ of this site encourages it. This works for me:
Mostly characters äåö are not a problematic as the default character set used by browsers and tomcat/java for webapps is latin1 ie. ISO-8859-1 which "understands" those characters.
To get UTF-8 working under Java+Tomcat+Linux/Windows+Mysql requires the following:
It's necessary to configure that the connector uses UTF-8 to encode url (GET request) parameters:
<Connector port="8080" maxHttpHeaderSize="8192"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true"
compression="on"
compressionMinSize="128"
noCompressionUserAgents="gozilla, traviata"
compressableMimeType="text/html,text/xml,text/plain,text/css,text/ javascript,application/x-javascript,application/javascript"
URIEncoding="UTF-8"
/>
The key part being URIEncoding="UTF-8" in the above example. This quarantees that Tomcat handles all incoming GET parameters as UTF-8 encoded. As a result, when the user writes the following to the address bar of the browser:
https://localhost:8443/ID/Users?action=search&name=*?*
the character ? is handled as UTF-8 and is encoded to (usually by the browser before even getting to the server) as %D0%B6.
POST request are not affected by this.
Then it's time to force the java webapp to handle all requests and responses as UTF-8 encoded. This requires that we define a character set filter like the following:
package fi.foo.filters;
import javax.servlet.*;
import java.io.IOException;
public class CharsetFilter implements Filter {
private String encoding;
public void init(FilterConfig config) throws ServletException {
encoding = config.getInitParameter("requestEncoding");
if (encoding == null) encoding = "UTF-8";
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain next)
throws IOException, ServletException {
// Respect the client-specified character encoding
// (see HTTP specification section 3.4.1)
if (null == request.getCharacterEncoding()) {
request.setCharacterEncoding(encoding);
}
// Set the default response content type and encoding
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
next.doFilter(request, response);
}
public void destroy() {
}
}
This filter makes sure that if the browser hasn't set the encoding used in the request, that it's set to UTF-8.
The other thing done by this filter is to set the default response encoding ie. the encoding in which the returned html/whatever is. The alternative is to set the response encoding etc. in each controller of the application.
This filter has to be added to the web.xml or the deployment descriptor of the webapp:
<!--CharsetFilter start-->
<filter>
<filter-name>CharsetFilter</filter-name>
<filter-class>fi.foo.filters.CharsetFilter</filter-class>
<init-param>
<param-name>requestEncoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharsetFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The instructions for making this filter are found at the tomcat wiki (http://wiki.apache.org/tomcat/Tomcat/UTF-8)
In your web.xml, add the following:
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>
Alternatively, all JSP-pages of the webapp would need to have the following at the top of them:
<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
If some kind of a layout with different JSP-fragments is used, then this is needed in all of them.
JSP page encoding tells the JVM to handle the characters in the JSP page in the correct encoding. Then it's time to tell the browser in which encoding the html page is:
This is done with the following at the top of each xhtml page produced by the webapp:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fi">
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
...
When using a db, it has to be defined that the connection uses UTF-8 encoding. This is done in context.xml or wherever the JDBC connection is defiend as follows:
<Resource name="jdbc/AppDB"
auth="Container"
type="javax.sql.DataSource"
maxActive="20" maxIdle="10" maxWait="10000"
username="foo"
password="bar"
driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/ ID_development?useEncoding=true&characterEncoding=UTF-8"
/>
The used database must use UTF-8 encoding. This is achieved by creating the database with the following:
CREATE DATABASE `ID_development`
/*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_swedish_ci */;
Then, all of the tables need to be in UTF-8 also:
CREATE TABLE `Users` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(30) collate utf8_swedish_ci default NULL
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci ROW_FORMAT=DYNAMIC;
The key part being CHARSET=utf8.
MySQL serveri has to be configured also. Typically this is done in Windows by modifying my.ini -file and in Linux by configuring my.cnf -file. In those files it should be defined that all clients connected to the server use utf8 as the default character set and that the default charset used by the server is also utf8.
[client]
port=3306
default-character-set=utf8
[mysql]
default-character-set=utf8
These also need to have the character set defined. For example:
DELIMITER $$
DROP FUNCTION IF EXISTS `pathToNode` $$
CREATE FUNCTION `pathToNode` (ryhma_id INT) RETURNS TEXT CHARACTER SET utf8
READS SQL DATA
BEGIN
DECLARE path VARCHAR(255) CHARACTER SET utf8;
SET path = NULL;
...
RETURN path;
END $$
DELIMITER ;
If and when it's defined in tomcat's server.xml that GET request parameters are encoded in UTF-8, the following GET requests are handled properly:
https://localhost:8443/ID/Users?action=search&name=Petteri
https://localhost:8443/ID/Users?action=search&name=?
Because ASCII-characters are encoded in the same way both with latin1 and UTF-8, the string "Petteri" is handled correctly.
The Cyrillic character ? is not understood at all in latin1. Because Tomcat is instructed to handle request parameters as UTF-8 it encodes that character correctly as %D0%B6.
If and when browsers are instructed to read the pages in UTF-8 encoding (with request headers and html meta-tag), at least Firefox 2/3 and other browsers from this period all encode the character themselves as %D0%B6.
The end result is that all users with name "Petteri" are found and also all users with the name "?" are found.
HTTP-specification defines that by default URLs are encoded as latin1. This results in firefox2, firefox3 etc. encoding the following
https://localhost:8443/ID/Users?action=search&name=*Päivi*
in to the encoded version
https://localhost:8443/ID/Users?action=search&name=*P%E4ivi*
In latin1 the character ä is encoded as %E4. Even though the page/request/everything is defined to use UTF-8. The UTF-8 encoded version of ä is %C3%A4
The result of this is that it's quite impossible for the webapp to correly handle the request parameters from GET requests as some characters are encoded in latin1 and others in UTF-8. Notice: POST requests do work as browsers encode all request parameters from forms completely in UTF-8 if the page is defined as being UTF-8
A very big thank you for the writers of the following for giving the answers for my problem:
mysql supports the Basic Multilingual Plane using 3-byte UTF-8 characters. If you need to go outside of that (certain alphabets require more than 3-bytes of UTF-8), then you either need to use a flavor of VARBINARY
column type or use the utf8mb4
character set (which requires MySQL 5.5.3 or later). Just be aware that using the utf8
character set in MySQL won't work 100% of the time.
One more thing If you are using Apache + Tomcat + mod_JK connector then you also need to do following changes:
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" URIEncoding="UTF-8"/>
/etc/httpd/conf
and add AddDefaultCharset utf-8
in httpd.conf file
. Note: First check that it is exist or not. If exist you may update it with this line. You can add this line at bottom also.Docker Compose has been updated. They now have a version 2 file format.
Version 2 files are supported by Compose 1.6.0+ and require a Docker Engine of version 1.10.0+.
They now support the networking feature of Docker which when run sets up a default network called myapp_default
From their documentation your file would look something like the below:
version: '2'
services:
web:
build: .
ports:
- "8000:8000"
fpm:
image: phpfpm
nginx
image: nginx
As these containers are automatically added to the default myapp_default network they would be able to talk to each other. You would then have in the Nginx config:
fastcgi_pass fpm:9000;
Also as mentioned by @treeface in the comments remember to ensure PHP-FPM is listening on port 9000, this can be done by editing /etc/php5/fpm/pool.d/www.conf
where you will need listen = 9000
.
I have kept the below here for those using older version of Docker/Docker compose and would like the information.
I kept stumbling upon this question on google when trying to find an answer to this question but it was not quite what I was looking for due to the Q/A emphasis on docker-compose (which at the time of writing only has experimental support for docker networking features). So here is my take on what I have learnt.
Docker has recently deprecated its link feature in favour of its networks feature
Therefore using the Docker Networks feature you can link containers by following these steps. For full explanations on options read up on the docs linked previously.
First create your network
docker network create --driver bridge mynetwork
Next run your PHP-FPM container ensuring you open up port 9000 and assign to your new network (mynetwork
).
docker run -d -p 9000 --net mynetwork --name php-fpm php:fpm
The important bit here is the --name php-fpm
at the end of the command which is the name, we will need this later.
Next run your Nginx container again assign to the network you created.
docker run --net mynetwork --name nginx -d -p 80:80 nginx:latest
For the PHP and Nginx containers you can also add in --volumes-from
commands etc as required.
Now comes the Nginx configuration. Which should look something similar to this:
server {
listen 80;
server_name localhost;
root /path/to/my/webroot;
index index.html index.htm index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass php-fpm:9000;
fastcgi_index index.php;
include fastcgi_params;
}
}
Notice the fastcgi_pass php-fpm:9000;
in the location block. Thats saying contact container php-fpm
on port 9000
. When you add containers to a Docker bridge network they all automatically get a hosts file update which puts in their container name against their IP address. So when Nginx sees that it will know to contact the PHP-FPM container you named php-fpm
earlier and assigned to your mynetwork
Docker network.
You can add that Nginx config either during the build process of your Docker container or afterwards its up to you.
Try giving 5 ',' in every line, similar to line number 4.
Now you can use the SQL Server Management Studio to do this.
function hour_min($minutes){// Total
if($minutes <= 0) return '00 Hours 00 Minutes';
else
return sprintf("%02d",floor($minutes / 60)).' Hours '.sprintf("%02d",str_pad(($minutes % 60), 2, "0", STR_PAD_LEFT)). " Minutes";
}
echo hour_min(250); //Function Call will return value : 04 Hours 10 Minutes
The only way to deal with this non-intrusively is to:
select
from the pipes' file descriptors, perform merge-sort on the available log entries, and flush to centralized log. Repeat.)it stands for your website where your app is running on. like you have made an app www.xyz.pqr then you will type this www.xyz.pqr in App domain the site where your app is running on should be secure and valid
For Linux (I am using Fedora 30) the Shortcut is (Window/Start + Space) Try that and tell me. That works for me
You can use std::find
bool found = (std::find(my_list.begin(), my_list.end(), my_var) != my_list.end());
You need to include <algorithm>
. It should work on standard containers, vectors lists, etc...
element(by.model('parent_id')).sendKeys('BKN01');
To target IE10 and IE11 only (and not Edge):
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
/* add your IE10-IE11 css here */
}
I have no experience with Git, but I have with Mercurial which is also a distributed VCS. It depends on the project really, but in our case a distributed VCS suited the project as basically eliminated frequent broken builds.
I think it depends on the project really, as some are better suited towards a client-server VCS, and others towads a distributed one.
You can set the figure size if you explicitly create the figure with
plt.figure(figsize=(3,4))
You need to set figure size before calling plt.plot()
To change the format of the saved figure just change the extension in the file name. However, I don't know if any of matplotlib backends support tiff
If you are using 5.6 php,
sudo apt-get install php5.6-curl
If you want to assert that the two lists are identical, don't complicate things with Hamcrest:
assertEquals(expectedList, actual.getList());
If you really intend to perform an order-insensitive comparison, you can call the containsInAnyOrder
varargs method and provide values directly:
assertThat(actual.getList(), containsInAnyOrder("item1", "item2"));
(Assuming that your list is of String
, rather than Agent
, for this example.)
If you really want to call that same method with the contents of a List
:
assertThat(actual.getList(), containsInAnyOrder(expectedList.toArray(new String[expectedList.size()]));
Without this, you're calling the method with a single argument and creating a Matcher
that expects to match an Iterable
where each element is a List
. This can't be used to match a List
.
That is, you can't match a List<Agent>
with a Matcher<Iterable<List<Agent>>
, which is what your code is attempting.
You can use ternary expression. There are two ways to do this:
<div ng-style="myVariable > 100 ? {'color': 'red'} : {'color': 'blue'}"></div>
or...
<div ng-style="{'color': (myVariable > 100) ? 'red' : 'blue' }"></div>
It's not possible to save content to the website using only client-side scripting such as JavaScript and jQuery, but by submitting the data in an AJAX POST request you could perform the other half very easily on the server-side.
However, I would not recommend having raw content such as scripts so easily writeable to your hosting as this could easily be exploited. If you want to learn more about AJAX POST requests, you can read the jQuery API page:
http://api.jquery.com/jQuery.post/
And here are some things you ought to be aware of if you still want to save raw script files on your hosting. You have to be very careful with security if you are handling files like this!
File uploading (most of this applies if sending plain text too if javascript can choose the name of the file) http://www.developershome.com/wap/wapUpload/wap_upload.asp?page=security https://www.owasp.org/index.php/Unrestricted_File_Upload
Another way to do this is to use the Ruby on Rails debugger. There's a Ruby on Rails guide about debugging at http://guides.rubyonrails.org/debugging_rails_applications.html
Basically, start the server with the -u option:
./script/server -u
And then insert a breakpoint into your script where you would like to have access to the controllers, helpers, etc.
class EventsController < ApplicationController
def index
debugger
end
end
And when you make a request and hit that part in the code, the server console will return a prompt where you can then make requests, view objects, etc. from a command prompt. When finished, just type 'cont' to continue execution. There are also options for extended debugging, but this should at least get you started.
The link you gave does actually describe the differences, but it's buried at the bottom of the page:
http://www.cplusplus.com/reference/cstdio/fopen/
Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.
The conversion could be to normalize \r\n
to \n
(or vice-versa), or maybe ignoring characters beyond 0x7F (a-la 'text mode' in FTP). Personally I'd open everything in binary-mode and use a good text-encoding library for dealing with text.
public static void mulptiTransfer(WebDriver driver, By dropdownID, String text, By to)
{
String valuetext = null;
WebElement element = locateElement(driver, dropdownID, 10);
Select select = new Select(element);
List<WebElement> options = element.findElements(By.tagName("option"));
for (WebElement value: options)
{
valuetext = value.getText();
if (valuetext.equalsIgnoreCase(text))
{
try
{
select.selectByVisibleText(valuetext);
locateElement(driver, to, 5).click();
break;
}
catch (Exception e)
{
System.out.println(valuetext + "Value not found in Dropdown to Select");
}
}
}
}
Relative imports (as in from .. import mymodule
) only work in a package.
To import 'mymodule' that is in the parent directory of your current module:
import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
import mymodule
edit: the __file__
attribute is not always given. Instead of using os.path.abspath(__file__)
I now suggested using the inspect module to retrieve the filename (and path) of the current file
// styles.css
html {
scroll-behavior: smooth
}
Source: https://www.w3schools.com/howto/howto_css_smooth_scroll.asp#section2
Your code contains two problems:
==
, not =
.jQuery.text()
joins all text nodes of matched elements into a single string. If you have two successive elements, of which the first contains 'some'
and the second contains 'Text'
, then your code will incorrectly think that there exists an element that contains 'someText'
.I suggest the following instead:
if ($('#field > div.field-item:contains("someText")').length > 0) {
$("#somediv").addClass("thisClass");
}
You can easily do it by calling this method :
public static Bitmap RotateImage(Image image, float angle)
{
if (image == null)
throw new ArgumentNullException("image");
PointF offset = new PointF((float)image.Width / 2, (float)image.Height / 2);
//create a new empty bitmap to hold rotated image
Bitmap rotatedBmp = new Bitmap(image.Width, image.Height);
rotatedBmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);
//make a graphics object from the empty bitmap
Graphics g = Graphics.FromImage(rotatedBmp);
//Put the rotation point in the center of the image
g.TranslateTransform(offset.X, offset.Y);
//rotate the image
g.RotateTransform(angle);
//move the image back
g.TranslateTransform(-offset.X, -offset.Y);
//draw passed in image onto graphics object
g.DrawImage(image, new PointF(0, 0));
return rotatedBmp;
}
don't forget to add a reference to System.Drawing.dll on your project
Example of this method call :
Image image = new Bitmap("waves.png");
Image newImage = RotateImage(image, 360);
newImage.Save("newWaves.png");
you have to use capital True and False not true and false
You can hijack your Android audio port using an Arduino board like this. Then, you have two options (as far as I'm concerned):
1) Buy another Arduino Shield that supports RFID. I haven't seen one that supports UHF so far.
2) Try to connect your Arduino hijack with a USB RFID reader and build some embedded hardware kit.
Right now, I'm working in the second option but with iPhone.
I'm not properly answering the question but, I think it makes sense to clear why we should specify the radix.
On MDN documentation we can read that:
If radix is undefined or 0 (or absent), JavaScript assumes the following:
Source: MDN parseInt()
For install with zsh and Homebrew:
brew install nvm
Then Add the following to ~/.zshrc or your desired shell configuration file:
export NVM_DIR="$HOME/.nvm"
. "/usr/local/opt/nvm/nvm.sh"
Then install a node version and use it.
nvm install 7.10.1
nvm use 7.10.1
<style type="text/css">
p.boldpara {font-weight:bold;}
</style>
</head>
<body>
<p class="boldpara">Stack overflow is good site for developers. I really like this site </p>
</body>
</html>
For modern reference, in Symfony 2.4+, you cannot name the arguments for the Constructor Injection method anymore. According to the documentation You would pass in:
services:
test.common.userservice:
class: Test\CommonBundle\Services\UserService
arguments: [ "@doctrine.orm.entity_manager" ]
And then they would be available in the order they were listed via the arguments (if there are more than 1).
public function __construct(EntityManager $entityManager) {
$this->em = $entityManager;
}
Actually there is. There is a static method valueOf in the java.sql.Date
object which does exactly that. So we have
java.util.Date date = java.sql.Date.valueOf(localDate);
and that's it. No explicit setting of time zones because the local time zone is taken implicitly.
From docs:
The provided LocalDate is interpreted as the local date in the local time zone.
The java.sql.Date
subclasses java.util.Date
so the result is a java.util.Date
also.
And for the reverse operation there is a toLocalDate method in the java.sql.Date class. So we have:
LocalDate ld = new java.sql.Date(date.getTime()).toLocalDate();
With your example:
avgDists = np.array([1, 8, 6, 9, 4])
Obtain indexes of n maximal values:
ids = np.argpartition(avgDists, -n)[-n:]
Sort them in descending order:
ids = ids[np.argsort(avgDists[ids])[::-1]]
Obtain results (for n=4):
>>> avgDists[ids]
array([9, 8, 6, 4])
It has to do with the Normal Form for the SQL language. IF
statements can, by definition, only take a single SQL statement. However, there is a special kind of SQL statement which can contain multiple SQL statements, the BEGIN-END
block.
If you omit the BEGIN-END
block, your SQL will run fine, but it will only execute the first statement as part of the IF
.
Basically, this:
IF @Term = 3
INSERT INTO @Classes
SELECT
XXXXXX
FROM XXXX blah blah blah
is equivalent to the same thing with the BEGIN-END
block, because you are only executing a single statement. However, for the same reason that not including the curly-braces on an IF
statement in a C-like language is a bad idea, it is always preferable to use BEGIN
and END
.
Here is a brief pointer on void
pointers: https://www.learncpp.com/cpp-tutorial/613-void-pointers/
6.13 — Void pointers
Because the void pointer does not know what type of object it is pointing to, it cannot be dereferenced directly! Rather, the void pointer must first be explicitly cast to another pointer type before it is dereferenced.
If a void pointer doesn't know what it's pointing to, how do we know what to cast it to? Ultimately, that is up to you to keep track of.
Void pointer miscellany
It is not possible to do pointer arithmetic on a void pointer. This is because pointer arithmetic requires the pointer to know what size object it is pointing to, so it can increment or decrement the pointer appropriately.
Assuming the machine's memory is byte-addressable and does not require aligned accesses, the most generic and atomic (closest to the machine level representation) way of interpreting a void*
is as a pointer-to-a-byte, uint8_t*
. Casting a void*
to a uint8_t*
would allow you to, for example, print out the first 1/2/4/8/however-many-you-desire bytes starting at that address, but you can't do much else.
uint8_t* byte_p = (uint8_t*)p;
for (uint8_t* i = byte_p; i < byte_p + 8; i++) {
printf("%x ",*i);
}
try this once.
$wp_query->set_404();
status_header(404);
get_template_part('404');
In C++, there is only a subtle difference. It's a holdover from C, in which it makes a difference.
The C language standard (C89 §3.1.2.3, C99 §6.2.3, and C11 §6.2.3) mandates separate namespaces for different categories of identifiers, including tag identifiers (for struct
/union
/enum
) and ordinary identifiers (for typedef
and other identifiers).
If you just said:
struct Foo { ... };
Foo x;
you would get a compiler error, because Foo
is only defined in the tag namespace.
You'd have to declare it as:
struct Foo x;
Any time you want to refer to a Foo
, you'd always have to call it a struct Foo
. This gets annoying fast, so you can add a typedef
:
struct Foo { ... };
typedef struct Foo Foo;
Now struct Foo
(in the tag namespace) and just plain Foo
(in the ordinary identifier namespace) both refer to the same thing, and you can freely declare objects of type Foo
without the struct
keyword.
The construct:
typedef struct Foo { ... } Foo;
is just an abbreviation for the declaration and typedef
.
Finally,
typedef struct { ... } Foo;
declares an anonymous structure and creates a typedef
for it. Thus, with this construct, it doesn't have a name in the tag namespace, only a name in the typedef namespace. This means it also cannot be forward-declared. If you want to make a forward declaration, you have to give it a name in the tag namespace.
In C++, all struct
/union
/enum
/class
declarations act like they are implicitly typedef
'ed, as long as the name is not hidden by another declaration with the same name. See Michael Burr's answer for the full details.
One option is using Object.keys()
:
Object.keys(driversCounter)
It works fine for modern browsers (however, Internet Explorer supports it starting from version 9 only).
To add compatible support you can copy the code snippet provided in MDN.
The first thing you need to know is that HashSet
acts like a Set
, which means you add your object directly to the HashSet
and it cannot contain duplicates. You just add your value directly in HashSet
.
However, HashMap
is a Map
type. That means every time you add an entry, you add a key-value pair.
In HashMap
you can have duplicate values, but not duplicate keys. In HashMap
the new entry will replace the old one. The most recent entry will be in the HashMap
.
Understanding Link between HashMap and HashSet:
Remember, HashMap
can not have duplicate keys. Behind the scene HashSet
uses a HashMap
.
When you attempt to add any object into a HashSet
, this entry is actually stored as a key in the HashMap
- the same HashMap
that is used behind the scene of HashSet
. Since this underlying HashMap
needs a key-value pair, a dummy value is generated for us.
Now when you try to insert another duplicate object into the same HashSet
, it will again attempt to be insert it as a key in the HashMap
lying underneath. However, HashMap
does not support duplicates. Hence, HashSet
will still result in having only one value of that type. As a side note, for every duplicate key, since the value generated for our entry in HashSet is some random/dummy value, the key is not replaced at all. it will be ignored as removing the key and adding back the same key (the dummy value is the same) would not make any sense at all.
Summary:
HashMap
allows duplicate values
, but not keys
.
HashSet
cannot contains duplicates.
To play with whether the addition of an object is successfully completed or not, you can check the boolean
value returned when you call .add()
and see if it returns true
or false
. If it returned true
, it was inserted.
With angular 6 and rxjs 6 Observable.throw()
, Observable.off()
has been deprecated instead you need to use throwError
ex :
return this.http.get('yoururl')
.pipe(
map(response => response.json()),
catchError((e: any) =>{
//do your processing here
return throwError(e);
}),
);
I suggest that you give an if to the div than:
$("#my_div_id").html();
The serial port communication programs moserial
or gtkterm
provide an easy way to check connectivity and modify /dev/ttyUSB0
(or /dev/ttyUSB1
!) settings. Even though there maybe only a single USB to RS232 adapter, the n
designation /dev/ttyUSBn
can and does change periodically! Both moserial
and gtkterm
will show what port designation is relevant in their respective pull down menus when selecting an appropriate port
to use.
Check out help.ubuntu.com/community/Minicom for details on minicom
.
perhaps
$id = isset($_GET['id'])?$_GET['id']:null;
and
$other_var = isset($_GET['othervar'])?$_GET['othervar']:null;
This chains work in my case:
git rm -r WebApplication/packages
There was a confirmation git-dialog. You should choose "y" option.
git commit -m "blabla"
git push -f origin <ur_branch>
Extract characters from a string:
var str = "Hello world!";
var res = str.substring(1,4);
The result of res
will be:
ell
http://www.w3schools.com/jsref/jsref_substring.asp
$('.dep_buttons').mouseover(function(){
$(this).text().substring(0,25);
if($(this).text().length > 30) {
$(this).stop().animate({height:"150px"},150);
}
$(".dep_buttons").mouseout(function(){
$(this).stop().animate({height:"40px"},150);
});
});
For Google chrome Version 56.0.2924.87 (Latest Release) cookies are found inside profile1 folder.
If you browse that you can find variety of information.
There is a separate file called "Cookies". Also the Cache folder is inside this folder.
Path : C:\Users\user_name\AppData\Local\Google\Chrome\User Data\Profile 1
Remember to replace user_name.
For Version 61.0.3163.100
Path :
C:\Users\user_name\AppData\Local\Google\Chrome\User Data\Default
Inside this folder there is Cookies file and Cache folder.
var http = require('http');
http.createServer(function (req, res) {
}).listen(80, '127.0.0.1');
console.log('Server running at http://127.0.0.1:80/');
How about
SELECT *
FROM Employees
WHERE PhoneNumber IN (
SELECT PhoneNumber
FROM Employees
GROUP BY PhoneNumber
HAVING COUNT(Employee_ID) > 1
)
Add new column to Table with default value.
ALTER TABLE NAME_OF_TABLE
ADD COLUMN_NAME datatype
DEFAULT DEFAULT_VALUE
I found it best to just remove the DOM completely.
$(".form-group #selectId option[value='39']").remove();
Cross browser compatible. Works on IE11 too
The list selector drawable is a StateListDrawable
— it contains reference to multiple drawables for each state the list can be, like selected, focused, pressed, disabled...
While you can retrieve the drawable using getSelector()
, I don't believe you can retrieve a specific Drawable
from a StateListDrawable
, nor does it seem possible to programmatically retrieve the colour directly from a ColorDrawable
anyway.
As for setting the colour, you need a StateListDrawable
as described above. You can set this on your list using the android:listSelector
attribute, defining the drawable in XML like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:state_focused="true"
android:drawable="@drawable/item_disabled" />
<item android:state_pressed="true"
android:drawable="@drawable/item_pressed" />
<item android:state_focused="true"
android:drawable="@drawable/item_focused" />
</selector>
Another recursive approach:
# change directory to target folder:
cd /Volumes/path/to/folder
# find all things of type "f" (file),
# then pipe "|" each result as an argument (xargs -0)
# to the "xattr -c" command:
find . -type f -print0 | xargs -0 xattr -c
# Sometimes you may have to use a star * instead of the dot.
# The dot just means "here" (whereever your cd'd to
find * -type f -print0 | xargs -0 xattr -c
Beware of circular references when DOM objects are involved:
Memory leak patterns in JavaScript
Keep in mind that memory can only be reclaimed when there are no active references to the object. This is a common pitfall with closures and event handlers, as some JS engines will not check which variables actually are referenced in inner functions and just keep all local variables of the enclosing functions.
Here's a simple example:
function init() {
var bigString = new Array(1000).join('xxx');
var foo = document.getElementById('foo');
foo.onclick = function() {
// this might create a closure over `bigString`,
// even if `bigString` isn't referenced anywhere!
};
}
A naive JS implementation can't collect bigString
as long as the event handler is around. There are several ways to solve this problem, eg setting bigString = null
at the end of init()
(delete
won't work for local variables and function arguments: delete
removes properties from objects, and the variable object is inaccessible - ES5 in strict mode will even throw a ReferenceError
if you try to delete a local variable!).
I recommend to avoid unnecessary closures as much as possible if you care for memory consumption.
What happens if I promote the column to be a/the PK, too (a.k.a. identifying relationship)? As the column is now the PK, I must tag it with @Id (...).
This enhanced support of derived identifiers is actually part of the new stuff in JPA 2.0 (see the section 2.4.1 Primary Keys Corresponding to Derived Identities in the JPA 2.0 specification), JPA 1.0 doesn't allow Id
on a OneToOne
or ManyToOne
. With JPA 1.0, you'd have to use PrimaryKeyJoinColumn
and also define a Basic
Id
mapping for the foreign key column.
Now the question is: are @Id + @JoinColumn the same as just @PrimaryKeyJoinColumn?
You can obtain a similar result but using an Id
on OneToOne
or ManyToOne
is much simpler and is the preferred way to map derived identifiers with JPA 2.0. PrimaryKeyJoinColumn
might still be used in a JOINED inheritance strategy. Below the relevant section from the JPA 2.0 specification:
11.1.40 PrimaryKeyJoinColumn Annotation
The
PrimaryKeyJoinColumn
annotation specifies a primary key column that is used as a foreign key to join to another table.The
PrimaryKeyJoinColumn
annotation is used to join the primary table of an entity subclass in theJOINED
mapping strategy to the primary table of its superclass; it is used within aSecondaryTable
annotation to join a secondary table to a primary table; and it may be used in aOneToOne
mapping in which the primary key of the referencing entity is used as a foreign key to the referenced entity[108]....
If no
PrimaryKeyJoinColumn
annotation is specified for a subclass in the JOINED mapping strategy, the foreign key columns are assumed to have the same names as the primary key columns of the primary table of the superclass....
Example: Customer and ValuedCustomer subclass
@Entity @Table(name="CUST") @Inheritance(strategy=JOINED) @DiscriminatorValue("CUST") public class Customer { ... } @Entity @Table(name="VCUST") @DiscriminatorValue("VCUST") @PrimaryKeyJoinColumn(name="CUST_ID") public class ValuedCustomer extends Customer { ... }
[108] The derived id mechanisms described in section 2.4.1.1 are now to be preferred over
PrimaryKeyJoinColumn
for the OneToOne mapping case.
This source http://weblogs.java.net/blog/felipegaucho/archive/2009/10/24/jpa-join-table-additional-state states that using @ManyToOne and @Id works with JPA 1.x. Who's correct now?
The author is using a pre release JPA 2.0 compliant version of EclipseLink (version 2.0.0-M7 at the time of the article) to write an article about JPA 1.0(!). This article is misleading, the author is using something that is NOT part of JPA 1.0.
For the record, support of Id
on OneToOne
and ManyToOne
has been added in EclipseLink 1.1 (see this message from James Sutherland, EclipseLink comitter and main contributor of the Java Persistence wiki book). But let me insist, this is NOT part of JPA 1.0.
I created an email address validation routine based on Wikipedia's documented rules and sample addresses. For those that don't mind looking at a little more code, here you go. Honestly, I had no idea how many crazy rules there were in the email address specification. I don't fully validate the hostname or ipaddress, but it still passes all of the test cases on wikipedia.
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace EmailValidateUnitTests
{
[TestClass]
public class EmailValidationUnitTests
{
[TestMethod]
public void TestEmailValidate()
{
// Positive Assertions
Assert.IsTrue("[email protected]".IsValidEmailAddress());
Assert.IsTrue("[email protected]".IsValidEmailAddress());
Assert.IsTrue("[email protected]".IsValidEmailAddress());
Assert.IsTrue("[email protected]".IsValidEmailAddress());
Assert.IsTrue("\"much.more unusual\"@example.com".IsValidEmailAddress());
Assert.IsTrue("\"[email protected]\"@example.com".IsValidEmailAddress()); //"[email protected]"@example.com
Assert.IsTrue("\"very.(),:;<>[]\\\".VERY.\\\"very@\\\\ \\\"very\\\".unusual\"@strange.example.com".IsValidEmailAddress()); //"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com
Assert.IsTrue("admin@mailserver1".IsValidEmailAddress());
Assert.IsTrue("#!$%&'*+-/=?^_`{}|[email protected]".IsValidEmailAddress());
Assert.IsTrue("\"()<>[]:,;@\\\\\\\"!#$%&'*+-/=?^_`{}| ~.a\"@example.org".IsValidEmailAddress()); //"()<>[]:,;@\\\"!#$%&'*+-/=?^_`{}| ~.a"@example.org
Assert.IsTrue("\" \"@example.org".IsValidEmailAddress()); //" "@example.org (space between the quotes)
Assert.IsTrue("example@localhost".IsValidEmailAddress());
Assert.IsTrue("[email protected]".IsValidEmailAddress());
Assert.IsTrue("user@com".IsValidEmailAddress());
Assert.IsTrue("user@localserver".IsValidEmailAddress());
Assert.IsTrue("user@[IPv6:2001:db8::1]".IsValidEmailAddress());
Assert.IsTrue("user@[192.168.2.1]".IsValidEmailAddress());
Assert.IsTrue("(comment and stuff)[email protected]".IsValidEmailAddress());
Assert.IsTrue("joe(comment and stuff)@gmail.com".IsValidEmailAddress());
Assert.IsTrue("joe@(comment and stuff)gmail.com".IsValidEmailAddress());
Assert.IsTrue("[email protected](comment and stuff)".IsValidEmailAddress());
// Failure Assertions
Assert.IsFalse("joe(fail me)[email protected]".IsValidEmailAddress());
Assert.IsFalse("joesmith@gma(fail me)il.com".IsValidEmailAddress());
Assert.IsFalse("[email protected](comment and stuff".IsValidEmailAddress());
Assert.IsFalse("Abc.example.com".IsValidEmailAddress());
Assert.IsFalse("A@b@[email protected]".IsValidEmailAddress());
Assert.IsFalse("a\"b(c)d,e:f;g<h>i[j\\k][email protected]".IsValidEmailAddress()); //a"b(c)d,e:f;g<h>i[j\k][email protected]
Assert.IsFalse("just\"not\"[email protected]".IsValidEmailAddress()); //just"not"[email protected]
Assert.IsFalse("this is\"not\\[email protected]".IsValidEmailAddress()); //this is"not\[email protected]
Assert.IsFalse("this\\ still\\\"not\\\\[email protected]".IsValidEmailAddress());//this\ still\"not\\[email protected]
Assert.IsFalse("[email protected]".IsValidEmailAddress());
Assert.IsFalse("[email protected]".IsValidEmailAddress());
Assert.IsFalse(" [email protected]".IsValidEmailAddress());
Assert.IsFalse("[email protected] ".IsValidEmailAddress());
}
}
public static class ExtensionMethods
{
private const string ValidLocalPartChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%&'*+-/=?^_`{|}~";
private const string ValidQuotedLocalPartChars = "(),:;<>@[]. ";
private const string ValidDomainPartChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-:";
private enum EmailParseMode
{
BeginLocal, Local, QuotedLocalEscape, QuotedLocal, QuotedLocalEnd, LocalSplit, LocalComment,
At,
Domain, DomainSplit, DomainComment, BracketedDomain, BracketedDomainEnd
};
public static bool IsValidEmailAddress(this string s)
{
bool valid = true;
bool hasLocal = false, hasDomain = false;
int commentStart = -1, commentEnd = -1;
var mode = EmailParseMode.BeginLocal;
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if (mode == EmailParseMode.BeginLocal || mode == EmailParseMode.LocalSplit)
{
if (c == '(') { mode = EmailParseMode.LocalComment; commentStart = i; commentEnd = -1; }
else if (c == '"') { mode = EmailParseMode.QuotedLocal; }
else if (ValidLocalPartChars.IndexOf(c) >= 0) { mode = EmailParseMode.Local; hasLocal = true; }
else { valid = false; break; }
}
else if (mode == EmailParseMode.LocalComment)
{
if (c == ')')
{
mode = EmailParseMode.Local; commentEnd = i;
// comments can only be at beginning and end of parts...
if (commentStart != 0 && ((commentEnd + 1) < s.Length) && s[commentEnd + 1] != '@') { valid = false; break; }
}
}
else if (mode == EmailParseMode.Local)
{
if (c == '.') mode = EmailParseMode.LocalSplit;
else if (c == '@') mode = EmailParseMode.At;
else if (c == '(') { mode = EmailParseMode.LocalComment; commentStart = i; commentEnd = -1; }
else if (ValidLocalPartChars.IndexOf(c) >= 0) { hasLocal = true; }
else { valid = false; break; }
}
else if (mode == EmailParseMode.QuotedLocal)
{
if (c == '"') { mode = EmailParseMode.QuotedLocalEnd; }
else if (c == '\\') { mode = EmailParseMode.QuotedLocalEscape; }
else if (ValidLocalPartChars.IndexOf(c) >= 0 || ValidQuotedLocalPartChars.IndexOf(c) >= 0) { hasLocal = true; }
else { valid = false; break; }
}
else if (mode == EmailParseMode.QuotedLocalEscape)
{
if (c == '"' || c == '\\') { mode = EmailParseMode.QuotedLocal; hasLocal = true; }
else { valid = false; break; }
}
else if (mode == EmailParseMode.QuotedLocalEnd)
{
if (c == '.') { mode = EmailParseMode.LocalSplit; }
else if (c == '@') mode = EmailParseMode.At;
else if (c == '(') { mode = EmailParseMode.LocalComment; commentStart = i; commentEnd = -1; }
else { valid = false; break; }
}
else if (mode == EmailParseMode.At)
{
if (c == '[') { mode = EmailParseMode.BracketedDomain; }
else if (c == '(') { mode = EmailParseMode.DomainComment; commentStart = i; commentEnd = -1; }
else if (ValidDomainPartChars.IndexOf(c) >= 0) { mode = EmailParseMode.Domain; hasDomain = true; }
else { valid = false; break; }
}
else if (mode == EmailParseMode.DomainComment)
{
if (c == ')')
{
mode = EmailParseMode.Domain;
commentEnd = i;
// comments can only be at beginning and end of parts...
if ((commentEnd + 1) != s.Length && (commentStart > 0) && s[commentStart - 1] != '@') { valid = false; break; }
}
}
else if (mode == EmailParseMode.DomainSplit)
{
if (ValidDomainPartChars.IndexOf(c) >= 0) { mode = EmailParseMode.Domain; hasDomain = true; }
else { valid = false; break; }
}
else if (mode == EmailParseMode.Domain)
{
if (c == '(') { mode = EmailParseMode.DomainComment; commentStart = i; commentEnd = -1; }
else if (c == '.') { mode = EmailParseMode.DomainSplit; }
else if (ValidDomainPartChars.IndexOf(c) >= 0) { hasDomain = true; }
else { valid = false; break; }
}
else if (mode == EmailParseMode.BracketedDomain)
{
if (c == ']') { mode = EmailParseMode.BracketedDomainEnd; }
else if (c == '.' || ValidDomainPartChars.IndexOf(c) >= 0) { hasDomain = true; }
else { valid = false; break; }
}
else if (mode == EmailParseMode.BracketedDomain)
{
if (c == '(') { mode = EmailParseMode.DomainComment; commentStart = i; commentEnd = -1; }
else { valid = false; break; }
}
}
bool unfinishedComment = (commentEnd == -1 && commentStart >= 0);
return hasLocal && hasDomain && valid && !unfinishedComment;
}
}
}
input type="range" min="0" max="50" value="0" style="margin-left: 6%;width: 88%;background-color: whitesmoke;"
above code changes range input style.....
I would use a library to create your JSON String
for you. Some options are:
This will make dealing with escaping much easier. An example (using org.json
) would be:
JSONObject obj = new JSONObject();
obj.put("id", userID);
obj.put("type", methoden);
obj.put("msg", msget);
// etc.
final String json = obj.toString(); // <-- JSON string
This may also be useful: {{ form.field.as_hidden }}
This may be a 'special' case but was fiddling with this piece of code:
ForceType application/x-httpd-php SetHandler application/x-httpd-php
As a quick test for extentionless file handling, when a similar problem occurred.
Some but not all php files thereafter treated the css files as php and thus succesfully loaded the css but not handled it as css, thus zero rules were executed when checking f12 style editor.
Perhaps something similar might occur to any-one else here and this tidbit might help.
REPLACE(<your xml column>,'&',chr(38)||'amp;')
Use the npm bin
command to get the node modules /bin directory of your project
$ $(npm bin)/<binary-name> [args]
e.g.
$ $(npm bin)/bower install
Without any third-party tools and any app, you can find unused CSS and javascript by using chrome dev tools in the coverage tab. read the post below from google developers. chrome coverage tab
Just remove the "px" in the style.height assignation, like:
<button type="button" onClick = "document.getElementById('chartdiv').style.height = 200px"> </button>
Should be
<button type="button" onClick = "document.getElementById('chartdiv').style.height = 200">Click Me!</button>
Your code does not work because it is not doing what you are expecting it to do. Switch blocks take in a value, and compare each case to the given value, looking for equality. Your comparison value is an integer, but most of your case expressions resolve to a boolean value.
So, for example, say liCount = 2
. Your first case will not match, because 2 != 0
. Your second case, (liCount<=5 && liCount>0)
evaluates to true
, but 2 != true
, so this case will not match either.
For this reason, as many others have said, you should use a series of if...then...else if
blocks to do this.
GRANT SELECT ON *.* TO 'user'@'localhost' IDENTIFIED BY 'password';
This will create a user with SELECT
privilege for all database including Views.
Try the -Force
parameter:
New-Item -ItemType Directory -Force -Path C:\Path\That\May\Or\May\Not\Exist
You can use Test-Path -PathType Container
to check first.
See the New-Item MSDN help article for more details.
I also tried to use CURRVAL, in my case to find out if some process inserted new rows to some table with that sequence as Primary Key. My assumption was that CURRVAL would be the fastest method. But a) CurrVal does not work, it will just get the old value because you are in another Oracle session, until you do a NEXTVAL in your own session. And b) a select max(PK) from TheTable
is also very fast, probably because a PK is always indexed. Or select count(*) from TheTable
. I am still experimenting, but both SELECTs seem fast.
I don't mind a gap in a sequence, but in my case I was thinking of polling a lot, and I would hate the idea of very large gaps. Especially if a simple SELECT would be just as fast.
Conclusion:
function liReplace(replacement) {
$(".dropit-submenu li").each(function() {
var t = $(this);
t.html(t.html().replace(replacement, "*" + replacement + "*"));
t.children(":first").html(t.children(":first").html().replace(replacement, "*" +` `replacement + "*"));
t.children(":first").html(t.children(":first").html().replace(replacement + " ", ""));
alert(t.children(":first").text());
});
}
t.html(t.html()
t.children(":first")
Sample <a title="alpc" href="#">alpc</a>
a short summary:
track by
is used in order to link your data with the DOM generation (and mainly re-generation) made by ng-repeat.
when you add track by
you basically tell angular to generate a single DOM element per data object in the given collection
this could be useful when paging and filtering, or any case where objects are added or removed from ng-repeat
list.
usually, without track by
angular will link the DOM objects with the collection by injecting an expando property - $$hashKey
- into your JavaScript objects, and will regenerate it (and re-associate a DOM object) with every change.
full explanation:
http://www.bennadel.com/blog/2556-using-track-by-with-ngrepeat-in-angularjs-1-2.htm
a more practical guide:
http://www.codelord.net/2014/04/15/improving-ng-repeat-performance-with-track-by/
(track by is available in angular > 1.2 )
if you want to read settings from the DLL's config file but not from the the root applications web.config or app.config use below code to read configuration in the dll.
var appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
string dllConfigData = appConfig.AppSettings.Settings["dllConfigData"].Value;
To clarify, you should use HTTP error codes where they fit with the protocol, and not use HTTP status codes to send business logic errors.
Errors like insufficient balance, no cabs available, bad user/password qualify for HTTP status 200
with application specific error handling in the response body.
See this software engineering answer:
I would say it is better to be explicit about the separation of protocols. Let the HTTP server and the web browser do their own thing, and let the app do its own thing. The app needs to be able to make requests, and it needs the responses--and its logic as to how to request, how to interpret the responses, can be more (or less) complex than the HTTP perspective.
I'm not so comfortable with regular expressions, and my example results from a datetimepicker field formatted m/d/Y h:mA. In this legal example, you have to arrive before the actual deposition hearing. I use replace function to clean up the dates so that I can process them as Date objects and compare them.
function compareDateTimes() {
//date format ex "04/20/2017 01:30PM"
//the problem is that this format results in Invalid Date
//var d0 = new Date("04/20/2017 01:30PM"); => Invalid Date
var start_date = $(".letter #depo_arrival_time").val();
var end_date = $(".letter #depo_dateandtime").val();
if (start_date=="" || end_date=="") {
return;
}
//break it up for processing
var d1 = stringToDate(start_date);
var d2 = stringToDate(end_date);
var diff = d2.getTime() - d1.getTime();
if (diff < 0) {
end_date = moment(d2).format("MM/DD/YYYY hh:mA");
$(".letter #depo_arrival_time").val(end_date);
}
}
function stringToDate(the_date) {
var arrDate = the_date.split(" ");
var the_date = arrDate[0];
var the_time = arrDate[1];
var arrTime = the_time.split(":");
var blnPM = (arrTime[1].indexOf("PM") > -1);
//first fix the hour
if (blnPM) {
if (arrTime[0].indexOf("0")==0) {
var clean_hour = arrTime[0].substr(1,1);
arrTime[0] = Number(clean_hour) + 12;
}
arrTime[1] = arrTime[1].replace("PM", ":00");
} else {
arrTime[1] = arrTime[1].replace("AM", ":00");
}
var date_object = new Date(the_date);
//now replace the time
date_object = String(date_object).replace("00:00:00", arrTime.join(":"));
date_object = new Date(date_object);
return date_object;
}
very simple answer
Here is a property I use in one of my applications
public List<string> OperationModes
{
get
{
return Enum.GetNames(typeof(SomeENUM)).ToList();
}
}
Are you meaning?
data2 <- data1[good,]
With
data1[good]
you're selecting columns in a wrong way (using a logical vector of complete rows).
Consider that parameter pollutant
is not used; is it a column name that you want to extract? if so it should be something like
data2 <- data1[good, pollutant]
Furthermore consider that you have to rbind
the data.frame
s inside the for
loop, otherwise you get only the last data.frame (its completed.cases)
And last but not least, i'd prefer generating filenames eg with
id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")
A little modified chunk of ?sprintf
The string fmt
(in our case "%3d"
) contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through ...
. The allowed conversion specifications start with a %
and end with one of the letters in the set aAdifeEgGosxX%
. These letters denote the following types:
d
: integerEg a more general example
sprintf("I am %10d years old", 25)
[1] "I am 25 years old"
^^^^^^^^^^
| |
1 10
if your application uses threads directly or indirectly (i.e. behind the scene like in a 3rd-party library) it is absolutely common to have threads terminate after they are done... which is basically what you describe... the debugger shows this message... you can configure the debugger to not display this message if you don't want it...
If the above does not help then please provide more details since I am not sure what exactly the problem is you face...
Related to how to link to the README.md
of a GitHub repository to a specific line number of code
You have three cases:
We can link to (custom commit)
But Link will ALWAYS link to old file version, which will NOT contains new updates in the master branch for example. Example:
https://github.com/username/projectname/blob/b8d94367354011a0470f1b73c8f135f095e28dd4/file.txt#L10
We can link to (custom branch) like (master-branch). But the link will ALWAYS link to the latest file version which will contain new updates. Due to new updates, the link may point to an invalid business line number. Example:
https://github.com/username/projectname/blob/master/file.txt#L10
GitHub can NOT make AUTO-link to any file either to (custom commit) nor (master-branch) Because of following business issues:
Android Parcelable code generator
public class Sample {
int id;
String name;
}
For firefox links appear to be "special". The only way I was able to get this working was to use the createEvent described here on MDN and call the initMouseEvent function. Even that didn't work completely, I had to manually tell the browser to open a link...
var theEvent = document.createEvent("MouseEvent");
theEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
var element = document.getElementById('link');
element.dispatchEvent(theEvent);
while (element)
{
if (element.tagName == "A" && element.href != "")
{
if (element.target == "_blank") { window.open(element.href, element.target); }
else { document.location = element.href; }
element = null;
}
else
{
element = element.parentElement;
}
}
You should analyze your style.css file, possibly using Developer Tools in your favorite browser, to see which rule sets font size on the element in a manner that overrides the one in a style
attribute. Apparently, it has to be one using the !important
specifier, which generally indicates poor logic and structure in styling.
Primarily, modify the style.css file so that it does not use !important
. Failing this, add !important
to the rule in style
attribute. But you should aim at reducing the use of !important
, not increasing it.
Yes, your secret key appears to be missing. Without it, you will not be able to decrypt the files.
Do you have the key backed up somewhere?
Re-creating the keys, whether you use the same passphrase or not, will not work. Each key pair is unique.
I had this issue after upgrading Android Studio to 3.2 and even upgrade some SDK-Packages.
The cause was that the path to emulator had changed, so don't use ...../Android/Sdk/tools/emulator
but instead ....../Android/Sdk/emulator/emulator
.
Try this one, with code coloration:
You can use Collections.binarySearch to search an element in your list (assuming the list is sorted):
Collections.binarySearch(list, new YourObject("a1", "b",
"c"), new Comparator<YourObject>() {
@Override
public int compare(YourObject o1, YourObject o2) {
return o1.getName().compareTo(o2.getName());
}
});
which will return a negative number if the object is not present in the collection or else it will return the index
of the object. With this you can search for objects with different searching strategies.
Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.
In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.
Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.
Since it is really a formatting issue when displaying the date (e.g. displays in local time), I like to use the new(ish) Intl.DateTimeFormat object to perform the formatting as it is more explicit and provides more output options:
const dateOptions = { timeZone: 'UTC', month: 'long', day: 'numeric', year: 'numeric' };
const dateFormatter = new Intl.DateTimeFormat('en-US', dateOptions);
const dateAsFormattedString = dateFormatter.format(new Date('2019-06-01T00:00:00.000+00:00'));
console.log(dateAsFormattedString) // "June 1, 2019"
As shown, by setting the timeZone to 'UTC' it will not perform local conversions. As a bonus, it also allows you to create more polished outputs. You can read more about the Intl.DateTimeFormat object from Mozilla - Intl.DateTimeFormat.
Edit:
The same functionality can be achieved without creating a new Intl.DateTimeFormat
object. Simply pass the locale and date options directly into the toLocaleDateString()
function.
const dateOptions = { timeZone: 'UTC', month: 'long', day: 'numeric', year: 'numeric' };
const myDate = new Date('2019-06-01T00:00:00.000+00:00');
today.toLocaleDateString('en-US', dateOptions); // "June 1, 2019"
let ar = ['a', 'b', 'c', 'd'];
function change( old_array, old_index , new_index ){
return old_array.map(( item , index, array )=>{
if( index === old_index ) return array[ new_index ];
else if( index === new_index ) return array[ old_index ];
else return item;
});
}
let result = change( ar, 0, 1 );
console.log( result );
result:
["b", "a", "c", "d"]
In recent versions of Git you can add multiple pushurl
s for a given remote. Use the following to add two pushurl
s to your origin
:
git remote set-url --add --push origin git://original/repo.git
git remote set-url --add --push origin git://another/repo.git
So when you push to origin
, it will push to both repositories.
UPDATE 1: Git 1.8.0.1 and 1.8.1 (and possibly other versions) seem to have a bug that causes --add
to replace the original URL the first time you use it, so you need to re-add the original URL using the same command. Doing git remote -v
should reveal the current URLs for each remote.
UPDATE 2: Junio C. Hamano, the Git maintainer, explained it's how it was designed. Doing git remote set-url --add --push <remote_name> <url>
adds a pushurl
for a given remote, which overrides the default URL for pushes. However, you may add multiple pushurl
s for a given remote, which then allows you to push to multiple remotes using a single git push
. You can verify this behavior below:
$ git clone git://original/repo.git
$ git remote -v
origin git://original/repo.git (fetch)
origin git://original/repo.git (push)
$ git config -l | grep '^remote\.'
remote.origin.url=git://original/repo.git
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
Now, if you want to push to two or more repositories using a single command, you may create a new remote named all
(as suggested by @Adam Nelson in comments), or keep using the origin
, though the latter name is less descriptive for this purpose. If you still want to use origin
, skip the following step, and use origin
instead of all
in all other steps.
So let's add a new remote called all
that we'll reference later when pushing to multiple repositories:
$ git remote add all git://original/repo.git
$ git remote -v
all git://original/repo.git (fetch) <-- ADDED
all git://original/repo.git (push) <-- ADDED
origin git://original/repo.git (fetch)
origin git://original/repo.git (push)
$ git config -l | grep '^remote\.all'
remote.all.url=git://original/repo.git <-- ADDED
remote.all.fetch=+refs/heads/*:refs/remotes/all/* <-- ADDED
Then let's add a pushurl
to the all
remote, pointing to another repository:
$ git remote set-url --add --push all git://another/repo.git
$ git remote -v
all git://original/repo.git (fetch)
all git://another/repo.git (push) <-- CHANGED
origin git://original/repo.git (fetch)
origin git://original/repo.git (push)
$ git config -l | grep '^remote\.all'
remote.all.url=git://original/repo.git
remote.all.fetch=+refs/heads/*:refs/remotes/all/*
remote.all.pushurl=git://another/repo.git <-- ADDED
Here git remote -v
shows the new pushurl
for push, so if you do git push all master
, it will push the master
branch to git://another/repo.git
only. This shows how pushurl
overrides the default url (remote.all.url).
Now let's add another pushurl
pointing to the original repository:
$ git remote set-url --add --push all git://original/repo.git
$ git remote -v
all git://original/repo.git (fetch)
all git://another/repo.git (push)
all git://original/repo.git (push) <-- ADDED
origin git://original/repo.git (fetch)
origin git://original/repo.git (push)
$ git config -l | grep '^remote\.all'
remote.all.url=git://original/repo.git
remote.all.fetch=+refs/heads/*:refs/remotes/all/*
remote.all.pushurl=git://another/repo.git
remote.all.pushurl=git://original/repo.git <-- ADDED
You see both pushurl
s we added are kept. Now a single git push all master
will push the master
branch to both git://another/repo.git
and git://original/repo.git
.
Try with regex \d
:
$words = preg_replace('/\d/', '', $words );
\d
is an equivalent for [0-9]
which is an equivalent for numbers range from 0
to 9
.