public static void main(String[] args) {
int[] arr1 = {2,4,6,8,10,999};
int[] arr2 = {1,3,5,9,100,1001};
int[] arr3 = new int[arr1.length + arr2.length];
int temp = 0;
for (int i = 0; i < (arr3.length); i++) {
if(temp == arr2.length){
arr3[i] = arr1[i-temp];
}
else if (((i-temp)<(arr1.length)) && (arr1[i-temp] < arr2[temp])){
arr3[i] = arr1[i-temp];
}
else{
arr3[i] = arr2[temp];
temp++;
}
}
for (int i : arr3) {
System.out.print(i + ", ");
}
}
Output is :
1, 2, 3, 4, 5, 6, 8, 9, 10, 100, 999, 1001,
def merge(l1, l2, out=[]):
if l1==[]: return out+l2
if l2==[]: return out+l1
if l1[0]<l2[0]: return merge(l1[1:], l2, out+l1[0:1])
return merge(l1, l2[1:], out+l2[0:1])
def merge_sort(l): return (lambda h: l if h<1 else merge(merge_sort(l[:h]), merge_sort(l[h:])))(len(l)/2)
print(merge_sort([1,4,6,3,2,5,78,4,2,1,4,6,8]))
Quick sort is worst case O(n^2), however, the average case consistently out performs merge sort. Each algorithm is O(nlogn), but you need to remember that when talking about Big O we leave off the lower complexity factors. Quick sort has significant improvements over merge sort when it comes to constant factors.
Merge sort also requires O(2n) memory, while quick sort can be done in place (requiring only O(n)). This is another reason that quick sort is generally preferred over merge sort.
Extra info:
The worst case of quick sort occurs when the pivot is poorly chosen. Consider the following example:
[5, 4, 3, 2, 1]
If the pivot is chosen as the smallest or largest number in the group then quick sort will run in O(n^2). The probability of choosing the element that is in the largest or smallest 25% of the list is 0.5. That gives the algorithm a 0.5 chance of being a good pivot. If we employ a typical pivot choosing algorithm (say choosing a random element), we have 0.5 chance of choosing a good pivot for every choice of a pivot. For collections of a large size the probability of always choosing a poor pivot is 0.5 * n. Based on this probability quick sort is efficient for the average (and typical) case.
#define SWAP(type, a, b) \
do { type t=(a);(a)=(b);(b)=t; } while (0)
static void reverse_(int* a, int* b)
{
for ( --b; a < b; a++, b-- )
SWAP(int, *a, *b);
}
static int* rotate_(int* a, int* b, int* c)
/* swap the sequence [a,b) with [b,c). */
{
if (a != b && b != c)
{
reverse_(a, b);
reverse_(b, c);
reverse_(a, c);
}
return a + (c - b);
}
static int* lower_bound_(int* a, int* b, const int key)
/* find first element not less than @p key in sorted sequence or end of
* sequence (@p b) if not found. */
{
int i;
for ( i = b-a; i != 0; i /= 2 )
{
int* mid = a + i/2;
if (*mid < key)
a = mid + 1, i--;
}
return a;
}
static int* upper_bound_(int* a, int* b, const int key)
/* find first element greater than @p key in sorted sequence or end of
* sequence (@p b) if not found. */
{
int i;
for ( i = b-a; i != 0; i /= 2 )
{
int* mid = a + i/2;
if (*mid <= key)
a = mid + 1, i--;
}
return a;
}
static void ip_merge_(int* a, int* b, int* c)
/* inplace merge. */
{
int n1 = b - a;
int n2 = c - b;
if (n1 == 0 || n2 == 0)
return;
if (n1 == 1 && n2 == 1)
{
if (*b < *a)
SWAP(int, *a, *b);
}
else
{
int* p, * q;
if (n1 <= n2)
p = upper_bound_(a, b, *(q = b+n2/2));
else
q = lower_bound_(b, c, *(p = a+n1/2));
b = rotate_(p, b, q);
ip_merge_(a, p, b);
ip_merge_(b, q, c);
}
}
void mergesort(int* v, int n)
{
if (n > 1)
{
int h = n/2;
mergesort(v, h); mergesort(v+h, n-h);
ip_merge_(v, v+h, v+n);
}
}
Adds support code and modifications to accelerate the merge when an auxiliary buffer of any size is available (still works without additional memory). Uses forward and backward merging, ring rotation, small sequence merging and sorting, and iterative mergesort.
#include <stdlib.h>
#include <string.h>
static int* copy_(const int* a, const int* b, int* out)
{
int count = b - a;
if (a != out)
memcpy(out, a, count*sizeof(int));
return out + count;
}
static int* copy_backward_(const int* a, const int* b, int* out)
{
int count = b - a;
if (b != out)
memmove(out - count, a, count*sizeof(int));
return out - count;
}
static int* merge_(const int* a1, const int* b1, const int* a2,
const int* b2, int* out)
{
while ( a1 != b1 && a2 != b2 )
*out++ = (*a1 <= *a2) ? *a1++ : *a2++;
return copy_(a2, b2, copy_(a1, b1, out));
}
static int* merge_backward_(const int* a1, const int* b1,
const int* a2, const int* b2, int* out)
{
while ( a1 != b1 && a2 != b2 )
*--out = (*(b1-1) > *(b2-1)) ? *--b1 : *--b2;
return copy_backward_(a1, b1, copy_backward_(a2, b2, out));
}
static unsigned int gcd_(unsigned int m, unsigned int n)
{
while ( n != 0 )
{
unsigned int t = m % n;
m = n;
n = t;
}
return m;
}
static void rotate_inner_(const int length, const int stride,
int* first, int* last)
{
int* p, * next = first, x = *first;
while ( 1 )
{
p = next;
if ((next += stride) >= last)
next -= length;
if (next == first)
break;
*p = *next;
}
*p = x;
}
static int* rotate_(int* a, int* b, int* c)
/* swap the sequence [a,b) with [b,c). */
{
if (a != b && b != c)
{
int n1 = c - a;
int n2 = b - a;
int* i = a;
int* j = a + gcd_(n1, n2);
for ( ; i != j; i++ )
rotate_inner_(n1, n2, i, c);
}
return a + (c - b);
}
static void ip_merge_small_(int* a, int* b, int* c)
/* inplace merge.
* @note faster for small sequences. */
{
while ( a != b && b != c )
if (*a <= *b)
a++;
else
{
int* p = b+1;
while ( p != c && *p < *a )
p++;
rotate_(a, b, p);
b = p;
}
}
static void ip_merge_(int* a, int* b, int* c, int* t, const int ts)
/* inplace merge.
* @note works with or without additional memory. */
{
int n1 = b - a;
int n2 = c - b;
if (n1 <= n2 && n1 <= ts)
{
merge_(t, copy_(a, b, t), b, c, a);
}
else if (n2 <= ts)
{
merge_backward_(a, b, t, copy_(b, c, t), c);
}
/* merge without buffer. */
else if (n1 + n2 < 48)
{
ip_merge_small_(a, b, c);
}
else
{
int* p, * q;
if (n1 <= n2)
p = upper_bound_(a, b, *(q = b+n2/2));
else
q = lower_bound_(b, c, *(p = a+n1/2));
b = rotate_(p, b, q);
ip_merge_(a, p, b, t, ts);
ip_merge_(b, q, c, t, ts);
}
}
static void ip_merge_chunk_(const int cs, int* a, int* b, int* t,
const int ts)
{
int* p = a + cs*2;
for ( ; p <= b; a = p, p += cs*2 )
ip_merge_(a, a+cs, p, t, ts);
if (a+cs < b)
ip_merge_(a, a+cs, b, t, ts);
}
static void smallsort_(int* a, int* b)
/* insertion sort.
* @note any stable sort with low setup cost will do. */
{
int* p, * q;
for ( p = a+1; p < b; p++ )
{
int x = *p;
for ( q = p; a < q && x < *(q-1); q-- )
*q = *(q-1);
*q = x;
}
}
static void smallsort_chunk_(const int cs, int* a, int* b)
{
int* p = a + cs;
for ( ; p <= b; a = p, p += cs )
smallsort_(a, p);
smallsort_(a, b);
}
static void mergesort_lower_(int* v, int n, int* t, const int ts)
{
int cs = 16;
smallsort_chunk_(cs, v, v+n);
for ( ; cs < n; cs *= 2 )
ip_merge_chunk_(cs, v, v+n, t, ts);
}
static void* get_buffer_(int size, int* final)
{
void* p = NULL;
while ( size != 0 && (p = malloc(size)) == NULL )
size /= 2;
*final = size;
return p;
}
void mergesort(int* v, int n)
{
/* @note buffer size may be in the range [0,(n+1)/2]. */
int request = (n+1)/2 * sizeof(int);
int actual;
int* t = (int*) get_buffer_(request, &actual);
/* @note allocation failure okay. */
int tsize = actual / sizeof(int);
mergesort_lower_(v, n, t, tsize);
free(t);
}
I know that this is a very old post but just wanted to say that using flexbox on a parent element would disable margin collapsing for its child elements.
Note that usage of a SerialPort.DataReceived
event is optional. You can set proper timeout using SerialPort.ReadTimeout
and continuously call SerialPort.Read()
after you wrote something to a port until you get a full response.
Moreover you can use SerialPort.BaseStream
property to extract an underlying Stream
instance. The benefit of using a Stream
is that you can easily utilize various decorators with it:
var port = new SerialPort();
// LoggingStream inherits Stream, implements IDisposable, needen abstract methods and
// overrides needen virtual methods.
Stream portStream = new LoggingStream(port.BaseStream);
portStream.Write(...); // Logs write buffer.
portStream.Read(...); // Logs read buffer.
For more information check:
You can use coalesce(column_name,0)
instead of just column_name
. The coalesce
function returns the first non-NULL value in the list.
I should mention that per-row functions like this are usually problematic for scalability. If you think your database may get to be a decent size, it's often better to use extra columns and triggers to move the cost from the select
to the insert/update
.
This amortises the cost assuming your database is read more often than written (and most of them are).
There is a list of Sqlite wrappers for .Net at http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers. From what I've heard http://sqlite.phxsoftware.com/ is quite good. This particular one lets you access Sqlite through ADO.Net just like any other database.
/*To get duplicate data in table */
SELECT COUNT(EmpCode),EmpCode FROM tbl_Employees WHERE Status=1
GROUP BY EmpCode HAVING COUNT(EmpCode) > 1
If you're using MySQL you can log the queries using MySQL's query log. I don't know if other vendors provide this feature, but chances are they do.
I think this statement might do what you want.
INSERT INTO newTableName (SELECT column1, column2, column3 FROM oldTable);
You can't delete objects, they are removed when there are no more references to them. You can delete references with delete
.
However, if you have created circular references in your objects you may have to de-couple some things.
C style, simple ring buffer for integers. First use init than use put and get. If buffer does not contain any data it returns "0" zero.
//=====================================
// ring buffer address based
//=====================================
#define cRingBufCount 512
int sRingBuf[cRingBufCount]; // Ring Buffer
int sRingBufPut; // Input index address
int sRingBufGet; // Output index address
Bool sRingOverWrite;
void GetRingBufCount(void)
{
int r;
` r= sRingBufPut - sRingBufGet;
if ( r < cRingBufCount ) r+= cRingBufCount;
return r;
}
void InitRingBuffer(void)
{
sRingBufPut= 0;
sRingBufGet= 0;
}
void PutRingBuffer(int d)
{
sRingBuffer[sRingBufPut]= d;
if (sRingBufPut==sRingBufGet)// both address are like ziro
{
sRingBufPut= IncRingBufferPointer(sRingBufPut);
sRingBufGet= IncRingBufferPointer(sRingBufGet);
}
else //Put over write a data
{
sRingBufPut= IncRingBufferPointer(sRingBufPut);
if (sRingBufPut==sRingBufGet)
{
sRingOverWrite= Ture;
sRingBufGet= IncRingBufferPointer(sRingBufGet);
}
}
}
int GetRingBuffer(void)
{
int r;
if (sRingBufGet==sRingBufPut) return 0;
r= sRingBuf[sRingBufGet];
sRingBufGet= IncRingBufferPointer(sRingBufGet);
sRingOverWrite=False;
return r;
}
int IncRingBufferPointer(int a)
{
a+= 1;
if (a>= cRingBufCount) a= 0;
return a;
}
You can do this in Javascript
.
var time = new Date();
console.log(time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds());
At present it returns 15:5:18
. Note that if any of the values are less than 10, they will display using only one digit, not two.
Check this in JSFiddle
Updates:
For prefixed 0's try
var time = new Date();
console.log(
("0" + time.getHours()).slice(-2) + ":" +
("0" + time.getMinutes()).slice(-2) + ":" +
("0" + time.getSeconds()).slice(-2));
For me when I run git clone, Git will store the cloned package in the directory that I am running the command from.
- I use windows.
for example :
C:\Users\user>git clone https://github.com/broosaction/aria
will create a folder:
C:\Users\user\aria
The accepted answer only shows files in the current directory's tree. To show all of the tracked files that have been committed (on the current branch), use
git ls-tree --full-tree --name-only -r HEAD
--full-tree
makes the command run as if you were in the repo's root directory.-r
recurses into subdirectories. Combined with --full-tree
, this gives you all committed, tracked files.--name-only
removes SHA / permission info for when you just want the file paths.HEAD
specifies which branch you want the list of tracked, committed files for. You could change this to master
or any other branch name, but HEAD
is the commit you have checked out right now.This is the method from the accepted answer to the ~duplicate question https://stackoverflow.com/a/8533413/4880003.
GUID is Microsoft's implementation of the UUID standard.
Per Wikipedia:
The term GUID usually refers to Microsoft's implementation of the Universally Unique Identifier (UUID) standard.
An updated quote from that same Wikipedia article:
RFC 4122 itself states that UUIDs "are also known as GUIDs". All this suggests that "GUID", while originally referring to a variant of UUID used by Microsoft, has become simply an alternative name for UUID…
Since you are working in currency why not simply do this:
Console.Writeline("Earnings this week: {0:c}", answer);
This will format answer as currency, so on my machine (UK) it will come out as:
Earnings this week: £209.00
You can use annotate your method with @Scheduled(cron ="0 1 1 * * ?")
.
0 - is for seconds
1- 1 minute
1 - hour of the day.
If it's not a local application powered by JavaScript with full access permissions, you can't get the size of any file just from the path name. Web pages running javascript do not have access to the local filesystem for security reasons.
You can use a graceful degrading file uploader like SWFUpload if you want to show a progress bar. HTML5 also has the File API, but that is not widely supported just yet. If a user selects the file for an input[type=file]
element, you can get details about the file from the files
collection:
alert(myInp.files[0].size);
In addition to axtavt's answer, don't forget you can inject Entity Manager in your custom implementation if you need it to build your queries:
public class AccountRepositoryImpl implements AccountRepositoryCustom {
@PersistenceContext
private EntityManager em;
public void customMethod() {
...
em.createQuery(yourCriteria);
...
}
}
I use the plugin Chrome extension works pretty well:
[https://userstyles.org/styles/157357/jupyter-notebook-wide][1]
Check https://github.com/mmin18/FlexLayout which you can use percent or java expression directly in layout xml.
<EditText
app:layout_left="0%"
app:layout_right="60%"
app:layout_height="wrap_content"/>
<EditText
app:layout_left="prev.right+10dp"
app:layout_right="100%"
app:layout_height="wrap_content"/>
Password Strength Algorithm:
Password Length:
5 Points: Less than 4 characters
10 Points: 5 to 7 characters
25 Points: 8 or more
Letters:
0 Points: No letters
10 Points: Letters are all lower case
20 Points: Letters are upper case and lower case
Numbers:
0 Points: No numbers
10 Points: 1 number
20 Points: 3 or more numbers
Characters:
0 Points: No characters
10 Points: 1 character
25 Points: More than 1 character
Bonus:
2 Points: Letters and numbers
3 Points: Letters, numbers, and characters
5 Points: Mixed case letters, numbers, and characters
Password Text Range:
>= 90: Very Secure
>= 80: Secure
>= 70: Very Strong
>= 60: Strong
>= 50: Average
>= 25: Weak
>= 0: Very Weak
Settings Toggle to true or false, if you want to change what is checked in the password
var m_strUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var m_strLowerCase = "abcdefghijklmnopqrstuvwxyz";
var m_strNumber = "0123456789";
var m_strCharacters = "!@#$%^&*?_~"
Check password
function checkPassword(strPassword)
{
// Reset combination count
var nScore = 0;
// Password length
// -- Less than 4 characters
if (strPassword.length < 5)
{
nScore += 5;
}
// -- 5 to 7 characters
else if (strPassword.length > 4 && strPassword.length < 8)
{
nScore += 10;
}
// -- 8 or more
else if (strPassword.length > 7)
{
nScore += 25;
}
// Letters
var nUpperCount = countContain(strPassword, m_strUpperCase);
var nLowerCount = countContain(strPassword, m_strLowerCase);
var nLowerUpperCount = nUpperCount + nLowerCount;
// -- Letters are all lower case
if (nUpperCount == 0 && nLowerCount != 0)
{
nScore += 10;
}
// -- Letters are upper case and lower case
else if (nUpperCount != 0 && nLowerCount != 0)
{
nScore += 20;
}
// Numbers
var nNumberCount = countContain(strPassword, m_strNumber);
// -- 1 number
if (nNumberCount == 1)
{
nScore += 10;
}
// -- 3 or more numbers
if (nNumberCount >= 3)
{
nScore += 20;
}
// Characters
var nCharacterCount = countContain(strPassword, m_strCharacters);
// -- 1 character
if (nCharacterCount == 1)
{
nScore += 10;
}
// -- More than 1 character
if (nCharacterCount > 1)
{
nScore += 25;
}
// Bonus
// -- Letters and numbers
if (nNumberCount != 0 && nLowerUpperCount != 0)
{
nScore += 2;
}
// -- Letters, numbers, and characters
if (nNumberCount != 0 && nLowerUpperCount != 0 && nCharacterCount != 0)
{
nScore += 3;
}
// -- Mixed case letters, numbers, and characters
if (nNumberCount != 0 && nUpperCount != 0 && nLowerCount != 0 && nCharacterCount != 0)
{
nScore += 5;
}
return nScore;
}
// Runs password through check and then updates GUI
function runPassword(strPassword, strFieldID)
{
// Check password
var nScore = checkPassword(strPassword);
// Get controls
var ctlBar = document.getElementById(strFieldID + "_bar");
var ctlText = document.getElementById(strFieldID + "_text");
if (!ctlBar || !ctlText)
return;
// Set new width
ctlBar.style.width = (nScore*1.25>100)?100:nScore*1.25 + "%";
// Color and text
// -- Very Secure
/*if (nScore >= 90)
{
var strText = "Very Secure";
var strColor = "#0ca908";
}
// -- Secure
else if (nScore >= 80)
{
var strText = "Secure";
vstrColor = "#7ff67c";
}
// -- Very Strong
else
*/
if (nScore >= 80)
{
var strText = "Very Strong";
var strColor = "#008000";
}
// -- Strong
else if (nScore >= 60)
{
var strText = "Strong";
var strColor = "#006000";
}
// -- Average
else if (nScore >= 40)
{
var strText = "Average";
var strColor = "#e3cb00";
}
// -- Weak
else if (nScore >= 20)
{
var strText = "Weak";
var strColor = "#Fe3d1a";
}
// -- Very Weak
else
{
var strText = "Very Weak";
var strColor = "#e71a1a";
}
if(strPassword.length == 0)
{
ctlBar.style.backgroundColor = "";
ctlText.innerHTML = "";
}
else
{
ctlBar.style.backgroundColor = strColor;
ctlText.innerHTML = strText;
}
}
// Checks a string for a list of characters
function countContain(strPassword, strCheck)
{
// Declare variables
var nCount = 0;
for (i = 0; i < strPassword.length; i++)
{
if (strCheck.indexOf(strPassword.charAt(i)) > -1)
{
nCount++;
}
}
return nCount;
}
You can customize by yourself according to your requirement.
To keep the accordion nature intact when wanting to also use 'hide' and 'show' functions like .collapse( 'hide' )
, you must initialize the collapsible panels with the parent property set in the object with toggle: false
before making any calls to 'hide' or 'show'
// initialize collapsible panels
$('#accordion .collapse').collapse({
toggle: false,
parent: '#accordion'
});
// show panel one (will collapse others in accordion)
$( '#collapseOne' ).collapse( 'show' );
// show panel two (will collapse others in accordion)
$( '#collapseTwo' ).collapse( 'show' );
// hide panel two (will not collapse/expand others in accordion)
$( '#collapseTwo' ).collapse( 'hide' );
The easiest answer is to just use the cors package.
const cors = require('cors');
const app = require('express')();
app.use(cors());
That will enable CORS across the board. If you want to learn how to enable CORS without outside modules, all you really need is some Express middleware that sets the 'Access-Control-Allow-Origin' header. That's the minimum you need to allow cross-request domains from a browser to your server.
app.options('*', (req, res) => {
res.set('Access-Control-Allow-Origin', '*');
res.send('ok');
});
app.use((req, res) => {
res.set('Access-Control-Allow-Origin', '*');
});
Surely have a mutex-wrapped variable initialised to false
, that the thread sets to true
as the last thing it does before exiting. Is that atomic enough for your needs?
Having 2 elements with the same ID is not valid html according to the W3C specification.
When your CSS selector only has an ID selector (and is not used on a specific context), jQuery uses the native document.getElementById
method, which returns only the first element with that ID.
However, in the other two instances, jQuery relies on the Sizzle selector engine (or querySelectorAll
, if available), which apparently selects both elements. Results may vary on a per browser basis.
However, you should never have two elements on the same page with the same ID. If you need it for your CSS, use a class instead.
If you absolutely must select by duplicate ID, use an attribute selector:
$('[id="a"]');
Take a look at the fiddle: http://jsfiddle.net/P2j3f/2/
Note: if possible, you should qualify that selector with a tag selector, like this:
$('span[id="a"]');
You could also check if the required certificates are installed to make sure that it allows the dependencies to be downloaded.
As I notice The application could not be verified. raise up because in your device there is already an app installed with the same bundle identifier.
I got this issue because in my device there is my app that download from App store. and i test its update Version from Xcode. And i used same identifier that is live app and my development testing app. So i just remove app-store Live app from my device and this error going to be fix.
2017 update: Object.values, lodash values and toArray do it. And to preserve keys map and spread operator play nice:
// import { toArray, map } from 'lodash'_x000D_
const map = _.map_x000D_
_x000D_
const input = {_x000D_
key: {_x000D_
value: 'value'_x000D_
}_x000D_
}_x000D_
_x000D_
const output = map(input, (value, key) => ({_x000D_
key,_x000D_
...value_x000D_
}))_x000D_
_x000D_
console.log(output)_x000D_
// >> [{key: 'key', value: 'value'}])
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
_x000D_
Some might encounter this error (I got it while implementing PHP-MySQLi-JSON-Google Chart Example):
You called the draw() method with the wrong type of data rather than a DataTable or DataView.
The solution would be: replace jsapi and just use loader.js with:
google.charts.load('current', {packages: ['corechart']}) and
google.charts.setOnLoadCallback
-- according to the release notes --> The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.
&& and || were on the list of things to implement (still are) but did not pop up as the next most useful thing to add. The reason is that we have -AND and -OR. If you think it is important, please file a suggestion on Connect and we'll consider it for V3.
Duplicate your table into a table to be archived:
SELECT * INTO ArchiveTable FROM MyTable
Delete all entries in your table:
DELETE * FROM MyTable
I use backgroundrb.
http://backgroundrb.rubyforge.org/
I use it to run scheduled tasks as well as tasks that take too long for the normal client/server relationship.
template <class outType, class inType>
outType safe_cast(inType pointer)
{
void* temp = static_cast<void*>(pointer);
return static_cast<outType>(temp);
}
I tried to conclude and wrote a simple safe cast using templates. Note that this solution doesn't guarantee to cast pointers on a functions.
In IntelliJ 2017.2.4 I just closed the project and reopened it and I got a dialog asking me if I wanted to link with build.gradle which opened up the import dialog for Gradle projects.
No need to delete any files or add the idea plugin to build.gradle.
I tried a lot of ways and functions that suggested above, but they didn't work in my project. Anyway I have found solution and here it is:
try {
InputStream path = this.getClass().getClassLoader().getResourceAsStream("img/left-hand.png");
img = ImageIO.read(path);
} catch (IOException e) {
e.printStackTrace();
}
tul,
.getClass().getResource(fileName)
it considers the
location of the fileName is the same location of the of the calling
class..getClass().getClassLoader().getResource(fileName)
it
considers the location of the fileName is the root - in other words
bin
folder.Source :
package Sound;
public class ResourceTest {
public static void main(String[] args) {
String fileName = "Kalimba.mp3";
System.out.println(fileName);
System.out.println(new ResourceTest().getClass().getResource(fileName));
System.out.println(new ResourceTest().getClass().getClassLoader().getResource(fileName));
}
}
Output :
Kalimba.mp3
file:/C:/Users/User/Workspaces/MyEclipse%208.5/JMplayer/bin/Sound/Kalimba.mp3
file:/C:/Users/User/Workspaces/MyEclipse%208.5/JMplayer/bin/Kalimba.mp3
Can be done using the id of the element
example
<label><input type="radio" name="travel_mode" value="Flight" id="Flight"> Flight </label>
<label><input type="radio" name="travel_mode" value="Train" id="Train"> Train </label>
<label><input type="radio" name="travel_mode" value="Bus" id="Bus"> Bus </label>
<label><input type="radio" name="travel_mode" value="Road" id="Road"> Other </label>
js:
$('#' + selected).prop('checked',true);
UPDATE table
SET A = IF(A > 0 AND A < 1, 1, IF(A > 1 AND A < 2, 2, A))
WHERE A IS NOT NULL;
you might want to use CEIL()
if A
is always a floating point value > 0
and <= 2
I have posted this as a separate answer as it is unrelated to my existing answer.
This issue recently cropped up again for accessing a parent from an iframe referencing a subdomain and the existing fixes did not work.
This time the answer was to modify the document.domain of the parent page and the iframe to be the same. This will fool the same origin policy checks into thinking they co-exist on exactly the same domain (subdomains are considered a different host and fail the same origin policy check).
Insert the following to the <head>
of the page in the iframe to match the parent domain (adjust for your doctype).
<script>
document.domain = "mydomain.com";
</script>
Please note that this will throw an error on localhost development, so use a check like the following to avoid the error:
if (!window.location.href.match(/localhost/gi)) {
document.domain = "mydomain.com";
}
This obviously does not work if the blank lines contain tabs or blanks. Many web pages (e.g. http://www.guardian.co.uk/) contain these white lines, as a result of a faulty HTML editor.
Remove white space using regular expression as follows:
change pattern: [\t ]+$ into nothing.
where [\t ] matches either tab or space. '+' matches one or more occurrences, and '$' marks the end of line.
Then use notepad++/textFX to remove single or extra empty lines. Be sure that these blank lines are not significant in the given context.
Found my solution thanks to Error with .htaccess and mod_rewrite
For Apache 2.4 and in all *.conf files (e.g. httpd-vhosts.conf, http.conf, httpd-autoindex.conf ..etc) use
Require all granted
instead of
Order allow,deny
Allow from all
The Order and Allow directives are deprecated in Apache 2.4.
This error happens because the local repository can't identify the remote branch at first time. So you need to do it first. It can be done using following commands:
git remote add origin 'url_of_your_github_project'
git push -u origin master
You can use:
CurrentDb.Execute "ALTER TABLE yourTable ALTER COLUMN myID COUNTER(1,1)"
I hope you have no relationships that use this table, I hope it is empty, and I hope you understand that all you can (mostly) rely on an autonumber to be is unique. You can get gaps, jumps, very large or even negative numbers, depending on the circumstances. If your autonumber means something, you have a major problem waiting to happen.
Hmm... what's different this time? http://jsfiddle.net/fdsaP/2/
Renders in Chrome fine. Do you need it cross-browser? It really helps being specific.
EDIT: Youtube renders the object
and embed
with no explicit wmode set, meaning it defaults to "window" which means it overlays everything. You need to either:
a) Host the page that contains the object/embed code yourself and add wmode="transparent" param element to object and attribute to embed if you choose to serve both elements
b) Find a way for youtube to specify those.
I know this is old and answered, but here is another way to do it. Particularly if you don't want the UTF8 BOM at the start of your string and you want the text indented:
using (var ms = new MemoryStream())
using (var x = new XmlTextWriter(ms, new UTF8Encoding(false))
{ Formatting = Formatting.Indented })
{
// ...
return Encoding.UTF8.GetString(ms.ToArray());
}
If you are using Java 7, Files (in the standard library) is the best approach:
/* You can get Path from file also: file.toPath() */
Files.copy(InputStream in, Path target)
Files.copy(Path source, OutputStream out)
Edit: Of course it's just useful when you create one of InputStream or OutputStream from file. Use file.toPath()
to get path from file.
To write into an existing file (e.g. one created with File.createTempFile()
), you'll need to pass the REPLACE_EXISTING
copy option (otherwise FileAlreadyExistsException
is thrown):
Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING)
Split is slow, but not as slow as Scanner. StringTokenizer is faster than split. However, I found that I could obtain double the speed, by trading some flexibility, to get a speed-boost, which I did at JFastParser https://github.com/hughperkins/jfastparser
Testing on a string containing one million doubles:
Scanner: 10642 ms
Split: 715 ms
StringTokenizer: 544ms
JFastParser: 290ms
I tried with an alternate method:
Hit F12 key Then, at right hand side in the drop down menu, select internet explorer version 9.
That's it and it worked for me.
All commands must be executed while connected to the right database in the right database cluster. Make sure of it.
The user needs access to the database, obviously:
GRANT CONNECT ON DATABASE my_db TO my_user;
And (at least) the USAGE
privilege on the schema:
GRANT USAGE ON SCHEMA public TO my_user;
Or grant USAGE
on all custom schemas:
DO
$$
BEGIN
-- RAISE NOTICE '%', ( -- use instead of EXECUTE to see generated commands
EXECUTE (
SELECT string_agg(format('GRANT USAGE ON SCHEMA %I TO my_user', nspname), '; ')
FROM pg_namespace
WHERE nspname <> 'information_schema' -- exclude information schema and ...
AND nspname NOT LIKE 'pg\_%' -- ... system schemas
);
END
$$;
Then, all permissions for all tables (requires Postgres 9.0 or later).
And don't forget sequences (if any):
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO my_user;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO my_user;
For older versions you could use the "Grant Wizard" of pgAdmin III (the default GUI).
There are some other objects, the manual for GRANT
has the complete list as of Postgres 12:
privileges on a database object (table, column, view, foreign table, sequence, database, foreign-data wrapper, foreign server, function, procedure, procedural language, schema, or tablespace)
But the rest is rarely needed. More details:
Consider upgrading to a current version.
If you get this issue, then either
Me help next:
git stash
git pull origin master
git apply
git commit -m "some comment"
git push
ng-pristine ($pristine)
Boolean True if the form/input has not been used yet (not modified by the user)
ng-dirty ($dirty)
Boolean True if the form/input has been used (modified by the user)
$setDirty(); Sets the form to a dirty state. This method can be called to add the 'ng-dirty' class and set the form to a dirty state (ng-dirty class). This method will propagate current state to parent forms.
$setPristine(); Sets the form to its pristine state. This method sets the form's $pristine state to true, the $dirty state to false, removes the ng-dirty class and adds the ng-pristine class. Additionally, it sets the $submitted state to false. This method will also propagate to all the controls contained in this form.
Setting a form back to a pristine state is often useful when we want to 'reuse' a form after saving or resetting it.
Step by step to setup zxing 3.2.1 in eclipse
method s2ws works well. Hope helps.
std::wstring s2ws(const std::string& s) {
std::string curLocale = setlocale(LC_ALL, "");
const char* _Source = s.c_str();
size_t _Dsize = mbstowcs(NULL, _Source, 0) + 1;
wchar_t *_Dest = new wchar_t[_Dsize];
wmemset(_Dest, 0, _Dsize);
mbstowcs(_Dest,_Source,_Dsize);
std::wstring result = _Dest;
delete []_Dest;
setlocale(LC_ALL, curLocale.c_str());
return result;
}
Go to the preview version of tomcat e.g. : tomcat 8.3 and copy catalina.jar file and paste into the existing tomcat which you have facing the issue
Edit: Use printf("val = 0x%" PRIx64 "\n", val);
instead.
Try printf("val = 0x%llx\n", val);
. See the printf manpage:
ll (ell-ell). A following integer conversion corresponds to a long long int or unsigned long long int argument, or a following n conversion corresponds to a pointer to a long long int argument.
Edit: Even better is what @M_Oehm wrote: There is a specific macro for that, because unit64_t
is not always a unsigned long long
: PRIx64
see also this stackoverflow answer
Add a class to the containing div, then set the following css on it:
.img-overlay {
position: relative;
max-width: 500px; //whatever your max-width should be
}
position: relative
is required on a parent element of children with position: absolute
for the children to be positioned in relation to that parent.
If you don't care about the order this should work:
Set<Direction> directions = EnumSet.allOf(Direction.class);
for(Direction direction : directions) {
// do stuff
}
if you have an array you can do:
Arrays.asList(parameters).toString()
After lots of investigation in the same issue I found this one to be extremely convenient: https://github.com/flagbug/FlagFtp
For example (try doing this with the standard .net "library" - it will be a real pain) -> Recursively retreving all files on the FTP server:
public IEnumerable<FtpFileInfo> GetFiles(string server, string user, string password)
{
var credentials = new NetworkCredential(user, password);
var baseUri = new Uri("ftp://" + server + "/");
var files = new List<FtpFileInfo>();
AddFilesFromSubdirectory(files, baseUri, credentials);
return files;
}
private void AddFilesFromSubdirectory(List<FtpFileInfo> files, Uri uri, NetworkCredential credentials)
{
var client = new FtpClient(credentials);
var lookedUpFiles = client.GetFiles(uri);
files.AddRange(lookedUpFiles);
foreach (var subDirectory in client.GetDirectories(uri))
{
AddFilesFromSubdirectory(files, subDirectory.Uri, credentials);
}
}
ax.axis('off')
, will as Joe Kington pointed out, remove everything except the plotted line.
For those wanting to only remove the frame (border), and keep labels, tickers etc, one can do that by accessing the spines
object on the axis. Given an axis object ax
, the following should remove borders on all four sides:
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
And, in case of removing x
and y
ticks from the plot:
ax.get_xaxis().set_ticks([])
ax.get_yaxis().set_ticks([])
I've had this sort of problem.....
The solve: cmd
/ powershell
run as ADMINISTRATOR! I always forget.
Notice: In powershell
, you need to put .\
for example:
.\httpd -k shutdown .\httpd -k stop .\httpd -k uninstall
Result: Removing the apache2.4
service The Apache2.4
service has been removed successfully.
use zip
columns = zip(*rows) #transpose rows to columns
print columns[0] #print the first column
#you can also do more with the columns
print columns[1] # or print the second column
columns.append([7,7,7]) #add a new column to the end
backToRows = zip(*columns) # now we are back to rows with a new column
print backToRows
you can also use numpy
a = numpy.array(a)
print a[:,0]
Edit: zip object is not subscriptable. It need to be converted to list to access as list:
column = list(zip(*row))
Tested and Working procedure:
Goto the file path
..\apache-tomcat-7.0.x\webapps\ROOT\index.jsp
remove the whole content or declare the below lines of code at the top of the index.jsp
<% response.sendRedirect("http://yourRedirectionURL"); %>
Please note that in jsp file you need to start the above line with <% and end with %>
Some use cases of looping through an array in the functional programming way in JavaScript:
const myArray = [{x:100}, {x:200}, {x:300}];
myArray.forEach((element, index, array) => {
console.log(element.x); // 100, 200, 300
console.log(index); // 0, 1, 2
console.log(array); // same myArray object 3 times
});
Note: Array.prototype.forEach() is not a functional way strictly speaking, as the function it takes as the input parameter is not supposed to return a value, which thus cannot be regarded as a pure function.
const people = [
{name: 'John', age: 23},
{name: 'Andrew', age: 3},
{name: 'Peter', age: 8},
{name: 'Hanna', age: 14},
{name: 'Adam', age: 37}];
const anyAdult = people.some(person => person.age >= 18);
console.log(anyAdult); // true
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]
Note: The map() method creates a new array with the results of calling a provided function on every element in the calling array.
const myArray = [{x:100}, {x:200}, {x:300}];
const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
console.log(sum); // 600 = 0 + 100 + 200 + 300
const average = sum / myArray.length;
console.log(average); // 200
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray= myArray.map(element => {
return {
...element,
x: element.x * 2
};
});
console.log(myArray); // [100, 200, 300]
console.log(newArray); // [200, 400, 600]
const people = [
{name: 'John', group: 'A'},
{name: 'Andrew', group: 'C'},
{name: 'Peter', group: 'A'},
{name: 'James', group: 'B'},
{name: 'Hanna', group: 'A'},
{name: 'Adam', group: 'B'}];
const groupInfo = people.reduce((groups, person) => {
const {A = 0, B = 0, C = 0} = groups;
if (person.group === 'A') {
return {...groups, A: A + 1};
} else if (person.group === 'B') {
return {...groups, B: B + 1};
} else {
return {...groups, C: C + 1};
}
}, {});
console.log(groupInfo); // {A: 3, C: 1, B: 2}
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray = myArray.filter(element => element.x > 250);
console.log(newArray); // [{x:300}]
Note: The filter() method creates a new array with all elements that pass the test implemented by the provided function.
const people = [
{ name: "John", age: 21 },
{ name: "Peter", age: 31 },
{ name: "Andrew", age: 29 },
{ name: "Thomas", age: 25 }
];
let sortByAge = people.sort(function (p1, p2) {
return p1.age - p2.age;
});
console.log(sortByAge);
const people = [ {name: "john", age:23},
{name: "john", age:43},
{name: "jim", age:101},
{name: "bob", age:67} ];
const john = people.find(person => person.name === 'john');
console.log(john);
The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function.
I have used the following for this issue. I know it's not very elegant, but it's working.
DateTime zeroTime = new DateTime(1, 1, 1);
var date1 = new DateTime(1983, 03, 04);
var date2 = DateTime.Now;
var dif = date2 - date1;
int years = (zeroTime + dif).Year - 1;
Log.DebugFormat("Years -->{0}", years);
thead {
position: fixed;
height: 10px; /* This is whatever height you want */
}
tbody {
position: fixed;
margin-top: 10px; /* This has to match the height of thead */
height: 300px; /* This is whatever height you want */
}
Either escape the quote:
$text1= "From time to \"time\"";
or use single quotes to denote your string:
$text1= 'From time to "time"';
Most of answers are correct only want to add one point here
In Spark 2.0 the two APIs (DataFrame +DataSet) will be unified together into a single API.
"Unifying DataFrame and Dataset: In Scala and Java, DataFrame and Dataset have been unified, i.e. DataFrame is just a type alias for Dataset of Row. In Python and R, given the lack of type safety, DataFrame is the main programming interface."
Datasets are similar to RDDs, however, instead of using Java serialization or Kryo they use a specialized Encoder to serialize the objects for processing or transmitting over the network.
Spark SQL supports two different methods for converting existing RDDs into Datasets. The first method uses reflection to infer the schema of an RDD that contains specific types of objects. This reflection based approach leads to more concise code and works well when you already know the schema while writing your Spark application.
The second method for creating Datasets is through a programmatic interface that allows you to construct a schema and then apply it to an existing RDD. While this method is more verbose, it allows you to construct Datasets when the columns and their types are not known until runtime.
Here you can find RDD tof Data frame conversation answer
Unlike Java, you cannot define multiple constructors. However, you can define a default value if one is not passed.
def __init__(self, city="Berlin"):
self.city = city
This is my favorite method for being easy to read:
Dir.glob("*/*.txt") do |my_text_file|
puts "working on: #{my_text_file}..."
end
And you can even extend this to work on all files in subdirs:
Dir.glob("**/*.txt") do |my_text_file| # note one extra "*"
puts "working on: #{my_text_file}..."
end
You could speed up the initialization and simplify the code by using the the Parallel class (.NET 4 and newer):
public static void PopulateByteArray(byte[] byteArray, byte value)
{
Parallel.For(0, byteArray.Length, i => byteArray[i] = value);
}
Of course you can create the array at the same time:
public static byte[] CreateSpecialByteArray(int length, byte value)
{
var byteArray = new byte[length];
Parallel.For(0, length, i => byteArray[i] = value);
return byteArray;
}
You have referenced the jQuery JS file haven't you? There's no reason why farzad's answer shouldn't work.
Although View.getVisibility() does get the visibility, its not a simple true/false. A view can have its visibility set to one of three things.
View.VISIBLE The view is visible.
View.INVISIBLE The view is invisible, but any spacing it would normally take up will still be used. Its "invisible"
View.GONE The view is gone, you can't see it and it doesn't take up the "spot".
So to answer your question, you're looking for:
if (myImageView.getVisibility() == View.VISIBLE) {
// Its visible
} else {
// Either gone or invisible
}
console.log() just takes whatever you pass to it and writes it to a console's log window. If you pass in an array, you'll be able to inspect the array's contents. Pass in an object, you can examine the object's attributes/methods. pass in a string, it'll log the string. Basically it's "document.write" but can intelligently take apart its arguments and write them out elsewhere.
It's useful to outputting occasional debugging information, but not particularly useful if you have a massive amount of debugging output.
To watch as a script's executing, you'd use a debugger instead, which allows you step through the code line-by-line. console.log's used when you need to display what some variable's contents were for later inspection, but do not want to interrupt execution.
To open shared preference
in android studio
Open device explorer file from right side- data>data> >shared_prefs
find the attached image for more description
This worked for me. TypeScript Version: 2.8.3
for (const [key, value] of Object.entries(myMap)) {
console.log(key, value);
}
For example, if you want to select every 10th row in MSSQL, you can use;
SELECT * FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY ColumnName1 ASC) AS rownumber, ColumnName1, ColumnName2
FROM TableName
) AS foo
WHERE rownumber % 10 = 0
Just take the MOD and change number 10 here any number you want.
To understand why it does not return the list:
sort() doesn't return any value while the sort() method just sorts the elements of a given list in a specific order - ascending or descending without returning any value.
So problem is with answer = newList.sort()
where answer is none.
Instead you can just do return newList.sort()
.
The syntax of the sort() method is:
list.sort(key=..., reverse=...)
Alternatively, you can also use Python's in-built function sorted() for the same purpose.
sorted(list, key=..., reverse=...)
Note: The simplest difference between sort() and sorted() is: sort() doesn't return any value while, sorted() returns an iterable list.
So in your case answer = sorted(newList)
.
There are many ways to include external css and js files as specified in below code but you can choose one of them, i have tested them all, they work the same.
<link rel="stylesheet" href="{{ asset('css/stylesheet.css') }}" /><!--Recommended-->
<link rel="stylesheet" href="{{ URL::asset('css/somestylesheet.css') }}" />
<link rel="stylesheet" href="{{ URL::to('css/otherstylesheet.css') }}" />
<link rel="stylesheet" href="{{ url('css/anotherstylesheet.css') }}" />
Maybe there are more ways to load it.
but keep in mind that if you are loading the css and js from other than a public folder then better to use Laravel mix
.
Also remember that it must be:
#include "stdafx.h"
#include <iostream>
and not the other way around
#include <iostream>
#include "stdafx.h"
Use the free DLL Export Viewer, it is very easy to use.
Just some examples on usage of array_split
, split
, hsplit
and vsplit
:
n [9]: a = np.random.randint(0,10,[4,4])
In [10]: a
Out[10]:
array([[2, 2, 7, 1],
[5, 0, 3, 1],
[2, 9, 8, 8],
[5, 7, 7, 6]])
Some examples on using array_split
:
If you give an array or list as second argument you basically give the indices (before) which to 'cut'
# split rows into 0|1 2|3
In [4]: np.array_split(a, [1,3])
Out[4]:
[array([[2, 2, 7, 1]]),
array([[5, 0, 3, 1],
[2, 9, 8, 8]]),
array([[5, 7, 7, 6]])]
# split columns into 0| 1 2 3
In [5]: np.array_split(a, [1], axis=1)
Out[5]:
[array([[2],
[5],
[2],
[5]]),
array([[2, 7, 1],
[0, 3, 1],
[9, 8, 8],
[7, 7, 6]])]
An integer as second arg. specifies the number of equal chunks:
In [6]: np.array_split(a, 2, axis=1)
Out[6]:
[array([[2, 2],
[5, 0],
[2, 9],
[5, 7]]),
array([[7, 1],
[3, 1],
[8, 8],
[7, 6]])]
split
works the same but raises an exception if an equal split is not possible
In addition to array_split
you can use shortcuts vsplit
and hsplit
.
vsplit
and hsplit
are pretty much self-explanatry:
In [11]: np.vsplit(a, 2)
Out[11]:
[array([[2, 2, 7, 1],
[5, 0, 3, 1]]),
array([[2, 9, 8, 8],
[5, 7, 7, 6]])]
In [12]: np.hsplit(a, 2)
Out[12]:
[array([[2, 2],
[5, 0],
[2, 9],
[5, 7]]),
array([[7, 1],
[3, 1],
[8, 8],
[7, 6]])]
I had the same problem when setting the center of the map with map.setCenter()
. Using Number()
solved for me. Had to use parseFloat
to truncate the data.
code snippet:
var centerLat = parseFloat(data.lat).toFixed(0);
var centerLng = parseFloat(data.long).toFixed(0);
map.setCenter({
lat: Number(centerLat),
lng: Number(centerLng)
});
"Am i doing it right?Is there better/smarter way to achieve the output this code gave me?"
Generally speaking, yes, you're doing it right. Tkinter has no native scrollable container other than the canvas. As you can see, it's really not that difficult to set up. As your example shows, it only takes 5 or 6 lines of code to make it work -- depending on how you count lines.
"Why must i use grid method?(i tried place method, but none of the labels appear on the canvas?)"
You ask about why you must use grid. There is no requirement to use grid. Place, grid and pack can all be used. It's simply that some are more naturally suited to particular types of problems. In this case it looks like you're creating an actual grid -- rows and columns of labels -- so grid is the natural choice.
"What so special about using anchor='nw' when creating window on canvas?"
The anchor tells you what part of the window is positioned at the coordinates you give. By default, the center of the window will be placed at the coordinate. In the case of your code above, you want the upper left ("northwest") corner to be at the coordinate.
Download PDFObject library from https://pdfobject.com/ and check the below code: I hope it will work you.
<!DOCTYPE html>
<html>
<head>
<title>Pdf Read</title>
<style>
.pdfobject-container { height: 500px;}
.pdfobject { border: 1px solid #666; }
</style>
<script src="pdfobject.min.js"></script>
</head>
<body>
<div id="example1"></div>
<script>PDFObject.embed("pdfread.pdf", "#example1");</script>
</body>
</html>
Since any DateTime can be cast to a float, and the decimal part of the number represent the time itself:
DECLARE @date DATETIME = GETDATE()
SELECT CAST(CAST(@date AS FLOAT) - FLOOR(CAST(@date AS FLOAT)) AS DATETIME
This will result a datetime like '1900-01-01 hour of the day' you can cast it as time, timestamp or even use convert to get the formatted time.
I guess this works in any version of SQL since cast a datetime to float is compatible since version 2005.
Hope it helps.
I figured there's no way except going into the file system to find out if text.txt is a directory or just a file. If you wanted something simple, maybe you can just use:
s.Substring(s.LastIndexOf(@"\"));
I added a HorizontalAlignment="Center" (The default is "Strech") and it solved my problem because it made the datagrid only as wide as needed. (Removed the datagrid's Width setting if you have one.)
In this table you can see the difference between each model:
See http://www.1keydata.com/datawarehousing/data-modeling-levels.html for more information and some data model examples.
Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "]
with array("title" => "Welcome ")
I think that if you have a to
, you must use a from
.
I would think of something like :
@keyframe in {
from: transform: rotate(0deg);
to: transform: rotate(360deg);
}
@keyframe out {
from: transform: rotate(360deg);
to: transform: rotate(0deg);
}
Of course must have checked it already, but I found strange that you only use the transform
property since CSS3 is not fully implemented everywhere. Maybe it would work better with the following considerations :
@-webkit-keyframes
, no particuliar version needed@-webkit-keyframes
since version 5+@keyframes
since version 16 (v5-15 used @-moz-keyframes
)@-webkit-keyframes
version 15-22 (only v12 used @-o-keyframes
)@keyframes
since version 10+EDIT :
I came up with that fiddle :
Using minimal code. Is it approaching what you were expecting ?
Difference between 'true XHTML', 'faux XHTML' and HTML as well as importance of the server-sent MIME type had been already described here well. If you want to try it out right now, here is simple editable snippet with live preview including self-closed script tag for capable browsers:
div { display: flex; }_x000D_
div + div {flex-direction: column; }
_x000D_
<div>Mime type: <label><input type="radio" onchange="t.onkeyup()" id="x" checked name="mime"> application/xhtml+xml</label>_x000D_
<label><input type="radio" onchange="t.onkeyup()" name="mime"> text/html</label></div>_x000D_
<div><textarea id="t" rows="4" _x000D_
onkeyup="i.src='data:'+(x.checked?'application/xhtml+xml':'text/html')+','+encodeURIComponent(t.value)"_x000D_
><?xml version="1.0"?>_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"_x000D_
[<!ENTITY x "true XHTML">]>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<body>_x000D_
<p>_x000D_
<span id="greet" swapto="Hello">Hell, NO :(</span> &x;._x000D_
<script src="data:text/javascript,(g=document.getElementById('greet')).innerText=g.getAttribute('swapto')" />_x000D_
Nice to meet you!_x000D_
<!-- _x000D_
Previous text node and all further content falls into SCRIPT element content in text/html mode, so is not rendered. Because no end script tag is found, no script runs in text/html_x000D_
-->_x000D_
</p>_x000D_
</body>_x000D_
</html></textarea>_x000D_
_x000D_
<iframe id="i" height="80"></iframe>_x000D_
_x000D_
<script>t.onkeyup()</script>_x000D_
</div>
_x000D_
You should see Hello, true XHTML. Nice to meet you!
below textarea.
For incapable browsers you can copy content of the textarea and save it as a file with .xhtml
(or .xht
) extension (thanks Alek for this hint).
JSONObject obj = new JSONObject();
try {
obj.put("id", "3");
obj.put("name", "NAME OF STUDENT");
obj.put("year", "3rd");
obj.put("curriculum", "Arts");
obj.put("birthday", "5/5/1993");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray js=new JSONArray(obj.toString());
JSONObject obj2 = new JSONObject();
obj2.put("student", js.toString());
You can query the ALL_OBJECTS view:
select owner
, object_name
, object_type
from ALL_OBJECTS
where object_name = 'FOO'
To find synonyms:
select *
from ALL_SYNONYMS
where synonym_name = 'FOO'
Just to clarify, if a user user's SQL statement references an object name with no schema qualification (e.g. 'FOO'), Oracle FIRST checks the user's schema for an object of that name (including synonyms in that user's schema). If Oracle can't resolve the reference from the user's schema, Oracle then checks for a public synonym.
If you are looking specifically for constraints on a particular table_name:
select c.*
from all_constraints c
where c.table_name = 'FOO'
union all
select cs.*
from all_constraints cs
join all_synonyms s
on (s.table_name = cs.table_name
and s.table_owner = cs.owner
and s.synonym_name = 'FOO'
)
HTH
-- addendum:
If your user is granted access to the DBA_ views (e.g. if your user has been granted SELECT_CATALOG_ROLE), you can substitute 'DBA_
' in place of 'ALL_
' in the preceding SQL examples. The ALL_x
views only show objects which you have been granted privileges. The DBA_x
views will show all database objects, whether you have privileges on them or not.
This is a well-known problem with Java type erasure: T is just a type variable, and you must indicate actual class, usually as Class argument. Without such information, best that can be done is to use bounds; and plain T is roughly same as 'T extends Object'. And Jackson will then bind JSON Objects as Maps.
In this case, tester method needs to have access to Class, and you can construct
JavaType type = mapper.getTypeFactory().
constructCollectionType(List.class, Foo.class)
and then
List<Foo> list = mapper.readValue(new File("input.json"), type);
//example
char character;//to be scanned
char merge[2];// this is just temporary array to merge with
merge[0] = character;
merge[1] = '\0';
//now you have changed it into a string
Use filter
(short version without doing a function with lambda
, using __le__
):
j2 = filter((5).__le__, j)
Example (python 3):
>>> j=[4,5,6,7,1,3,7,5]
>>> j2 = filter((5).__le__, j)
>>> j2
<filter object at 0x000000955D16DC18>
>>> list(j2)
[5, 6, 7, 7, 5]
>>>
Example (python 2):
>>> j=[4,5,6,7,1,3,7,5]
>>> j2 = filter((5).__le__, j)
>>> j2
[5, 6, 7, 7, 5]
>>>
Use __le__
i recommend this, it's very easy, __le__
is your friend
If want to sort it to desired output (both versions):
>>> j=[4,5,6,7,1,3,7,5]
>>> j2 = filter((5).__le__, j)
>>> sorted(j2)
[5, 5, 6, 7, 7]
>>>
Use sorted
>>> from timeit import timeit
>>> timeit(lambda: [i for i in j if i >= 5]) # Michael Mrozek
1.4558496298222325
>>> timeit(lambda: filter(lambda x: x >= 5, j)) # Justin Ardini
0.693048732089828
>>> timeit(lambda: filter((5).__le__, j)) # Mine
0.714461565831428
>>>
So Justin wins!!
With number=1
:
>>> from timeit import timeit
>>> timeit(lambda: [i for i in j if i >= 5],number=1) # Michael Mrozek
1.642193421957927e-05
>>> timeit(lambda: filter(lambda x: x >= 5, j),number=1) # Justin Ardini
3.421236300482633e-06
>>> timeit(lambda: filter((5).__le__, j),number=1) # Mine
1.8474676011237534e-05
>>>
So Michael wins!!
>>> from timeit import timeit
>>> timeit(lambda: [i for i in j if i >= 5],number=10) # Michael Mrozek
4.721306089550126e-05
>>> timeit(lambda: filter(lambda x: x >= 5, j),number=10) # Justin Ardini
1.0947956184281793e-05
>>> timeit(lambda: filter((5).__le__, j),number=10) # Mine
1.5053439710754901e-05
>>>
So Justin wins again!!
When using Spring, one can also use Spring Integration object-to-map-transformer. It's probably not worth adding Spring as a dependency just for this.
For documentation, search for "Object-to-Map Transformer" on http://docs.spring.io/spring-integration/docs/4.0.4.RELEASE/reference/html/messaging-transformation-chapter.html
Essentially, it traverses the entire object graph reachable from the object given as input, and produces a map from all primitive type/String fields on the objects. It can be configured to output either:
Here's an example from their page:
public class Parent{
private Child child;
private String name;
// setters and getters are omitted
}
public class Child{
private String name;
private List<String> nickNames;
// setters and getters are omitted
}
Output will be:
{person.name=George, person.child.name=Jenna, person.child.nickNames[0]=Bimbo . . . etc}
A reverse transformer is also available.
zip update.zip $(git diff --name-only commit commit)
I appreciate this is a very old question but I thought I would add another answer for future users as all the answers to date use some form of Assembly.GetTypes
.
Whilst GetTypes() will indeed return all types, it does not necessarily mean you could activate them and could thus potentially throw a ReflectionTypeLoadException
.
A classic example for not being able to activate a type would be when the type returned is derived
from base
but base
is defined in a different assembly from that of derived
, an assembly that the calling assembly does not reference.
So say we have:
Class A // in AssemblyA
Class B : Class A, IMyInterface // in AssemblyB
Class C // in AssemblyC which references AssemblyB but not AssemblyA
If in ClassC
which is in AssemblyC
we then do something as per accepted answer:
var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));
Then it will throw a ReflectionTypeLoadException
.
This is because without a reference to AssemblyA
in AssemblyC
you would not be able to:
var bType = typeof(ClassB);
var bClass = (ClassB)Activator.CreateInstance(bType);
In other words ClassB
is not loadable which is something that the call to GetTypes checks and throws on.
So to safely qualify the result set for loadable types then as per this Phil Haacked article Get All Types in an Assembly and Jon Skeet code you would instead do something like:
public static class TypeLoaderExtensions {
public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly) {
if (assembly == null) throw new ArgumentNullException("assembly");
try {
return assembly.GetTypes();
} catch (ReflectionTypeLoadException e) {
return e.Types.Where(t => t != null);
}
}
}
And then:
private IEnumerable<Type> GetTypesWithInterface(Assembly asm) {
var it = typeof (IMyInterface);
return asm.GetLoadableTypes().Where(it.IsAssignableFrom).ToList();
}
$('#test').click(function() {_x000D_
var todayDate = moment("01.01.2019", "DD.MM.YYYY");_x000D_
var endDate = moment("08.02.2019", "DD.MM.YYYY");_x000D_
_x000D_
var result = 'Diff: ' + todayDate.diff(endDate, 'days');_x000D_
_x000D_
$('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: #ffb;_x000D_
padding: 10px;_x000D_
border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
The pop
method of dicts (like self.data
, i.e. {'a':'aaa','b':'bbb','c':'ccc'}
, here) takes two arguments -- see the docs
The second argument, default
, is what pop
returns if the first argument, key
, is absent.
(If you call pop
with just one argument, key
, it raises an exception if that key's absent).
In your example, print b.pop('a',{'b':'bbb'})
, this is irrelevant because 'a'
is a key in b.data
. But if you repeat that line...:
b=a()
print b.pop('a',{'b':'bbb'})
print b.pop('a',{'b':'bbb'})
print b.data
you'll see it makes a difference: the first pop
removes the 'a'
key, so in the second pop
the default
argument is actually returned (since 'a'
is now absent from b.data
).
Swift 4 Examples
Example #1 using closure
NotificationCenter.default.addObserver(forName: .UIApplicationUserDidTakeScreenshot,
object: nil,
queue: OperationQueue.main) { notification in
print("\(notification) that a screenshot was taken!")
}
Example #2 with selector
NotificationCenter.default.addObserver(self,
selector: #selector(screenshotTaken),
name: .UIApplicationUserDidTakeScreenshot,
object: nil)
@objc func screenshotTaken() {
print("Screenshot taken!")
}
You can create a focus listener on the EditText
on the AlertDialog
, then get the AlertDialog
's Window
. From there you can make the soft keyboard show by calling setSoftInputMode
.
final AlertDialog dialog = ...;
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
});
If you're writing a bash script, call it by name:
#!/bin/bash
/bin/sh is not guaranteed to be bash. This caused a ton of broken scripts in Ubuntu some years ago (IIRC).
The source builtin works just fine in bash; but you might as well just use dot like Norman suggested.
In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like
float total;
total += theItem.getUnits() * theItem.getPrice();
total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.
There are several reasons you could have problems loading from lib - see here for details - http://www.williambharding.com/blog/technology/rails-3-autoload-modules-and-classes-in-production/
I was able to invoke a shell script using this command:
ssh ${serverhost} "./sh/checkScript.ksh"
Of course, checkScript.ksh
must exist in the $HOME/sh
directory.
I'm not fine with solutions that iterates over a collection and inside the loop manipulating the content of even that collection. This can result in unexpected behaviour.
See also here: https://stackoverflow.com/a/2304578/655224 and in a comment the given link http://php.net/manual/en/control-structures.foreach.php#88578
So, when using foreach
if seems to be OK but IMHO the much more readable and simple solution is to filter your collection to a new one.
/**
* Filter all `selected` items
*
* @link https://laravel.com/docs/7.x/collections#method-filter
*/
$selected = $collection->filter(function($value, $key) {
return $value->selected;
})->toArray();
If the data is populated from the database, you might consider not using an <input>
tag to display it. Nevertheless, you can disable it right in the tag:
<input type='text' value='${magic.database.value}' disabled>
If you need to disable it with Javascript later, you can set the "disabled" attribute:
document.getElementById('theInput').disabled = true;
The reason I suggest not showing the value as an <input>
is that, in my experience, it causes layout issues. If the text is long, then in an <input>
the user will need to try and scroll the text, which is not something normal people would guess to do. If you just drop it into a <span>
or something, you have more styling flexibility.
While correct that this will work:
TimeSpan time = TimeSpan.Parse("07:35");
And if you are using it for validation...
TimeSpan time;
if (!TimeSpan.TryParse("07:35", out time))
{
// handle validation error
}
Consider that TimeSpan
is primarily intended to work with elapsed time, rather than time-of-day. It will accept values larger than 24 hours, and will accept negative values also.
If you need to validate that the input string is a valid time-of-day (>= 00:00 and < 24:00), then you should consider this instead:
DateTime dt;
if (!DateTime.TryParseExact("07:35", "HH:mm", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// handle validation error
}
TimeSpan time = dt.TimeOfDay;
As an added benefit, this will also parse 12-hour formatted times when an AM or PM is included, as long as you provide the appropriate format string, such as "h:mm tt"
.
Just discovered that if the source table for a subform is updated using adodb, it takes a while until the requery can find the updated information.
In my case, I was adding some records with 'dbconn.execute "sql" ' and wondered why the requery command in vba doesn't seem to work. When I was debugging, the requery worked. Added a 2-3 second wait in the code before requery just to test made a difference.
But changing to 'currentdb.execute "sql" ' fixed the problem immediately.
The problem with your code is :
String show[]= {rs4.getString(1)};
String actuate[]={rs4.getString(2)};
This will create a new array every time your loop (an not append as you might be assuming) and hence in the end you will have only one element per array.
Here is one more way to solve this :
StringBuilder sids = new StringBuilder ();
StringBuilder lids = new StringBuilder ();
while (rs4.next()) {
sids.append(rs4.getString(1)).append(" ");
lids.append(rs4.getString(2)).append(" ");
}
String show[] = sids.toString().split(" ");
String actuate[] = lids.toString().split(" ");
These arrays will have all the required element.
Because Intent has size limit . I use public static object to do pass bitmap from service to broadcast ....
public class ImageBox {
public static Queue<Bitmap> mQ = new LinkedBlockingQueue<Bitmap>();
}
pass in my service
private void downloadFile(final String url){
mExecutorService.submit(new Runnable() {
@Override
public void run() {
Bitmap b = BitmapFromURL.getBitmapFromURL(url);
synchronized (this){
TaskCount--;
}
Intent i = new Intent(ACTION_ON_GET_IMAGE);
ImageBox.mQ.offer(b);
sendBroadcast(i);
if(TaskCount<=0)stopSelf();
}
});
}
My BroadcastReceiver
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
LOG.d(TAG, "BroadcastReceiver get broadcast");
String action = intent.getAction();
if (DownLoadImageService.ACTION_ON_GET_IMAGE.equals(action)) {
Bitmap b = ImageBox.mQ.poll();
if(b==null)return;
if(mListener!=null)mListener.OnGetImage(b);
}
}
};
I strongly recommend every developer to start using strict mode now. There are enough browsers supporting it that strict mode will legitimately help save us from errors we didn’t even know were in your code.
Apparently, at the initial stage there will be errors we have never encountered before. To get the full benefit, we need to do proper testing after switching to strict mode to make sure we have caught everything. Definitely we don’t just throw use strict
in our code and assume there are no errors. So the churn is that it’s time to start using this incredibly useful language feature to write better code.
For example,
var person = {
name : 'xyz',
position : 'abc',
fullname : function () { "use strict"; return this.name; }
};
JSLint is a debugger written by Douglas Crockford. Simply paste in your script, and it’ll quickly scan for any noticeable issues and errors in your code.
For Windows users when using PyCharm and a virtual environment under Windows, you can use the /k parameter to cmd.exe to set the virtual environment automatically.
Go to Settings, Terminal, Default shell and add /K <path-to-your-activate.bat>
.
I don't have the reputation to comment on the earlier response so posting this corrected version. This really saves a LOT of time.
Update:
Note: Pycharm now supports virtual environments directly and it seems to work well for me - so my workaround not needed anymore.
Well guys, the solution to the problem is the following:
1) Folder 00A: 2) Counter: the last number 3) Help: the last number
Folder Perflib:
Last Counter: 00A folder´s Counter
Last Help: 00A folder´s Help
Ready, verify the same number in both. success
If you want to compare with a particular date , You can directly write it like :
select * from `table_name` where timestamp >= '2018-07-07';
// here the timestamp is the name of the column having type as timestamp
or
For fetching today date , CURDATE() function is available , so :
select * from `table_name` where timestamp >= CURDATE();
You have an error in you script tag construction, this:
<script language="JavaScript" type="text/javascript" script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
Should look like this:
<script language="JavaScript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
You have a 'script' word lost in the middle of your script tag. Also you should remove the http:// to let the browser decide whether to use HTTP or HTTPS.
UPDATE
But your main error is that you are including jQuery UI (ONLY) you must include jQuery first! jQuery UI and jQuery are used together, not in separate. jQuery UI depends on jQuery. You should put this line before jQuery UI:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
For me it was using {{ }} instead of {% %}:
href="{{ static 'bootstrap.min.css' }}" # wrong
href="{% static 'bootstrap.min.css' %}" # right
try:
var myjson = '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}';
var newJ= $.parseJSON(myjson);
alert(newJ.TeamList[0].teamname);
May be I missed something but exec did not worked as asynchronous for me in windows environment i used following in windows and it worked like charm ;)
$script_exec = "c:/php/php.exe c:/path/my_ascyn_script.php";
pclose(popen("start /B ". $script_exec, "r"));
Bill's answer is correct, but it is shocking to see that among all the other answers no one points out the most significant aspect.
It has been said over and over again, that in an identifying relationship the child can not exist without the parent. (e.g. user287724). This is true, but completely misses the point. It would be enough for the foreign key to be non-null to achieve this. It does not need to be part of the primary key.
So here is the real reason:
The purpose of an identifying relationship is that the foreign key can NEVER CHANGE, because it is part of the primary key... therefore identifying!!!
i'm impressed of the deep discussion.
my 2 cents:
from datetime import datetime import time
the timestamp in utc is:
timestamp = \
(datetime.utcnow() - datetime(1970,1,1)).total_seconds()
or,
timestamp = time.time()
if now results from datetime.now(), in the same DST
utcoffset = (datetime.now() - datetime.utcnow()).total_seconds()
timestamp = \
(now - datetime(1970,1,1)).total_seconds() - utcoffset
Best Solution courtesy https://www.youtube.com/watch?v=0MHoNU7ytaw the width and height of the card view determine the size of the images it contains set up is as follows:
implementation 'androidx.cardview:cardview:1.0.0'
<androidx.cardview.widget.CardView
android:layout_width="300dp"
android:layout_height="270dp"
android:layout_gravity="center"
app:cardCornerRadius="150dp"
app:cardBackgroundColor="@color/trans"
>
<ImageView
android:id="@+id/resultImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/congrats"
android:layout_gravity="center">
</ImageView>
</androidx.cardview.widget.CardView>```
I know it's very late to answer the question but with Auto-Property you can do something like that:
public static Singleton Instance { get; } = new Singleton();
Where Singleton
is you class and can be via, in this case the readonly property Instance
.
Run cmd
and then run node server.js
. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)
startdate = moment().subtract(1, 'days').startOf('day')
Try this I am also not 100 % sure
for( int i = 0 ;i< dt.Rows.Count; i++)
{
If(dt.Rows[i].Product_id == 2)
{
dt.Rows[i].Columns["Product_name"].ColumnName = "cde";
}
}
To convert a string to a number, subtract 0. To convert a number to a string, add "" (the empty string).
5 + 1 will give you 6
(5 + "") + 1 will give you "51"
("5" - 0) + 1 will give you 6
#Single line
'''
multi-line
comment
'''
"""
also,
multi-line comment
"""
You need the :not()
selector:
$('div[class^="first-"]:not(.first-bar)')
or, alternatively, the .not()
method:
$('div[class^="first-"]').not('.first-bar');
Swift 2.x
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
print("do some work")
}
Swift 3.x --&-- Swift 4
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
print("do some work")
}
or pass a escaping closure
func delay(seconds: Double, completion: @escaping()-> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + seconds, execute: completion)
}
For an example if you want to have a loop that stopped when it has counted all of the people in a group. We will consider the value X to be equal to the number of the people in the group, and the counter will be used to count all of the people in the group. To write the
while(!condition)
the code will be:
int x = people;
int counter = 0;
while(x != counter)
{
counter++;
}
return 0;
I am using macOS catalina ,
npm init
I got error
operation not permitted, uv_cwd
in 2021, this is how you can fix this problem.
very simple:
step 1: go to parent folder
cd ../
step 2: go to your project folder again,
cd your-project-folder
That is it. it works.
Use a version of pip
installed against the Python instance you want to install new packages to.
In many distributions, there may be separate python2.6-pip
and python2.7-pip
packages, invoked with binary names such as pip-2.6
and pip-2.7
. If pip is not packaged in your distribution for the desired target, you might look for a setuptools or easyinstall package, or use virtualenv (which will always include pip in a generated environment).
pip's website includes installation instructions, if you can't find anything within your distribution.
Note: z-index only works on positioned elements (position:absolute
, position:relative
, or position:fixed
). Use one of those.
If there is no selection, you can use the properties .selectionStart
or .selectionEnd
(with no selection they're equal).
var cursorPosition = $('#myTextarea').prop("selectionStart");
Note that this is not supported in older browsers, most notably IE8-. There you'll have to work with text ranges, but it's a complete frustration.
I believe there is a library somewhere which is dedicated to getting and setting selections/cursor positions in input elements, though. I can't recall its name, but there seem to be dozens on articles about this subject.
Did you try export
directive of Make itself (assuming that you use GNU Make)?
export PATH := bin:$(PATH)
test all:
x
Also, there is a bug in you example:
test all:
PATH=bin:${PATH}
@echo $(PATH)
x
First, the value being echo
ed is an expansion of PATH
variable performed by Make, not the shell. If it prints the expected value then, I guess, you've set PATH
variable somewhere earlier in your Makefile, or in a shell that invoked Make. To prevent such behavior you should escape dollars:
test all:
PATH=bin:$$PATH
@echo $$PATH
x
Second, in any case this won't work because Make executes each line of the recipe in a separate shell. This can be changed by writing the recipe in a single line:
test all:
export PATH=bin:$$PATH; echo $$PATH; x
You can combine attribute selectors this way:
$("[attr1=val][attr2=val]")...
so that an element has to satisfy both conditions. Of course you can use this for more than two. Also, don't do [type=checkbox]
. jQuery has a selector for that, namely :checkbox
so the end result is:
$("input:checkbox[name=ProductCode]")...
Attribute selectors are slow however so the recommended approach is to use ID and class selectors where possible. You could change your markup to:
<input type="checkbox" class="ProductCode" name="ProductCode"value="396P4">
<input type="checkbox" class="ProductCode" name="ProductCode"value="401P4">
<input type="checkbox" class="ProductCode" name="ProductCode"value="F460129">
allowing you to use the much faster selector of:
$("input.ProductCode")...
If your intention is to get hold of already instantiated controller of another component and that if you are following component/directive based approach you can always require
a controller (instance of a component) from a another component that follows a certain hierarchy.
For example:
//some container component that provides a wizard and transcludes the page components displayed in a wizard
myModule.component('wizardContainer', {
...,
controller : function WizardController() {
this.disableNext = function() {
//disable next step... some implementation to disable the next button hosted by the wizard
}
},
...
});
//some child component
myModule.component('onboardingStep', {
...,
controller : function OnboadingStepController(){
this.$onInit = function() {
//.... you can access this.container.disableNext() function
}
this.onChange = function(val) {
//..say some value has been changed and it is not valid i do not want wizard to enable next button so i call container's disable method i.e
if(notIsValid(val)){
this.container.disableNext();
}
}
},
...,
require : {
container: '^^wizardContainer' //Require a wizard component's controller which exist in its parent hierarchy.
},
...
});
Now the usage of these above components might be something like this:
<wizard-container ....>
<!--some stuff-->
...
<!-- some where there is this page that displays initial step via child component -->
<on-boarding-step ...>
<!--- some stuff-->
</on-boarding-step>
...
<!--some stuff-->
</wizard-container>
There are many ways you can set up require.
(no prefix) - Locate the required controller on the current element. Throw an error if not found.
? - Attempt to locate the required controller or pass null to the link fn if not found.
^ - Locate the required controller by searching the element and its parents. Throw an error if not found.
^^ - Locate the required controller by searching the element's parents. Throw an error if not found.
?^ - Attempt to locate the required controller by searching the element and its parents or pass null to the link fn if not found.
?^^ - Attempt to locate the required controller by searching the element's parents, or pass null to the link fn if not found.
Old Answer:
You need to inject $controller
service to instantiate a controller inside another controller. But be aware that this might lead to some design issues. You could always create reusable services that follows Single Responsibility and inject them in the controllers as you need.
Example:
app.controller('TestCtrl2', ['$scope', '$controller', function ($scope, $controller) {
var testCtrl1ViewModel = $scope.$new(); //You need to supply a scope while instantiating.
//Provide the scope, you can also do $scope.$new(true) in order to create an isolated scope.
//In this case it is the child scope of this scope.
$controller('TestCtrl1',{$scope : testCtrl1ViewModel });
testCtrl1ViewModel.myMethod(); //And call the method on the newScope.
}]);
In any case you cannot call TestCtrl1.myMethod()
because you have attached the method on the $scope
and not on the controller instance.
If you are sharing the controller, then it would always be better to do:-
.controller('TestCtrl1', ['$log', function ($log) {
this.myMethod = function () {
$log.debug("TestCtrl1 - myMethod");
}
}]);
and while consuming do:
.controller('TestCtrl2', ['$scope', '$controller', function ($scope, $controller) {
var testCtrl1ViewModel = $controller('TestCtrl1');
testCtrl1ViewModel.myMethod();
}]);
In the first case really the $scope
is your view model, and in the second case it the controller instance itself.
This might be more desirable, that is use float instead
SELECT fullName, CAST(totalBal as float) totalBal FROM client_info ORDER BY totalBal DESC
String query="select * from test1 where "+selected+" like '%"+SelectedStr+"%';";
PreparedStatement preparedStatement=con.prepareStatement(query);
// where seleced and SelectedStr are String Variables in my program
try this
if($('input:radio:checked').length > 0){
// go on with script
}else{
// NOTHING IS CHECKED
}
Spinner don't support Hint, i recommend you to make a custom spinner adapter.
check this link : https://stackoverflow.com/a/13878692/1725748
If your input file has a fixed amount of columns separated by commas and you know in which columns are the strings it might be best to use the function
textscan()
Note that you can specify a format where you read up to a maximum number of characters in the string or until a delimiter (comma) is found.
From git doc: http://git-scm.com/docs/git-stash
drop [-q|--quiet] []
Remove a single stashed state from the stash list. When no is given, it removes the latest one. i.e. stash@{0}
, otherwise must be a valid stash log reference of the form stash@{}.
example:
git stash drop stash@{5}
This would delete the stash entry 5. To see all the list of stashes:
git stash list
I also experienced this problem and found the easy solution to be
public string ReturnValues()
{
string _var = ""; // Setting an innitial value
if (.....) // Looking at conditions
{
_var = "true"; // Re-assign the value of _var
}
return _var; // Return the value of var
}
This also works with other return types and gives the least amount of problems
The initial value I chose was a fall-back value and I was able to re-assign the value as many times as required.
Tips from 2020:
From Flask 1.0, it defaults to enable multiple threads (source), you don't need to do anything, just upgrade it with:
$ pip install -U flask
If you are using flask run
instead of app.run()
with older versions, you can control the threaded behavior with a command option (--with-threads/--without-threads
):
$ flask run --with-threads
It's same as app.run(threaded=True)
In order to create a File from a HTTP URL you need to download the contents from that URL:
URL url = new URL("http://www.google.ro/logos/2011/twain11-hp-bg.jpg");
URLConnection connection = url.openConnection();
InputStream in = connection.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("downloaded.jpg"));
byte[] buf = new byte[512];
while (true) {
int len = in.read(buf);
if (len == -1) {
break;
}
fos.write(buf, 0, len);
}
in.close();
fos.flush();
fos.close();
The downloaded file will be found at the root of your project: {project}/downloaded.jpg
What you can do is set specific width and height to your iframe (for example these could be equal to your window dimensions) and then applying a scale transformation to it. The scale value will be the ratio between your window width and the dimension you wanted to set to your iframe.
E.g.
<iframe width="1024" height="768" src="http://www.bbc.com" style="-webkit-transform:scale(0.5);-moz-transform-scale(0.5);"></iframe>
Off the top of my head, the following are the only built-ins that are subscriptable:
string: "foobar"[3] == "b"
tuple: (1,2,3,4)[3] == 4
list: [1,2,3,4][3] == 4
dict: {"a":1, "b":2, "c":3}["c"] == 3
But mipadi's answer is correct - any class that implements __getitem__
is subscriptable
If you do not want to define a separate class for nested json , Defining nested json object as JsonNode should work ,for example :
{"id":2,"socket":"0c317829-69bf-43d6-b598-7c0c550635bb","type":"getDashboard","data":{"workstationUuid":"ddec1caa-a97f-4922-833f-632da07ffc11"},"reply":true}
@JsonProperty("data")
private JsonNode data;
Codeigniter adapting version as method of some model:
public function enum_values($table_name, $field_name)
{
$query = $this->db->query("SHOW COLUMNS FROM `{$table_name}` LIKE '{$field_name}'");
if(!$query->num_rows()) return array();
preg_match_all('~\'([^\']*)\'~', $query->row('Type'), $matches);
return $matches[1];
}
Result:
array(2) {
[0]=> string(13) "administrator"
[1]=> string(8) "customer"
}
My Java version was the 1.6 and I found that was using 1.7 with CDI however after that I changed the Java version to 1.7 and import the package javax.faces.bean.ManagedBean and everything worked.
Thanks @PM77-1
Try it -
package com;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
public class CheckBoxImageView extends ImageView implements View.OnClickListener {
boolean checked;
int defImageRes;
int checkedImageRes;
OnCheckedChangeListener onCheckedChangeListener;
public CheckBoxImageView(Context context, AttributeSet attr, int defStyle) {
super(context, attr, defStyle);
init(attr, defStyle);
}
public CheckBoxImageView(Context context, AttributeSet attr) {
super(context, attr);
init(attr, -1);
}
public CheckBoxImageView(Context context) {
super(context);
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
setImageResource(checked ? checkedImageRes : defImageRes);
}
private void init(AttributeSet attributeSet, int defStyle) {
TypedArray a = null;
if (defStyle != -1)
a = getContext().obtainStyledAttributes(attributeSet, R.styleable.CheckBoxImageView, defStyle, 0);
else
a = getContext().obtainStyledAttributes(attributeSet, R.styleable.CheckBoxImageView);
defImageRes = a.getResourceId(0, 0);
checkedImageRes = a.getResourceId(1, 0);
checked = a.getBoolean(2, false);
a.recycle();
setImageResource(checked ? checkedImageRes : defImageRes);
setOnClickListener(this);
}
@Override
public void onClick(View v) {
checked = !checked;
setImageResource(checked ? checkedImageRes : defImageRes);
onCheckedChangeListener.onCheckedChanged(this, checked);
}
public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
this.onCheckedChangeListener = onCheckedChangeListener;
}
public static interface OnCheckedChangeListener {
void onCheckedChanged(View buttonView, boolean isChecked);
}
}
Add this attrib -
<declare-styleable name="CheckBoxImageView">
<attr name="default_img" format="integer"/>
<attr name="checked_img" format="integer"/>
<attr name="checked" format="boolean"/>
</declare-styleable>
Use like -
<com.adonta.ziva.consumer.wrapper.CheckBoxImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/checkBox"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:clickable="true"
android:padding="5dp"
app:checked_img="@drawable/check_box_checked"
app:default_img="@drawable/check_box" />
It will fix all your porblems.
Following is the code snippet which shows better way to handle the response body as a String whether it's a valid response or error response for the HTTP POST request:
BufferedReader reader = null;
OutputStream os = null;
String payload = "";
try {
URL url1 = new URL("YOUR_URL");
HttpURLConnection postConnection = (HttpURLConnection) url1.openConnection();
postConnection.setRequestMethod("POST");
postConnection.setRequestProperty("Content-Type", "application/json");
postConnection.setDoOutput(true);
os = postConnection.getOutputStream();
os.write(eventContext.getMessage().getPayloadAsString().getBytes());
os.flush();
String line;
try{
reader = new BufferedReader(new InputStreamReader(postConnection.getInputStream()));
}
catch(IOException e){
if(reader == null)
reader = new BufferedReader(new InputStreamReader(postConnection.getErrorStream()));
}
while ((line = reader.readLine()) != null)
payload += line.toString();
}
catch (Exception ex) {
log.error("Post request Failed with message: " + ex.getMessage(), ex);
} finally {
try {
reader.close();
os.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
return null;
}
}
Maybe the following helps you.
arraylistname.get(position);
The foreign keys are there to ensure data integrity, so you can't drop a column as long as it's part of a foreign key. You need to drop the key first.
I would think the following query would do it:
ALTER TABLE assignmentStuff DROP FOREIGN KEY assignmentIDX;
The doxypy input filter allows you to use pretty much all of Doxygen's formatting tags in a standard Python docstring format. I use it to document a large mixed C++ and Python game application framework, and it's working well.
Define a helper function like this
function checkWhitespace(inputString){
let stringArray = inputString.split(' ');
let output = true;
for (let el of stringArray){
if (el!=''){
output=false;
}
}
return output;
}
Then check your input field value by passing through as an argument. If function returns true, that means value is only white space.
As an example
let inputValue = $('#firstName').val();
if(checkWhitespace(inputValue)) {
// Show Warnings or return warnings
}else {
// // Block of code-probably store input value into database
}
Just one more line for @tofutim answer ... if you want custom field name for concatenated row ...
SELECT
(
col1 || '-' || SUBSTR('00' || col2, -2, 2) | '-' || SUBSTR('0000' || col3, -4, 4)
) AS my_column
FROM
mytable;
Tested on SQLite 3.8.8.3, Thanks!
You could just use the FolderBrowserDialog
class from the System.Windows.Forms
namespace.
I don't know if this is good enough but I made a static ThreadHelperClass class and implemented it as following .Now I can easily set text property of various controls without much coding .
public static class ThreadHelperClass
{
delegate void SetTextCallback(Form f, Control ctrl, string text);
/// <summary>
/// Set text property of various controls
/// </summary>
/// <param name="form">The calling form</param>
/// <param name="ctrl"></param>
/// <param name="text"></param>
public static void SetText(Form form, Control ctrl, string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (ctrl.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
form.Invoke(d, new object[] { form, ctrl, text });
}
else
{
ctrl.Text = text;
}
}
}
Using the code:
private void btnTestThread_Click(object sender, EventArgs e)
{
Thread demoThread =
new Thread(new ThreadStart(this.ThreadProcSafe));
demoThread.Start();
}
// This method is executed on the worker thread and makes
// a thread-safe call on the TextBox control.
private void ThreadProcSafe()
{
ThreadHelperClass.SetText(this, textBox1, "This text was set safely.");
ThreadHelperClass.SetText(this, textBox2, "another text was set safely.");
}
Mine was different again. I was setting the user-agent like so:
NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
This was causing something on the web page to freak out and leak memory. Not sure why but removing this sorted the issue for me.
Simple as this: <input type="text" name="email" value="e-mail..." onFocus="this.value=''">
xhr.file = file;
; the file object is not supposed to be attached this way.xhr.send(file)
doesn't send the file. You have to use the FormData
object to wrap the file into a multipart/form-data
post data object:
var formData = new FormData();
formData.append("thefile", file);
xhr.send(formData);
After that, the file can be access in $_FILES['thefile']
(if you are using PHP).
Remember, MDC and Mozilla Hack demos are your best friends.
EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.
That is just in SDK 23, Httpclient and others are deprecated. You can correct it by changing the target SDK version like below:
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "vahid.hoseini.com.testclient"
minSdkVersion 10
targetSdkVersion 22
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.1.1'
}
There are so many answers here, but if you're trying to change the jks password on a Mac in Android Studio. Here are the easiest steps I could find
1) Open Terminal and cd to where your .jks is located
2) keytool -storepasswd -new NEWPASSWORD -keystore YOURKEYSTORE.jks
3) enter your current password
com.fasterxml.jackson.databind.type.TypeFactory._hashMapSuperInterfaceChain(HierarchicType)
com.fasterxml.jackson.databind.type.TypeFactory._findSuperInterfaceChain(Type, Class)
com.fasterxml.jackson.databind.type.TypeFactory._findSuperTypeChain(Class, Class)
com.fasterxml.jackson.databind.type.TypeFactory.findTypeParameters(Class, Class, TypeBindings)
com.fasterxml.jackson.databind.type.TypeFactory.findTypeParameters(JavaType, Class)
com.fasterxml.jackson.databind.type.TypeFactory._fromParamType(ParameterizedType, TypeBindings)
com.fasterxml.jackson.databind.type.TypeFactory._constructType(Type, TypeBindings)
com.fasterxml.jackson.databind.type.TypeFactory.constructType(TypeReference)
com.fasterxml.jackson.databind.ObjectMapper.convertValue(Object, TypeReference)
The method _hashMapSuperInterfaceChain in class com.fasterxml.jackson.databind.type.TypeFactory is synchronized. Am seeing contention on the same at high loads.
May be another reason to avoid a static ObjectMapper
You're obviously not disposing of things.
Consider the "using" command when temporarily using objects that implement IDisposable.
i believe the reason it is not working in your example is that you have imported datetime
like so :
from datetime import datetime
this leads to the error you see
In [30]: isinstance(x, datetime.date)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/<ipython-input-30-9a298ea6fce5> in <module>()
----> 1 isinstance(x, datetime.date)
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
if you simply import like so :
import datetime
the code will run as shown in all of the other answers
In [31]: import datetime
In [32]: isinstance(x, datetime.date)
Out[32]: True
In [33]:
thanks for pointing me in the right direction. I found user.config located at this monstrosity: c:\users\USER\AppData\Local\COMPANY\APPLICATION.exe_Url_LOOKSLIKESOMEKINDOFHASH\VERSION\user.config.
I had to uprev the version on my application and all the settings seemed to have vanished. application created a new folder with the new version and used the default settings. took forever to find where the file was stored, but then it was a simple copy and paste to get the settings to the new version.
I'm assuming the contents of src/main/resources/
is copied to WEB-INF/classes/
inside your .war at build time. If that is the case you can just do (substituting real values for the classname and the path being loaded).
URL sqlScriptUrl = MyServletContextListener.class
.getClassLoader().getResource("sql/script.sql");
The solution below works in Firefox also, without any JavaScript:
option[default] {_x000D_
display: none;_x000D_
}
_x000D_
<select>_x000D_
<option value="" default selected>Select Your Age</option>_x000D_
<option value="1">1</option>_x000D_
<option value="2">2</option>_x000D_
<option value="3">3</option>_x000D_
<option value="4">4</option>_x000D_
</select>
_x000D_
After installing pytorch, I got a similar error when I used:
import torch
Removing NumPy didn't help (I actually renamed NumPy, so I reverted back after it didn't work). The following commands worked for me:
sudo pip install numpy --upgrade
sudo easy_install numpy
You can either use the $_SERVER['REQUEST_TIME']
variable (available since PHP 5.1.0) or the time()
function to get the current Unix timestamp.
You may write a recursive algorithm in Batch that gives you exact control of what you do in every nested subdirectory:
@echo off
call :treeProcess
goto :eof
:treeProcess
rem Do whatever you want here over the files of this subdir, for example:
copy *.* C:\dest\dir
for /D %%d in (*) do (
cd %%d
call :treeProcess
cd ..
)
exit /b
Windows Batch File Looping Through Directories to Process Files?
You can set a breakpoint, and then just open the debug console. So, the first thing you need to turn on your debug console:
After you've enabled, set a break-point to where you want it to:
After you're done setting the break-point:
Once that has been completed:
They both track your changes to the collection, just call the SaveChanges() method that should update the DB.
Two very different types of Pipes Angular - Pipes and RxJS - Pipes
A pipe takes in data as input and transforms it to a desired output. In this page, you'll use pipes to transform a component's birthday property into a human-friendly date.
import { Component } from '@angular/core';
@Component({
selector: 'app-hero-birthday',
template: `<p>The hero's birthday is {{ birthday | date }}</p>`
})
export class HeroBirthdayComponent {
birthday = new Date(1988, 3, 15); // April 15, 1988
}
Observable operators are composed using a pipe method known as Pipeable Operators. Here is an example.
import {Observable, range} from 'rxjs';
import {map, filter} from 'rxjs/operators';
const source$: Observable<number> = range(0, 10);
source$.pipe(
map(x => x * 2),
filter(x => x % 3 === 0)
).subscribe(x => console.log(x));
The output for this in the console would be the following:
0
6
12
18
For any variable holding an observable, we can use the .pipe() method to pass in one or multiple operator functions that can work on and transform each item in the observable collection.
So this example takes each number in the range of 0 to 10, and multiplies it by 2. Then, the filter function to filter the result down to only the odd numbers.
I figured it this way:
* { padding: 0; margin: 0 }
body { height: 100%; white-space: nowrap }
html { height: 100% }
.red { background: red }
.blue { background: blue }
.yellow { background: yellow }
.header { width: 100%; height: 10%; position: fixed }
.wrapper { width: 1000%; height: 100%; background: green }
.page { width: 10%; height: 100%; float: left }
<div class="header red"></div>
<div class="wrapper">
<div class="page yellow"></div>
<div class="page blue"></div>
<div class="page yellow"></div>
<div class="page blue"></div>
<div class="page yellow"></div>
<div class="page blue"></div>
<div class="page yellow"></div>
<div class="page blue"></div>
<div class="page yellow"></div>
<div class="page blue"></div>
</div>
I have the wrapper at 1000% and ten pages at 10% each. I set mine up to still have "pages" with each being 100% of the window (color coded). You can do eight pages with an 800% wrapper. I guess you can leave out the colors and have on continues page. I also set up a fixed header, but that's not necessary. Hope this helps.
<div style="display: inline">
<div style="width:80%; display: inline-block; float:left; margin-right: 10px;"></div>
<div style="width: 19%; display: inline-block; border: 1px solid red"></div>
</div>
Nothing special. Just as same as common Java Class Instance.
But those class are Synthetic proxy classes
created by java.lang.reflect.Proxy#newProxyInstance
Introduced in 1.3
http://docs.oracle.com/javase/1.3/docs/relnotes/features.html#reflection
It is a part of Java. so each JVM should support it.
In short : they are created using JVM ASM tech ( defining javabyte code at runtime )
something using same tech:
java.lang.reflect.Proxy#newProxyInstance
getProxyClass0
to obtain a `Class
`
ProxyGenerator.generateProxyClass
which return a byte[]define class
to load the generated $Proxy
Class (the classname you have seen)each method is build with same bytecode like
invocation handler
's invoke()
invocation handler
's invoke()
the class(bytecode) represent in form of byte[]
How to draw a class
Thinking your java codes are compiled into bytecodes, just do this at runtime
core method in sun/misc/ProxyGenerator.java
generateClassFile
/**
* Generate a class file for the proxy class. This method drives the
* class file generation process.
*/
private byte[] generateClassFile() {
/* ============================================================
* Step 1: Assemble ProxyMethod objects for all methods to
* generate proxy dispatching code for.
*/
/*
* Record that proxy methods are needed for the hashCode, equals,
* and toString methods of java.lang.Object. This is done before
* the methods from the proxy interfaces so that the methods from
* java.lang.Object take precedence over duplicate methods in the
* proxy interfaces.
*/
addProxyMethod(hashCodeMethod, Object.class);
addProxyMethod(equalsMethod, Object.class);
addProxyMethod(toStringMethod, Object.class);
/*
* Now record all of the methods from the proxy interfaces, giving
* earlier interfaces precedence over later ones with duplicate
* methods.
*/
for (int i = 0; i < interfaces.length; i++) {
Method[] methods = interfaces[i].getMethods();
for (int j = 0; j < methods.length; j++) {
addProxyMethod(methods[j], interfaces[i]);
}
}
/*
* For each set of proxy methods with the same signature,
* verify that the methods' return types are compatible.
*/
for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
checkReturnTypes(sigmethods);
}
/* ============================================================
* Step 2: Assemble FieldInfo and MethodInfo structs for all of
* fields and methods in the class we are generating.
*/
try {
methods.add(generateConstructor());
for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
for (ProxyMethod pm : sigmethods) {
// add static field for method's Method object
fields.add(new FieldInfo(pm.methodFieldName,
"Ljava/lang/reflect/Method;",
ACC_PRIVATE | ACC_STATIC));
// generate code for proxy method and add it
methods.add(pm.generateMethod());
}
}
methods.add(generateStaticInitializer());
} catch (IOException e) {
throw new InternalError("unexpected I/O Exception");
}
if (methods.size() > 65535) {
throw new IllegalArgumentException("method limit exceeded");
}
if (fields.size() > 65535) {
throw new IllegalArgumentException("field limit exceeded");
}
/* ============================================================
* Step 3: Write the final class file.
*/
/*
* Make sure that constant pool indexes are reserved for the
* following items before starting to write the final class file.
*/
cp.getClass(dotToSlash(className));
cp.getClass(superclassName);
for (int i = 0; i < interfaces.length; i++) {
cp.getClass(dotToSlash(interfaces[i].getName()));
}
/*
* Disallow new constant pool additions beyond this point, since
* we are about to write the final constant pool table.
*/
cp.setReadOnly();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
try {
/*
* Write all the items of the "ClassFile" structure.
* See JVMS section 4.1.
*/
// u4 magic;
dout.writeInt(0xCAFEBABE);
// u2 minor_version;
dout.writeShort(CLASSFILE_MINOR_VERSION);
// u2 major_version;
dout.writeShort(CLASSFILE_MAJOR_VERSION);
cp.write(dout); // (write constant pool)
// u2 access_flags;
dout.writeShort(ACC_PUBLIC | ACC_FINAL | ACC_SUPER);
// u2 this_class;
dout.writeShort(cp.getClass(dotToSlash(className)));
// u2 super_class;
dout.writeShort(cp.getClass(superclassName));
// u2 interfaces_count;
dout.writeShort(interfaces.length);
// u2 interfaces[interfaces_count];
for (int i = 0; i < interfaces.length; i++) {
dout.writeShort(cp.getClass(
dotToSlash(interfaces[i].getName())));
}
// u2 fields_count;
dout.writeShort(fields.size());
// field_info fields[fields_count];
for (FieldInfo f : fields) {
f.write(dout);
}
// u2 methods_count;
dout.writeShort(methods.size());
// method_info methods[methods_count];
for (MethodInfo m : methods) {
m.write(dout);
}
// u2 attributes_count;
dout.writeShort(0); // (no ClassFile attributes for proxy classes)
} catch (IOException e) {
throw new InternalError("unexpected I/O Exception");
}
return bout.toByteArray();
}
addProxyMethod
/**
* Add another method to be proxied, either by creating a new
* ProxyMethod object or augmenting an old one for a duplicate
* method.
*
* "fromClass" indicates the proxy interface that the method was
* found through, which may be different from (a subinterface of)
* the method's "declaring class". Note that the first Method
* object passed for a given name and descriptor identifies the
* Method object (and thus the declaring class) that will be
* passed to the invocation handler's "invoke" method for a given
* set of duplicate methods.
*/
private void addProxyMethod(Method m, Class fromClass) {
String name = m.getName();
Class[] parameterTypes = m.getParameterTypes();
Class returnType = m.getReturnType();
Class[] exceptionTypes = m.getExceptionTypes();
String sig = name + getParameterDescriptors(parameterTypes);
List<ProxyMethod> sigmethods = proxyMethods.get(sig);
if (sigmethods != null) {
for (ProxyMethod pm : sigmethods) {
if (returnType == pm.returnType) {
/*
* Found a match: reduce exception types to the
* greatest set of exceptions that can thrown
* compatibly with the throws clauses of both
* overridden methods.
*/
List<Class<?>> legalExceptions = new ArrayList<Class<?>>();
collectCompatibleTypes(
exceptionTypes, pm.exceptionTypes, legalExceptions);
collectCompatibleTypes(
pm.exceptionTypes, exceptionTypes, legalExceptions);
pm.exceptionTypes = new Class[legalExceptions.size()];
pm.exceptionTypes =
legalExceptions.toArray(pm.exceptionTypes);
return;
}
}
} else {
sigmethods = new ArrayList<ProxyMethod>(3);
proxyMethods.put(sig, sigmethods);
}
sigmethods.add(new ProxyMethod(name, parameterTypes, returnType,
exceptionTypes, fromClass));
}
Full code about gen the proxy method
private MethodInfo generateMethod() throws IOException {
String desc = getMethodDescriptor(parameterTypes, returnType);
MethodInfo minfo = new MethodInfo(methodName, desc,
ACC_PUBLIC | ACC_FINAL);
int[] parameterSlot = new int[parameterTypes.length];
int nextSlot = 1;
for (int i = 0; i < parameterSlot.length; i++) {
parameterSlot[i] = nextSlot;
nextSlot += getWordsPerType(parameterTypes[i]);
}
int localSlot0 = nextSlot;
short pc, tryBegin = 0, tryEnd;
DataOutputStream out = new DataOutputStream(minfo.code);
code_aload(0, out);
out.writeByte(opc_getfield);
out.writeShort(cp.getFieldRef(
superclassName,
handlerFieldName, "Ljava/lang/reflect/InvocationHandler;"));
code_aload(0, out);
out.writeByte(opc_getstatic);
out.writeShort(cp.getFieldRef(
dotToSlash(className),
methodFieldName, "Ljava/lang/reflect/Method;"));
if (parameterTypes.length > 0) {
code_ipush(parameterTypes.length, out);
out.writeByte(opc_anewarray);
out.writeShort(cp.getClass("java/lang/Object"));
for (int i = 0; i < parameterTypes.length; i++) {
out.writeByte(opc_dup);
code_ipush(i, out);
codeWrapArgument(parameterTypes[i], parameterSlot[i], out);
out.writeByte(opc_aastore);
}
} else {
out.writeByte(opc_aconst_null);
}
out.writeByte(opc_invokeinterface);
out.writeShort(cp.getInterfaceMethodRef(
"java/lang/reflect/InvocationHandler",
"invoke",
"(Ljava/lang/Object;Ljava/lang/reflect/Method;" +
"[Ljava/lang/Object;)Ljava/lang/Object;"));
out.writeByte(4);
out.writeByte(0);
if (returnType == void.class) {
out.writeByte(opc_pop);
out.writeByte(opc_return);
} else {
codeUnwrapReturnValue(returnType, out);
}
tryEnd = pc = (short) minfo.code.size();
List<Class<?>> catchList = computeUniqueCatchList(exceptionTypes);
if (catchList.size() > 0) {
for (Class<?> ex : catchList) {
minfo.exceptionTable.add(new ExceptionTableEntry(
tryBegin, tryEnd, pc,
cp.getClass(dotToSlash(ex.getName()))));
}
out.writeByte(opc_athrow);
pc = (short) minfo.code.size();
minfo.exceptionTable.add(new ExceptionTableEntry(
tryBegin, tryEnd, pc, cp.getClass("java/lang/Throwable")));
code_astore(localSlot0, out);
out.writeByte(opc_new);
out.writeShort(cp.getClass(
"java/lang/reflect/UndeclaredThrowableException"));
out.writeByte(opc_dup);
code_aload(localSlot0, out);
out.writeByte(opc_invokespecial);
out.writeShort(cp.getMethodRef(
"java/lang/reflect/UndeclaredThrowableException",
"<init>", "(Ljava/lang/Throwable;)V"));
out.writeByte(opc_athrow);
}
Before MySQL 5.7.6 this works from the command line:
mysql -e "SET PASSWORD FOR 'root'@'localhost' = PASSWORD('$w0rdf1sh');"
I don't have a mysql install to test on but I think in your case it would be
mysql -e "UPDATE mysql.user SET Password=PASSWORD('$w0rdf1sh') WHERE User='tate256';"
Mixed Subtype
The "mixed" subtype of "multipart" is intended for use when the body parts are independent and need to be bundled in a particular order. Any "multipart" subtypes that an implementation does not recognize must be treated as being of subtype "mixed".
Alternative Subtype
The "multipart/alternative" type is syntactically identical to "multipart/mixed", but the semantics are different. In particular, each of the body parts is an "alternative" version of the same information
If you are using Linux + Sun JDK/JRE 32bits, change the "-vm" to:
-vm
[your_jdk_folder]/jre/lib/i386/client/libjvm.so
If you are using Linux + Sun JDK/JRE 64bits, change the "-vm" to:
-vm
[your_jdk_folder]/jre/lib/amd64/server/libjvm.so
That's working fine for me on Ubuntu 8.10 and 9.04
If you are using Python, I would suggest by exploring the request object:
dir(request)
Since the object support the method dict:
request.__dict__
It can be printed or saved. I use it to log 404 codes in Flask:
@app.errorhandler(404)
def not_found(e):
with open("./404.csv", "a") as f:
f.write(f'{datetime.datetime.now()},{request.__dict__}\n')
return send_file('static/images/Darknet-404-Page-Concept.png', mimetype='image/png')
It might help to "How to write the code for countdown watch in AngularJS"
Step 1 : HTML Code-sample
<div ng-app ng-controller="ExampleCtrl">
<div ng-show="countDown_text > 0">Your password is expired in 180 Seconds.</div>
<div ng-show="countDown_text > 0">Seconds left {{countDown_text}}</div>
<div ng-show="countDown_text == 0">Your password is expired!.</div>
</div>
Step 2 : The AngulaJs code-sample
function ExampleCtrl($scope, $timeout) {
var countDowner, countDown = 10;
countDowner = function() {
if (countDown < 0) {
$("#warning").fadeOut(2000);
countDown = 0;
return; // quit
} else {
$scope.countDown_text = countDown; // update scope
countDown--; // -1
$timeout(countDowner, 1000); // loop it again
}
};
$scope.countDown_text = countDown;
countDowner()
}
The full example over countdown watch in AngularJs as given below.
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Example - Single Timer Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script>
function ExampleCtrl($scope, $timeout) {
var countDowner, countDown = 10;
countDowner = function() {
if (countDown < 0) {
$("#warning").fadeOut(2000);
countDown = 0;
return; // quit
} else {
$scope.countDown_text = countDown; // update scope
countDown--; // -1
$timeout(countDowner, 1000); // loop it again
}
};
$scope.countDown_text = countDown;
countDowner()
}
</script>
</head>
<body>
<div ng-app ng-controller="ExampleCtrl">
<div ng-show="countDown_text > 0">Your password is expired in 180 Seconds.</div>
<div ng-show="countDown_text > 0">Seconds left {{countDown_text}}</div>
<div ng-show="countDown_text == 0">Your password is expired!.</div>
</div>
</body>
</html>
Add sudo to your command line, like:
$ sudo firebase init
Only Visual Studio 2015 Enterprise has code coverage built-in. See the feature matrix for details.
You can use the OpenCover.UI extension for code coverage check inside Visual Studio. It supports MSTest, nUnit, and xUnit.
The new version can be downloaded from here (release notes).
In modern Swift 5, with return capability:
/**
Makes sure no other thread reenters the closure before the one running has not returned
*/
@discardableResult
public func synchronized<T>(_ lock: AnyObject, closure:() -> T) -> T {
objc_sync_enter(lock)
defer { objc_sync_exit(lock) }
return closure()
}
Use it like this, to take advantage the return value capability:
let returnedValue = synchronized(self) {
// Your code here
return yourCode()
}
Or like that otherwise:
synchronized(self) {
// Your code here
yourCode()
}
What would you use a ConcurrentList for?
The concept of a Random Access container in a threaded world isn't as useful as it may appear. The statement
if (i < MyConcurrentList.Count)
x = MyConcurrentList[i];
as a whole would still not be thread-safe.
Instead of creating a ConcurrentList, try to build solutions with what's there. The most common classes are the ConcurrentBag and especially the BlockingCollection.
$('button').toggle(
function() {
$('#B').css('left', '0')
}, function() {
$('#B').css('left', '200px')
})
You can also see any animated version at http://jsfiddle.net/hThGb/2/
I prefer to stop the MongoDB server using the port
command itself.
sudo port unload mongodb
And to start it again.
sudo port load mongodb
Hey this is pretty simple to solve this error.Just follow this steps:
First uninstall any existing installation:
pip uninstall scikit-image
or, on conda-based systems:
conda uninstall scikit-image
Now, clone scikit-image on your local computer, and install:
git clone https://github.com/scikit-image/scikit-image.git
cd scikit-image
pip install -e .
To update the installation:
git pull # Grab latest source
pip install -e . # Reinstall
For other os and manual process please check this Link.
Make sure to check your build.gradle and that it doesn't use a newer SDK version than what is installed on your AVD. That's only if you use Android Studio though.
I think it really depends on why this error is given. It may be the bitness issue, but it may also be because of a deinstaller bug that leaves registry entries behind.
I just had this case because I need two versions of Python on my system. When I tried to install SCons (using Python2), the .msi installer failed, saying it only found Python3 in the registry. So I uninstalled it, with the result that no Python was found at all. Frustrating! (workaround: install SCons with pip install --egg --upgrade scons
)
Anyway, I'm sure there are threads on that phenomenon. I just thought it would fit here because this was one of my top search results.