I'm pretty new to iOS and Phonegap as well, but I was able to do this by adding in an eventListener. I did the same thing (using the example you reference), and couldn't get it to work. But this seemed to do the trick:
// Event listener to determine change (horizontal/portrait)
window.addEventListener("orientationchange", updateOrientation);
function updateOrientation(e) {
switch (e.orientation)
{
case 0:
// Do your thing
break;
case -90:
// Do your thing
break;
case 90:
// Do your thing
break;
default:
break;
}
}
You may have some luck searching the PhoneGap Google Group for the term "orientation".
One example I read about as an example on how to detect orientation was Pie Guy: (game, js file). It's similar to the code you've posted, but like you... I couldn't get it to work.
One caveat: the eventListener worked for me, but I'm not sure if this is an overly intensive approach. So far it's been the only way that's worked for me, but I don't know if there are better, more streamlined ways.
UPDATE fixed the code above, it works now
Bootstrap 4 solution
bootstrap 4 ships built-in toggle. Here is the documentation. https://getbootstrap.com/docs/4.3/components/forms/#switches
The mixin from @ivanlivski is great.
I've extended it to
The updated code is available here: https://github.com/sknutsonsf/python-contrib/blob/master/src/django/utils/ModelDiffMixin.py
To help people new to Python or Django, I'll give a more complete example. This particular usage is to take a file from a data provider and ensure the records in the database reflect the file.
My model object:
class Station(ModelDiffMixin.ModelDiffMixin, models.Model):
station_name = models.CharField(max_length=200)
nearby_city = models.CharField(max_length=200)
precipitation = models.DecimalField(max_digits=5, decimal_places=2)
# <list of many other fields>
def is_float_changed (self,v1, v2):
''' Compare two floating values to just two digit precision
Override Default precision is 5 digits
'''
return abs (round (v1 - v2, 2)) > 0.01
The class that loads the file has these methods:
class UpdateWeather (object)
# other methods omitted
def update_stations (self, filename):
# read all existing data
all_stations = models.Station.objects.all()
self._existing_stations = {}
# insert into a collection for referencing while we check if data exists
for stn in all_stations.iterator():
self._existing_stations[stn.id] = stn
# read the file. result is array of objects in known column order
data = read_tabbed_file(filename)
# iterate rows from file and insert or update where needed
for rownum in range(sh.nrows):
self._update_row(sh.row(rownum));
# now anything remaining in the collection is no longer active
# since it was not found in the newest file
# for now, delete that record
# there should never be any of these if the file was created properly
for stn in self._existing_stations.values():
stn.delete()
self._num_deleted = self._num_deleted+1
def _update_row (self, rowdata):
stnid = int(rowdata[0].value)
name = rowdata[1].value.strip()
# skip the blank names where data source has ids with no data today
if len(name) < 1:
return
# fetch rest of fields and do sanity test
nearby_city = rowdata[2].value.strip()
precip = rowdata[3].value
if stnid in self._existing_stations:
stn = self._existing_stations[stnid]
del self._existing_stations[stnid]
is_update = True;
else:
stn = models.Station()
is_update = False;
# object is new or old, don't care here
stn.id = stnid
stn.station_name = name;
stn.nearby_city = nearby_city
stn.precipitation = precip
# many other fields updated from the file
if is_update == True:
# we use a model mixin to simplify detection of changes
# at the cost of extra memory to store the objects
if stn.has_changed == True:
self._num_updated = self._num_updated + 1;
stn.save();
else:
self._num_created = self._num_created + 1;
stn.save()
I always make a call from the end of the JavaScript files for registering its loading and it used to work perfect for me for all the browsers.
Ex: I have an index.htm, Js1.js and Js2.js. I add the function IAmReady(Id) in index.htm header and call it with parameters 1 and 2 from the end of the files, Js1 and Js2 respectively. The IAmReady function will have a logic to run the boot code once it gets two calls (storing the the number of calls in a static/global variable) from the two js files.
https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html
The correct way to use LOCK TABLES and UNLOCK TABLES with transactional tables, such as InnoDB tables, is to begin a transaction with SET autocommit = 0 (not START TRANSACTION) followed by LOCK TABLES, and to not call UNLOCK TABLES until you commit the transaction explicitly. For example, if you need to write to table t1 and read from table t2, you can do this:
SET autocommit=0;
LOCK TABLES t1 WRITE, t2 READ, ...;... do something with tables t1 and t2 here ...
COMMIT;
UNLOCK TABLES;
If you want to update your project using SVN then first of all:
Go to the path on which your project is stored through command prompt.
Use the command SVN update
That's it.
public static void Main(string[] args)
{
string json = @" {
""children"": [
{
""url"": ""foo.pdf"",
""expanded"": false,
""label"": ""E14288-Passive-40085-2014_09_26.pdf"",
""last_modified"": ""2014-09-28T11:19:49.000Z"",
""type"": 1,
""size"": 60929
}
]
}";
var result = JsonConvert.DeserializeObject<ChildrenRootObject>(json);
DataTable tbl = DataTableFromObject(result.children);
}
public static DataTable DataTableFromObject<T>(IList<T> list)
{
DataTable tbl = new DataTable();
tbl.TableName = typeof(T).Name;
var propertyInfos = typeof(T).GetProperties();
List<string> columnNames = new List<string>();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
tbl.Columns.Add(propertyInfo.Name, propertyInfo.PropertyType);
columnNames.Add(propertyInfo.Name);
}
foreach(var item in list)
{
DataRow row = tbl.NewRow();
foreach (var name in columnNames)
{
row[name] = item.GetType().GetProperty(name).GetValue(item, null);
}
tbl.Rows.Add(row);
}
return tbl;
}
public class Child
{
public string url { get; set; }
public bool expanded { get; set; }
public string label { get; set; }
public DateTime last_modified { get; set; }
public int type { get; set; }
public int size { get; set; }
}
public class ChildrenRootObject
{
public List<Child> children { get; set; }
}
NullPointerException with JSP can also happen if:
A getter returns a non-public inner class.
This code will fail if you remove Getters's access modifier or make it private or protected.
JAVA:
package com.myPackage;
public class MyClass{
//: Must be public or you will get:
//: org.apache.jasper.JasperException:
//: java.lang.NullPointerException
public class Getters{
public String
myProperty(){ return(my_property); }
};;
//: JSP EL can only access functions:
private Getters _get;
public Getters get(){ return _get; }
private String
my_property;
public MyClass(String my_property){
super();
this.my_property = my_property;
_get = new Getters();
};;
};;
JSP
<%@ taglib uri ="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="com.myPackage.MyClass" %>
<%
MyClass inst = new MyClass("[PROP_VALUE]");
pageContext.setAttribute("my_inst", inst );
%><html lang="en"><body>
${ my_inst.get().myProperty() }
</body></html>
You could do it like this:
<a class="btn btn-primary announce" data-toggle="modal" data-id="107" >Announce</a>
Then use jQuery to bind the click and send the Announce data-id as the value in the modals #cafeId:
$(document).ready(function(){
$(".announce").click(function(){ // Click to only happen on announce links
$("#cafeId").val($(this).data('id'));
$('#createFormId').modal('show');
});
});
This one is nice, but doesn't work as mmyers noticed, because of the square brackets:
Arrays.toString(objectArray).split(",")
This one is ugly but works:
Arrays.toString(objectArray).replaceFirst("^\\[", "").replaceFirst("\\]$", "").split(",")
If you use this code you must be sure that the strings returned by your objects' toString() don't contain commas.
The easiest/best supported method is to use <table cellspacing="10">
The css way: border-spacing (not supported by IE I don't think)
<!-- works in firefox, opera, safari, chrome -->_x000D_
<style type="text/css">_x000D_
_x000D_
table.foobar {_x000D_
border: solid black 1px;_x000D_
border-spacing: 10px;_x000D_
}_x000D_
table.foobar td {_x000D_
border: solid black 1px;_x000D_
}_x000D_
_x000D_
_x000D_
</style>_x000D_
_x000D_
<table class="foobar" cellpadding="0" cellspacing="0">_x000D_
<tr><td>foo</td><td>bar</td></tr>_x000D_
</table>
_x000D_
Edit: if you just want to pad the cell content, and not space them you can simply use
<table cellpadding="10">
OR
td {
padding: 10px;
}
// GET DATE & TIME IN ANY FORMAT
import java.util.Calendar;
import java.text.SimpleDateFormat;
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}
Taken from here
After searching and trying multiple non working options to get my select default option working. I find a clean solution at: http://www.undefinednull.com/2014/08/11/a-brief-walk-through-of-the-ng-options-in-angularjs/
<select class="ajg-stereo-fader-input-name ajg-select-left" ng-options="option.name for option in selectOptions" ng-model="inputLeft"></select>
<select class="ajg-stereo-fader-input-name ajg-select-right" ng-options="option.name for option in selectOptions" ng-model="inputRight"></select>
scope.inputLeft = scope.selectOptions[0];
scope.inputRight = scope.selectOptions[1];
You can use the following code to check if a textbox object is null/empty
'Checks if the box is null
If Me.TextBox & "" <> "" Then
'Enter Code here...
End if
Personally, I find the TryParse
method easier to read, which one you'll actually want to use depends on your use-case: if errors can be handled locally you are expecting errors and a bool from TryParse
is good, else you might want to just let the exceptions fly.
I would expect the TryParse
to be faster too, since it avoids the overhead of exception handling. But use a benchmark tool, like Jon Skeet's MiniBench to compare the various possibilities.
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
For Https
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^(.*)$ http%1://www.%{HTTP_HOST}/$1 [R=301,L]
// 24-hour time to 12-hour time
$time_in_12_hour_format = date("g:i a", strtotime("13:30"));
// 12-hour time to 24-hour time
$time_in_24_hour_format = date("H:i", strtotime("1:30 PM"));
List is an interface. You need a specific class in the end so either try
List l = new ArrayList();
or
List l = new LinkedList();
Whichever suit your needs.
I just want to add that if the constructor is called from a different file, then something as simple as forgetting to export the constructor with
module.exports = NAME_OF_CONSTRUCTOR
will also cause the "Not a constructor" exception.
The CSS table model is based on the HTML table model http://www.w3.org/TR/CSS21/tables.html
A table is divided into ROWS, and each row contains one or more cells. Cells are children of ROWS, they are NEVER children of columns.
"display: table-column" does NOT provide a mechanism for making columnar layouts (e.g. newspaper pages with multiple columns, where content can flow from one column to the next).
Rather, "table-column" ONLY sets attributes that apply to corresponding cells within the rows of a table. E.g. "The background color of the first cell in each row is green" can be described.
The table itself is always structured the same way it is in HTML.
In HTML (observe that "td"s are inside "tr"s, NOT inside "col"s):
<table ..>
<col .. />
<col .. />
<tr ..>
<td ..></td>
<td ..></td>
</tr>
<tr ..>
<td ..></td>
<td ..></td>
</tr>
</table>
Corresponding HTML using CSS table properties (Note that the "column" divs do not contain any contents -- the standard does not allow for contents directly in columns):
.mytable {_x000D_
display: table;_x000D_
}_x000D_
.myrow {_x000D_
display: table-row;_x000D_
}_x000D_
.mycell {_x000D_
display: table-cell;_x000D_
}_x000D_
.column1 {_x000D_
display: table-column;_x000D_
background-color: green;_x000D_
}_x000D_
.column2 {_x000D_
display: table-column;_x000D_
}
_x000D_
<div class="mytable">_x000D_
<div class="column1"></div>_x000D_
<div class="column2"></div>_x000D_
<div class="myrow">_x000D_
<div class="mycell">contents of first cell in row 1</div>_x000D_
<div class="mycell">contents of second cell in row 1</div>_x000D_
</div>_x000D_
<div class="myrow">_x000D_
<div class="mycell">contents of first cell in row 2</div>_x000D_
<div class="mycell">contents of second cell in row 2</div>_x000D_
</div>_x000D_
</div>
_x000D_
OPTIONAL: both "rows" and "columns" can be styled by assigning multiple classes to each row and cell as follows. This approach gives maximum flexibility in specifying various sets of cells, or individual cells, to be styled:
//Useful css declarations, depending on what you want to affect, include:_x000D_
_x000D_
/* all cells (that have "class=mycell") */_x000D_
.mycell {_x000D_
}_x000D_
_x000D_
/* class row1, wherever it is used */_x000D_
.row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 (if you've put "class=mycell" on each cell) */_x000D_
.row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 */_x000D_
.row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows */_x000D_
.cell1 {_x000D_
}_x000D_
_x000D_
/* row1 inside class mytable (so can have different tables with different styles) */_x000D_
.mytable .row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 of a mytable */_x000D_
.mytable .row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 of a mytable */_x000D_
.mytable .row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows of a mytable */_x000D_
.mytable .cell1 {_x000D_
}
_x000D_
<div class="mytable">_x000D_
<div class="column1"></div>_x000D_
<div class="column2"></div>_x000D_
<div class="myrow row1">_x000D_
<div class="mycell cell1">contents of first cell in row 1</div>_x000D_
<div class="mycell cell2">contents of second cell in row 1</div>_x000D_
</div>_x000D_
<div class="myrow row2">_x000D_
<div class="mycell cell1">contents of first cell in row 2</div>_x000D_
<div class="mycell cell2">contents of second cell in row 2</div>_x000D_
</div>_x000D_
</div>
_x000D_
In today's flexible designs, which use <div>
for multiple purposes, it is wise to put some class on each div, to help refer to it. Here, what used to be <tr>
in HTML became class myrow
, and <td>
became class mycell
. This convention is what makes the above CSS selectors useful.
PERFORMANCE NOTE: putting class names on each cell, and using the above multi-class selectors, is better performance than using selectors ending with *
, such as .row1 *
or even .row1 > *
. The reason is that selectors are matched last first, so when matching elements are being sought, .row1 *
first does *
, which matches all elements, and then checks all the ancestors of each element, to find if any ancestor has class row1
. This might be slow in a complex document on a slow device. .row1 > *
is better, because only the immediate parent is examined. But it is much better still to immediately eliminate most elements, via .row1 .cell1
. (.row1 > .cell1
is an even tighter spec, but it is the first step of the search that makes the biggest difference, so it usually isn't worth the clutter, and the extra thought process as to whether it will always be a direct child, of adding the child selector >
.)
The key point to take away re performance is that the last item in a selector should be as specific as possible, and should never be *
.
Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (drawable == null) {
drawable = getRandomDrawable();
}
The equals()
method checks for value equality, which means that it compares the contents of two objects. Since null
is not an object, this crashes when trying to compare the contents of your object to the contents of null
.
The ==
operator checks for reference equality, which means that it looks whether the two objects are actually the very same object. This does not require the objects to actually exist; two nonexistent objects (null
references) are also equal.
I think these official guide should work for your case.
VS Code allows you to quickly search over all files in the currently-opened folder. Press Ctrl+Shift+F and enter in your search term. Search results are grouped into files containing the search term, with an indication of the hits in each file and its location. Expand a file to see a preview of all of the hits within that file. Then single-click on one of the hits to view it in the editor.
import numpy as np
w=np.array([ 0.4, 0.8, 1.6, 0.8, 0.4])
np.random.choice(w, p=w/sum(w))
yes, if( (A) && (B) ) will fail on the first clause, if (A) evaluates false.
this applies to any language btw, not just C derivatives. For threaded and parallel processing this is a different story ;)
I would do the following (copy-paste the whole stuff below into immediate window / query window and execute)
DECLARE @foo int
DECLARE @unclefoo smalldatetime
SET @foo = DATEDIFF(minute, CAST('2013.01.01 00:00:00' AS datetime),CAST('2013.01.01 00:03:59' AS datetime)) -- AS 'Duration (Minutes)'
SET @unclefoo = DATEADD(minute, @foo, '2000.01.01')
SELECT CAST(@unclefoo AS time)
@foo
stores the value you generate in your question. The "trick" comes by then:
we create a smalldatetime
variable (in my case it's yyyy.mm.dd
format) and increment it with your int
value, then display (or store if you want) the time
part only.
This copies the 5 cells to the right of the activecell. If you have a range selected, the active cell is the top left cell in the range.
Sub Copy5CellsToRight()
ActiveCell.Offset(, 1).Resize(1, 5).Copy
End Sub
If you want to include the activecell in the range that gets copied, you don't need the offset:
Sub ExtendAndCopy5CellsToRight()
ActiveCell.Resize(1, 6).Copy
End Sub
Note that you don't need to select before copying.
If you are using firefox then the firebug plug-in console is an excellent way of examining objects
console.debug(myObject);
Alternatively you can loop through the properties (including methods) like this:
for (property in object) {
// do what you want with property, object[property].value
}
This one worked like a charm for me where the date picker just has previous and next buttons and Month and year as texts.
Page objects are as follows
[FindsBy(How =How.ClassName, Using = "ui-datepicker-calendar")]
public IWebElement tblCalendar;
[FindsBy(How = How.XPath, Using = "//a[@title=\"Prev\"]")]
public IWebElement btnPrevious;
[FindsBy(How = How.XPath, Using = "//a[@title=\"Next\"]")]
public IWebElement btnNext;
[FindsBy(How = How.ClassName, Using = "ui-datepicker-year")]
public IWebElement lblYear;
[FindsBy(How = How.ClassName, Using = "ui-datepicker-month")]
public IWebElement lblMonth;
public void SelectDateFromDatePicker(string year, string month, string date)
{
while (year != lblYear.Text)
{
if (int.Parse(year) < int.Parse(lblYear.Text))
{
btnPrevious.Clicks();
}
else
{
btnNext.Clicks();
}
}
while (lblMonth.Text != "January")
{
btnPrevious.Clicks();
}
while (month != lblMonth.Text)
{
btnNext.Clicks();
}
IWebElement dateField = PropertiesCollection.driver.FindElement(By.XPath("//a[text()=\""+ date+"\"]"));
dateField.Clicks();
}
1) Maybe oveflow: hidden; will do the trick?
2) You need to set the size of each div with the text and button so that each of these divs have the same height. Then for your button:
button {
position: absolute;
bottom: 0;
}
You would probably want this. Simplest solution would be
Create file first.
open file via
f = open('<filename>', 'w')
or
f = open('<filename>', 'a')
in case you want to append to file
Now, write to the same file via
f.write(<text to be written>)
Close the file after you are done using it
#good pracitice
f.close()
a better solution is
runAllManagedModulesForAllRequest is a clever thing to do respect removing and resinserting session module.
alk.
I tried with CSS, and or you need to use display: table or you need to use new css that is not yet supported on most browsers (2016).
So, I wrote a jquery plugin to do it for us, I am happy to share it:
_x000D_
//Credit Efy Teicher_x000D_
$(document).ready(function () {_x000D_
$(".fillHight").fillHeight();_x000D_
$(".fillWidth").fillWidth();_x000D_
});_x000D_
_x000D_
window.onresize = function (event) {_x000D_
$(".fillHight").fillHeight();_x000D_
$(".fillWidth").fillWidth();_x000D_
}_x000D_
_x000D_
$.fn.fillHeight = function () {_x000D_
var siblingsHeight = 0;_x000D_
this.siblings("div").each(function () {_x000D_
siblingsHeight = siblingsHeight + $(this).height();_x000D_
});_x000D_
_x000D_
var height = this.parent().height() - siblingsHeight;_x000D_
this.height(height);_x000D_
};_x000D_
_x000D_
_x000D_
$.fn.fillWidth = function (){_x000D_
var siblingsWidth = 0;_x000D_
this.siblings("div").each(function () {_x000D_
siblingsWidth += $(this).width();_x000D_
});_x000D_
_x000D_
var width =this.parent().width() - siblingsWidth;_x000D_
this.width(width);_x000D_
}
_x000D_
* {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
html {_x000D_
}_x000D_
_x000D_
html, body, .fillParent {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>_x000D_
<div class="fillParent" style="background-color:antiquewhite">_x000D_
<div>_x000D_
no1_x000D_
</div>_x000D_
<div class="fillHight">_x000D_
no2 fill_x000D_
</div>_x000D_
<div class="deb">_x000D_
no3_x000D_
</div>_x000D_
</div>
_x000D_
There is also some more detail on the use of <mvc:annotation-driven />
in the Spring docs. In a nutshell, <mvc:annotation-driven />
gives you greater control over the inner workings of Spring MVC. You don't need to use it unless you need one or more of the features outlined in the aforementioned section of the docs.
Also, there are other "annotation-driven" tags available to provide additional functionality in other Spring modules. For example, <transaction:annotation-driven />
enables the use of the @Transaction annotation, <task:annotation-driven />
is required for @Scheduled et al...
FileInputStream with InputStreamReader is better than directly using FileReader, because the latter doesn't allow you to specify encoding charset.
Here is an example using BufferedReader, FileInputStream and InputStreamReader together, so that you could read lines from a file.
List<String> words = new ArrayList<>();
List<String> meanings = new ArrayList<>();
public void readAll( ) throws IOException{
String fileName = "College_Grade4.txt";
String charset = "UTF-8";
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(fileName), charset));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if( line.length() == 0 ) continue;
int idx = line.indexOf("\t");
words.add( line.substring(0, idx ));
meanings.add( line.substring(idx+1));
}
reader.close();
}
use either of these codes
$('#dropDownId :selected').text();
OR
$('#dropDownId').text();
<script type="text/javascript">
$(document).ready(function() {
$(this).attr("title", "sometitle");
});
</script>
The System.Math.Round
method uses the Double
structure, which, as others have pointed out, is prone to floating point precision errors. The simple solution I found to this problem when I encountered it was to use the System.Decimal.Round
method, which doesn't suffer from the same problem and doesn't require redifining your variables as decimals:
Decimal.Round(0.575, 2, MidpointRounding.AwayFromZero)
Result: 0.58
I was looking solution for my Ionic Cordova app push notification.
Thanks to Syed Rafay's answer.
in app.component.ts
const options: PushOptions = {
android: {
topics: ['all']
},
in Server file
"to" => "/topics/all",
Register for a notification prior to calling the class method.
Swift code:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "displayAlert", name: "ErrorOccured", object: nil)
In the displayAlert
instance method you could display your alert.
You could do that:
KeyValuePair<TKey, TValue>
's in the dictionary (which will be a sizable performance hit if you have a number of entries in the dictionary) Use Method 1 if performance is not a consideration, use Method 2 if memory is not a consideration.
Also, all keys must be unique, but the values are not required to be unique. You may have more than one key with the specified value.
Is there any reason you can't reverse the key-value relationship?
A static method belongs to the class itself and a non-static (aka instance) method belongs to each object that is generated from that class. If your method does something that doesn't depend on the individual characteristics of its class, make it static (it will make the program's footprint smaller). Otherwise, it should be non-static.
Example:
class Foo {
int i;
public Foo(int i) {
this.i = i;
}
public static String method1() {
return "An example string that doesn't depend on i (an instance variable)";
}
public int method2() {
return this.i + 1; // Depends on i
}
}
You can call static methods like this: Foo.method1()
. If you try that with method2, it will fail. But this will work: Foo bar = new Foo(1); bar.method2();
The following function searches on multiple patterns, separated by commas. You can also specify an exclusion, eg: "!web.config" will search for all files and exclude "web.config". Patterns can be mixed.
private string[] FindFiles(string directory, string filters, SearchOption searchOption)
{
if (!Directory.Exists(directory)) return new string[] { };
var include = (from filter in filters.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) where !string.IsNullOrEmpty(filter.Trim()) select filter.Trim());
var exclude = (from filter in include where filter.Contains(@"!") select filter);
include = include.Except(exclude);
if (include.Count() == 0) include = new string[] { "*" };
var rxfilters = from filter in exclude select string.Format("^{0}$", filter.Replace("!", "").Replace(".", @"\.").Replace("*", ".*").Replace("?", "."));
Regex regex = new Regex(string.Join("|", rxfilters.ToArray()));
List<Thread> workers = new List<Thread>();
List<string> files = new List<string>();
foreach (string filter in include)
{
Thread worker = new Thread(
new ThreadStart(
delegate
{
string[] allfiles = Directory.GetFiles(directory, filter, searchOption);
if (exclude.Count() > 0)
{
lock (files)
files.AddRange(allfiles.Where(p => !regex.Match(p).Success));
}
else
{
lock (files)
files.AddRange(allfiles);
}
}
));
workers.Add(worker);
worker.Start();
}
foreach (Thread worker in workers)
{
worker.Join();
}
return files.ToArray();
}
Usage:
foreach (string file in FindFiles(@"D:\628.2.11", @"!*.config, !*.js", SearchOption.AllDirectories))
{
Console.WriteLine(file);
}
Like this:
$dd = document.getElementById("yourselectelementid");
$so = $dd.options[$dd.selectedIndex];
None of the above helped for me.
I am using Kubernetes on Google Cloud with tesla k-80 gpu.
Follow along this guide to ensure you installed everything correctly: https://cloud.google.com/kubernetes-engine/docs/how-to/gpus
I was missing few important things:
For COS node:
kubectl apply -f https://raw.githubusercontent.com/GoogleCloudPlatform/container-engine-accelerators/master/nvidia-driver-installer/cos/daemonset-preloaded.yaml
For UBUNTU node:
kubectl apply -f https://raw.githubusercontent.com/GoogleCloudPlatform/container-engine-accelerators/master/nvidia-driver-installer/ubuntu/daemonset-preloaded.yaml
Make sure an update was rolled to your nodes. Restart them if upgrades are off.
I use this image nvidia/cuda:10.1-base-ubuntu16.04 in my docker
You have to set gpu limit! This is the only way the node driver can communicate with the pod. In your yaml configuration add this under your container:
resources:
limits:
nvidia.com/gpu: 1
You need to set the location
header as follows:
header('Location: http://www.example.com/');
Replacing http://www.example.com
of course with the url of your landing page.
Add this where you have finished logging the user in.
Note: When redirecting the user will be immediately redirected so you're message probably won't display.
Additionally, you need to move your PHP code to the top of the file for this solution to work.
On another side note, please see my comment above regarding the use of the deprecated mysql
statements and consider using the newer, safer and improved mysqli
or PDO
statements.
You could do:
brew reinstall php55-imagick
Where php55 is your PHP version.
function function_one() {
function_two();
}
function function_two() {
//enter code here
}
for those like me who are looking to send objects other than primitives, since you can't create a parameterized constructor in your fragment, just add a setter accessor in your fragment, this always works for me.
As starblue says, height is just recursive. In pseudo-code:
height(node) = max(height(node.L), height(node.R)) + 1
Now height could be defined in two ways. It could be the number of nodes in the path from the root to that node, or it could be the number of links. According to the page you referenced, the most common definition is for the number of links. In which case the complete pseudo code would be:
height(node):
if node == null:
return -1
else:
return max(height(node.L), height(node.R)) + 1
If you wanted the number of nodes the code would be:
height(node):
if node == null:
return 0
else:
return max(height(node.L), height(node.R)) + 1
Either way, the rebalancing algorithm I think should work the same.
However, your tree will be much more efficient (O(ln(n))) if you store and update height information in the tree, rather than calculating it each time. (O(n))
When it says "If the balance factor of R is 1", it is talking about the balance factor of the right branch, when the balance factor at the top is 2. It is telling you how to choose whether to do a single rotation or a double rotation. In (python like) Pseudo-code:
if balance factor(top) = 2: // right is imbalanced
if balance factor(R) = 1: //
do a left rotation
else if balance factor(R) = -1:
do a double rotation
else: // must be -2, left is imbalanced
if balance factor(L) = 1: //
do a left rotation
else if balance factor(L) = -1:
do a double rotation
I hope this makes sense
The copy
command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.
Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).
I tried a variation of your command as follows in SQL*Plus (with no errors):
copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;
After I executed the above statement, I also truncate the new_emp table and executed this command:
copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;
With SQL Developer, you could do the following to perform a similar approach to copying objects:
On the tool bar, select Tools>Database copy.
Identify source and destination connections with the copy options you would like.
For object type, select table(s).
The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).
The cleanest way is to test for it's existence, drop it if it exists, and then recreate it. You can't embed a "create proc" statement inside an IF statement. This should do nicely:
IF OBJECT_ID('MySproc', 'P') IS NOT NULL
DROP PROC MySproc
GO
CREATE PROC MySproc
AS
BEGIN
...
END
Check out this directive that manages effectively lists of checkboxes. I hope it works for you. CheckList Model
merge two object using Object.assign and spread operator.
Wrong way(Modify original object because targeting o1)
var o1 = { X: 10 };
var o2 = { Y: 20 };
var o3 = { Z: 30 };
var merge = Object.assign(o1, o2, o3);
console.log(merge) // {X:10, Y:20, Z:30}
console.log(o1) // {X:10, Y:20, Z:30}
Right ways
Object.assign({}, o1, o2, o3) ==> targeting new object
{...o1, ...o2, ...o3} ==> spreading objects
var o1 = { X: 10 };_x000D_
var o2 = { Y: 20 };_x000D_
var o3 = { Z: 30 };_x000D_
_x000D_
console.log('Does not modify original objects because target {}');_x000D_
var merge = Object.assign({}, o1, o2, o3);_x000D_
console.log(merge); // { X: 10, Y: 20, Z: 30 }_x000D_
console.log(o1)_x000D_
_x000D_
console.log('Does not modify original objects')_x000D_
var spreadMerge = {...o1, ...o2, ...o3};_x000D_
console.log(spreadMerge);_x000D_
console.log(o1);
_x000D_
Any time you do a remove() or a removeAll(), you should call
validate();
repaint();
after you have completed add()'ing the new components.
Calling validate() or revalidate() is mandatory when you do a remove() - see the relevant javadocs.
My own testing indicates that repaint() is also necessary. I'm not sure exactly why.
It seems clear that $(TESTS)
is empty so your 1.4.0 makefile is effectively
all:
clean:
rm -f gtest.a gtest_main.a *.o
Indeed, all has nothing to do. and clean does exactly what it says rm -f gtest.a ...
In PowerShell, the "sc" command is an alias for the Set-Content cmdlet. You can workaround this using the following syntax:
sc.exe config Service obj= user password= pass
Specyfying the .exe extension, PowerShell bypasses the alias lookup.
HTH
To keep the change in file but not to commit I did this
git add .
git reset -- main/dontcheckmein.txt
git commit -m "commit message"
to verify the file is excluded do
git status
This might be an old question, but there's an alternate method you can use that no one has mentioned. It's possible to specify the password directly in the connection URI. The documentation can be found here, alternatively here.
You can provide your username and password directly in the connection URI provided to psql
:
# postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
psql postgresql://username:password@localhost:5432/mydb
What you're trying to do is to monitor the property of attribute in directive. You can watch the property of attribute changes using $observe() as follows:
angular.module('myApp').directive('conversation', function() {
return {
restrict: 'E',
replace: true,
compile: function(tElement, attr) {
attr.$observe('typeId', function(data) {
console.log("Updated data ", data);
}, true);
}
};
});
Keep in mind that I used the 'compile' function in the directive here because you haven't mentioned if you have any models and whether this is performance sensitive.
If you have models, you need to change the 'compile' function to 'link' or use 'controller' and to monitor the property of a model changes, you should use $watch(), and take of the angular {{}} brackets from the property, example:
<conversation style="height:300px" type="convo" type-id="some_prop"></conversation>
And in the directive:
angular.module('myApp').directive('conversation', function() {
return {
scope: {
typeId: '=',
},
link: function(scope, elm, attr) {
scope.$watch('typeId', function(newValue, oldValue) {
if (newValue !== oldValue) {
// You actions here
console.log("I got the new value! ", newValue);
}
}, true);
}
};
});
Scikit learn introduced a delicious new method called export_text
in version 0.21 (May 2019) to extract the rules from a tree. Documentation here. It's no longer necessary to create a custom function.
Once you've fit your model, you just need two lines of code. First, import export_text
:
from sklearn.tree import export_text
Second, create an object that will contain your rules. To make the rules look more readable, use the feature_names
argument and pass a list of your feature names. For example, if your model is called model
and your features are named in a dataframe called X_train
, you could create an object called tree_rules
:
tree_rules = export_text(model, feature_names=list(X_train.columns))
Then just print or save tree_rules
. Your output will look like this:
|--- Age <= 0.63
| |--- EstimatedSalary <= 0.61
| | |--- Age <= -0.16
| | | |--- class: 0
| | |--- Age > -0.16
| | | |--- EstimatedSalary <= -0.06
| | | | |--- class: 0
| | | |--- EstimatedSalary > -0.06
| | | | |--- EstimatedSalary <= 0.40
| | | | | |--- EstimatedSalary <= 0.03
| | | | | | |--- class: 1
As others have mentioned, comments are referenced with a #
and are documented here. However, unlike some languages, the #
must be at the beginning of the line. If they occur part way through the line, they are interpreted as an argument and may result in unexpected behavior.
# This is a comment
COPY test_dir target_dir # This is not a comment, it is an argument to COPY
RUN echo hello world # This is an argument to RUN but the shell may ignore it
It should also be noted that parser directives have recently been added to the Dockerfile which have the same syntax as a comment. They need to appear at the top of the file, before any other comments or commands. Originally, this directive was added for changing the escape character to support Windows:
# escape=`
FROM microsoft/nanoserver
COPY testfile.txt c:\
RUN dir c:\
The first line, while it appears to be a comment, is a parser directive to change the escape character to a backtick so that the COPY
and RUN
commands can use the backslash in the path. A parser directive is also used with BuildKit to change the frontend parser with a syntax
line. See the experimental syntax for more details on how this is being used in practice.
With a multi-line command, the commented lines are ignored, but you need to comment out every line individually:
$ cat Dockerfile
FROM busybox:latest
RUN echo first command \
# && echo second command disabled \
&& echo third command
$ docker build .
Sending build context to Docker daemon 23.04kB
Step 1/2 : FROM busybox:latest
---> 59788edf1f3e
Step 2/2 : RUN echo first command && echo third command
---> Running in b1177e7b563d
first command
third command
Removing intermediate container b1177e7b563d
---> 5442cfe321ac
Successfully built 5442cfe321ac
I used this:
HTMLDatetoIsoDate(htmlDate){
let year = Number(htmlDate.toString().substring(0, 4))
let month = Number(htmlDate.toString().substring(5, 7))
let day = Number(htmlDate.toString().substring(8, 10))
return new Date(year, month - 1, day)
}
isoDateToHtmlDate(isoDate){
let date = new Date(isoDate);
let dtString = ''
let monthString = ''
if (date.getDate() < 10) {
dtString = '0' + date.getDate();
} else {
dtString = String(date.getDate())
}
if (date.getMonth()+1 < 10) {
monthString = '0' + Number(date.getMonth()+1);
} else {
monthString = String(date.getMonth()+1);
}
return date.getFullYear()+'-' + monthString + '-'+dtString
}
Source: http://gooplus.fr/en/2017/07/13/angular2-typescript-isodate-to-html-date/
You can actually release your Excel Application object cleanly, but you do have to take care.
The advice to maintain a named reference for absolutely every COM object you access and then explicitly release it via Marshal.FinalReleaseComObject()
is correct in theory, but, unfortunately, very difficult to manage in practice. If one ever slips anywhere and uses "two dots", or iterates cells via a for each
loop, or any other similar kind of command, then you'll have unreferenced COM objects and risk a hang. In this case, there would be no way to find the cause in the code; you would have to review all your code by eye and hopefully find the cause, a task that could be nearly impossible for a large project.
The good news is that you do not actually have to maintain a named variable reference to every COM object you use. Instead, call GC.Collect()
and then GC.WaitForPendingFinalizers()
to release all the (usually minor) objects to which you do not hold a reference, and then explicitly release the objects to which you do hold a named variable reference.
You should also release your named references in reverse order of importance: range objects first, then worksheets, workbooks, and then finally your Excel Application object.
For example, assuming that you had a Range object variable named xlRng
, a Worksheet variable named xlSheet
, a Workbook variable named xlBook
and an Excel Application variable named xlApp
, then your cleanup code could look something like the following:
// Cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.FinalReleaseComObject(xlRng);
Marshal.FinalReleaseComObject(xlSheet);
xlBook.Close(Type.Missing, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(xlBook);
xlApp.Quit();
Marshal.FinalReleaseComObject(xlApp);
In most code examples you'll see for cleaning up COM objects from .NET, the GC.Collect()
and GC.WaitForPendingFinalizers()
calls are made TWICE as in:
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
This should not be required, however, unless you are using Visual Studio Tools for Office (VSTO), which uses finalizers that cause an entire graph of objects to be promoted in the finalization queue. Such objects would not be released until the next garbage collection. However, if you are not using VSTO, you should be able to call GC.Collect()
and GC.WaitForPendingFinalizers()
just once.
I know that explicitly calling GC.Collect()
is a no-no (and certainly doing it twice sounds very painful), but there is no way around it, to be honest. Through normal operations you will generate hidden objects to which you hold no reference that you, therefore, cannot release through any other means other than calling GC.Collect()
.
This is a complex topic, but this really is all there is to it. Once you establish this template for your cleanup procedure you can code normally, without the need for wrappers, etc. :-)
I have a tutorial on this here:
Automating Office Programs with VB.Net / COM Interop
It's written for VB.NET, but don't be put off by that, the principles are exactly the same as when using C#.
When using literal strings (start with @") this might be easier
char tab = '\u0009';
string A = "Apple";
string B = "Bob";
string myStr = String.Format(@"{0}:{1}{2}", A, tab, B);
Would result in Apple:<tab>Bob
The PDO solution, just for a better implementation then mysql_*
:
$array = $pdo->query("SELECT id, title, '$year-month-10' as start,url
FROM table")->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($array);
Nice feature is also that it will leave integers as integers as opposed to strings.
Only you want to set default value parameter. This calling third overloading method.
dt.Columns.Add("MyRow", type(System.Int32),0);
You can achieve the same using
<select [ngModel]="object">
<option *ngFor="let object of objects;let i= index;" [value]="object.value" selected="i==0">{{object.name}}</option>
</select>
You should use the optional argument indent
.
header, output = client.request(twitterRequest, method="GET", body=None,
headers=None, force_auth_header=True)
# now write output to a file
twitterDataFile = open("twitterData.json", "w")
# magic happens here to make it pretty-printed
twitterDataFile.write(simplejson.dumps(simplejson.loads(output), indent=4, sort_keys=True))
twitterDataFile.close()
We get err_cache_miss error while using the bowser. Its mean there may be a problem with your browser. It due the items in the cache may be unusable or some configurations are not configured correctly. You may get the solution to clear browser data or Check browser extensions and remove extensions which you felt cause the problem or Resetting your browser or Update your browser or Disabling cache system. These are some tricks to come out this error.
Here is something that is not exactly like what you had in previous answers, but it could be helpful to some:
body {
display: flex;
flex-direction: column;
height: 100vh;
margin: 0px;
}
#one {
background-color: red;
}
#two {
margin-top: 0px;
background-color: black;
color: white;
overflow-y: scroll;
}
You can put a meta refresh Tag in the irc_online.php
<meta http-equiv="refresh" content="30">
OR you can use Javascript with setInterval to refresh the src of the Source...
<script>
window.setInterval("reloadIFrame();", 30000);
function reloadIFrame() {
document.frames["frameNameHere"].location.reload();
}
</script>
Suggest do this in your code-behind before sending down to SQL Server.
int userVal = int.Parse(txtboxname.Text);
Perhaps try to parse and optionally let the user know.
int? userVal;
if (int.TryParse(txtboxname.Text, out userVal)
{
DoSomething(userVal.Value);
}
else
{ MessageBox.Show("Hey, we need an int over here."); }
The exception you note means that you're not including the value in the call to the stored proc. Try setting a debugger breakpoint in your code at the time you call down into the code that builds the call to SQL Server.
Ensure you're actually attaching the parameter to the SqlCommand.
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@ParamName", SqlDbType.Int);
cmd.Parameters["@ParamName"].Value = newName;
conn.Open();
string someReturn = (string)cmd.ExecuteScalar();
}
Perhaps fire up SQL Profiler on your database to inspect the SQL statement being sent/executed.
One of reasons why you will get this Notice: Array to string conversion in… is that you are combining group of arrays. Example, sorting out several first and last names.
To echo elements of array properly, you can use the function, implode(separator, array)
Example:
implode(' ', $var)
result:
first name[1], last name[1]
first name[2], last name[2]
More examples from W3C.
The compiler looks for each symbol being used in the current translation unit is previously declared or not in the current unit. It is just a matter of style providing all method signatures at the beginning of a source file while definitions are provided later. The significant use of it is when you use a pointer to a class as member variable of another class.
//foo.h
class bar; // This is useful
class foo
{
bar* obj; // Pointer or even a reference.
};
// foo.cpp
#include "bar.h"
#include "foo.h"
So, use forward-declarations in classes when ever possible. If your program just has functions( with ho header files), then providing prototypes at the beginning is just a matter of style. This would be anyhow the case had if the header file was present in a normal program with header that has only functions.
when new props or states being received (like you call setState
here), React will invoked some functions, which are called componentWillUpdate
and componentDidUpdate
in your case, just simply add a componentDidUpdate
function to call this.drawGrid()
here is working code in JS Bin
as I mentioned, in the code, componentDidUpdate
will be invoked after this.setState(...)
then componentDidUpdate
inside is going to call this.drawGrid()
read more about component Lifecycle in React https://facebook.github.io/react/docs/component-specs.html#updating-componentwillupdate
var count=0;
let myArray = '{"1":"a","2":"b","3":"c","4":"d"}'
var data = JSON.parse(myArray);
for (let key in data) {
let value = data[key]; // get the value by key
console.log("key: , value:", key, value);
count = count + 1;
}
console.log("size:",count);
Check that your singing identity IN YOUR TARGET properties is correct. This one over-rides what you have in your project properties.
Also: I dunno if this is true - but I wasn't getting emails detailing my binary rejections when I did the "ready for binary upload" from a PC - but I DID get an email when I did this on the MAC
Yes, Eclipse can be a pain, as almost any IDE can. Please remain factual, however.
Switching to a new workspace should help you. Eclipse has almost no settings that are stored outside your workspace.
setattr()
We use setattr to add an attribute to our class instance. We pass the class instance, the attribute name, and the value.
getattr()
With getattr we retrive these values
For example
Employee = type("Employee", (object,), dict())
employee = Employee()
# Set salary to 1000
setattr(employee,"salary", 1000 )
# Get the Salary
value = getattr(employee, "salary")
print(value)
The solution I opted for was to format the date with the mysql query :
String l_mysqlQuery = "SELECT DATE_FORMAT(time, '%Y-%m-%d %H:%i:%s') FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));
I had the exact same issue.
Even though my mysql table contains dates formatted as such : 2017-01-01 21:02:50
String l_mysqlQuery = "SELECT time FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));
was returning a date formatted as such :
2017-01-01 21:02:50.0
You could inject $routeParams
to your controller and access all the params that where used when the route was resolved.
E.g.:
// route was: app.dev/backend/:type/:id
function MyCtrl($scope, $routeParams, $log) {
// use the params
$log.info($routeParams.type, $routeParams.id);
};
See angular $routeParams documentation for further information.
font is deprecated use span instead Html.fromHtml("<span style=color:red>"+content+"</span>")
In my case(Bootstrap) the issue was, having the JQuery 3.0.0 which is also not fine, So using a version which is an earlier version like 2.2.4.
The Error i got was: Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3
Using any of these CDN below as the source would help if this is the case!
jQuery version 2.2.4:
http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.4.js
http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.4.min.js
Hope this helped at least someone!.. :)
Thank you!
As a windows user, run an Admin powershell and launch :
python -m pip install --upgrade pip
How you test depends on the Property's DataType:
| Type | Test | Test2 | Numeric (Long, Integer, Double etc.) | If obj.Property = 0 Then | | Boolen (True/False) | If Not obj.Property Then | If obj.Property = False Then | Object | If obj.Property Is Nothing Then | | String | If obj.Property = "" Then | If LenB(obj.Property) = 0 Then | Variant | If obj.Property = Empty Then |
You can tell the DataType by pressing F2 to launch the Object Browser and looking up the Object. Another way would be to just use the TypeName function:MsgBox TypeName(obj.Property)
Add produces = "application/json"
in @RequestMapping
If you are on bootstrap 3+, this can be shortened a bit further if using Jquery.
HTML
<a href="#" data-target="#my_modal" data-toggle="modal" class="identifyingClass" data-id="my_id_value">Open Modal</a>
<div class="modal fade" id="my_modal" tabindex="-1" role="dialog" aria-labelledby="my_modalLabel">
<div class="modal-dialog" role="dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal Title</h4>
</div>
<div class="modal-body">
Modal Body
<input type="hidden" name="hiddenValue" id="hiddenValue" value="" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">No</button>
<button type="button" class="btn btn-primary">Yes</button>
</div>
</div>
</div>
JQUERY
<script type="text/javascript">
$(function () {
$(".identifyingClass").click(function () {
var my_id_value = $(this).data('id');
$(".modal-body #hiddenValue").val(my_id_value);
})
});
</script>
One way
// join type can be inner, left, right, fullouter
val mergedDf = df1.join(df2, Seq("keyCol"), "inner")
// keyCol can be multiple column names seperated by comma
val mergedDf = df1.join(df2, Seq("keyCol1", "keyCol2"), "left")
Another way
import spark.implicits._
val mergedDf = df1.as("d1").join(df2.as("d2"), ($"d1.colName" === $"d2.colName"))
// to select specific columns as output
val mergedDf = df1.as("d1").join(df2.as("d2"), ($"d1.colName" === $"d2.colName")).select($"d1.*", $"d2.anotherColName")
Not very simple but:
a = [1,1,1,2,2,3]
b = a.group_by {|n| n}.each {|k,v| v.pop [1,3].count(k)}.values.flatten
=> [1, 1, 2, 2]
Also handles the case for multiples in the 'subtrahend':
a = [1,1,1,2,2,3]
b = a.group_by {|n| n}.each {|k,v| v.pop [1,1,3].count(k)}.values.flatten
=> [1, 2, 2]
EDIT: this is more an enhancement combining Norm212 and my answer to make a "functional" solution.
b = [1,1,3].each.with_object( a ) { |del| a.delete_at( a.index( del ) ) }
Put it in a lambda if needed:
subtract = lambda do |minuend, subtrahend|
subtrahend.each.with_object( minuend ) { |del| minuend.delete_at( minuend.index( del ) ) }
end
then:
subtract.call a, [1,1,3]
In layman terms it's strongly structured vs unstructured, which implies that you have different degrees of adaptability for your DB. Differences arise in indexation particularly as you need to ensure that a certain reference index can link to a another item -> this a relation. The more strict structure of relational DB comes from this requirement.
To note that NosDB apaprently provides both relational and non relational DBs and a way to query both http://www.alachisoft.com/nosdb/sql-cheat-sheet.html
You need to add the new line character \n
:
console.log('line one \nline two')
would display:
line one
line two
Go to C:\wamp\alias
. Open the file phpmyadmin.conf
and change
<Directory "c:/wamp/apps/phpmyadmin3.5.1/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
</Directory>
to
<Directory "c:/wamp/apps/phpmyadmin3.5.1/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Allow,Deny
Allow from all
</Directory>
problem solved
The following usually does the trick:
echo "$(cd "$(dirname "$1")" && pwd -P)/$(basename "$1")"
Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.
If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like
double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);
(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)
Maybe an old thread, but this code might be useful to visitors who want to create without regex
def listToString(s):
# initialize an empty string
str1 = ""
# return string
return (str1.join(s))
r = "Hello! How are you? *Smiling_Face* *Heart* erwer"
r1 = list(r)
i = 0
r2 = list()
start = True
for string in r1:
if string == "*":
if(start):
start = False
else:
start = True
else:
if(start):
r2.append(string)
else:
print("skipped" + string)
print(listToString(r2))
I have written a custom code for setInterval function which can also help
let interval;
function startInterval(){
interval = setInterval(appendDateToBody, 1000);
console.log(interval);
}
function appendDateToBody() {
document.body.appendChild(
document.createTextNode(new Date() + " "));
}
function stopInterval() {
clearInterval(interval);
console.log(interval);
}
_x000D_
<!DOCTYPE html>
<html>
<head>
<title>setInterval</title>
</head>
<body>
<input type="button" value="Stop" onclick="stopInterval();" />
<input type="button" value="Start" onclick="startInterval();" />
</body>
</html>
_x000D_
I'm using Android Studio 0.5.4 (Mavericks).
Preferences ? Gradle ? Global Gradle Settings ? Offline work
might be surprised to know.. its PHP. read all about it here
package example;
public class PrintSeqTwoThreads {
public static void main(String[] args) {
final Object mutex = new Object();
Thread t1 = new Thread() {
@Override
public void run() {
for (int j = 0; j < 10;) {
synchronized (mutex) {
System.out.println(Thread.currentThread().getName() + " " + j);
j = j + 2;
mutex.notify();
try {
mutex.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
Thread t2 = new Thread() {
@Override
public void run() {
for (int j = 1; j < 10;) {
synchronized (mutex) {
System.out.println(Thread.currentThread().getName() + " " + j);
j = j + 2;
mutex.notify();
try {
mutex.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
t1.start();
t2.start();
}
}
You can also wrap your text in label fields, so your form will be more self-explainable semantically.
Just remember to float labels and inputs to the left and to add a specific width to them, and the containing form. Then you can add margins to both of them, to adjust the spacing between the lines (you understand, of course, that this is a pretty minimal markup that expects content to be as big as to some limit).
That way you wont have to add any more elements, just the label-input pairs, all of them wrapped in a form element.
For example:
<form>
<label for="txtName">Name</label>
<input id"txtName" type="text">
<label for="txtEmail">Email</label>
<input id"txtEmail" type="text">
<label for="txtAddress">Address</label>
<input id"txtAddress" type="text">
...
<input type="submit" value="Submit The Form">
</form>
And the css will be:
form{
float:left; /*to clear the floats of inner elements,usefull if you wanna add a border or background image*/
width:300px;
}
label{
float:left;
width:150px;
margin-bottom:10px; /*or whatever you want the spacing to be*/
}
input{
float:left;
width:150px;
margin-bottom:10px; /*or whatever you want the spacing to be*/
}
@Peheje will work, but you will have problem with unicode. To fix it I use the code on https://stackoverflow.com/a/30106551/5277071;
let b64DecodeUnicode = str =>_x000D_
decodeURIComponent(_x000D_
Array.prototype.map.call(atob(str), c =>_x000D_
'%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)_x000D_
).join(''))_x000D_
_x000D_
let parseJwt = token =>_x000D_
JSON.parse(_x000D_
b64DecodeUnicode(_x000D_
token.split('.')[1].replace('-', '+').replace('_', '/')_x000D_
)_x000D_
)_x000D_
_x000D_
_x000D_
let form = document.getElementById("form")_x000D_
form.addEventListener("submit", (e) => {_x000D_
form.out.value = JSON.stringify(_x000D_
parseJwt(form.jwt.value)_x000D_
)_x000D_
e.preventDefault();_x000D_
})
_x000D_
textarea{width:300px; height:60px; display:block}
_x000D_
<form id="form" action="parse">_x000D_
<textarea name="jwt">eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkrDtGhuIETDs8OoIiwiYWRtaW4iOnRydWV9.469tBeJmYLERjlKi9u6gylb-2NsjHLC_6kZNdtoOGsA</textarea>_x000D_
<textarea name="out"></textarea>_x000D_
<input type="submit" value="parse" />_x000D_
</form>
_x000D_
Sometimes, it may help switching off AllowAutoRedirect
and setting both login POST
and page GET
requests the same user agent.
request.UserAgent = userAgent;
request.AllowAutoRedirect = false;
This code is work for me
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
// add your action here that you want
return true;
}
else if (id==R.id.login)
{
// add your action here that you want
}
return super.onOptionsItemSelected(item);
}
I recently struggled with this issue for 3 days. How the client is sending the request might not be the cause, the server might not be configured to handle multipart requests. This is what I had to do to get it working:
pom.xml - Added commons-fileupload dependency (download and add the jar to your project if you are not using dependency management such as maven)
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-version}</version>
</dependency>
web.xml - Add multipart filter and mapping
<filter>
<filter-name>multipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>multipartFilter</filter-name>
<url-pattern>/springrest/*</url-pattern>
</filter-mapping>
app-context.xml - Add multipart resolver
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize">
<beans:value>10000000</beans:value>
</beans:property>
</beans:bean>
Your Controller
@RequestMapping(value=Constants.REQUEST_MAPPING_ADD_IMAGE, method = RequestMethod.POST, produces = { "application/json"})
public @ResponseBody boolean saveStationImage(
@RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_FILE) MultipartFile file,
@RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_URI) String imageUri,
@RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_TYPE) String imageType,
@RequestParam(value = Constants.MONGO_FIELD_STATION_ID) String stationId) {
// Do something with file
// Return results
}
Your client
public static Boolean updateStationImage(StationImage stationImage) {
if(stationImage == null) {
Log.w(TAG + ":updateStationImage", "Station Image object is null, returning.");
return null;
}
Log.d(TAG, "Uploading: " + stationImage.getImageUri());
try {
RestTemplate restTemplate = new RestTemplate();
FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
formConverter.setCharset(Charset.forName("UTF8"));
restTemplate.getMessageConverters().add(formConverter);
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(Collections.singletonList(MediaType.parseMediaType("application/json")));
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add(Constants.STATION_PROFILE_IMAGE_FILE, new FileSystemResource(stationImage.getImageFile()));
parts.add(Constants.STATION_PROFILE_IMAGE_URI, stationImage.getImageUri());
parts.add(Constants.STATION_PROFILE_IMAGE_TYPE, stationImage.getImageType());
parts.add(Constants.FIELD_STATION_ID, stationImage.getStationId());
return restTemplate.postForObject(Constants.REST_CLIENT_URL_ADD_IMAGE, parts, Boolean.class);
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
Log.e(TAG + ":addStationImage", sw.toString());
}
return false;
}
That should do the trick. I added as much information as possible because I spent days, piecing together bits and pieces of the full issue, I hope this will help.
<input type="file" id="picfile" name="picf" />
<input type="text" id="txtName" style="width: 144px;" />
$("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;
var file = document.getElementById("picfile").files[0];
formData.append("FileUpload", file);
formData.append("Name", Name);
$.ajax({
type: "POST",
url: '/Category_Subcategory/Save_Category',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (msg) {
alert(msg);
},
error: function (error) {
alert("errror");
}
});
});
[HttpPost]
public ActionResult Save_Category()
{
string Name=Request.Form[1];
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
}
}
It should be mentioned that since it is entirely possible to run DLL's just as any other executable, it has long been considered a security issue. As such, there have been a number of security improvements and registry hacks (sorry no longer have ref-links) that prevents running DLL's from regular user space without extra privileges.
As a good example. I recall making these hacks, but since I no longer remember what exactly I did. I can no longer run any DLLs from normal user shell environment, even though starting various Win apps from GUI works just fine.
That said, one should definitely read "Dynamic-Link Library Security" and "Best Practices to Prevent DLL Hijacking".
I managed to load an application.properties file in external path while using -jar option.
The key was PropertiesLauncher.
To use PropertiesLauncher, pom.xml file must be changed like this:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration> <!-- added -->
<layout>ZIP</layout> <!-- to use PropertiesLaunchar -->
</configuration>
</plugin>
</plugins>
</build>
For this, I referenced the following StackOverflow question: spring boot properties launcher unable to use . BTW, In Spring Boot Maven Plugin document(http://docs.spring.io/spring-boot/docs/1.1.7.RELEASE/maven-plugin/repackage-mojo.html), there is no mention that specifying ZIP triggers that PropertiesLauncher is used. (Perhaps in another document?)
After the jar file had been built, I could see that the PropertiesLauncher is used by inspecting Main-Class property in META-INF/MENIFEST.MF in the jar.
Now, I can run the jar as follows(in Windows):
java -Dloader.path=file:///C:/My/External/Dir,MyApp-0.0.1-SNAPSHOT.jar -jar MyApp-0.0.1-SNAPSHOT.jar
Note that the application jar file is included in loader.path.
Now an application.properties file in C:\My\External\Dir\config is loaded.
As a bonus, any file (for example, static html file) in that directory can also be accessed by the jar since it's in the loader path.
As for the non-jar (expanded) version mentioned in UPDATE 2, maybe there was a classpath order problem.
call: getStackTraceAsString(sqlEx)
public String getStackTraceAsString(Exception exc)
{
String stackTrace = "*** Error in getStackTraceAsString()";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream( baos );
exc.printStackTrace(ps);
try {
stackTrace = baos.toString( "UTF8" ); // charsetName e.g. ISO-8859-1
}
catch( UnsupportedEncodingException ex )
{
Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
}
ps.close();
try {
baos.close();
}
catch( IOException ex )
{
Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
}
return stackTrace;
}
$prefix = '_';
$arr = array_combine(
array_map(function($v) use ($prefix){
return $prefix.$v;
}, array_keys($arr)),
array_values($arr)
);
As ping
works, but telnet
to port 80
does not, the HTTP port 80
is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?).
You need to add some code to your python program, that handles the proxy, like described here:
try adding to tsconfig.json file: "noImplicitAny": false
worked for me
SQL Server by default uses the mdy
date format and so the below works:
SELECT convert(datetime, '07/23/2009', 111)
and this does not work:
SELECT convert(datetime, '23/07/2009', 111)
I myself have been struggling to come up with a single query that can handle both date formats: mdy
and dmy
.
However, you should be ok with the third date format - ymd
.
Adding to slebetman answer:
When you say Node.JS
can handle 10,000 concurrent requests they are essentially non-blocking requests i.e. these requests are majorly pertaining to database query.
Internally, event loop
of Node.JS
is handling a thread pool
, where each thread handles a non-blocking request
and event loop continues to listen to more request after delegating work to one of the thread of the thread pool
. When one of the thread completes the work, it send a signal to the event loop
that it has finished aka callback
. Event loop
then process this callback and send the response back.
As you are new to NodeJS, do read more about nextTick
to understand how event loop works internally.
Read blogs on http://javascriptissexy.com, they were really helpful for me when I started with JavaScript/NodeJS.
# Switch delimiter to //, so phpMyAdmin will not execute it line by line.
DELIMITER //
CREATE PROCEDURE usp_rateChapter12
(IN numRating_Chapter INT(11) UNSIGNED,
IN txtRating_Chapter VARCHAR(250),
IN chapterName VARCHAR(250),
IN addedBy VARCHAR(250)
)
BEGIN
DECLARE numRating_Chapter INT;
DECLARE txtRating_Chapter VARCHAR(250);
DECLARE chapterName1 VARCHAR(250);
DECLARE addedBy1 VARCHAR(250);
DECLARE chapterId INT;
DECLARE studentId INT;
SET chapterName1 = chapterName;
SET addedBy1 = addedBy;
SET chapterId = (SELECT chapterId
FROM chapters
WHERE chaptername = chapterName1);
SET studentId = (SELECT Id
FROM students
WHERE email = addedBy1);
SELECT chapterId;
SELECT studentId;
INSERT INTO ratechapter (rateBy, rateText, rateLevel, chapterRated)
VALUES (studentId, txtRating_Chapter, numRating_Chapter,chapterId);
END //
//DELIMITER;
you can find your answer in the combination of these two pages in the API:
ref is used to register a reference to an element or a child component. The reference will be registered under the parent component’s $refs object. If used on a plain DOM element, the reference will be that element
An object that holds child components that have ref registered.
The following code will help you
mvv_count_df.select('mvv').rdd.map(lambda row : row[0]).collect()
No, you would need to url-encode it, since base64 strings can contain the "+", "=" and "/" characters which could alter the meaning of your data - look like a sub-folder.
Valid base64 characters are below.
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
You need to use Range
and Valu
e functions.
Range
would be the cell where you want the text you want
Value
would be the text that you want in that Cell
Range("A1").Value="whatever text"
Here's an option if you need to escape multiple %'s in a string with some already escaped.
(?:[^%]|^)(?:(%%)+|)(%)(?:[^%])
To sanitise the message before passing it to String.format, you can use the following
Pattern p = Pattern.compile("(?:[^%]|^)(?:(%%)+|)(%)(?:[^%])");
Matcher m1 = p.matcher(log);
StringBuffer buf = new StringBuffer();
while (m1.find())
m1.appendReplacement(buf, log.substring(m1.start(), m1.start(2)) + "%%" + log.substring(m1.end(2), m1.end()));
// Return the sanitised message
String escapedString = m1.appendTail(buf).toString();
This works with any number of formatting characters, so it will replace % with %%, %%% with %%%%, %%%%% with %%%%%% etc.
It will leave any already escaped characters alone (e.g. %%, %%%% etc.)
I liked the solution from Ruidge, but I needed more control from XML. So I changed it to Kotlin and added attributes.
1) Copy the Kotlin class:
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
class DashedDividerView : View {
constructor(context: Context) : this(context, null, 0)
constructor(context: Context, attributeSet: AttributeSet) : this(context, attributeSet, 0)
companion object {
const val DIRECTION_VERTICAL = 0
const val DIRECTION_HORIZONTAL = 1
}
private var dGap = 5.25f
private var dWidth = 5.25f
private var dColor = Color.parseColor("#EE0606")
private var direction = DIRECTION_HORIZONTAL
private val paint = Paint()
private val path = Path()
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
val typedArray = context.obtainStyledAttributes(
attrs,
R.styleable.DashedDividerView,
defStyleAttr,
R.style.DashedDividerDefault
)
dGap = typedArray.getDimension(R.styleable.DashedDividerView_dividerDashGap, dGap)
dWidth = typedArray.getDimension(R.styleable.DashedDividerView_dividerDashWidth, dWidth)
dColor = typedArray.getColor(R.styleable.DashedDividerView_dividerDashColor, dColor)
direction =
typedArray.getInt(R.styleable.DashedDividerView_dividerDirection, DIRECTION_HORIZONTAL)
paint.color = dColor
paint.style = Paint.Style.STROKE
paint.pathEffect = DashPathEffect(floatArrayOf(dWidth, dGap), 0f)
paint.strokeWidth = dWidth
typedArray.recycle()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
path.moveTo(0f, 0f)
if (direction == DIRECTION_HORIZONTAL) {
path.lineTo(measuredWidth.toFloat(), 0f)
} else {
path.lineTo(0f, measuredHeight.toFloat())
}
canvas.drawPath(path, paint)
}
}
2) Create an attr file in the /res directory and add this
<declare-styleable name="DashedDividerView">
<attr name="dividerDashGap" format="dimension" />
<attr name="dividerDashWidth" format="dimension" />
<attr name="dividerDashColor" format="reference|color" />
<attr name="dividerDirection" format="enum">
<enum name="vertical" value="0" />
<enum name="horizontal" value="1" />
</attr>
</declare-styleable>
3) Add a style to the styles file
<style name="DashedDividerDefault">
<item name="dividerDashGap">2dp</item>
<item name="dividerDashWidth">2dp</item>
<!-- or any color -->
<item name="dividerDashColor">#EE0606</item>
<item name="dividerDirection">horizontal</item>
</style>
4) Now you can use the default style
<!-- here will be your path to the class -->
<com.your.package.app.DashedDividerView
android:layout_width="match_parent"
android:layout_height="2dp"
/>
or set attributes in XML
<com.your.package.app.DashedDividerView
android:layout_width="match_parent"
android:layout_height="2dp"
app:dividerDirection="horizontal"
app:dividerDashGap="2dp"
app:dividerDashWidth="2dp"
app:dividerDashColor="@color/light_gray"/>
The data containing the date column can be read by using the below code:
data = pd.csv(file_path,parse_dates=[date_column])
Once the data is read by using the above line of code, the column containing the information about the date can be accessed using pd.date_time()
like:
pd.date_time(data[date_column], format = '%d/%m/%y')
to change the format of date as per the requirement.
You should be able to use the /quiet
or /qn
options with msiexec
to perform a silent install.
MSI packages export public properties, which you can set with the PROPERTY=value
syntax on the end of the msiexec
parameters.
For example, this command installs a package with no UI and no reboot, with a log and two properties:
msiexec /i c:\path\to\package.msi /quiet /qn /norestart /log c:\path\to\install.log PROPERTY1=value1 PROPERTY2=value2
You can read the options for msiexec
by just running it with no options from Start -> Run.
Because you store the array in the stack. You should store it in the heap. See this link to understand the concept of the heap and the stack.
The first visible character is '!' according to ASCII table.And the last one is '~' So "!file.doc" or "~file.doc' will be the top one depending your ranking order. You can check the ascii table here: http://www.asciitable.com/
Edit: This answer is based on the opinion of the author and not facts.
HTML:
<div id="log"></div>
JS:
document.getElementById("log").innerHTML="WHATEVER YOU WANT...";
Escape the square brackets:
...
WHERE m.definition Like '%\[ABD\]%' ESCAPE '\'
Then the square brackets will be treated as a string literals not as wild cards.
This is how I used clearInterval() method to stop the timer after 10 seconds.
function startCountDown() {_x000D_
var countdownNumberEl = document.getElementById('countdown-number');_x000D_
var countdown = 10;_x000D_
const interval = setInterval(() => {_x000D_
countdown = --countdown <= 0 ? 10 : countdown;_x000D_
countdownNumberEl.textContent = countdown;_x000D_
if (countdown == 1) {_x000D_
clearInterval(interval);_x000D_
}_x000D_
}, 1000)_x000D_
}
_x000D_
<head>_x000D_
<body>_x000D_
<button id="countdown-number" onclick="startCountDown();">Show Time </button>_x000D_
</body>_x000D_
</head>
_x000D_
Some practical tests...
This test is using a system partition. Results for a non-system partition are a bit better.
Score decrease:
Read: 5%
Write: 16%
Without BitLocker:
With BitLocker:
So you can see that with a very strong configuration and a modern SSD disk you can see a small performance degradation with tests. I don't know what about a typical work, especially with the Visual Studio.
What might be easier, is to have two buttons and show/hide them in your functions. (ie. display:none|block;
) Each button could then have it's own onclick with whatever code you need.
So, at first button1
would be display:block
and button2
would be display:none
. Then when you click button1
it would switch button2
to be display:block
and button1
to be display:none
.
I wanted to update slider as well as the inputbox. For me following is working
a.slider('value',1520);
$("#labelAID").val(1520);
where a
is object as following.
var a= $( "<div id='slider' style='width:200px;margin-left:20px;'></div>" ).insertAfter( "#labelAID" ).slider({
min: 0,
max: 2000,
range: "min",
value: 111,
slide: function( event, ui ) {
$("#labelAID").val(ui.value );
}
});
$( "#labelAID" ).keyup(function() {
a.slider( "value",$( "#labelAID" ).val() );
});
Try this:
onclick="myfunction(
'/myController/myAction',
function(){myfuncionOnOK('/myController2/myAction2','myParameter2');},
function(){myfuncionOnCancel('/myController3/myAction3','myParameter3');}
);"
Then you just need to call these two functions passed to myfunction
:
function myfunction(url, f1, f2) {
// …
f1();
f2();
}
To the first part of your question - yes, browsers cache css files (if this is not disabled by browser's configuration). Many browsers have key combination to reload a page without a cache. If you made changes to css and want users to see them immediately instead of waiting next time when browser reloads the files without caching, you can change the way CSS ir served by adding some parameters to the url like this:
/style.css?modified=20012009
Two options:
<button>multiline<br/>button<br/>text</button>
or
<input type="button" value="Carriage return separators" style="text-align:center;">
$is_checked = isset($_POST['your_checkbox_name']) &&
$_POST['your_checkbox_name'] == 'on';
Short circuit evaluation will take care so that you don't access your_checkbox_name
when it was not submitted.
For Python users the pattern to use with t3chbot's excellent answer looks like:
https://marketplace.visualstudio.com/_apis/public/gallery/publishers/ms-python/vsextensions/python/{version_number}/vspackage
be sure to scroll right to see where you have to enter the version number.
check out my js lib for caching: https://github.com/hoangnd25/cacheJS
My blog post: New way to cache your data with Javascript
Saving cache:
cacheJS.set({blogId:1,type:'view'},'<h1>Blog 1</h1>');
cacheJS.set({blogId:2,type:'view'},'<h1>Blog 2</h1>', null, {author:'hoangnd'});
cacheJS.set({blogId:3,type:'view'},'<h1>Blog 3</h1>', 3600, {author:'hoangnd',categoryId:2});
Retrieving cache:
cacheJS.get({blogId: 1,type: 'view'});
Flushing cache
cacheJS.removeByKey({blogId: 1,type: 'view'});
cacheJS.removeByKey({blogId: 2,type: 'view'});
cacheJS.removeByContext({author:'hoangnd'});
Switching provider
cacheJS.use('array');
cacheJS.use('array').set({blogId:1},'<h1>Blog 1</h1>')};
Put the elements which you want to shift to the centre within this div tag.
<div class="col d-flex justify-content-center">
</div>
Fastest approach, if you need to perform more than just one or two such removal operations (or even just one, but on a very long string!-), is to rely on the translate
method of strings, even though it does need some prep:
>>> import string
>>> allchars = ''.join(chr(i) for i in xrange(256))
>>> identity = string.maketrans('', '')
>>> nondigits = allchars.translate(identity, string.digits)
>>> s = 'abc123def456'
>>> s.translate(identity, nondigits)
'123456'
The translate
method is different, and maybe a tad simpler simpler to use, on Unicode strings than it is on byte strings, btw:
>>> unondig = dict.fromkeys(xrange(65536))
>>> for x in string.digits: del unondig[ord(x)]
...
>>> s = u'abc123def456'
>>> s.translate(unondig)
u'123456'
You might want to use a mapping class rather than an actual dict, especially if your Unicode string may potentially contain characters with very high ord values (that would make the dict excessively large;-). For example:
>>> class keeponly(object):
... def __init__(self, keep):
... self.keep = set(ord(c) for c in keep)
... def __getitem__(self, key):
... if key in self.keep:
... return key
... return None
...
>>> s.translate(keeponly(string.digits))
u'123456'
>>>
Nate Cook's answer is absolutely correct. Just for greater flexibility, I keep the following functions in my pack:
func getUIColorFromRGBThreeIntegers(red: Int, green: Int, blue: Int) -> UIColor {
return UIColor(red: CGFloat(Float(red) / 255.0),
green: CGFloat(Float(green) / 255.0),
blue: CGFloat(Float(blue) / 255.0),
alpha: CGFloat(1.0))
}
func getUIColorFromRGBHexValue(value: Int) -> UIColor {
return getUIColorFromRGBThreeIntegers(red: (value & 0xFF0000) >> 16,
green: (value & 0x00FF00) >> 8,
blue: value & 0x0000FF)
}
func getUIColorFromRGBString(value: String) -> UIColor {
let str = value.lowercased().replacingOccurrences(of: "#", with: "").
replacingOccurrences(of: "0x", with: "");
return getUIColorFromRGBHexValue(value: Int(str, radix: 16)!);
}
And this is how I use them:
// All three of them are identical:
let myColor1 = getUIColorFromRGBHexValue(value: 0xd5a637)
let myColor2 = getUIColorFromRGBString(value: "#D5A637")
let myColor3 = getUIColorFromRGBThreeIntegers(red: 213, green: 166, blue: 55)
Hope this will help. Everything is tested with Swift 3/Xcode 8.
I was getting a similar issue from the Apache Lounge 32 bit version. After downloading the 64 bit version, the issue was resolved.
Here is an excellent video explain the steps involved: https://www.youtube.com/watch?v=17qhikHv5hY
This message can also happen if git-lfs
is used and a file pointer was overwritten by a real file.
then you use:
git stash
git lfs migrate import
git pull
full output from my case
? git stash
Saved working directory and index state WIP on master: 5d4ad47 Merge branch 'feature/...' into 'master'
Encountered 1 file(s) that should have been pointers, but weren't:
public/apple-touch-icon.png
? git pull
Updating 5a4ad44..b25f79d
error: Your local changes to the following files would be overwritten by merge:
public/apple-touch-icon.png
Please commit your changes or stash them before you merge.
Aborting
? git lfs migrate import
migrate: Fetching remote refs: ..., done
migrate: Sorting commits: ..., done
migrate: Rewriting commits: 100% (0/0), done
migrate: Updating refs: ..., done
migrate: checkout: ..., done
? git pull
Updating 5d4ad47..a25c79a
Fast-forward
public/apple-touch-icon.png | Bin 2092 -> 130 bytes
public/favicon.ico | Bin 6518 -> 1150 bytes
2 files changed, 0 insertions(+), 0 deletions(-)
Simply PROJECTION deals with elimination or selection of columns, while SELECTION deals with elimination or selection of rows.
As I had to get only the version code and check whether app was updated or not, if yes, I had to launch the playstore to get updated one. I did it this way.
public class CheckForUpdate {
public static final String ACTION_APP_VERSION_CHECK = "app-version-check";
public static void launchPlayStoreApp(Context context)
{
// getPackageName() from Context or Activity object
final String appPackageName = context.getPackageName();
try {
context.startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=" + appPackageName)));
}
catch (android.content.ActivityNotFoundException anfe) {
context.startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=" +
appPackageName)));
}
}
public static int getRemoteVersionNumber(Context context)
{
int versionCode = 0;
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
String version = pInfo.versionName;
versionCode = pInfo.versionCode;
}
catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionCode;
}
}
Then I saved version code using shared preference by creating an util class.
public class PreferenceUtils {
// This is for version code
private final String APP_VERSION_CODE = "APP_VERSION_CODE";
private SharedPreferences sharedPreferencesAppVersionCode;
private SharedPreferences.Editor editorAppVersionCode;
private static Context mContext;
public PreferenceUtils(Context context)
{
this.mContext = context;
// This is for the app versioncode
sharedPreferencesAppVersionCode = mContext.getSharedPreferences(APP_VERSION_CODE,MODE_PRIVATE);
editorAppVersionCode = sharedPreferencesAppVersionCode.edit();
}
public void createAppVersionCode(int versionCode) {
editorAppVersionCode.putInt(APP_VERSION_CODE, versionCode);
editorAppVersionCode.apply();
}
public int getAppVersionCode()
{
return sharedPreferencesAppVersionCode.getInt(APP_VERSION_CODE,0); // As the default version code is 0
}
}
UltimateSAML SSO is an OASIS SAML v1.x and v2.0 specifications compliant .NET toolkit. It offers an elegant and easy way to add support for Single Sign-On and Single-Logout SAML to your ASP.NET, ASP.NET MVC, ASP.NET Core, Desktop, and Service applications. The lightweight library helps you provide SSO access to cloud and intranet websites using a single credentials entry.
Note that the ansible
command doesn't collect facts, but the ansible-playbook
command does. When running ansible -m setup
, the setup module happens to run the fact collection so you get the facts, but running ansible -m command
does not. Therefore the facts aren't available. This is why the other answers include playbook YAML files and indicate the lookup works.
when your add permission in manifest then in eclipse go to project and clic
k on clean project
From the command-line:
echo '{"one":1,"two":2}' | python -mjson.tool
which outputs:
{
"one": 1,
"two": 2
}
Programmtically, the Python manual describes pretty-printing JSON:
>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
{
"4": 5,
"6": 7
}
I think this query will do a case insensitive search:
SELECT * FROM trees WHERE trees.`title` ILIKE '%elm%';
Try that:
/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
/sbin/mkswap /var/swap.1
/sbin/swapon /var/swap.1
It is good programming practice to return an empty array []
if the expected return type is an array. This makes sure that the receiver of the json can treat the value as an array immediately without having to first check for null. It's the same way with empty objects using open-closed braces {}
.
Strings, Booleans and integers do not have an 'empty' form, so there it is okay to use null values.
This is also addressed in Joshua Blochs excellent book "Effective Java". There he describes some very good generic programming practices (often applicable to other programming langages as well). Returning empty collections instead of nulls is one of them.
Here's a link to that part of his book:
http://jtechies.blogspot.nl/2012/07/item-43-return-empty-arrays-or.html
use [\\W+]
or "[^a-zA-Z0-9]"
as regex to match any special characters and also use String.replaceAll(regex, String) to replace the spl charecter with an empty string. remember as the first arg of String.replaceAll is a regex you have to escape it with a backslash to treat em as a literal charcter.
String c= "hjdg$h&jk8^i0ssh6";
Pattern pt = Pattern.compile("[^a-zA-Z0-9]");
Matcher match= pt.matcher(c);
while(match.find())
{
String s= match.group();
c=c.replaceAll("\\"+s, "");
}
System.out.println(c);
If you are using this for Angular, then export a function via a named export. Such as:
function someFunc(){}
export { someFunc as someFuncName }
otherwise, Angular will complain that object is not a function.
Android locked down GET_ACCOUNTS
recently so some of the answers did not work for me. I got this working on Android 7.0 with the caveat that your users have to endure a permission dialog.
AndroidManifest.xml
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
MainActivity.java
package com.example.patrick.app2;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.accounts.AccountManager;
import android.accounts.Account;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.*;
public class MainActivity extends AppCompatActivity {
final static int requestcode = 4; //arbitrary constant less than 2^16
private static String getEmailId(Context context) {
AccountManager accountManager = AccountManager.get(context);
Account[] accounts = accountManager.getAccountsByType("com.google");
Account account;
if (accounts.length > 0) {
account = accounts[0];
} else {
return "length is zero";
}
return account.name;
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case requestcode:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
String emailAddr = getEmailId(getApplicationContext());
ShowMessage(emailAddr);
} else {
ShowMessage("Permission Denied");
}
}
}
public void ShowMessage(String email)
{
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage(email);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = getApplicationContext();
if ( ContextCompat.checkSelfPermission( context, android.Manifest.permission.GET_ACCOUNTS )
!= PackageManager.PERMISSION_GRANTED )
{
ActivityCompat.requestPermissions( this, new String[]
{ android.Manifest.permission.GET_ACCOUNTS },requestcode );
}
else
{
String possibleEmail = getEmailId(getApplicationContext());
ShowMessage(possibleEmail);
}
}
}
From the UITableViewDelegate
Protocol you can use the method willSelectRowAtIndexPath
and return nil
if you don't want the row selected.
In the same way the you can use the willDeselectRowAtIndexPath
method and return nil
if you don't want the row to deselect.
FOR MVC
-- WEB.CONFIG CODE IN APP SETTING --
<add key="PhaseLevel" value="1" />
-- ON VIEWS suppose you want to show or hide something based on web.config Value--
-- WRITE THIS ON TOP OF YOUR PAGE--
@{
var phase = System.Configuration.ConfigurationManager.AppSettings["PhaseLevel"].ToString();
}
-- USE ABOVE VALUE WHERE YOU WANT TO SHOW OR HIDE.
@if (phase != "1")
{
@Html.Partial("~/Views/Shared/_LeftSideBarPartial.cshtml")
}
I like the "struct hack" for having a dynamically sized object. This site explains it pretty well too (though they refer to the C99 version where you can write "str[]" as the last member of a struct). you could make a string "object" like this:
struct X {
int len;
char str[1];
};
int n = strlen("hello world");
struct X *string = malloc(sizeof(struct X) + n);
strcpy(string->str, "hello world");
string->len = n;
here, we've allocated a structure of type X on the heap that is the size of an int (for len), plus the length of "hello world", plus 1 (since str1 is included in the sizeof(X).
It is generally useful when you want to have a "header" right before some variable length data in the same block.
Shared resources. Especially in PHP, a database class, a template class, and a global variable depot class. All have to be shared by all modules/classes that are being used throughout the code.
It's a true object usage -> the template class contains the page template that is being built, and it gets shaped, added, changed by modules that are adding to page output. It has to be kept as a single instance so that this can happen, and the same goes for databases. With a shared database singleton, all modules' classes can get access to queries and get them without having to rerun them.
A global variable depot singleton provides you a global, reliable, and easily usable variable depot. It tidies up your code a great lot. Imagine having all configuration values in an array in a singleton like:
$gb->config['hostname']
or having all language values in an array like:
$gb->lang['ENTER_USER']
In the end of running the code for the page, you get, say, a now mature:
$template
Singleton, a $gb
singleton that has the lang array for replacing into it, and all output loaded and ready. You just replace them into the keys that are now present in mature template object's page value, and then serve it out to user.
The great advantage of this is you can do ANY post-processing you like on anything. You can pipe all language values to google translate, or another translate service and get them back, and replace them into their places, translated, for example. or, you can replace in page structures, or, content strings, as you want.
I used this method to change choosing Text Field
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if ([textField isEqual:self.emailRegisterTextField]) {
[self.usernameRegisterTextField becomeFirstResponder];
} else if ([textField isEqual:self.usernameRegisterTextField]) {
[self.passwordRegisterTextField becomeFirstResponder];
} else {
[textField resignFirstResponder];
// To click button for registration when you clicking button "Done" on the keyboard
[self createMyAccount:self.registrationButton];
}
return YES;
}
If you simply place text as a child(ren) of a column, this is the easiest way to have text automatically wrap. Assuming you don't have anything more complicated going on. In those cases, I would think you would create your container sized as you see fit and put another column inside and then your text. This seems to work nicely. Containers want to shrink to the size of its contents, and this seems to naturally conflict with wrapping, which requires more effort.
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text('This long text will wrap very nicely if there isn't room beyond the column\'s total width and if you have enough vertical space available to wrap into.',
style: TextStyle(fontSize: 16, color: primaryColor),
textAlign: TextAlign.center,),
],
),
if (pictureBox1.Image != null)
{
pictureBox1.Image.Dispose();
pictureBox1.Image = null;
}
I suggest making a tree of letters based on words. The tree would be composed of a letter structs, like this:
letter: char
isWord: boolean
Then you build up the tree, with each depth adding a new letter. In other words, on the first level there'd be the alphabet; then from each of those trees, there'd be another another 26 entries, and so on, until you've spelled out all the words. Hang onto this parsed tree, and it'll make all possible answers faster to look up.
With this parsed tree, you can very quickly find solutions. Here's the pseudo-code:
BEGIN:
For each letter:
if the struct representing it on the current depth has isWord == true, enter it as an answer.
Cycle through all its neighbors; if there is a child of the current node corresponding to the letter, recursively call BEGIN on it.
This could be sped up with a bit of dynamic programming. For example, in your sample, the two 'A's are both next to an 'E' and a 'W', which (from the point they hit them on) would be identical. I don't have enough time to really spell out the code for this, but I think you can gather the idea.
Also, I'm sure you'll find other solutions if you Google for "Boggle solver".
I think you mean to put the rolling of the random a,b,c, etc within the loop:
a = None # initialise
while not (a in winning_numbers):
# keep rolling an a until you get one not in winning_numbers
a = random.randint(1,30)
winning_numbers.append(a)
Otherwise, a
will be generated just once, and if it is in winning_numbers
already, it won't be added. Since the generation of a
is outside the while
(in your code), if a
is already in winning_numbers
then too bad, it won't be re-rolled, and you'll have one less winning number.
That could be what causes your error in if guess[i] == winning_numbers[i]
. (Your winning_numbers
isn't always of length 5).
I used to use the #define because they make code easier to read, and there should be no performances degradation compared to using numbers (0,1) coz' the preprocessor converts the #define into numbers before compilation. Once the application is run preprocessor does not come into the way again because the code is already compiled.
BTW it should be:
#define FALSE 0
#define TRUE 1
and remember that -1, -2, ... 2, 3, etc. all evaluates to true.
Having just gone round the internet to read up on this and the options in Spring I'd second Luke's answer, use BCrypt (it's mentioned in the source code at Spring).
The best resource I found to explain why to hash/salt and why use BCrypt is a good choice is here: Salted Password Hashing - Doing it Right.
I agree with previous comment that might be best to consider a different approach. My suggest would be write a console application and use the windows scheduler:
This will:
On MacOS:
svn upgrade
useState is a hook that lets you add state to a functional component. It accepts an argument which is the initial value of the state property and returns the current value of state property and a method which is capable of updating that state property.
Following is a simple example:
import React, {useState} from react
function HookCounter {
const [count, stateCount]= useState(0)
return(
<div>
<button onClick{( ) => setCount(count+1)}> count{count}</button>
</div>
)
}
useState accepts the initial value of the state variable which is zero in this case and returns a pair of values. The current value of the state has been called count and a method that can update the state variable has been called as setCount.
I use DUAL CORE 3-GHZ with 2GB RAM, windows 8 OS.
I can run eclipse and AVD (even running 2 AVD is still good) smoothly, as long as i dont open too much other tabs (Game, Browser, MS Word, etc).
Since Qt 5.8, we now have QDateTime::currentSecsSinceEpoch()
to deliver the seconds directly, a.k.a. as real Unix timestamp. So, no need to divide the result by 1000 to get seconds anymore.
Credits: also posted as comment to this answer. However, I think it is easier to find if it is a separate answer.
Yes, there are a few of them.
ReDoc [Article on swagger.io] [GitHub] [demo] - Reinvented OpenAPI/Swagger-generated API Reference Documentation (I'm the author)
OpenAPI GUI [GitHub] [demo] - GUI / visual editor for creating and editing OpenApi / Swagger definitions (has OpenAPI 3 support)
SwaggerUI-Angular [GitHub] [demo] - An angularJS implementation of Swagger UI
angular-swagger-ui-material [GitHub] [demo] - Material Design template for angular-swager-ui
You can do it by a combination of javascript and php:
<div id="cont"></div>
And by the other side;
<script>
var h = window.location.hash;
var h1 = (win.substr(1));//string with no #
var q1 = '<input type="text" id="hash" name="hash" value="'+h1+'">';
setInterval(function(){
if(win1!="")
{
document.querySelector('#cont').innerHTML = q1;
} else alert("Something went wrong")
},1000);
</script>
Then, on form submit you can retrieve the value via $_POST['hash'] (set the form)
Bootstrap 4 includes flexbox, so the method of vertical centering is much easier and doesn't require extra CSS.
Just use the d-flex
and align-items-center
utility classes..
<div class="jumbotron d-flex align-items-center">
<div class="container">
content
</div>
</div>
http://www.codeply.com/go/ui6ABmMTLv
Important: Vertical centering is relative to height. The parent container of the items you're attempting to center must have a defined height. If you want the height of the page use vh-100
or min-vh-100
on the parent! For example:
<div class="jumbotron d-flex align-items-center min-vh-100">
<div class="container text-center">
I am centered vertically
</div>
</div>
Why not this:
rsq <- function(x, y) summary(lm(y~x))$r.squared
rsq(obs, mod)
#[1] 0.8560185
Here is my contribution, that deals with any URL using http or https, and use Promises.
const http = require('http')
const https = require('https')
const url = require('url')
function getHeaders(myURL) {
const parsedURL = url.parse(myURL)
const options = {
protocol: parsedURL.protocol,
hostname: parsedURL.hostname,
method: 'HEAD',
path: parsedURL.path
}
let protocolHandler = (parsedURL.protocol === 'https:' ? https : http)
return new Promise((resolve, reject) => {
let req = protocolHandler.request(options, (res) => {
resolve(res.headers)
})
req.on('error', (e) => {
reject(e)
})
req.end()
})
}
getHeaders(myURL).then((headers) => {
console.log(headers)
})
Workaround:
t = time()
t2 = time(t.hour+1, t.minute, t.second, t.microsecond)
You can also omit the microseconds, if you don't need that much precision.
Apart from all the good answers already given, I'd like to add to @johan-leino's great answer. In my case, for some arbitrary reason, the CodeBehind
attribute was omitted from the @Page
directive/.aspx file. Likewise, it might be worthwhile to check the CodeFile
attribute for @Control
directives/.ascx files (obviously in conjunction with an Inherits
attribute in both cases).
Depending on the exact scenario and reason required to 'force' a regenerate of .designer.cs, one could also try to format the document (potentially indicating a parsing error) before (quick) saving (regardless whether there were any changes or not) and check the Error List for warnings.
Recently,I'm learning Wordpress,it provide a class WP_QUERY to operate the database. You can insert array or object to the database.I feel it is amazing,so I go to see how to achieve it.Maybe,some ideas you can get from it.The main function is: apply_filters.
apply_filters( $tag, $value, $key);
you can ignore the first parameter ,treat the second parameter as array,what the function do is sanitizing the array into string.
after inserting into the database,you can see this :
key s:12:"focal_length";s:3:"190";s:3:"iso";s:3:"400";s:13:"shutter_speed";s:6:"0.0004";s:5:"title";s:0:"";}}
view.isVisible = true
view.isInvisible = true
view.isGone = true
// For these to work, you need to use androidx and import:
import androidx.core.view.isVisible // or isInvisible/isGone
If you'd like them to be more consistent length, work for nullable views, and lower the chance of writing the wrong boolean, try using these custom extensions:
// Example
view.hide()
fun View?.show() {
if (this == null) return
if (!isVisible) isVisible = true
}
fun View?.hide() {
if (this == null) return
if (!isInvisible) isInvisible = true
}
fun View?.gone() {
if (this == null) return
if (!isGone) isGone = true
}
To make conditional visibility simple, also add these:
fun View?.show(visible: Boolean) {
if (visible) show() else gone()
}
fun View?.hide(hide: Boolean) {
if (hide) hide() else show()
}
fun View?.gone(gone: Boolean = true) {
if (gone) gone() else show()
}
Just add <relativePath />
so the parent in pom should look like:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath />
</parent>
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.util.Base64;
import java.util.Base64.Encoder;
/**
*
* @author shivshankar pal
*
* this code is working properly. doing proper encription and decription
note:- it will work only with jdk8
*
*
*/
public class TDes {
private static byte[] key = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02,
0x02, 0x02, 0x02, 0x02, 0x02, 0x02 };
private static byte[] keyiv = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00 };
public static String encode(String args) {
System.out.println("plain data==> " + args);
byte[] encoding;
try {
encoding = Base64.getEncoder().encode(args.getBytes("UTF-8"));
System.out.println("Base64.encodeBase64==>" + new String(encoding));
byte[] str5 = des3EncodeCBC(key, keyiv, encoding);
System.out.println("des3EncodeCBC==> " + new String(str5));
byte[] encoding1 = Base64.getEncoder().encode(str5);
System.out.println("Base64.encodeBase64==> " + new String(encoding1));
return new String(encoding1);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static String decode(String args) {
try {
System.out.println("encrypted data==>" + new String(args.getBytes("UTF-8")));
byte[] decode = Base64.getDecoder().decode(args.getBytes("UTF-8"));
System.out.println("Base64.decodeBase64(main encription)==>" + new String(decode));
byte[] str6 = des3DecodeCBC(key, keyiv, decode);
System.out.println("des3DecodeCBC==>" + new String(str6));
String data=new String(str6);
byte[] decode1 = Base64.getDecoder().decode(data.trim().getBytes("UTF-8"));
System.out.println("plaintext==> " + new String(decode1));
return new String(decode1);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "u mistaken in try block";
}
private static byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data) {
try {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede/ CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
byte[] bout = cipher.doFinal(data);
return bout;
} catch (Exception e) {
System.out.println("methods qualified name" + e);
}
return null;
}
private static byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data) {
try {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede/ CBC/NoPadding");//PKCS5Padding NoPadding
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
byte[] bout = cipher.doFinal(data);
return bout;
} catch (Exception e) {
System.out.println("methods qualified name" + e);
}
return null;
}
}
It's using extended slicing - a string is a sequence in Python, and shares some methods with other sequences (namely lists and tuples). There are three parts to slicing - start, stop and step. All of them have default values - start defaults to 0, stop defaults to len(sequence), and step defaults to 1. By specifying [::-1] you're saying "all the elements in sequence a, starting from the beginning, to the end going backward one at a time.
This feature was introduced in Python 2.3.5, and you can read more in the What's New docs.
A lot of answers include setting the contentOffset
to 0. I had a case in which I wanted the view inside the scrollView to be centered. This did the job for me:
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollView.contentOffset.y = -scrollView.contentInset.top
}
I found this topic while searching for run script for startup and shutdown Windows 10. Those answers above didn't working. For me on windows 10 worked when I put scripts to task scheduler. How to do this: press window key and write Task scheduler, open it, then on the right is Add task... button. Here you can add scripts. PS: I found action for startup and logout user, there is not for shutdown.
I'm going to show you how you can easily define iterators for your custom containers, but just in case I have created a c++11 library that allows you to easily create custom iterators with custom behavior for any type of container, contiguous or non-contiguous.
You can find it on Github
Here are the simple steps to creating and using custom iterators:
typedef blRawIterator< Type > iterator;
typedef blRawIterator< const Type > const_iterator;
iterator begin(){return iterator(&m_data[0]);};
const_iterator cbegin()const{return const_iterator(&m_data[0]);};
Finally, onto defining our custom iterator classes:
NOTE: When defining custom iterators, we derive from the standard iterator categories to let STL algorithms know the type of iterator we've made.
In this example, I define a random access iterator and a reverse random access iterator:
//-------------------------------------------------------------------
// Raw iterator with random access
//-------------------------------------------------------------------
template<typename blDataType>
class blRawIterator
{
public:
using iterator_category = std::random_access_iterator_tag;
using value_type = blDataType;
using difference_type = std::ptrdiff_t;
using pointer = blDataType*;
using reference = blDataType&;
public:
blRawIterator(blDataType* ptr = nullptr){m_ptr = ptr;}
blRawIterator(const blRawIterator<blDataType>& rawIterator) = default;
~blRawIterator(){}
blRawIterator<blDataType>& operator=(const blRawIterator<blDataType>& rawIterator) = default;
blRawIterator<blDataType>& operator=(blDataType* ptr){m_ptr = ptr;return (*this);}
operator bool()const
{
if(m_ptr)
return true;
else
return false;
}
bool operator==(const blRawIterator<blDataType>& rawIterator)const{return (m_ptr == rawIterator.getConstPtr());}
bool operator!=(const blRawIterator<blDataType>& rawIterator)const{return (m_ptr != rawIterator.getConstPtr());}
blRawIterator<blDataType>& operator+=(const difference_type& movement){m_ptr += movement;return (*this);}
blRawIterator<blDataType>& operator-=(const difference_type& movement){m_ptr -= movement;return (*this);}
blRawIterator<blDataType>& operator++(){++m_ptr;return (*this);}
blRawIterator<blDataType>& operator--(){--m_ptr;return (*this);}
blRawIterator<blDataType> operator++(int){auto temp(*this);++m_ptr;return temp;}
blRawIterator<blDataType> operator--(int){auto temp(*this);--m_ptr;return temp;}
blRawIterator<blDataType> operator+(const difference_type& movement){auto oldPtr = m_ptr;m_ptr+=movement;auto temp(*this);m_ptr = oldPtr;return temp;}
blRawIterator<blDataType> operator-(const difference_type& movement){auto oldPtr = m_ptr;m_ptr-=movement;auto temp(*this);m_ptr = oldPtr;return temp;}
difference_type operator-(const blRawIterator<blDataType>& rawIterator){return std::distance(rawIterator.getPtr(),this->getPtr());}
blDataType& operator*(){return *m_ptr;}
const blDataType& operator*()const{return *m_ptr;}
blDataType* operator->(){return m_ptr;}
blDataType* getPtr()const{return m_ptr;}
const blDataType* getConstPtr()const{return m_ptr;}
protected:
blDataType* m_ptr;
};
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// Raw reverse iterator with random access
//-------------------------------------------------------------------
template<typename blDataType>
class blRawReverseIterator : public blRawIterator<blDataType>
{
public:
blRawReverseIterator(blDataType* ptr = nullptr):blRawIterator<blDataType>(ptr){}
blRawReverseIterator(const blRawIterator<blDataType>& rawIterator){this->m_ptr = rawIterator.getPtr();}
blRawReverseIterator(const blRawReverseIterator<blDataType>& rawReverseIterator) = default;
~blRawReverseIterator(){}
blRawReverseIterator<blDataType>& operator=(const blRawReverseIterator<blDataType>& rawReverseIterator) = default;
blRawReverseIterator<blDataType>& operator=(const blRawIterator<blDataType>& rawIterator){this->m_ptr = rawIterator.getPtr();return (*this);}
blRawReverseIterator<blDataType>& operator=(blDataType* ptr){this->setPtr(ptr);return (*this);}
blRawReverseIterator<blDataType>& operator+=(const difference_type& movement){this->m_ptr -= movement;return (*this);}
blRawReverseIterator<blDataType>& operator-=(const difference_type& movement){this->m_ptr += movement;return (*this);}
blRawReverseIterator<blDataType>& operator++(){--this->m_ptr;return (*this);}
blRawReverseIterator<blDataType>& operator--(){++this->m_ptr;return (*this);}
blRawReverseIterator<blDataType> operator++(int){auto temp(*this);--this->m_ptr;return temp;}
blRawReverseIterator<blDataType> operator--(int){auto temp(*this);++this->m_ptr;return temp;}
blRawReverseIterator<blDataType> operator+(const int& movement){auto oldPtr = this->m_ptr;this->m_ptr-=movement;auto temp(*this);this->m_ptr = oldPtr;return temp;}
blRawReverseIterator<blDataType> operator-(const int& movement){auto oldPtr = this->m_ptr;this->m_ptr+=movement;auto temp(*this);this->m_ptr = oldPtr;return temp;}
difference_type operator-(const blRawReverseIterator<blDataType>& rawReverseIterator){return std::distance(this->getPtr(),rawReverseIterator.getPtr());}
blRawIterator<blDataType> base(){blRawIterator<blDataType> forwardIterator(this->m_ptr); ++forwardIterator; return forwardIterator;}
};
//-------------------------------------------------------------------
Now somewhere in your custom container class:
template<typename blDataType>
class blCustomContainer
{
public: // The typedefs
typedef blRawIterator<blDataType> iterator;
typedef blRawIterator<const blDataType> const_iterator;
typedef blRawReverseIterator<blDataType> reverse_iterator;
typedef blRawReverseIterator<const blDataType> const_reverse_iterator;
.
.
.
public: // The begin/end functions
iterator begin(){return iterator(&m_data[0]);}
iterator end(){return iterator(&m_data[m_size]);}
const_iterator cbegin(){return const_iterator(&m_data[0]);}
const_iterator cend(){return const_iterator(&m_data[m_size]);}
reverse_iterator rbegin(){return reverse_iterator(&m_data[m_size - 1]);}
reverse_iterator rend(){return reverse_iterator(&m_data[-1]);}
const_reverse_iterator crbegin(){return const_reverse_iterator(&m_data[m_size - 1]);}
const_reverse_iterator crend(){return const_reverse_iterator(&m_data[-1]);}
.
.
.
// This is the pointer to the
// beginning of the data
// This allows the container
// to either "view" data owned
// by other containers or to
// own its own data
// You would implement a "create"
// method for owning the data
// and a "wrap" method for viewing
// data owned by other containers
blDataType* m_data;
};
I encountered the same problem, just added the path where *mysql_config* resided to the environment variable PATH and it worked for me.
Version 2.6 and above:
PyCharm (far left menu) -> Preferences... -> Editor (bottom left section) -> General -> Appearance -> Show line numbers checkbox
Version 2.5 and below:
Settings -> Editor -> General -> Appearance -> Show line numbers checkbox
This was posted on the Hibernate forum a few years back when asked about why this worked in Hibernate 2 but not in Hibernate 3:
Limit was never a supported clause in HQL. You are meant to use setMaxResults().
So if it worked in Hibernate 2, it seems that was by coincidence, rather than by design. I think this was because the Hibernate 2 HQL parser would replace the bits of the query that it recognised as HQL, and leave the rest as it was, so you could sneak in some native SQL. Hibernate 3, however, has a proper AST HQL Parser, and it's a lot less forgiving.
I think Query.setMaxResults()
really is your only option.
If you get time as string in format such as 1441963946053 you simply could do something as following:
//String timestamp;
Long miliseconds = Long.valueOf(timestamp);
Timestamp ti = new Timestamp(miliseconds);
For instance your json looks like this : {"id":1,"content":"Hello, World!"}
You can access this thru angularjs like so:
angular.module('app', [])
.controller('myApp', function($scope, $http) {
$http.get('http://yourapp/api').
then(function(response) {
$scope.datafromapi = response.data;
});
});
Then on your html you would do it like this:
<!doctype html>
<html ng-app="myApp">
<head>
<title>Hello AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="hello.js"></script>
</head>
<body>
<div ng-controller="myApp">
<p>The ID is {{datafromapi.id}}</p>
<p>The content is {{datafromapi.content}}</p>
</div>
</body>
</html>
This calls the CDN for angularjs in case you don't want to download them.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="hello.js"></script>
Hope this helps.
Use for...of:
var mycars = [{name:'Susita'}, {name:'BMW'}];
for (var car of mycars)
{
document.write(car.name + "<br />");
}
_x000D_
Result:
Susita
BMW
What ended up finally working for me was to add the remote repository name to the git fetch
command, like this:
git fetch core
Now you can see all of them like this:
git branch --all
I found that not only did I have to restart Visual Studio Code but the node server process as well before I could get a good compile.
Here is what I wrote based on info found on this forum:
This is part of a MyDebugNamespace, Debug is apparently reserved and won't do as namespace name.
var DEBUG = true;
...
if (true == DEBUG && !test)
{
var sAlert = "Assertion failed! ";
if (null != message)
sAlert += "\n" + message;
if (null != err)
sAlert += "\n" + "File: " + err.fileName + "\n" + "Line: " + err.lineNumber;
alert(sAlert);
}
...
How to call:
MyDebugNamespace.Assert(new Error(""), (null != someVar), "Something is wrong!")
I included two functions with variable number of arguments calling this base code in my namespace so as to optionally omit message or error in calls.
This works fine with Firefox, IE6 and Chrome report the fileName and lineNumber as undefined.
First off, (though this won't change the performance at all) consider cleaning up your code, similar to this:
import matplotlib.pyplot as plt
import numpy as np
import time
x = np.arange(0, 2*np.pi, 0.01)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
lines = [ax.plot(x, y, style)[0] for ax, style in zip(axes, styles)]
fig.show()
tstart = time.time()
for i in xrange(1, 20):
for j, line in enumerate(lines, start=1):
line.set_ydata(np.sin(j*x + i/10.0))
fig.canvas.draw()
print 'FPS:' , 20/(time.time()-tstart)
With the above example, I get around 10fps.
Just a quick note, depending on your exact use case, matplotlib may not be a great choice. It's oriented towards publication-quality figures, not real-time display.
However, there are a lot of things you can do to speed this example up.
There are two main reasons why this is as slow as it is.
1) Calling fig.canvas.draw()
redraws everything. It's your bottleneck. In your case, you don't need to re-draw things like the axes boundaries, tick labels, etc.
2) In your case, there are a lot of subplots with a lot of tick labels. These take a long time to draw.
Both these can be fixed by using blitting.
To do blitting efficiently, you'll have to use backend-specific code. In practice, if you're really worried about smooth animations, you're usually embedding matplotlib plots in some sort of gui toolkit, anyway, so this isn't much of an issue.
However, without knowing a bit more about what you're doing, I can't help you there.
Nonetheless, there is a gui-neutral way of doing it that is still reasonably fast.
import matplotlib.pyplot as plt
import numpy as np
import time
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
fig.show()
# We need to draw the canvas before we start animating...
fig.canvas.draw()
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
def plot(ax, style):
return ax.plot(x, y, style, animated=True)[0]
lines = [plot(ax, style) for ax, style in zip(axes, styles)]
# Let's capture the background of the figure
backgrounds = [fig.canvas.copy_from_bbox(ax.bbox) for ax in axes]
tstart = time.time()
for i in xrange(1, 2000):
items = enumerate(zip(lines, axes, backgrounds), start=1)
for j, (line, ax, background) in items:
fig.canvas.restore_region(background)
line.set_ydata(np.sin(j*x + i/10.0))
ax.draw_artist(line)
fig.canvas.blit(ax.bbox)
print 'FPS:' , 2000/(time.time()-tstart)
This gives me ~200fps.
To make this a bit more convenient, there's an animations
module in recent versions of matplotlib.
As an example:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
def plot(ax, style):
return ax.plot(x, y, style, animated=True)[0]
lines = [plot(ax, style) for ax, style in zip(axes, styles)]
def animate(i):
for j, line in enumerate(lines, start=1):
line.set_ydata(np.sin(j*x + i/10.0))
return lines
# We'd normally specify a reasonable "interval" here...
ani = animation.FuncAnimation(fig, animate, xrange(1, 200),
interval=0, blit=True)
plt.show()
Those are called #include guards.
Once the header is included, it checks if a unique value (in this case HEADERFILE_H
) is defined. Then if it's not defined, it defines it and continues to the rest of the page.
When the code is included again, the first ifndef
fails, resulting in a blank file.
That prevents double declaration of any identifiers such as types, enums and static variables.
XMLHttpRequest is a built-in object in web browsers.
It is not distributed with Node; you have to install it separately,
Install it with npm,
npm install xmlhttprequest
Now you can require
it in your code.
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
That said, the http module is the built-in tool for making HTTP requests from Node.
Axios is a library for making HTTP requests which is available for Node and browsers that is very popular these days.
This is by far the easiest way I have found to use javascript regex to check phone number format. this particular example checks if it is a 10 digit number.
<input name="phone" pattern="^\d{10}$" type="text" size="50">
The input field gets flagged when submit button is clicked if the pattern doesn't match the value, no other css or js required.
! pip install --user <package>
The !
tells the notebook to execute the cell as a shell command.
You need to use a hashbang. Add it to the first line of your python script.
#! <full path of python interpreter>
Then change the file permissions, and add the executing permission.
chmod +x <filename>
And finally execute it using
./<filename>
If its in the current directory,