If you're a fan of NumPy
ish syntax, then there's tensor.shape
.
In [3]: ar = torch.rand(3, 3)
In [4]: ar.shape
Out[4]: torch.Size([3, 3])
# method-1
In [7]: list(ar.shape)
Out[7]: [3, 3]
# method-2
In [8]: [*ar.shape]
Out[8]: [3, 3]
# method-3
In [9]: [*ar.size()]
Out[9]: [3, 3]
P.S.: Note that tensor.shape
is an alias to tensor.size()
, though tensor.shape
is an attribute of the tensor in question whereas tensor.size()
is a function.
In case you installed yarn globally like this
$ sudo npm install -g yarn
Just run this in terminal
$ sudo npm uninstall -g yarn
Tested now on my local machine running Ubuntu. Works perfect!
$("span").mouseover(function () {
$(this).css({"background-color":"green","font-size":"20px","color":"red"});
});
<div>
Sachin Tendulkar has been the most complete batsman of his time, the most prolific runmaker of all time, and arguably the biggest cricket icon the game has ever known. His batting is based on the purest principles: perfect balance, economy of movement, precision in stroke-making.
</div>
Just add these two line in your css id #some_div
display: block;
overflow: auto;
After that you will get what your are looking for !
If you code for iOS 13.0 or later and want a timestamp, then you can use:
let currentDate = NSDate.now
getSupportActionBar().setDisplayShowTitleEnabled(false);
in some cases we can’t provide guarantee for the type of elements or objects present inside our collection or wise, at the time of retrieval compulsory we should perform type casting otherwise we will get compile time error.
Arrays are always type safe that is we can provide the guarantee for the type of elements present inside array. to achieve type safety we have to use typecasting.
from selenium import webdriver
import time
driver = webdriver.Firefox(executable_path=r'TO\Your\Path\geckodriver.exe')
driver.get('https://www.google.com/')
# Open a new window
driver.execute_script("window.open('');")
# Switch to the new window
driver.switch_to.window(driver.window_handles[1])
driver.get("http://stackoverflow.com")
time.sleep(3)
# Open a new window
driver.execute_script("window.open('');")
# Switch to the new window
driver.switch_to.window(driver.window_handles[2])
driver.get("https://www.reddit.com/")
time.sleep(3)
# close the active tab
driver.close()
time.sleep(3)
# Switch back to the first tab
driver.switch_to.window(driver.window_handles[0])
driver.get("https://bing.com")
time.sleep(3)
# Close the only tab, will also close the browser.
driver.close()
Reference: Need Help Opening A New Tab in Selenium
This Jar Explorer is good enough.
Supports three decompiler types: JD, Procyon and Fernflower.
Allows to search files and duplicates in any java archive.
Also user can modify jar by D&D files and edit some non-class files.
public String removeFirst(String input)
{
return input.substring(1);
}
<?php
$start_date = '2015-01-01';
$end_date = '2015-06-30';
while (strtotime($start_date) <= strtotime($end_date)) {
echo "$start_daten";
$start_date = date ("Y-m-d", strtotime("+1 days", strtotime($start_date)));
}
?>
I would use your suggested code, but with a slight simplification:
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256); // for example
SecretKey secretKey = keyGen.generateKey();
Let the provider select how it plans to obtain randomness - don't define something that may not be as good as what the provider has already selected.
This code example assumes (as Maarten points out below) that you've configured your java.security
file to include your preferred provider at the top of the list. If you want to manually specify the provider, just call KeyGenerator.getInstance("AES", "providerName");
.
For a truly secure key, you need to be using a hardware security module (HSM) to generate and protect the key. HSM manufacturers will typically supply a JCE provider that will do all the key generation for you, using the code above.
The missing piece here is Data Conversion
object. It should be in between OLE DB Source and Destination object.
You have to tell your SQLCommand objects to use the transaction:
cmd1.Transaction = transaction;
or in the constructor:
SqlCommand cmd1 = new SqlCommand("select...", connectionsql, transaction);
Make sure to have the connectionsql object open, too.
But all you are doing are SELECT statements. Transactions would benefit more when you use INSERT, UPDATE, etc type actions.
I was able to figure it out. In case someone wants to know below the code that worked for me:
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] byteArray = Encoding.UTF8.GetBytes(sOriginal);
byte[] asciiArray = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, byteArray);
string finalString = ascii.GetString(asciiArray);
Let me know if there is a simpler way o doing it.
Try WindowsIdentity.GetCurrent()
. You need to add reference to System.Security.Principal
If you don't want to use the EditText solution then you might have better luck with:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourLayout);
(TextView)findViewById(R.id.yourTextViewId).setMovementMethod(ArrowKeyMovementMethod.getInstance());
}
Below query will help to find postgres configuration file.
postgres=# SHOW config_file;
config_file
-------------------------------------
/var/lib/pgsql/data/postgresql.conf
(1 row)
[root@node1 usr]# cd /var/lib/pgsql/data/
[root@node1 data]# ls -lrth
total 48K
-rw------- 1 postgres postgres 4 Nov 25 13:58 PG_VERSION
drwx------ 2 postgres postgres 6 Nov 25 13:58 pg_twophase
drwx------ 2 postgres postgres 6 Nov 25 13:58 pg_tblspc
drwx------ 2 postgres postgres 6 Nov 25 13:58 pg_snapshots
drwx------ 2 postgres postgres 6 Nov 25 13:58 pg_serial
drwx------ 4 postgres postgres 36 Nov 25 13:58 pg_multixact
-rw------- 1 postgres postgres 20K Nov 25 13:58 postgresql.conf
-rw------- 1 postgres postgres 1.6K Nov 25 13:58 pg_ident.conf
-rw------- 1 postgres postgres 4.2K Nov 25 13:58 pg_hba.conf
drwx------ 3 postgres postgres 60 Nov 25 13:58 pg_xlog
drwx------ 2 postgres postgres 18 Nov 25 13:58 pg_subtrans
drwx------ 2 postgres postgres 18 Nov 25 13:58 pg_clog
drwx------ 5 postgres postgres 41 Nov 25 13:58 base
-rw------- 1 postgres postgres 92 Nov 25 14:00 postmaster.pid
drwx------ 2 postgres postgres 18 Nov 25 14:00 pg_notify
-rw------- 1 postgres postgres 57 Nov 25 14:00 postmaster.opts
drwx------ 2 postgres postgres 32 Nov 25 14:00 pg_log
drwx------ 2 postgres postgres 4.0K Nov 25 14:00 global
drwx------ 2 postgres postgres 25 Nov 25 14:20 pg_stat_tmp
simply you can use
$("#yourtextboxid").attr("placeholder", "variable");
where, if variable is string then you can use like above, if it is variable replace it with the name like "variable" with out double quotes.
eg: $("#youtextboxid").attr("placeholder", variable);
it will work.
Or you can make a simple function like this:
// Provided 'c' is only a numeric character
int parseInt (char c) {
return c - '0';
}
No, you cannot modify it, as the string can be stored in read-only memory. If you want to modify it, you can use an array instead e.g.
char a[] = "This is a string";
Or alternately, you could allocate memory using malloc e.g.
char *a = malloc(100);
strcpy(a, "This is a string");
free(a); // deallocate memory once you've done
Moment is great time manipulation library but it's considered as a legacy project, and the team is recommending to use other libraries.
date-fns is one of the best lightweight libraries, it's modular, so you can pick the functions you need and reduce bundle size (issue & statement).
Another common argument against using Moment in modern applications is its size. Moment doesn't work well with modern "tree shaking" algorithms, so it tends to increase the size of web application bundles.
import { format } from 'date-fns' // 21K (gzipped: 5.8K)
import moment from 'moment' // 292.3K (gzipped: 71.6K)
Format date with date-fns
:
// moment.js
moment().format('MM/DD/YYYY');
// => "12/18/2020"
// date-fns
import { format } from 'date-fns'
format(new Date(), 'MM/dd/yyyy');
// => "12/18/2020"
More on cheat sheet with the list of functions which you can use to replace moment.js: You-Dont-Need-Momentjs
you can get value of checkbox and status by
$('.i-checks').on('ifChanged', function(event) {
alert('checked = ' + event.target.checked);
alert('value = ' + event.target.value);
});
SELECT e.*,
cnt.colCount
FROM eventsTable e
INNER JOIN (
select columnName,count(columnName) as colCount
from eventsTable e2
group by columnName
) as cnt on cnt.columnName = e.columnName
WHERE e.columnName='Business'
-- Added space
Sounds like a good opportunity to use an AlertDialog.
As basic as it seems, Android does not have a built-in dialog to do this (as far as I know). Fortunately, it's just a little extra work on top of creating a standard AlertDialog. You simply need to create an EditText for the user to input data, and set it as the view of the AlertDialog. You can customize the type of input allowed using setInputType, if you need.
If you're able to use a member variable, you can simply set the variable to the value of the EditText, and it will persist after the dialog has dismissed. If you can't use a member variable, you may need to use a listener to send the string value to the right place. (I can edit and elaborate more if this is what you need).
Within your class:
private String m_Text = "";
Within the OnClickListener of your button (or in a function called from there):
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");
// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
m_Text = input.getText().toString();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
This is the easiest way to do it: http://jsfiddle.net/thirtydot/jwJBd/
(or with table-layout: fixed
for even width distribution: http://jsfiddle.net/thirtydot/jwJBd/59/)
This won't work in IE7.
#horizontal-style {
display: table;
width: 100%;
/*table-layout: fixed;*/
}
#horizontal-style li {
display: table-cell;
}
#horizontal-style a {
display: block;
border: 1px solid red;
text-align: center;
margin: 0 5px;
background: #999;
}
Old answer before your edit: http://jsfiddle.net/thirtydot/DsqWr/
If infinity is a possible value, I would use numpy.isfinite
numpy.isfinite(myarray).all()
If the above evaluates to True
, then myarray
contains no, numpy.nan
, numpy.inf
or -numpy.inf
values.
numpy.nan
will be OK with numpy.inf
values, for example:
In [11]: import numpy as np
In [12]: b = np.array([[4, np.inf],[np.nan, -np.inf]])
In [13]: np.isnan(b)
Out[13]:
array([[False, False],
[ True, False]], dtype=bool)
In [14]: np.isfinite(b)
Out[14]:
array([[ True, False],
[False, False]], dtype=bool)
You can handle loading the excel file content by writing Java code using Apache POI library (https://poi.apache.org/). The library is developed for working with MS office application data including Excel.
I have recently created the application based on the technology that will help you to load Excel files to the Postgres database. The application is available under http://www.abespalov.com/. The application is tested only for Windows, but should work for Linux as well.
The application automatically creates necessary tables with the same columns as in the Excel files and populate the tables with content. You can export several files in parallel. You can skip the step to convert the files into the CSV format. The application handles the xls and xlsx formats.
Overall application stages are :
{
fileExtension = FilenameUtils.getExtension(inputSheetFile.getName());
if (fileExtension.equalsIgnoreCase("xlsx")) {
workbook = createWorkbook(openOPCPackage(inputSheetFile));
} else {
workbook =
createWorkbook(openNPOIFSFileSystemPackage(inputSheetFile));
}
sheet = workbook.getSheetAt(0);
}
{
Iterator<Row> rowIterator = InitInputFilesImpl.sheet.rowIterator();
//skip a header
if (rowIterator.hasNext()) {
rowIterator.next();
}
while (rowIterator.hasNext()) {
Row row = (Row) rowIterator.next();
// inserting rows
}
}
Here you can find all Java code for the application created for exporting excel to Postgres (https://github.com/palych-piter/Excel2DB).
You actually don't need any jQuery to check if there is an overflow happening or not. Using element.offsetHeight
, element.offsetWidth
, element.scrollHeight
and element.scrollWidth
you can determine if your element have content bigger than it's size:
if (element.offsetHeight < element.scrollHeight ||
element.offsetWidth < element.scrollWidth) {
// your element have overflow
} else {
// your element doesn't have overflow
}
See example in action: Fiddle
But if you want to know what element inside your element is visible or not then you need to do more calculation. There is three states for a child element in terms of visibility:
If you want to count semi-visible items it would be the script you need:
var invisibleItems = [];
for(var i=0; i<element.childElementCount; i++){
if (element.children[i].offsetTop + element.children[i].offsetHeight >
element.offsetTop + element.offsetHeight ||
element.children[i].offsetLeft + element.children[i].offsetWidth >
element.offsetLeft + element.offsetWidth ){
invisibleItems.push(element.children[i]);
}
}
And if you don't want to count semi-visible you can calculate with a little difference.
Update:
Often people want the most recent version of gcc, and devtoolset is being kept up-to-date, so maybe you want devtoolset-N where N={4,5,6,7...}, check yum for the latest available on your system). Updated the cmds below for N=7.
There is a package for gcc-7.2.1 for devtoolset-7 as an example. First you need to enable the Software Collections, then it's available in devtoolset-7:
sudo yum install centos-release-scl
sudo yum install devtoolset-7-gcc*
scl enable devtoolset-7 bash
which gcc
gcc --version
you can use webview in android that will use chrome browser Or you can try Phonegap or sencha Touch
One can also follow the below steps : Spyder -> Tools -> Open Command Prompt -> write the command "pip install html5lib"
For Sharepoint 2007
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\LOGS
Another option is to do another "git stash" of the local uncommitted changes, then combine the two git stashes. Unfortunately git seems to not have a way to easily combine two stashes. So one option is to create two .diff files and apply them both--at lest its not an extra commit and doesn't involve a ten step process :|
Use the ListView.ItemContainerStyle property to give your ListViewItems an EventSetter that will handle the PreviewMouseLeftButtonDown event. Then, in the handler, check to see if the item that was clicked is selected.
XAML:
<ListView ItemsSource={Binding MyItems}>
<ListView.View>
<GridView>
<!-- declare a GridViewColumn for each property -->
</GridView>
</ListView.View>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListViewItem_PreviewMouseLeftButtonDown" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
Code-behind:
private void ListViewItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var item = sender as ListViewItem;
if (item != null && item.IsSelected)
{
//Do your stuff
}
}
About the INT, TINYINT... These are different data types, INT is 4-byte number, TINYINT is 1-byte number. More information here - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT.
The syntax of TINYINT data type is TINYINT(M), where M indicates the maximum display width (used only if your MySQL client supports it).
There is a slight difference between the top answers, namely SUM(case when kind = 1 then 1 else 0 end)
and SUM(kind=1)
.
When all values in column kind
happen to be NULL
, the result of SUM(case when kind = 1 then 1 else 0 end)
is 0
, whereas the result of SUM(kind=1)
is NULL
.
An example (http://sqlfiddle.com/#!9/b23807/2):
Schema:
CREATE TABLE Table1
(`first_col` int, `second_col` int)
;
INSERT INTO Table1
(`first_col`, `second_col`)
VALUES
(1, NULL),
(1, NULL),
(NULL, NULL)
;
Query results:
SELECT SUM(first_col=1) FROM Table1;
-- Result: 2
SELECT SUM(first_col=2) FROM Table1;
-- Result: 0
SELECT SUM(second_col=1) FROM Table1;
-- Result: NULL
SELECT SUM(CASE WHEN second_col=1 THEN 1 ELSE 0 END) FROM Table1;
-- Result: 0
I've created a library that uses multipart uploads in the background to avoid buffering everything in memory and also doesn't write to disk: https://github.com/alexmojaki/s3-stream-upload
Did you already check your proxys here?
git config --global --list
or
git config --local --list
I know this is an ancient question. I'm still offering an alternative. Recently I met the same issue and found no existing and portable command to do that. So I wrote the following shell script which includes a function that can do the trick.
#! /bin/sh
function normalize {
local rc=0
local ret
if [ $# -gt 0 ] ; then
# invalid
if [ "x`echo $1 | grep -E '^/\.\.'`" != "x" ] ; then
echo $1
return -1
fi
# convert to absolute path
if [ "x`echo $1 | grep -E '^\/'`" == "x" ] ; then
normalize "`pwd`/$1"
return $?
fi
ret=`echo $1 | sed 's;/\.\($\|/\);/;g' | sed 's;/[^/]*[^/.]\+[^/]*/\.\.\($\|/\);/;g'`
else
read line
normalize "$line"
return $?
fi
if [ "x`echo $ret | grep -E '/\.\.?(/|$)'`" != "x" ] ; then
ret=`normalize "$ret"`
rc=$?
fi
echo "$ret"
return $rc
}
https://gist.github.com/bestofsong/8830bdf3e5eb9461d27313c3c282868c
In this case you use -1.
int &z = 12;
On the right hand side, a temporary object of type int
is created from the integral literal 12
, but the temporary cannot be bound to non-const reference. Hence the error. It is same as:
int &z = int(12); //still same error
Why a temporary gets created? Because a reference has to refer to an object in the memory, and for an object to exist, it has to be created first. Since the object is unnamed, it is a temporary object. It has no name. From this explanation, it became pretty much clear why the second case is fine.
A temporary object can be bound to const reference, which means, you can do this:
const int &z = 12; //ok
For the sake of the completeness, I would like to add that C++11 has introduced rvalue-reference, which can bind to temporary object. So in C++11, you can write this:
int && z = 12; //C+11 only
Note that there is &&
intead of &
. Also note that const
is not needed anymore, even though the object which z
binds to is a temporary object created out of integral-literal 12
.
Since C++11 has introduced rvalue-reference, int&
is now henceforth called lvalue-reference.
You've another instance of Tomcat already running. You can confirm this by going to http://localhost:8080 in your webbrowser and check if you get the Tomcat default home page or a Tomcat-specific 404 error page. Both are equally valid evidence that Tomcat runs fine; if it didn't, then you would have gotten a browser specific HTTP connection timeout error message.
You need to shutdown it. Go to /bin subfolder of the Tomcat installation folder and execute the shutdown.bat (Windows) or shutdown.sh (Unix) script.
for more help please chech this answer.
You want the :checkbox:checked
selector and map
to create an array of the values:
var checkedValues = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked')
, or for a common name $('input[name="Foo"]:checked')
- Update -
If you don't need IE support then you can now make the map()
call more succinct by using an arrow function:
var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();
_.isArray(image_array) && !_.isEmpty(image_array)
This works on the Spring Tool Suite v 3.1.0.RELEASE, but I'm guessing it's also available on Eclipse as well.
After deleting the artifacts by hand (as stated by palacsint above) in the /username/.m2
directory, re-index the files by doing the following:
Go to:
Windows->Preferences->Maven->User Settings
menu.Click the Reindex
button next to the Local Repository
text box. Click "Apply" then "OK" and you're done.
if ( 0 < i && i < 100)
if ( 'a' <= c && c <= 'z' )
I have not used the classes from the Java NIO package, but it seems they might be of some help here. Specifically, java.nio.channels.Channels and java.nio.channels.InterruptibleChannel.
You can create a directory with PHP using the mkdir() function.
mkdir("/path/to/my/dir", 0700);
You can use fopen() to create a file inside that directory with the use of the mode w
.
fopen('myfile.txt', 'w');
w : Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
$(document).ready(function() {
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
$('#datepicker1').datepicker({
format: 'dd-mm-yyyy',
orientation: 'bottom'
});
$('#datepicker1').datepicker('setDate', today);
});
Here's a solution that is simple, short, easy to understand, and works perfectly for me. I needed to draw to the screen when another thread ends; but couldn't because the main thread has control of the screen. So:
(1) I created the global variable: boolean end1 = false;
The thread sets it to true when ending. That is picked up in the mainthread by "postDelayed" loop, where it is responded to.
(2) My thread contains:
void myThread() {
end1 = false;
new CountDownTimer(((60000, 1000) { // milliseconds for onFinish, onTick
public void onFinish()
{
// do stuff here once at end of time.
end1 = true; // signal that the thread has ended.
}
public void onTick(long millisUntilFinished)
{
// do stuff here repeatedly.
}
}.start();
}
(3) Fortunately, "postDelayed" runs in the main thread, so that's where in check the other thread once each second. When the other thread ends, this can begin whatever we want to do next.
Handler h1 = new Handler();
private void checkThread() {
h1.postDelayed(new Runnable() {
public void run() {
if (end1)
// resond to the second thread ending here.
else
h1.postDelayed(this, 1000);
}
}, 1000);
}
(4) Finally, start the whole thing running somewhere in your code by calling:
void startThread()
{
myThread();
checkThread();
}
You can use to_date
, e.g.
> Event.last.starts_at
=> Wed, 13 Jan 2021 16:49:36.292979000 CET +01:00
> Event.last.starts_at.to_date
=> Wed, 13 Jan 2021
These are called "match variables". As previously mentioned they contain the text from your last regular expression match.
More information is in Essential Perl. (Ctrl + F for 'Match Variables' to find the corresponding section.)
This question is from 2012, some things are changed from that date, and since it still receives a lot of traffic from google, I feel like completing it adding flexbox as a solution.
By now, flexbox is the advised pattern to be used, even if it lacks IE9 support.
The only thing you have to care about is adding display: flex
in the parent element. As default and without the need of setting other property, all the children of that element will be aligned in the same row.
If you want to read more about flexbox
, you can do it here.
.container {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
img {_x000D_
margin: 6px;_x000D_
}
_x000D_
<div class="container">_x000D_
<img src="https://placekitten.com/g/300/300" /> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
</div>
_x000D_
Here's how I did it:
void sha256_hash_string (unsigned char hash[SHA256_DIGEST_LENGTH], char outputBuffer[65])
{
int i = 0;
for(i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
}
outputBuffer[64] = 0;
}
void sha256_string(char *string, char outputBuffer[65])
{
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, string, strlen(string));
SHA256_Final(hash, &sha256);
int i = 0;
for(i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
}
outputBuffer[64] = 0;
}
int sha256_file(char *path, char outputBuffer[65])
{
FILE *file = fopen(path, "rb");
if(!file) return -534;
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
const int bufSize = 32768;
unsigned char *buffer = malloc(bufSize);
int bytesRead = 0;
if(!buffer) return ENOMEM;
while((bytesRead = fread(buffer, 1, bufSize, file)))
{
SHA256_Update(&sha256, buffer, bytesRead);
}
SHA256_Final(hash, &sha256);
sha256_hash_string(hash, outputBuffer);
fclose(file);
free(buffer);
return 0;
}
It's called like this:
static unsigned char buffer[65];
sha256("string", buffer);
printf("%s\n", buffer);
Well, you can always try WHERE textcolumn LIKE "%SUBSTRING%"
- but this is guaranteed to be pretty slow, as your query can't do an index match because you are looking for characters on the left side.
It depends on the field type - a textarea usually won't be saved as VARCHAR, but rather as (a kind of) TEXT field, so you can use the MATCH AGAINST operator.
To get the columns that don't match, simply put a NOT in front of the like: WHERE textcolumn NOT LIKE "%SUBSTRING%"
.
Whether the search is case-sensitive or not depends on how you stock the data, especially what COLLATION you use. By default, the search will be case-insensitive.
I say that doing a WHERE field LIKE "%value%"
is slower than WHERE field LIKE "value%"
if the column field has an index, but this is still considerably faster than getting all values and having your application filter. Both scenario's:
1/ If you do SELECT field FROM table WHERE field LIKE "%value%"
, MySQL will scan the entire table, and only send the fields containing "value".
2/ If you do SELECT field FROM table
and then have your application (in your case PHP) filter only the rows with "value" in it, MySQL will also scan the entire table, but send all the fields to PHP, which then has to do additional work. This is much slower than case #1.
Solution: Please do use the WHERE
clause, and use EXPLAIN
to see the performance.
To do it properly, you need to handle the exceptions.
Here is how I do a wait for an iFrame. This requires that your JUnit test class pass the instance of RemoteWebDriver into the page object :
public class IFrame1 extends LoadableComponent<IFrame1> {
private RemoteWebDriver driver;
@FindBy(id = "iFrame1TextFieldTestInputControlID" )
public WebElement iFrame1TextFieldInput;
@FindBy(id = "iFrame1TextFieldTestProcessButtonID" )
public WebElement copyButton;
public IFrame1( RemoteWebDriver drv ) {
super();
this.driver = drv;
this.driver.switchTo().defaultContent();
waitTimer(1, 1000);
this.driver.switchTo().frame("BodyFrame1");
LOGGER.info("IFrame1 constructor...");
}
@Override
protected void isLoaded() throws Error {
LOGGER.info("IFrame1.isLoaded()...");
PageFactory.initElements( driver, this );
try {
assertTrue( "Page visible title is not yet available.", driver
.findElementByCssSelector("body form#webDriverUnitiFrame1TestFormID h1")
.getText().equals("iFrame1 Test") );
} catch ( NoSuchElementException e) {
LOGGER.info("No such element." );
assertTrue("No such element.", false);
}
}
@Override
protected void load() {
LOGGER.info("IFrame1.load()...");
Wait<WebDriver> wait = new FluentWait<WebDriver>( driver )
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring( NoSuchElementException.class )
.ignoring( StaleElementReferenceException.class ) ;
wait.until( ExpectedConditions.presenceOfElementLocated(
By.cssSelector("body form#webDriverUnitiFrame1TestFormID h1") ) );
}
....
NOTE: You can see my entire working example here.
tutu's answer is on the right track, but his recursion is a little awkward. I think this is cleaner:
private static void setViewAndChildrenEnabled(View view, boolean enabled) {
view.setEnabled(enabled);
if (view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) view;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View child = viewGroup.getChildAt(i);
setViewAndChildrenEnabled(child, enabled);
}
}
}
You can do that like this:
from datetime import datetime
from threading import Timer
x=datetime.today()
y=x.replace(day=x.day+1, hour=1, minute=0, second=0, microsecond=0)
delta_t=y-x
secs=delta_t.seconds+1
def hello_world():
print "hello world"
#...
t = Timer(secs, hello_world)
t.start()
This will execute a function (eg. hello_world) in the next day at 1a.m.
EDIT:
As suggested by @PaulMag, more generally, in order to detect if the day of the month must be reset due to the reaching of the end of the month, the definition of y in this context shall be the following:
y = x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0) + timedelta(days=1)
With this fix, it is also needed to add timedelta to the imports. The other code lines maintain the same. The full solution, using also the total_seconds() function, is therefore:
from datetime import datetime, timedelta
from threading import Timer
x=datetime.today()
y = x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0) + timedelta(days=1)
delta_t=y-x
secs=delta_t.total_seconds()
def hello_world():
print "hello world"
#...
t = Timer(secs, hello_world)
t.start()
If you came here because you were looking for a simple way to browse any VOLUME
:
docker volume list
docker run -it --rm --mount source=[NAME OF VOLUME],target=/volume busybox
cd /volume
to enter the volume.I've figured it out, you can add to request mapping produces = "text/plain;charset=UTF-8"
@RequestMapping(value = "/rest/create/document", produces = "text/plain;charset=UTF-8")
@ResponseBody
public void create(Document document, HttpServletRespone respone) throws UnsupportedEncodingException {
Document newDocument = DocumentService.create(Document);
return jsonSerializer.serialize(newDocument);
}
//this gets you both the item (myItem.value) and its index (myItem.i)
@foreach (var myItem in Model.Members.Select((value,i) => new {i, value}))
{
<li>The index is @myItem.i and a value is @myItem.value.Name</li>
}
More info on my blog post http://jimfrenette.com/2012/11/razor-foreach-loop-with-index/
This is how you should be using mysql_fetch_assoc():
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
// Do stuff with $row
}
$result should be a resource. Even if the query returns no rows, $result is still a resource. The only time $result is a boolean value, is if there was an error when querying the database. In which case, you should find out what that error is by using mysql_error() and ensure that it can't happen. Then you don't have to hide from any errors.
You should always cover the base that errors may happen by doing:
if (!$result) {
die(mysql_error());
}
At least then you'll be more likely to actually fix the error, rather than leave the users with a glaring ugly error in their face.
To delete column use this,
ALTER TABLE `tbl_Country` DROP `your_col`
Try this, it worked for me in a similar case:-
$http.get("your api url", {
headers: {
'If-Modified-Since': '0',
"Pragma": "no-cache",
"Expires": -1,
"Cache-Control": "no-cache, no-store, must-revalidate"
}
})
JObject implements IDictionary, so you can use it that way. For ex,
var cycleJson = JObject.Parse(@"{""name"":""john""}");
//add surname
cycleJson["surname"] = "doe";
//add a complex object
cycleJson["complexObj"] = JObject.FromObject(new { id = 1, name = "test" });
So the final json will be
{
"name": "john",
"surname": "doe",
"complexObj": {
"id": 1,
"name": "test"
}
}
You can also use dynamic
keyword
dynamic cycleJson = JObject.Parse(@"{""name"":""john""}");
cycleJson.surname = "doe";
cycleJson.complexObj = JObject.FromObject(new { id = 1, name = "test" });
Use Where-Object
, like:
Get-ChildItem 'PATH' -recurse -include @("*.tif*","*.jp2","*.pdf") |
Where-Object { $_.CreationTime -gt "03/01/2013" -and $_.CreationTime -lt "03/31/2013" }
Select-Object FullName, CreationTime, @{Name="Mbytes";Expression={$_.Length/1Kb}}, @{Name="Age";Expression={(((Get-Date) - $_.CreationTime).Days)}} |
Export-Csv 'PATH\scans.csv'
If your repo have 2FA enabled. Highly suggest to use the app provided by github.com Here is the link: https://desktop.github.com/
After you downloaded it and installed it. Follow the withard, the app will ask you to provide the one time password for login. Once you filled in the one time password, you could see your repo/projects now.
This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.
change it to:
$(function () {
var specialElementHandlers = {
'#editor': function (element,renderer) {
return true;
}
};
$('#cmd').click(function () {
var doc = new jsPDF();
doc.fromHTML(
$('#target').html(), 15, 15,
{ 'width': 170, 'elementHandlers': specialElementHandlers },
function(){ doc.save('sample-file.pdf'); }
);
});
});
and it will work.
It is better to parse the URL properly - this way you can handle http://.../file.doc?foo
and http://.../foo.doc/file.exe
correctly.
from urlparse import urlparse
import os
path = urlparse(url_string).path
ext = os.path.splitext(path)[1]
if ext in extensionsToCheck:
print(url_string)
I added some color to a GitHub markup page using emoji Enicode chars, e.g. or -- some emoji characters are colored in some browsers.
There are also some colored emoji alphabets: blood types ???; parking sign ?; Metro sign ??; a few others with two or more letters, such as , and boxed digits such as 0??. Flag emojis will show as letters (often colored) if the flag is not available: .
However, I don't think there is a complete colored alphabet defined in emoji.
If you are using the tidyverse, you can use
as_data_frame(table(myvector))
to get a tibble (i.e. a data frame with some minor variations from the base class)
We actually don't need to setup loops for detecting javaScript changes. We already setting up many event listeners to the element we want to detect. just triggering any un harmful event will make the job.
$("input[name='test-element']").on("propertychange change click keyup input paste blur", function(){
console.log("yeh thats worked!");
});
$("input[name='test-element']").val("test").trigger("blur");
and ofc this is only available if you have the full control on javascript changes on your project.
Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.
-
is the 'binary operator' your error is referencing, and either CurrentDay
or MA
(or both) are non-numeric.
A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). +
is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).
R only knows how to apply +
(and other binary operators, such as -
) to numeric arguments:
> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator
When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.
EDIT:
Your error lies in the use of [
instead of [[
. Because Day
is a list, subsetting with [
will return a list, not a numeric vector. [[
, however, returns an object of the class of the item contained in the list:
> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator
> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3
Transaction
, as you've defined it, returns a list of two vectors. Above, Day
is a list contain one vector. Day2
, however, is simply a vector.
You can import like this
import("jquery").then((jQuery) => {
window.$ = jQuery;
window.jQuery = jQuery;
import("bootstrap").then((_bs)=>{
$(function() {});
})
});
In .net, every instance of Object, or any type derived therefrom, includes a data structure which contains information about its type. "Real" value types in .net do not contain any such information. To allow data in value types to be manipulated by routines that expect to receive types derived from object, the system automatically defines for each value type a corresponding class type with the same members and fields. Boxing creates a new instances of this class type, copying the fields from a value type instance. Unboxing copies the fields from an instance of the class type to an instance of the value type. All of the class types which are created from value types are derived from the ironically named class ValueType (which, despite its name, is actually a reference type).
Had to restart the Eclipse after completing the installation of ARM EABI v7a system image.
What you really need is to compare two objects of the same kind.
Create an NSDate out of your string date (@"2009-05-11") :
http://blog.evandavey.com/2008/12/how-to-convert-a-string-to-nsdate.html
If the current date is a string too, make it an NSDate. If its already an NSDate, leave it.
This is one way I know of. With git
, there always seems to be more than one way to do it.
git log -p commit1 commit2
Some handy quick functions (if you're not using Boost):
template<typename T>
std::string ToString(const T& v)
{
std::ostringstream ss;
ss << v;
return ss.str();
}
template<typename T>
T FromString(const std::string& str)
{
std::istringstream ss(str);
T ret;
ss >> ret;
return ret;
}
Example:
int i = FromString<int>(s);
std::string str = ToString(i);
Works for any streamable types (floats etc). You'll need to #include <sstream>
and possibly also #include <string>
.
I implemented very fast Postgresq data loader with native libpq methods. Try my package https://www.nuget.org/packages/NpgsqlBulkCopy/
Try:
document.getElementById("foo").onclick = function (){alert('foo');};
.form-group .required .control-label:after
should probably be .form-group.required .control-label:after
. The removal of the space between .form-group and .required is the change.
Old thread I know, but I lost a couple of hours of my life with this. You also need to set the DB info in the .env file. You don't have to specify the driver here because the default specified in database.php is used (I think). I was struggling because it had DB_CONNECTION=mysql
in the .env file and I was using pgsql.
OK, I don't think the official snippet mentioned by galuszkak should be used everywhere, we should concern the case that some bug may be triggered during the handler such as hello_world
function. Whether the response is correct or uncorrect, the Access-Control-Allow-Origin
header is what we should concern. So, thing is very simple, just like bellow:
@blueprint.after_request # blueprint can also be app~~
def after_request(response):
header = response.headers
header['Access-Control-Allow-Origin'] = '*'
return response
That is all~~
create or replace
TRIGGER triggername BEFORE INSERT ON
table FOR EACH ROW
BEGIN
/*
Write any select condition if you want to get the data from other tables
*/
:NEW.COLUMNA:= UPPER(COLUMNA);
--:NEW.COUMNa:= NULL;
END;
The above trigger will update the column value before inserting. For example if we give the value of COLUMNA as null it will update the column as null for each insert statement.
As of now GCM only works for chrome and android. similarly firefox and other browsers has their own api.
Now coming to the question how to implement push notification so that it will work for all common browsers with own back end.
2.after getting endpoint using Ajax save it along with browser name.
3.You need to create back end which has fields for title,message, icon,click URL as per your requirements. now after click on send notification, call a function say send_push(). In this write code for different browsers for example
3.1. for chrome
$headers = array(
'Authorization: key='.$api_key(your gcm key),
'Content-Type: application/json',
);
$msg = array('to'=>'register id saved to your server');
$url = 'https://android.googleapis.com/gcm/send';
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($msg));
$result = curl_exec($ch);
3.2. for mozilla
$headers = array(
'Content-Type: application/json',
'TTL':6000
);
$url = 'https://updates.push.services.mozilla.com/wpush/v1/REGISTER_ID_TO SEND NOTIFICATION_ON';
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
for other browsers please google...
You can do it in Python 2.7+ with python-dateutil
(which is insalled on Mac by default):
>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>> datetime.now(tzlocal()).isoformat()
'2016-10-22T12:45:45.353489-03:00'
Or you if you want to convert from an existed stored string:
>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>> from dateutil.parser import parse
>>> parse("2016-10-21T16:33:27.696173").replace(tzinfo=tzlocal()).isoformat()
'2016-10-21T16:33:27.696173-03:00' <-- Atlantic Daylight Time (ADT)
>>> parse("2016-01-21T16:33:27.696173").replace(tzinfo=tzlocal()).isoformat()
'2016-01-21T16:33:27.696173-04:00' <-- Atlantic Standard Time (AST)
My contribution ONLY for SQLite:
/**
* Returns an array of column names for a given table.
* Arg. $dsn should be replaced by $this->dsn in a class definition.
*
* @param string $dsn Database connection string,
* e.g.'sqlite:/home/user3/db/mydb.sq3'
* @param string $table The name of the table
*
* @return string[] An array of table names
*/
public function getTableColumns($dsn, $table) {
$dbh = new \PDO($dsn);
return $dbh->query('PRAGMA table_info(`'.$table.'`)')->fetchAll(\PDO::FETCH_COLUMN, 1);
}
If you only need two search terms, arguably the most readable approach is to run each search and intersect the results:
comm -12 <(grep -rl word1 . | sort) <(grep -rl word2 . | sort)
Now there is an official way to add "PlantUML integration" plugin to your JetBrains product.
Installation steps please refer: https://stackoverflow.com/a/53387418/5320704
Here is the Code. I have tested all the possible test case on Hacker Rank.
static String isBalanced(String input) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < input.length(); i++) {
Character ch = input.charAt(i);
if (input.charAt(i) == '{' || input.charAt(i) == '['
|| input.charAt(i) == '(') {
stack.push(input.charAt(i));
} else {
if (stack.isEmpty()
|| (stack.peek() == '[' && ch != ']')
|| (stack.peek() == '{' && ch != '}')
|| (stack.peek() == '(' && ch != ')')) {
return "NO";
} else {
stack.pop();
}
}
}
if (stack.empty())
return "YES";
return "NO";
}
Remember that you must first load jquery script and then the script js
<script type="text/javascript" src="http://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="example.js"></script>
Html is read sequentially!
You can't call _doPostBack()
because it forces submition of the form. Why don't you disable the PostBack
on the UpdatePanel
?
I was able to solve "ORA-00604: error" by Droping with purge.
DROP TABLE tablename PURGE
For List<List<List<x>>>
and so on, use
list.SelectMany(x => x.SelectMany(y => y)).ToList();
This has been posted in a comment, but it does deserves a separate reply in my opinion.
In order to do this without FuncAnimation (eg you want to execute other parts of the code while the plot is being produced or you want to be updating several plots at the same time), calling draw
alone does not produce the plot (at least with the qt backend).
The following works for me:
import matplotlib.pyplot as plt
plt.ion()
class DynamicUpdate():
#Suppose we know the x range
min_x = 0
max_x = 10
def on_launch(self):
#Set up plot
self.figure, self.ax = plt.subplots()
self.lines, = self.ax.plot([],[], 'o')
#Autoscale on unknown axis and known lims on the other
self.ax.set_autoscaley_on(True)
self.ax.set_xlim(self.min_x, self.max_x)
#Other stuff
self.ax.grid()
...
def on_running(self, xdata, ydata):
#Update data (with the new _and_ the old points)
self.lines.set_xdata(xdata)
self.lines.set_ydata(ydata)
#Need both of these in order to rescale
self.ax.relim()
self.ax.autoscale_view()
#We need to draw *and* flush
self.figure.canvas.draw()
self.figure.canvas.flush_events()
#Example
def __call__(self):
import numpy as np
import time
self.on_launch()
xdata = []
ydata = []
for x in np.arange(0,10,0.5):
xdata.append(x)
ydata.append(np.exp(-x**2)+10*np.exp(-(x-7)**2))
self.on_running(xdata, ydata)
time.sleep(1)
return xdata, ydata
d = DynamicUpdate()
d()
Method 1: Download ojdbc.jar
add ojdbc6.jar to deployment assembly. Right click on project->properties->select deployment assembly->click on 'Add' ->select 'Archives from File System'->browse to the folder where ojdbc6.jar is saved.->add the jar->click finish->Apply/OK.
Method 2:
if you want to add ojdbc.jar to your maven dependencies you follow this link: http://www.mkyong.com/maven/how-to-add-oracle-jdbc-driver-in-your-maven-local-repository/ . . Even if you're using a maven project it is not necessary to add ojdbc to maven dependencies(method 2), method 1 (adding directly to deployment assembly) works just fine.
If SSL support is not configurable in your site (ie. should be able to turn https on/off) - you can use the [RequireHttps] attribute on any controller / controller action you wish to secure.
Try this one. You can strip just '
and "
with:
$FileName = str_replace(array('\'', '"'), '', $UserInput);
SELECT *
FROM
(
SELECT * FROM TABLE_A
UNION ALL
SELECT * FROM TABLE_B
) dum
-- ORDER BY .....
but if you want to have all records from Table_A
on the top of the result list, the you can add user define value which you can use for ordering,
SELECT *
FROM
(
SELECT *, 1 sortby FROM TABLE_A
UNION ALL
SELECT *, 2 sortby FROM TABLE_B
) dum
ORDER BY sortby
Better to use try-with-resources then all that pre-java 7 finally business
static void appendStringToFile(Path file, String s) throws IOException {
try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
out.append(s);
out.newLine();
}
}
I know, the question is very old, but I found a nice solution.
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] init];
barButton.title = @"Custom Title";
self.navigationController.navigationBar.topItem.backBarButtonItem = barButton;
Works from childView! Tested with iOS 7.
If you want to apply an extra small class in Bootstrap 4,you need to use col-. important thing to know is that col-xs- is dropped in Bootstrap4
If getData
is protected then try making it public. The problem could exist in JAVA 1.6 and be absent in 1.5x
I got this for your problem. Illegal access error
There is a simple work around. The alert only comes up when you have a large amount of data in your clipboard. Just copy a random cell before you close the workbook and it won't show up anymore!
Hibernate definitely supports this. From the docs:
"Generated properties are properties which have their values generated by the database. Typically, Hibernate applications needed to refresh objects which contain any properties for which the database was generating values. Marking properties as generated, however, lets the application delegate this responsibility to Hibernate. Essentially, whenever Hibernate issues an SQL INSERT or UPDATE for an entity which has defined generated properties, it immediately issues a select afterwards to retrieve the generated values."
For properties generated on insert only, your property mapping (.hbm.xml) would look like:
<property name="foo" generated="insert"/>
For properties generated on insert and update your property mapping (.hbm.xml) would look like:
<property name="foo" generated="always"/>
Unfortunately, I don't know JPA, so I don't know if this feature is exposed via JPA (I suspect possibly not)
Alternatively, you should be able to exclude the property from inserts and updates, and then "manually" call session.refresh( obj ); after you have inserted/updated it to load the generated value from the database.
This is how you would exclude the property from being used in insert and update statements:
<property name="foo" update="false" insert="false"/>
Again, I don't know if JPA exposes these Hibernate features, but Hibernate does support them.
add to second div bottomDiv
and add this to css.
.bottomDiv{
position:relative;
bottom:150px;
left:150px;
}
In Xcode Version 6.1.1 (6A2008a), after "Processing Symbol Files", a folder containing symbols associated with the device (including iOS version and CPU type) was created in ~/Library/Developer/Xcode/iOS DeviceSupport/ like this:
For the inbuilt javaDB included in the JDK (Oracle's supported distribution of the Apache Derby) the below worked for me
alter table [table name] alter column [column name] not null;
In the case of a non blocking socket that has no data available, recv will throw the socket.error exception and the value of the exception will have the errno of either EAGAIN or EWOULDBLOCK. Example:
import sys
import socket
import fcntl, os
import errno
from time import sleep
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',9999))
fcntl.fcntl(s, fcntl.F_SETFL, os.O_NONBLOCK)
while True:
try:
msg = s.recv(4096)
except socket.error, e:
err = e.args[0]
if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
sleep(1)
print 'No data available'
continue
else:
# a "real" error occurred
print e
sys.exit(1)
else:
# got a message, do something :)
The situation is a little different in the case where you've enabled non-blocking behavior via a time out with socket.settimeout(n)
or socket.setblocking(False)
. In this case a socket.error is stil raised, but in the case of a time out, the accompanying value of the exception is always a string set to 'timed out'. So, to handle this case you can do:
import sys
import socket
from time import sleep
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',9999))
s.settimeout(2)
while True:
try:
msg = s.recv(4096)
except socket.timeout, e:
err = e.args[0]
# this next if/else is a bit redundant, but illustrates how the
# timeout exception is setup
if err == 'timed out':
sleep(1)
print 'recv timed out, retry later'
continue
else:
print e
sys.exit(1)
except socket.error, e:
# Something else happened, handle error, exit, etc.
print e
sys.exit(1)
else:
if len(msg) == 0:
print 'orderly shutdown on server end'
sys.exit(0)
else:
# got a message do something :)
As indicated in the comments, this is also a more portable solution since it doesn't depend on OS specific functionality to put the socket into non-blockng mode.
See recv(2) and python socket for more details.
With this step set permission to gradlew
steps {
echo 'Compile project'
sh "chmod +x gradlew"
sh "./gradlew clean build --no-daemon"
}
Just move the extra condition into the JOIN ON criteria, this way the existence of b is not required to return a result
SELECT a.* FROM a
LEFT JOIN b ON a.group_id=b.group_id AND b.user_id!=$_SESSION{['user_id']}
WHERE a.keyword LIKE '%".$keyword."%'
GROUP BY group_id
final keyword in the method input parameter is not needed. Java creates a copy of the reference to the object, so putting final on it doesn't make the object final but just the reference, which doesn't make sense
This should work:
$("#table-filters>ul>li.active").removeClass("active");
//Find all `li`s with class `active`, children of `ul`s, children of `table-filters`
Go to edit Android Virtual Devices and change the 1024 Under Memory Options to 768. If it still doesn't work, keep going lower and lower.
I had issues getting through a form because of this error.
I used Ctrl+Click to click the submit button and navigate through the form as usual.
Add this to the UIWebView delegate:
(edited to check for navigation type. you could also pass through file://
requests which would be relative links)
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked ) {
[[UIApplication sharedApplication] openURL:[request URL]];
return NO;
}
return YES;
}
Swift Version:
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if navigationType == UIWebViewNavigationType.LinkClicked {
UIApplication.sharedApplication().openURL(request.URL!)
return false
}
return true
}
Swift 3 version:
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if navigationType == UIWebViewNavigationType.linkClicked {
UIApplication.shared.openURL(request.url!)
return false
}
return true
}
Swift 4 version:
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
guard let url = request.url, navigationType == .linkClicked else { return true }
UIApplication.shared.open(url, options: [:], completionHandler: nil)
return false
}
Update
As openURL
has been deprecated in iOS 10:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked ) {
UIApplication *application = [UIApplication sharedApplication];
[application openURL:[request URL] options:@{} completionHandler:nil];
return NO;
}
return YES;
}
You can also install json-py from here http://sourceforge.net/projects/json-py/
For multiple classes
in the same js
file, extending Component
from @wordpress/element
, you can do that :
// classes.js
import { Component } from '@wordpress/element';
const Class1 = class extends Component {
}
const Class2 = class extends Component {
}
export { Class1, Class2 }
And import them in another js
file :
import { Class1, Class2 } from './classes';
I had a similar issue and it was an easy fix.
Add this in your HTML meta tag area :
<meta name="csrf-token" content="{{ csrf_token() }}">
Then under your JQuery reference, add this code :
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
If you are using the HTML form submit (not AJAX) then you need to put :
{{ csrf_field() }}
inside your form tags.
another way to access a column by number is to use a mapping dictionary where the key is the column name and the value is the column number
dates = pd.date_range('1/1/2000', periods=8)
df = pd.DataFrame(np.random.randn(8, 4),
index=dates, columns=['A', 'B', 'C', 'D'])
print(df)
dct={'A':0,'B':1,'C':2,'D':3}
columns=df.columns
print(df.iloc[:,dct['D']])
This might look stupid, but check if you haven't already added the folder/files you are trying to ignore to the index before. If you did, it does not matter what you put in your .gitignore file, the folders/files will still be staged.
I've found that the above solution will not work if you have to deal with control characters like 02
(STX) or 03
(ETX), anything under 10
will be read as a single digit and throw off everything after. I ran into this problem trying to parse through serial communications. So, I first took the hex string received and put it in a buffer object then converted the hex string into an array of the strings like so:
buf = Buffer.from(data, 'hex');
l = Buffer.byteLength(buf,'hex');
for (i=0; i<l; i++){
char = buf.toString('hex', i, i+1);
msgArray.push(char);
}
Then .join it
message = msgArray.join('');
then I created a hexToAscii
function just like in @Delan Azabani's answer above...
function hexToAscii(str){
hexString = str;
strOut = '';
for (x = 0; x < hexString.length; x += 2) {
strOut += String.fromCharCode(parseInt(hexString.substr(x, 2), 16));
}
return strOut;
}
then called the hexToAscii
function on 'message'
message = hexToAscii(message);
This approach also allowed me to iterate through the array and slice into the different parts of the transmission using the control characters so I could then deal with only the part of the data I wanted. Hope this helps someone else!
Setting val('')
will empty the input field. So you would use this:
Clear the input field when the page loads:
$(function(){
$('#shares').val('');
});
SELECT VARCHAR_FORMAT(CURRENT TIMESTAMP, 'YYYYMMDD')
FROM SYSIBM.SYSDUMMY1
Should work on both Mainframe and Linux/Unix/Windows DB2. Info Center entry for VARCHAR_FORMAT()
.
The command line is correct and works on a valid video file. I would make sure that you have installed the correct library to work with mp3, install lame o probe with another audio codec.
Usually
ffmpeg -formats
or
ffmpeg -codecs
would give sufficient information so that you know more.
In python 3.6 I got the value of last key from the following code
list(dict.keys())[-1]
I had mysterious SIGTERM shutdowns in our L.A.M.P. server, and it turned out to be an error in a custom PHP module, which was caused by mismatched versions. It was found by looking in the apache access/error logs at the time of malfunction. Don't forget to turn error logging on.
That's because the result of adding two Int16
is an Int32
.
Check the "conversions" paragraph here: http://msdn.microsoft.com/en-us/library/ybs77ex4%28v=vs.71%29.aspx
Just typing this single line would give you a json array ,
echo json_encode($array);
Normally you use json_encode
to read data from an ios or android app. so make sure you do not echo anything else other than the accurate json array.
You could have a dictionary where the entries are a list of other dictionaries:
fruit_dict = dict()
fruit_dict['banana'] = [{'yellow': 24}]
fruit_dict['apple'] = [{'red': 12}, {'green': 14}]
print fruit_dict
Output:
{'banana': [{'yellow': 24}], 'apple': [{'red': 12}, {'green': 14}]}
Edit: As eumiro pointed out, you could use a dictionary of dictionaries:
fruit_dict = dict()
fruit_dict['banana'] = {'yellow': 24}
fruit_dict['apple'] = {'red': 12, 'green': 14}
print fruit_dict
Output:
{'banana': {'yellow': 24}, 'apple': {'green': 14, 'red': 12}}
Try
list.GetType().GetGenericArguments()
There is a GetName
function on the SqlDataReader
which accepts the column index and returns the name of the column.
Conversely, there is a GetOrdinal
which takes in a column name and returns the column index.
Since Array(3)
will create an un-iterable array, it must be populated to allow the usage of the map
Array method. A way to "convert"
is to destruct it inside Array-brackets, which "forces" the Array to be filled with undefined
values, same as Array(N).fill(undefined)
<table>
{ [...Array(3)].map((_, index) => <tr key={index}/>) }
</table>
fill()
:<table>
{ Array(3).fill(<tr/>) }
</table>
?? Problem with above example is the lack of
key
prop, which is a must.
(Using an iterator'sindex
askey
is not recommended)
const tableSize = [3,4]
const Table = (
<table>
<tbody>
{ [...Array(tableSize[0])].map((tr, trIdx) =>
<tr key={trIdx}>
{ [...Array(tableSize[1])].map((a, tdIdx, arr) =>
<td key={trIdx + tdIdx}>
{arr.length * trIdx + tdIdx + 1}
</td>
)}
</tr>
)}
</tbody>
</table>
);
ReactDOM.render(Table, document.querySelector('main'))
_x000D_
td{ border:1px solid silver; padding:1em; }
_x000D_
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<main></main>
_x000D_
Use Libre Office API Here is an example
libreoffice --headless --convert-to html docx-file-path --outdir html-dir-path
Your question is missing most of the necessary information, so I'm going to make some assumptions:
The answer would be:
=IF(COUNTBLANK(F16:G16)<>2,H15+G16-F16,"")
COUNTBLANK
tells you how many cells are unfilled or set to "".
IF
lets you conditionally do one of two things based on whether the first statement is true or false. The second comma separated argument is what to do if it's true, the third comma separated argument is what to do if it's false.
<>
means "not equal to".
The equation says that if the number of blank cells in the range F16:G16
(your credit and debit cells) is not 2, which means both aren't blank, then calculate the equation you provided in your question. Otherwise set the cell to blank(""
).
When you copy this equation to new cells in column H other than H16
, it will update the row references so the proper rows for the credit and debit amounts are looked at.
CAVEAT: This equation is useful if you are just adding entries for credits and debits to the end of a list and want the running total to update automatically. You'd fill this equation down to some arbitrary long length well past the end of actual data. You wouldn't see the running total past the end of the credit/debit entries then, it would just be blank until you filled in a new credit/debit entry. If you left a blank row in your credit debit entries though, the reference to the previous total, H15
, would report blank, which is treated like a 0 in this case.
DECLARE @id INT
DECLARE @filename NVARCHAR(100)
DECLARE @getid CURSOR
SET @getid = CURSOR FOR
SELECT top 3 id,
filename
FROM table
OPEN @getid
WHILE 1=1
BEGIN
FETCH NEXT
FROM @getid INTO @id, @filename
IF @@FETCH_STATUS < 0 BREAK
print @id
END
CLOSE @getid
DEALLOCATE @getid
Solution is to change Delimiter.
Content of the csv file -> Note .. Also space and , in value
Values are 6 Dutch word aap,noot,mies,Piet, Gijs, Jan
Col1;Col2;Col3
a,ap;noo,t;mi es
P,iet;G ,ijs;Ja ,n
$csv = Import-Csv C:\TejaCopy.csv -Delimiter ';'
Answer:
Write-Host $csv
@{Col1=a,ap; Col2=noo,t; Col3=mi es} @{Col1=P,iet; Col2=G ,ijs; Col3=Ja ,n}
It is possible to read a CSV file and use other Delimiter to separate each column.
It worked for my script :-)
I just had the same problem .I solve it by adding this line:
@GeneratedValue(strategy=GenerationType.IDENTITY)
For pandas 0.10, where iloc
is unavalable, filter a DF
and get the first row data for the column VALUE
:
df_filt = df[df['C1'] == C1val & df['C2'] == C2val]
result = df_filt.get_value(df_filt.index[0],'VALUE')
if there is more then 1 row filtered, obtain the first row value. There will be an exception if the filter result in empty data frame.
Download the latest build from https://github.com/macvim-dev/macvim/releases
Expand the archive.
Put MacVim.app into /Applications/
.
Done.
Another reason of this problem can be column type of "payload" sessions table. If you have huge data on session, a text column wouldn't be enough. You will need MEDIUMTEXT or even LONGTEXT.
I had the same problem and the issue was that my child component had an @input
named formControl
.
So I just needed to change from:
<my-component [formControl]="formControl"><my-component/>
to:
<my-component [control]="control"><my-component/>
ts:
@Input()
control:FormControl;
First you need an object
public class MyObject {
public string Id {get;set;}
public string Text {get;set;}
...
}
Then in here
using (var twitpicResponse = (HttpWebResponse)request.GetResponse()) {
using (var reader = new StreamReader(twitpicResponse.GetResponseStream())) {
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
MyObject myojb = (MyObject)js.Deserialize(objText,typeof(MyObject));
}
}
I haven't tested with the hierarchical object you have, but this should give you access to the properties you want.
JavaScriptSerializer System.Web.Script.Serialization
You should use .keydown()
because .keypress()
will ignore "Arrows", for catching the key type use e.which
Press the result screen to focus (bottom right on fiddle screen) and then press arrow keys to see it work.
Notes:
.keypress()
will never be fired with Shift, Esc, and Delete but .keydown()
will..keypress()
in some browser will be triggered by arrow keys but its not cross-browser so its more reliable to use .keydown()
.More useful information
.which
Or .keyCode
of the event object - Some browsers won't support one of them but when using jQuery its safe to use the both since jQuery standardizes things. (I prefer .which
never had a problem with).ctrl | alt | shift | META
press with the actual captured key you should check the following properties of the event object - They will be set to TRUE if they were pressed:
event.ctrlKey
- ctrl event.altKey
- altevent.shiftKey
- shiftevent.metaKey
- META ( Command ? OR Windows Key )Finally - here are some useful key codes ( For a full list - keycode-cheatsheet ):
Java 8...
String joined = String.join("+", list);
Documentation: http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-
If your code doesn't cross filesystem boundaries, i.e. you're just working with one filesystem, then use java.io.File.separator
.
This will, as explained, get you the default separator for your FS. As Bringer128 explained, System.getProperty("file.separator")
can be overriden via command line options and isn't as type safe as java.io.File.separator
.
The last one, java.nio.file.FileSystems.getDefault().getSeparator();
was introduced in Java 7, so you might as well ignore it for now if you want your code to be portable across older Java versions.
So, every one of these options is almost the same as others, but not quite. Choose one that suits your needs.
string.punctuation contains following characters:
'!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~'
You can use translate and maketrans functions to map punctuations to empty values (replace)
import string
'This, is. A test!'.translate(str.maketrans('', '', string.punctuation))
Output:
'This is A test'
There is no limit. It only depends on your free memory and system maximum file size. But that doesn't mean you shouldn't take precautionary measure in tackling memory usage in your database. Always create a script that can delete rows that are out of use or that will keep total no of rows within a particular figure, say a thousand.
Just to clarify: from within your app, you can simply refer to the emulator as 'localhost' or 127.0.0.1.
Web traffic is routed through your development machine, so the emulator's external IP is whatever IP has been assigned to that machine by your provider. The development machine can always be reached from your device at 10.0.2.2.
Since you were asking only about the emulator's IP, what is it you're trying to do?
If your rollback segment/undo segment can accomodate the size of the transaction then option 2 is better. Option 1 is useful if you do not have the rollback capacity needed and have to break the large insert into smaller commits so you don't get rollback/undo segment too small errors.
import org.apache.commons.io.filefilter.WildcardFileFilter;
.........
.........
File dir = new File(fileDir);
FileFilter fileFilter = new WildcardFileFilter("*.txt");
File[] files = dir.listFiles(fileFilter);
The code above works great for me
If you write this yourself these are some of the points to keep in mind
Proper authentication between the device and the Sync Server
A sync protocol between the device and the server. It will usually go in 3 phases, authentication, data exchange, status exchange (which operations worked and which failed)
Pick your payload format. I suggest SyncML based XML mixed with JSON based format to represent the actual data. So SyncML for the protocol, and JSON for the actual data being exchanged. Using JSON Array while manipulating the data is always preferred as it is easy to access data using JSON Array.
Keeping track of data changes on both client and server. You can maintain a changelog of ids that change and pick them up during a sync session. Also, clear the changelog as the objects are successfully synchronized. You can also use a boolean variable to confirm the synchronization status, i.e. last time of sync. It will be helpful for end users to identify the time when last sync is done.
Need to have a way to communicate from the server to the device to start a sync session as data changes on the server. You can use C2DM or write your own persistent tcp based communication. The tcp approach is a lot seamless
A way to replicate data changes across multiple devices
And last but not the least, a way to detect and handle conflicts
Hope this helps as a good starting point.
For System.Timers.Timer, on separate thread, if SynchronizingObject is not set.
static System.Timers.Timer DummyTimer = null;
static void Main(string[] args)
{
try
{
Console.WriteLine("Main Thread Id: " + System.Threading.Thread.CurrentThread.ManagedThreadId);
DummyTimer = new System.Timers.Timer(1000 * 5); // 5 sec interval
DummyTimer.Enabled = true;
DummyTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnDummyTimerFired);
DummyTimer.AutoReset = true;
DummyTimer.Start();
Console.WriteLine("Hit any key to exit");
Console.ReadLine();
}
catch (Exception Ex)
{
Console.WriteLine(Ex.Message);
}
return;
}
static void OnDummyTimerFired(object Sender, System.Timers.ElapsedEventArgs e)
{
Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);
return;
}
Output you'd see if DummyTimer fired on 5 seconds interval:
Main Thread Id: 9
12
12
12
12
12
...
So, as seen, OnDummyTimerFired is executed on Workers thread.
No, further complication - If you reduce interval to say 10 ms,
Main Thread Id: 9
11
13
12
22
17
...
This is because if prev execution of OnDummyTimerFired isn't done when next tick is fired, then .NET would create a new thread to do this job.
Complicating things further, "The System.Timers.Timer class provides an easy way to deal with this dilemma—it exposes a public SynchronizingObject property. Setting this property to an instance of a Windows Form (or a control on a Windows Form) will ensure that the code in your Elapsed event handler runs on the same thread on which the SynchronizingObject was instantiated."
I agree with Ash, that should be fine. Alternatively you could use declarative CAS and actually prevent the program from running in the first place if they don't have access.
I believe some of the CAS features may not be present in C# 4.0 from what I've heard, not sure if that might be an issue or not.
The following worked for me on Windows.
git submodule init
git submodule update
I just ran into this issue when diffing my branch with master. Git returned one 'mode' error when I expected my branch to be identical to master. I fixed by deleting the file and then merging master in again.
First I ran the diff:
git checkout my-branch
git diff master
This returned:
diff --git a/bin/script.sh b/bin/script.sh
old mode 100755
new mode 100644
I then ran the following to fix:
rm bin/script.sh
git merge -X theirs master
After this, git diff
returned no differences between my-branch and master.
For shortened hex code like #fff or #000
int red = "colorString".charAt(1) == '0' ? 0 :
"colorString".charAt(1) == 'f' ? 255 : 228;
int green =
"colorString".charAt(2) == '0' ? 0 : "colorString".charAt(2) == 'f' ?
255 : 228;
int blue = "colorString".charAt(3) == '0' ? 0 :
"colorString".charAt(3) == 'f' ? 255 : 228;
Color.rgb(red, green,blue);
$('input').datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [ array.indexOf(string) == -1 ]
}
});
Split using a regular expression. Note I made the case more general with leading spaces. The list comprehension is to remove the null strings at the front and back.
>>> import re
>>> string = " blah, lots , of , spaces, here "
>>> pattern = re.compile("^\s+|\s*,\s*|\s+$")
>>> print([x for x in pattern.split(string) if x])
['blah', 'lots', 'of', 'spaces', 'here']
This works even if ^\s+
doesn't match:
>>> string = "foo, bar "
>>> print([x for x in pattern.split(string) if x])
['foo', 'bar']
>>>
Here's why you need ^\s+:
>>> pattern = re.compile("\s*,\s*|\s+$")
>>> print([x for x in pattern.split(string) if x])
[' blah', 'lots', 'of', 'spaces', 'here']
See the leading spaces in blah?
Clarification: above uses the Python 3 interpreter, but results are the same in Python 2.
My issue was due to what physical USB female port I plugged the Arduino cable into on my D-Link DUB-H7 (USB hub) on Windows 10. I had my Arduino plugged into one of the two ports way on the right (in the image below). The USB cable fit, and it powers the Arduino fine, but the Arduino wasn't seeing the port for some reason.
Windows does not recognize these two ports. Any of the other ports are fair game. In my case, the Tools > Port menu was grayed out. In this scenario, the "Ports" section in the object explorer was hidden. So to show the hidden devices, I chose View > show hidden. COM1 was what showed up originally. When I changed it to COM3, it didn't work.
There are many places where the COM port can be configured.
Windows > Control Panel > Device Manager > Ports > right click Arduino > Properties > Port Settings > Advanced > COM Port Number: [choose port]
Windows > Start Menu > Arduino > Tools > Ports > [choose port]
Windows > Start Menu > Arduino > File > Preferences > @ very bottom, there is a label named "More preferences can be edited directly in the file".
C:\Users{user name}\AppData\Local\Arduino15\preferences.txt
target_package = arduino
target_platform = avr
board = uno
software=ARDUINO
# Warn when data segment uses greater than this percentage
build.warn_data_percentage = 75
programmer = arduino:avrispmkii
upload.using = bootloader
upload.verify = true
serial.port=COM3
serial.databits=8
serial.stopbits=1
serial.parity=N
serial.debug_rate=9600
# I18 Preferences
# default chosen language (none for none)
editor.languages.current =
The user preferences.txt overrides this one:
C:\Users{user name}\Desktop\avrdude.conf
... search for "com" ... "com1" is the default
In more complicated build scenarios, it is common to break compilation into stages, with compilation and assembly happening first (output to object files), and linking object files into a final executable or library afterward--this prevents having to recompile all object files when their source files haven't changed. That's why including the linking flag -lm
isn't working when you put it in CFLAGS
(CFLAGS
is used in the compilation stage).
The convention for libraries to be linked is to place them in either LOADLIBES
or LDLIBS
(GNU make includes both, but your mileage may vary):
LDLIBS=-lm
This should allow you to continue using the built-in rules rather than having to write your own linking rule. For other makes, there should be a flag to output built-in rules (for GNU make, this is -p
). If your version of make does not have a built-in rule for linking (or if it does not have a placeholder for -l
directives), you'll need to write your own:
client.o: client.c
$(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c -o $@ $<
client: client.o
$(CC) $(LDFLAGS) $(TARGET_ARCH) $^ $(LOADLIBES) $(LDLIBS) -o $@
you have to git add css/mobile.css
the new file and git rm css/iphone.css
, so git knows about it. then it will show the same output in git status
you can see it clearly in the status output (the new name of the file):
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
and (the old name):
# Changed but not updated:
# (use "git add/rm <file>..." to update what will be committed)
i think behind the scenes git mv
is nothing more than a wrapper script which does exactly that: delete the file from the index and add it under a different name
I have created function to disable previous date, disable flexible weekend days (Like Saturday, Sunday)
We are using beforeShowDay method of jQuery UI datepicker plugin.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
var NotBeforeToday = function(date) {_x000D_
var now = new Date(); //this gets the current date and time_x000D_
if (date.getFullYear() == now.getFullYear() && date.getMonth() == now.getMonth() && date.getDate() >= now.getDate() && (date.getDay() > 0 && date.getDay() < 6) )_x000D_
return [true,""];_x000D_
if (date.getFullYear() >= now.getFullYear() && date.getMonth() > now.getMonth() && (date.getDay() > 0 && date.getDay() < 6))_x000D_
return [true,""];_x000D_
if (date.getFullYear() > now.getFullYear() && (date.getDay() > 0 && date.getDay() < 6))_x000D_
return [true,""];_x000D_
return [false,""];_x000D_
}_x000D_
_x000D_
_x000D_
jQuery("#datepicker").datepicker({_x000D_
beforeShowDay: NotBeforeToday_x000D_
});
_x000D_
Here today's date is 15th Sept. I have disabled Saturday and Sunday.
Playing with JavaScript in an HTA I had no luck with a driver={SQL Server};...
connection string, but a named DSN was OK :
I set up TestDSN and it tested OK, and then var strConn= "DSN=TestDSN";
worked, so I carried on experimenting for my in-house testing and learning purposes.
Our server has several instances running, e.g. server1\dev and server1\Test which made things slightly more tricky as I managed to waste some time forgetting to escape the \
as \\
:)
After some dead-ends with server=server1;instanceName=dev
in the connection strings, I eventually got this one to work :
var strConn= "Provider=SQLOLEDB;Data Source=server1\\dev;Trusted_Connection=Yes;Initial Catalog=MyDatabase;"
Using Windows credentials rather than supplying a user/pwd, I found an interesting diversion was discovering the subtleties of Integrated Security = true
v Integrated Security = SSPI
v Trusted_Connection=Yes
- see Difference between Integrated Security = True and Integrated Security = SSPI
Beware that RecordCount will come back as -1
if using the default adOpenForwardOnly type. If you're working with small result sets and/or don't mind the whole lot in memory at once, use rs.Open(strQuery, objConnection, 3);
(3=adOpenStatic) and this gives a valid rs.RecordCount
For example,
package main
import "fmt"
func main() {
type Map1 map[string]interface{}
type Map2 map[string]int
m := Map1{"foo": Map2{"first": 1}, "boo": Map2{"second": 2}}
//m = map[foo:map[first: 1] boo: map[second: 2]]
fmt.Println("m:", m)
for k, v := range m {
fmt.Println("k:", k, "v:", v)
}
}
Output:
m: map[boo:map[second:2] foo:map[first:1]]
k: boo v: map[second:2]
k: foo v: map[first:1]
Try doing this :
recipients="[email protected],[email protected],[email protected]"
And another approach, using shell here-doc :
/usr/sbin/sendmail "$recipients" <<EOF
subject:$subject
from:$from
Example Message
EOF
Be sure to separate the headers from the body with a blank line as per RFC 822.
Get a random number from 0 to 255, then convert it to hex:
function random_color_part() {
return str_pad( dechex( mt_rand( 0, 255 ) ), 2, '0', STR_PAD_LEFT);
}
function random_color() {
return random_color_part() . random_color_part() . random_color_part();
}
echo random_color();
names(x)[names(x) %in% c("q","e")]<-c("A","B")
Here is an applet where you can exercise some bit-operations, including shifting.
You have a collection of bits, and you move some of them beyond their bounds:
1111 1110 << 2
1111 1000
It is filled from the right with fresh zeros. :)
0001 1111 >> 3
0000 0011
Filled from the left. A special case is the leading 1. It often indicates a negative value - depending on the language and datatype. So often it is wanted, that if you shift right, the first bit stays as it is.
1100 1100 >> 1
1110 0110
And it is conserved over multiple shifts:
1100 1100 >> 2
1111 0011
If you don't want the first bit to be preserved, you use (in Java, Scala, C++, C as far as I know, and maybe more) a triple-sign-operator:
1100 1100 >>> 1
0110 0110
There isn't any equivalent in the other direction, because it doesn't make any sense - maybe in your very special context, but not in general.
Mathematically, a left-shift is a *=2, 2 left-shifts is a *=4 and so on. A right-shift is a /= 2 and so on.
wxLua has three sleep functions:
local wx = require 'wx'
wx.wxSleep(12) -- sleeps for 12 seconds
wx.wxMilliSleep(1200) -- sleeps for 1200 milliseconds
wx.wxMicroSleep(1200) -- sleeps for 1200 microseconds (if the system supports such resolution)
I've just stumbled over the same problem and found some interesting information and I wanted to put in my two cents and add it here.
First of all, as others have already mentioned, long-running operations should be done by a thread, which can be a background worker, an explicit thread, a thread from the threadpool or (since .Net 4.0) a task: Stackoverflow 570537: update-label-while-processing-in-windows-forms, so that the UI keeps responsive.
But for short tasks there is no real need for threading although it doesn't hurt of course.
I have created a winform with one button and one label to analyze this problem:
System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
label1->Text = "Start 1";
label1->Update();
System::Threading::Thread::Sleep(5000); // do other work
}
My analysis was stepping over the code (using F10) and seeing what happened. And after reading this article Multithreading in WinForms I have found something interesting. The article says at the bottom of the first page, that the UI thread can not repaint the UI until the currently executed function finishes and the window is marked by Windows as "not responding" instead after a while. I have also noticed that on my test application from above while stepping through it, but only in certain cases.
(For the following test it is important to not have Visual Studio set to fullscreen, you must be able to see your little application window at the same time next to it, You must not have to switch between the Visual Studio window for debugging and your application window to see what happens. Start the application, set a breakpoint at label1->Text ...
, put the application window beside the VS window and place the mouse cursor over the VS window.)
When I click once on VS after app start (to put the focues there and enable stepping) and step through it WITHOUT moving the mouse, the new text is set and the label is updated in the update() function. This means, the UI is repainted obviously.
When I step over the first line, then move the mouse around a lot and click somewhere, then step further, the new text is likely set and the update() function is called, but the UI is not updated/repainted and the old text remains there until the button1_click() function finishes. Instead of repainting, the window is marked as "not responsive"! It also doesn't help to add this->Update();
to update the whole form.
Adding Application::DoEvents();
gives the UI a chance to update/repaint. Anyway you have to take care that the user can not press buttons or perform other operations on the UI that are not permitted!! Therefore: Try to avoid DoEvents()!, better use threading (which I think is quite simple in .Net).
But (@Jagd, Apr 2 '10 at 19:25) you can omit .refresh()
and .invalidate()
.
My explanations is as following: AFAIK winform still uses the WINAPI function. Also MSDN article about System.Windows.Forms Control.Update method refers to WINAPI function WM_PAINT. The MSDN article about WM_PAINT states in its first sentence that the WM_PAINT command is only sent by the system when the message queue is empty. But as the message queue is already filled in the 2nd case, it is not send and thus the label and the application form are not repainted.
<>joke> Conclusion: so you just have to keep the user from using the mouse ;-) <>/joke>
None of these answers quite fit the problem i had as the migration i wanted to delete was missing:
I had created and run a migration in some other branch, which was then discarded. The problem is when a migration is run, rails adds the version into a schema_migrations
table in the database. So even if it isn't listed in your db structure or schema, rails looks for it.
You can reveal these orphaned migrations by running:
rails db:migrate:status
Note the versions of the missing migrations and head into the db console:
rails dbconsole
Now remove the versions from the migration table manually:
delete from schema_migrations where version='<version>';
You should now be good.
One important advantage of BFS would be that it can be used to find the shortest path between any two nodes in an unweighted graph. Whereas, we cannot use DFS for the same.
None of the above answers fixed this issue for me. I did it as following (Laravel with Ubuntu server):
<?php
$footerFile = '/var/www/website/main/resources/views/emails/elements/emailfooter.blade.php';
include($footerFile);
?>
In visual studio.
If no errors, you should be able to see the service reference in the object browser and all related methods.
If you want to get database encodings:
psql -U postgres -h somehost --list
You'll see something like:
List of databases
Name | Owner | Encoding
------------------------+----------+----------
db1 | postgres | UTF8
Here's how I did it...
public static ElementDefinitionImpl[] RemoveElementDefAt(
ElementDefinition[] oldList,
int removeIndex
)
{
ElementDefinitionImpl[] newElementDefList = new ElementDefinitionImpl[ oldList.Length - 1 ];
int offset = 0;
for ( int index = 0; index < oldList.Length; index++ )
{
ElementDefinitionImpl elementDef = oldList[ index ] as ElementDefinitionImpl;
if ( index == removeIndex )
{
// This is the one we want to remove, so we won't copy it. But
// every subsequent elementDef will by shifted down by one.
offset = -1;
}
else
{
newElementDefList[ index + offset ] = elementDef;
}
}
return newElementDefList;
}
check this link here i change display:inline-block http://cssdesk.com/gUGBH
If you're in a class inherited from UITableViewController
, then this is the swift version:
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let cell = self.tableView.cellForRowAtIndexPath(indexPath)
NSLog("did select and the text is \(cell?.textLabel?.text)")
}
Note that cell
is an optional, so it must be unwrapped - and the same for textLabel
. If any of the 2 is nil (unlikely to happen, because the method is called with a valid index path), if you want to be sure that a valid value is printed, then you should check that both cell
and textLabel
are both not nil:
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let cell = self.tableView.cellForRowAtIndexPath(indexPath)
let text = cell?.textLabel?.text
if let text = text {
NSLog("did select and the text is \(text)")
}
}
I'm rusty on SQL but I think you could use select as to make your own temporary query columns.
select field1, field2, 'example' as newfield from table1
That would only exist in your query results, of course. You're not actually modifying the table.
You can use event.key
function Input({onKeyPress}) {_x000D_
return (_x000D_
<div>_x000D_
<h2>Input</h2>_x000D_
<input type="text" onKeyPress={onKeyPress}/>_x000D_
</div>_x000D_
)_x000D_
}_x000D_
_x000D_
class Form extends React.Component {_x000D_
state = {value:""}_x000D_
_x000D_
handleKeyPress = (e) => {_x000D_
if (e.key === 'Enter') {_x000D_
this.setState({value:e.target.value})_x000D_
}_x000D_
}_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<section>_x000D_
<Input onKeyPress={this.handleKeyPress}/>_x000D_
<br/>_x000D_
<output>{this.state.value}</output>_x000D_
</section>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
<Form />,_x000D_
document.getElementById("react")_x000D_
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>_x000D_
<div id="react"></div>
_x000D_
Ids are meant to be unique, and never use an id that starts with a number, use data-attributes instead to set the target like so :
<div id="searchbycharacter">
<a class="searchbychar" href="#" data-target="numeric">0-9 |</a>
<a class="searchbychar" href="#" data-target="A"> A |</a>
<a class="searchbychar" href="#" data-target="B"> B |</a>
<a class="searchbychar" href="#" data-target="C"> C |</a>
... Untill Z
</div>
As for the jquery :
$(document).on('click','.searchbychar', function(event) {
event.preventDefault();
var target = "#" + this.getAttribute('data-target');
$('html, body').animate({
scrollTop: $(target).offset().top
}, 2000);
});
To access the first and last elements, try.
var nodes = div.querySelectorAll('[move_id]');
var first = nodes[0];
var last = nodes[nodes.length- 1];
For robustness, add index checks.
Yes, the order of nodes is pre-order depth-first. DOM's document order
is defined as,
There is an ordering, document order, defined on all the nodes in the document corresponding to the order in which the first character of the XML representation of each node occurs in the XML representation of the document after expansion of general entities. Thus, the document element node will be the first node. Element nodes occur before their children. Thus, document order orders element nodes in order of the occurrence of their start-tag in the XML (after expansion of entities). The attribute nodes of an element occur after the element and before its children. The relative order of attribute nodes is implementation-dependent.
There is no such thing as array constant in Go.
Quoting from the Go Language Specification: Constants:
There are boolean constants, rune constants, integer constants, floating-point constants, complex constants, and string constants. Rune, integer, floating-point, and complex constants are collectively called numeric constants.
A Constant expression (which is used to initialize a constant) may contain only constant operands and are evaluated at compile time.
The specification lists the different types of constants. Note that you can create and initialize constants with constant expressions of types having one of the allowed types as the underlying type. For example this is valid:
func main() {
type Myint int
const i1 Myint = 1
const i2 = Myint(2)
fmt.Printf("%T %v\n", i1, i1)
fmt.Printf("%T %v\n", i2, i2)
}
Output (try it on the Go Playground):
main.Myint 1
main.Myint 2
If you need an array, it can only be a variable, but not a constant.
I recommend this great blog article about constants: Constants
On Ubuntu you can try this command.
sudo npm cache clean -f
sudo npm install -g n
sudo n stable
Specific version : sudo n 8.11.3 instead of sudo n stable
Another workaround is using the good old scp
. This is useful in the case you need to copy a directory.
From your host run:
scp FILE_PATH_ON_YOUR_HOST IP_CONTAINER:DESTINATION_PATH
scp foo.txt 172.17.0.2:foo.txt
In the case you need to copy a directory:
scp -r DIR_PATH_ON_YOUR_HOST IP_CONTAINER:DESTINATION_PATH
scp -r directory 172.17.0.2:directory
be sure to install ssh into your container too.
apt-get install openssh-server
This could be done with DOM4 MutationObservers
but will only work in Firefox 14+/Chrome 18+ (for now).
However there is an "epic hack" (author's words not mine!) that works in all browsers that support CSS3 animations which are: IE10, Firefox 5+, Chrome 3+, Opera 12, Android 2.0+, Safari 4+. See the demo from the blog. The hack is to use a CSS3 animation event with a given name that is observed and acted upon in JavaScript.
You can use standard JS toFixed
method
var num = 5.56789;
var n=num.toFixed(2);
//5.57
In order to add commas (to separate 1000's) you can add regexp as follows (where num
is a number):
num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000
Complete example:
var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
//document.write(num) would write value as follows: $1,250.22
Separation character depends on country and locale. For some countries it may need to be .
You can Change it from:
Menu Settings -> Style Configurator
See on screenshot:
I prefer to use <script>console.log({$varname|@json_encode})</script>
to log to the console.
Seems the easiest method is simply to use the Replace method that ships with .Net and has been around since .Net 1.0:
string res = Microsoft.VisualBasic.Strings.Replace(res,
"%PolicyAmount%",
"$0",
Compare: Microsoft.VisualBasic.CompareMethod.Text);
In order to use this method, you have to add a Reference to the Microsoft.VisualBasic assemblly. This assembly is a standard part of the .Net runtime, it is not an extra download or marked as obsolete.
how about some live data callback,
class ProfileView{
private val _profileViewClicked = MutableLiveData<ProfileView>()
val profileViewClicked: LiveData<ProfileView> = _profileViewClicked
}
class ProfileActivity{
override fun onCreateView(...){
profileViewClicked.observe(viewLifecycleOwner, Observer {
activityMethod()
})
}
}
You can use skywind3000/asyncrun.vim as well. It is similar to what @FocusedWolf has listed.
For Rails 4, see this answer.
For Rails 3.x, configure a logger in config/environments/test.rb
:
config.logger = Logger.new(STDOUT)
config.logger.level = Logger::ERROR
This will interleave any errors that are logged during testing to STDOUT. You may wish to route the output to STDERR or use a different log level instead.
Sending these messages to both the console and a log file requires something more robust than Ruby's built-in Logger class. The logging gem will do what you want. Add it to your Gemfile
, then set up two appenders in config/environments/test.rb
:
logger = Logging.logger['test']
logger.add_appenders(
Logging.appenders.stdout,
Logging.appenders.file('example.log')
)
logger.level = :info
config.logger = logger
Since your JPA repository name is UserBoardRepository, your custom Interface name should be UserBoardRepositoryCustom (it should end with 'Custom') and your implementation class name should be UserBoardRepositoryImpl (should end with Impl; you can set it with a different postfix using the repository-impl-postfix property)