[SOLVED] Simple one command to fix this issue.
yum install http://mirror.centos.org/centos/7/extras/x86_64/Packages/container-selinux-2.107-3.el7.noarch.rpm
Clearly, there is no perfect answer. However, if you want to allow the user to
then the easiest way seems to be to move the focus off the selected cell, so that clicking it will trigger a Select event.
One option is to move the focus as I suggested above, but this prevents cell editing. Another option is to extend the selection by one cell (left/right/up/down),because this permits editing of the original cell, but will trigger a Select event if that cell is clicked again on its own.
If you only wanted to trap selection of a single column of cells, you could insert a hidden column to the right, extend the selection to include the hidden cell to the right when the user clicked,and this gives you an editable cell which can be trapped every time it is clicked. The code is as follows
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'prevent Select event triggering again when we extend the selection below
Application.EnableEvents = False
Target.Resize(1, 2).Select
Application.EnableEvents = True
End Sub
You can get some help from AuthorityUtils class. Checking role as a one-liner:
if (AuthorityUtils.authorityListToSet(SecurityContextHolder.getContext().getAuthentication().getAuthorities()).contains("ROLE_MANAGER")) {
/* ... */
}
Caveat: This does not check role hierarchy, if such exists.
Using an in
can have a performance impact. Joining two subqueries will not have the same performance impact and can be accomplished like this:
SELECT *
FROM (SELECT msisdn
,callid
,Change_color
,play_file_name
,date_played
FROM insert_log
WHERE play_file_name NOT IN('Prompt1','Conclusion_Prompt_1','silent')
ORDER BY callid ASC) t1
JOIN (SELECT MAX(date_played) AS date_played
FROM insert_log GROUP BY callid) t2
ON t1.date_played = t2.date_played
I had to unslick the carousel before the ajax call starts, but you can't do that until there is already a slick carousel. So, I set a variable to 0 and only run unslick after it changed
var slide = 0
if(slide>0)
$('#ui-id-1').slick('unslick');
$.ajax({
//do stuff, here
},
success: function( data ) {
$('#ui-id-1').slick();
slide++;
}
Small tweak to Luke's answer,
function reloadJs(src) {
src = $('script[src$="' + src + '"]').attr("src");
$('script[src$="' + src + '"]').remove();
$('<script/>').attr('src', src).appendTo('head');
}
and call it like,
reloadJs("myFile.js");
This will not have any path related issues.
In the first place, you should note that PDF and HTML and different formats that hardly have anything in common. If TCPDF allows you to provide input data using HTML and CSS it's because it implements a simple parser for these two languages and tries to figure out how to translate that into PDF. So it's logical that TCPDF only supports a little subset of the HTML and CSS specification and, even in supported stuff, it's probably not as perfect as in first class web browsers.
Said that, the question is: what's supported and what's not? The documentation basically skips the issue and let's you enjoy the trial and error method.
Having a look at the source code, we can see there's a protected method called TCPDF::getHtmlDomArray()
that, among other things, parses CSS declarations. I can see stuff like font-family
, list-style-type
or text-indent
but there's no margin
or padding
as far as I can see and, definitively, there's no float
at all.
To sum up: with TCPDF, you can use CSS for some basic formatting. If you need to convert from HTML to PDF, it's the wrong tool. (If that's the case, may I suggest wkhtmltopdf?)
i use this code in App manifest
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:logo="@drawable/logo2"
android:label="@string/title_text"
android:theme="@style/Theme.Zinoostyle" >
my logo file is 200*800 pixel and use this code in main activity.java
getActionBar().setDisplayShowTitleEnabled(false);
it will work Corectly
I have used Awesomium.NET. Although I don't like the fact that it's not open-source, and also the fact that it uses a pretty old Webkit rendering engine, it is really easy to use. That's about the only endorsement I can give it.
After using session_destroy()
, the session is destroyed behind the scenes. For some reason this doesn't affect the values in $_SESSION
, which was already populated for this request, but it will be empty in future requests.
You can manually clear $_SESSION
if you so desire ($_SESSION = [];
).
ls -lh file.txt | awk '{ print $5 }'
The other solutions didn't work for me. Maybe the old DOCTYPE in the project I am working on prevents HTML5 options.
My solution:
<form id="form_1" action="result.php" method="post"
onsubmit="sendForm(this.id);return false">
<input type="hidden" name="something" value="1">
</form>
js:
function sendForm(form_id){
var form = $('#'+form_id);
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: $(form).serialize(),
success: function(result) {
console.log(result)
}
});
}
These examples are from php.net. Thanks to you, I also just learned about the new php hashing functions.
Read the php documentation to find out about the possibilities and best practices: http://www.php.net/manual/en/function.password-hash.php
Save a password hash:
$options = [
'cost' => 11,
];
// Get the password from post
$passwordFromPost = $_POST['password'];
$hash = password_hash($passwordFromPost, PASSWORD_BCRYPT, $options);
// Now insert it (with login or whatever) into your database, use mysqli or pdo!
Get the password hash:
// Get the password from the database and compare it to a variable (for example post)
$passwordFromPost = $_POST['password'];
$hashedPasswordFromDB = ...;
if (password_verify($passwordFromPost, $hashedPasswordFromDB)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
This code nearly worked for me...but I wanted a multiple element filter so my mods to the filter pipe are below:
import { Pipe, PipeTransform, Injectable } from '@angular/core';
@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {
transform(json: any[], args: any[]): any[] {
const searchText = args[0];
const jsonKey = args[1];
let jsonKeyArray = [];
if (searchText == null || searchText === 'undefined') { return json; }
if (jsonKey.indexOf(',') > 0) {
jsonKey.split(',').forEach( function(key) {
jsonKeyArray.push(key.trim());
});
} else {
jsonKeyArray.push(jsonKey.trim());
}
if (jsonKeyArray.length === 0) { return json; }
// Start with new Array and push found objects onto it.
let returnObjects = [];
json.forEach( function ( filterObjectEntry ) {
jsonKeyArray.forEach( function (jsonKeyValue) {
if ( typeof filterObjectEntry[jsonKeyValue] !== 'undefined' &&
filterObjectEntry[jsonKeyValue].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
// object value contains the user provided text.
returnObjects.push(filterObjectEntry);
}
});
});
return returnObjects;
}
}
Now, instead of
jsonFilterBy:[ searchText, 'name']
you can do
jsonFilterBy:[ searchText, 'name, other, other2...']
gdb -ex=r --args myprogram arg1 arg2
-ex=r
is short for -ex=run
and tells gdb to run your program immediately, rather than wait for you to type "run" at the prompt. Then --args
says that everything that follows is the command and arguments, just as you'd normally type them at the commandline prompt.
Try using ifconfig -a
. Look for "inet xxx.xxx.xxx.xxx", that is your IP address
Ctrl+Alt+Down Copies current line to below like notepad++ (Ctrl+D)
If your whole screen is 180° rotted then you should disable your hotkey settings.
Right Click -> Graphics Options -> Hot Keys -> Disable
That it now you done try shortcut Ctrl+Alt+Down
You should use a datastore and proxy in ExtJs. There are plenty of examples of this, and the JSON reader automatically parses the JSON message into the model you specified.
There is no need to use basic Javascript when using ExtJs, everything is different, you should use the ExtJs ways to get everything right. Read there documentation carefully, it's good.
By the way, these examples also hold for Sencha Touch (especially v2), which is based on the same core functions as ExtJs.
I know this is an old thread but to further expand the answer here, by default IIS 7.5 creates application pool identity accounts to run the worker process under. You can't search for these accounts like normal user accounts when adding file permissions. To add them into NTFS permission ACL you can type the entire name of the application pool identity and it will work.
It is just a slight difference in the way the application pool identity accounts are handle as they are seen to be virtual accounts.
Also the username of the application pool identity is "IIS AppPool\application pool name" so if it was the application pool DefaultAppPool the user account would be "IIS AppPool\DefaultAppPool".
These can be seen if you open computer management and look at the members of the local group IIS_IUSRS. The SID appended to the end of them is not need when adding the account into an NTFS permission ACL.
Hope that helps
For browsers supporting Object.keys() you can simply do:
Object.keys(a).length;
Otherwise (notably in IE < 9), you can loop through the object yourself with a for (x in y)
loop:
var count = 0;
var i;
for (i in a) {
if (a.hasOwnProperty(i)) {
count++;
}
}
The hasOwnProperty
is there to make sure that you're only counting properties from the object literal, and not properties it "inherits" from its prototype.
How about using the INSERT ALL statement ?
INSERT ALL
INTO table_name VALUES ()
INTO table_name VALUES ()
...
SELECT Statement;
I remember that the last select statement is mandatory in order to make this request succeed. Don't remember why though. You might consider using PreparedStatement instead as well. lots of advantages !
Farid
I've had the same error parsing a string containing \n
into JSON. The solution was to use string.replace('\n','\\n')
Rolling back to the previous installations (to MySQL Community Server 5.7 and Workbench 6.1)and setting up new MySQL credentials worked for me!
To declare a function that takes a pointer to an int:
void Foo(int *x);
To use this function:
int x = 4;
int *x_ptr = &x;
Foo(x_ptr);
Foo(&x);
If you want a pointer for another type of object, it's much the same:
void Foo(Object *o);
But, you may prefer to use references. They are somewhat less confusing than pointers:
// pass a reference
void Foo(int &x)
{
x = 2;
}
//pass a pointer
void Foo_p(int *p)
{
*x = 9;
}
// pass by value
void Bar(int x)
{
x = 7;
}
int x = 4;
Foo(x); // x now equals 2.
Foo_p(&x); // x now equals 9.
Bar(x); // x still equals 9.
With references, you still get to change the x that was passed to the function (as you would with a pointer), but you don't have to worry about dereferencing or address of operations.
As recommended by others, check out the C++FAQLite. It's an excellent resource for this.
Edit 3 response:
bar = &foo means: Make bar point to foo in memory
Yes.
*bar = foo means Change the value that bar points to to equal whatever foo equals
Yes.
If I have a second pointer (int *oof), then:
bar = oof means: bar points to the oof pointer
bar will point to whatever oof points to. They will both point to the same thing.
bar = *oof means: bar points to the value that oof points to, but not to the oof pointer itself
No. You can't do this (assuming bar is of type int *) You can make pointer pointers. (int **), but let's not get into that... You cannot assign a pointer to an int (well, you can, but that's a detail that isn't in line with the discussion).
*bar = *oof means: change the value that bar points to to the value that oof points to
Yes.
&bar = &oof means: change the memory address that bar points to be the same as the memory address that oof points to
No. You can't do this because the address of operator returns an rvalue. Basically, that means you can't assign something to it.
list(your_iterator)
Java also provides a nice way of calling async methods. in java.util.concurrent we have ExecutorService that helps in doing the same. Initialize your object like this -
private ExecutorService asyncExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
and then call the function like-
asyncExecutor.execute(() -> {
TimeUnit.SECONDS.sleep(3L);}
First I think int&const icr=i;
is just int& icr = i
, Modifier 'const' makes no sense(It just means you cannot make the reference refer to other variable).
const int x = 10;
// int& const y = x; // Compiler error here
Second, constant reference just means you cannot change the value of variable through reference.
const int x = 10;
const int& y = x;
//y = 20; // Compiler error here
Third, Constant references can bind right-value. Compiler will create a temp variable to bind the reference.
float x = 10;
const int& y = x;
const int& z = y + 10;
cout << (long long)&x << endl; //print 348791766212
cout << (long long)&y << endl; //print 348791766276
cout << (long long)&z << endl; //print 348791766340
Your concatenation syntax is correct.
Most likely the callback function isn't even being called. You can test that by putting an alert()
, console.log()
or debugger
line in that function.
If it isn't being called, most likely there's an AJAX error. Look at chaining a .fail()
handler after $.post()
to find out what the error is, e.g.:
$.post('ajaxskeleton.php', {
red: text
}, function(){
$('#part' + number).html(text);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(arguments);
});
You can do that simply through 1 line of code using moment in Node JS. :)
let lastOneMonthDate = moment().subtract(30,"days").utc().toISOString()
Don't want UTC format, EASIER :P
let lastOneMonthDate = moment().subtract(30,"days").toISOString()
This code can help you :
$(document).ready(function() {
$('#calendar').fullCalendar({
events:
[
{
id: 1,
title: 'First Event',
start: ...,
end: ...,
description: 'first description'
},
{
id: 2,
title: 'Second Event',
start: ...,
end: ...,
description: 'second description'
}
],
eventRender: function(event, element) {
element.find('.fc-title').append("<br/>" + event.description);
}
});
}
Yes, you must open php.ini
and remove the semicolon to:
;extension=php_openssl.dll
If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext
) and add this to php.ini
in the "Dynamic Extensions" section:
extension=php_openssl.dll
Things have changed for PHP > 7. This is what i had to do for PHP 7.2.
Step: 1: Uncomment extension=openssl
Step: 2: Uncomment extension_dir = "ext"
Step: 3: Restart xampp.
Done.
Explanation: ( From php.ini )
If you wish to have an extension loaded automatically, use the following syntax:
extension=modulename
Note : The syntax used in previous PHP versions (extension=<ext>.so
and extension='php_<ext>.dll
) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>
) syntax.
Special Note: Be sure to appropriately set the extension_dir
directive.
I think what you're trying to do can be done through templates. I'm trying to read between the lines here. What you're trying to do is to call a method from some code, where it calls a derived version but the caller doesn't specify which class. Example:
class Foo {
public:
void M() {...}
};
class Bar : public Foo {
public:
void M() {...}
};
void Try()
{
xxx::M();
}
int main()
{
Try();
}
You want Try() to call the Bar version of M without specifying Bar. The way you do that for statics is to use a template. So change it like so:
class Foo {
public:
void M() {...}
};
class Bar : public Foo {
public:
void M() {...}
};
template <class T>
void Try()
{
T::M();
}
int main()
{
Try<Bar>();
}
Check your all privacy access policy option in Info.plist file.
In order to use my example,Your file "abc.txt" needs to look like:
[your-config]
path1 = "D:\test1\first"
path2 = "D:\test2\second"
path3 = "D:\test2\third"
Then in your software you can use the config parser:
import ConfigParser
and then in you code:
configParser = ConfigParser.RawConfigParser()
configFilePath = r'c:\abc.txt'
configParser.read(configFilePath)
Use case:
self.path = configParser.get('your-config', 'path1')
*Edit (@human.js)
in python 3, ConfigParser is renamed to configparser (as described here)
It's caused by n % x
where x = 0
in the first loop iteration. You can't calculate a modulus with respect to 0.
Can't take credit for this, but @grenade pointed out that npm dedupe
will fix the cause (too many files) and not the symptom.
Source: Grunt watch error - Waiting…Fatal error: watch ENOSPC.
To get the last element, simply use the size of the list as the second parameter. So for example, if you have 35 files, and you want the last five, you would do:
dataList.subList(30, 35);
A guaranteed safe way to do this is:
dataList.subList(Math.max(0, first), Math.min(dataList.size(), last) );
In addition to being able to add a number of days to a date, you can use interval data types assuming you are on Oracle 9i
or later, which can be somewhat easier to read,
SQL> ed
Wrote file afiedt.buf
SELECT sysdate, sysdate + interval '30' minute FROM dual
SQL> /
SYSDATE SYSDATE+INTERVAL'30'
-------------------- --------------------
02-NOV-2008 16:21:40 02-NOV-2008 16:51:40
Also, if your service is sending an object instead of an array add isArray:false to its declaration.
'query': {method: 'GET', isArray: false }
Maybe you can filter rows by possible columns like this :
DataRow[] filteredRows =
datatable.Select(string.Format("{0} LIKE '%{1}%'", columnName, value));
dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
As others have pointed out, you can also use the equivalent built-in math.hypot()
:
dist = math.hypot(x2 - x1, y2 - y1)
Just another way to do this:
=MID(A1, LEN(A1), 1)
Class is a template or type. An object is an instance of the class.
For example:
public class Tweet {
}
Tweet newTweet = new Tweet();
Tweet is a class and newTweet is an object of the class.
In case you are using quite popular in Spring Boot environment Kubernetes (K8S) or OpenShift, there's a possibility to store and retrieve application properties on runtime. This technique called secrets. In your configuration yaml file for Kubernetes or OpenShift you declare variable and placeholder for it, and on K8S\OpenShift side declare actual value which corresponds to this placeholder. For implementation details, see: K8S: https://kubernetes.io/docs/concepts/configuration/secret/ OpenShift: https://docs.openshift.com/container-platform/3.11/dev_guide/secrets.html
Should be .\SQLExpress
or localhost\SQLExpress
no $ sign at the end
See also here http://www.connectionstrings.com/sql-server-2008
For small tables DELETE
is often faster and needs less aggressive locking (for heavy concurrent load):
DELETE FROM tbl;
With no WHERE
condition.
For medium or bigger tables, go with TRUNCATE tbl
, like @Greg posted.
Thanks a lot guys for your quick comments.
This is what i will be using now. Posting the function here so that somebody may use it.
public function getDayOfWeek($pTimezone)
{
$userDateTimeZone = new DateTimeZone($pTimezone);
$UserDateTime = new DateTime("now", $userDateTimeZone);
$offsetSeconds = $UserDateTime->getOffset();
//echo $offsetSeconds;
return gmdate("l", time() + $offsetSeconds);
}
Report if you find any corrections.
Java references always point to an object. The object has a header that amongst other things identifies the concrete type (so casts can fail with ClassCastException
). For arrays, the start of the object also includes the length, the data then follows immediately after in memory (technically an implementation is free to do what it pleases, but it would be daft to do anything else). So, you can;t have a reference that points somewhere into an array.
In C pointers point anywhere and to anything, and you can point to the middle of an array. But you can't safely cast or find out how long the array is. In D the pointer contains an offset into the memory block and length (or equivalently a pointer to the end, I can't remember what the implementation actually does). This allows D to slice arrays. In C++ you would have two iterators pointing to the start and end, but C++ is a bit odd like that.
So getting back to Java, no you can't. As mentioned, NIO ByteBuffer
allows you to wrap an array and then slice it, but gives an awkward interface. You can of course copy, which is probably very much faster than you would think. You could introduce your own String
-like abstraction that allows you to slice an array (the current Sun implementation of String
has a char[]
reference plus a start offset and length, higher performance implementation just have the char[]
). byte[]
is low level, but any class-based abstraction you put on that is going to make an awful mess of the syntax, until JDK7 (perhaps).
You could try:
$j('div.contextualError.ckgcellphone').css('display')
According to MDN, "matchMedia" is the proper way to do this https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio#Monitoring_screen_resolution_or_zoom_level_changes
it's a bit finicky because each instance can only watch one MQ at a time, so if you're interested in any zoom level change you need to make a bunch of matchers.. but since the browser is in charge to emitting the events it's probably still more performant than polling, and you could throttle or debounce the callback or pin it to an animation frame or something - here's an implementation that seems pretty snappy, feel free to swap in _throttle or whatever if you're already depending on that.
Run the code snippet and zoom in and out in your browser, note the updated value in the markup - I only tested this in Firefox! lemme know if you see any issues.
const el = document.querySelector('#dppx')_x000D_
_x000D_
if ('matchMedia' in window) {_x000D_
function observeZoom(cb, opts) {_x000D_
opts = {_x000D_
// first pass for defaults - range and granularity to capture all the zoom levels in desktop firefox_x000D_
ceiling: 3,_x000D_
floor: 0.3,_x000D_
granularity: 0.05,_x000D_
...opts_x000D_
}_x000D_
const precision = `${opts.granularity}`.split('.')[1].length_x000D_
_x000D_
let val = opts.floor_x000D_
const vals = []_x000D_
while (val <= opts.ceiling) {_x000D_
vals.push(val)_x000D_
val = parseFloat((val + opts.granularity).toFixed(precision))_x000D_
}_x000D_
_x000D_
// construct a number of mediamatchers and assign CB to all of them_x000D_
const mqls = vals.map(v => matchMedia(`(min-resolution: ${v}dppx)`))_x000D_
_x000D_
// poor person's throttle_x000D_
const throttle = 3_x000D_
let last = performance.now()_x000D_
mqls.forEach(mql => mql.addListener(function() {_x000D_
console.debug(this, arguments)_x000D_
const now = performance.now()_x000D_
if (now - last > throttle) {_x000D_
cb()_x000D_
last = now_x000D_
}_x000D_
}))_x000D_
}_x000D_
_x000D_
observeZoom(function() {_x000D_
el.innerText = window.devicePixelRatio_x000D_
})_x000D_
} else {_x000D_
el.innerText = 'unable to observe zoom level changes, matchMedia is not supported'_x000D_
}
_x000D_
<div id='dppx'>--</div>
_x000D_
Goto Advanced tab----> data type of column---> Here change data type from DT_STR to DT_TEXT and column width 255. Now you can check it will work perfectly.
** Update ** A scalars converter has been added to retrofit that allows for a String
response with less ceremony than my original answer below.
Example interface --
public interface GitHubService {
@GET("/users/{user}")
Call<String> listRepos(@Path("user") String user);
}
Add the ScalarsConverterFactory
to your retrofit builder. Note: If using ScalarsConverterFactory
and another factory, add the scalars factory first.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
// add other factories here, if needed.
.build();
You will also need to include the scalars converter in your gradle file --
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
--- Original Answer (still works, just more code) ---
I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject
land. I suspect your specific problem might be better solved using a custom gson TypeAdapter
or a retrofit Converter
if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -
First, if you are using Retrofit 2, you should start using the Call
API. Instead of sending an object to convert as the type parameter, use ResponseBody
from okhttp --
public interface GitHubService {
@GET("/users/{user}")
Call<ResponseBody> listRepos(@Path("user") String user);
}
then you can create and execute your call --
GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});
Note The code above calls string()
on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream()
instead. See the ResponseBody
docs.
After working on this on and off for a few days, here is the answer I would have wished to find, using pywin32 to keep it nice and self contained.
This is complete working code for one loop-based and one thread-based solution. It may work on both python 2 and 3, although I've only tested the latest version on 2.7 and Win7. The loop should be good for polling code, and the tread should work with more server-like code. It seems to work nicely with the waitress wsgi server that does not have a standard way to shut down gracefully.
I would also like to note that there seems to be loads of examples out there, like this that are almost useful, but in reality misleading, because they have cut and pasted other examples blindly. I could be wrong. but why create an event if you never wait for it?
That said I still feel I'm on somewhat shaky ground here, especially with regards to how clean the exit from the thread version is, but at least I believe there are nothing misleading here.
To run simply copy the code to a file and follow the instructions.
Use a simple flag to terminate thread. The important bit is that "thread done" prints.
For a more elaborate example exiting from an uncooperative server thread see my post about the waitress wsgi server.
# uncomment mainthread() or mainloop() call below
# run without parameters to see HandleCommandLine options
# install service with "install" and remove with "remove"
# run with "debug" to see print statements
# with "start" and "stop" watch for files to appear
# check Windows EventViever for log messages
import socket
import sys
import threading
import time
from random import randint
from os import path
import servicemanager
import win32event
import win32service
import win32serviceutil
# see http://timgolden.me.uk/pywin32-docs/contents.html for details
def dummytask_once(msg='once'):
fn = path.join(path.dirname(__file__),
'%s_%s.txt' % (msg, randint(1, 10000)))
with open(fn, 'w') as fh:
print(fn)
fh.write('')
def dummytask_loop():
global do_run
while do_run:
dummytask_once(msg='loop')
time.sleep(3)
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global do_run
do_run = True
print('thread start\n')
dummytask_loop()
print('thread done\n')
def exit(self):
global do_run
do_run = False
class SMWinservice(win32serviceutil.ServiceFramework):
_svc_name_ = 'PyWinSvc'
_svc_display_name_ = 'Python Windows Service'
_svc_description_ = 'An example of a windows service in Python'
@classmethod
def parse_command_line(cls):
win32serviceutil.HandleCommandLine(cls)
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.stopEvt = win32event.CreateEvent(None, 0, 0, None) # create generic event
socket.setdefaulttimeout(60)
def SvcStop(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STOPPED,
(self._svc_name_, ''))
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.stopEvt) # raise event
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ''))
# UNCOMMENT ONE OF THESE
# self.mainthread()
# self.mainloop()
# Wait for stopEvt indefinitely after starting thread.
def mainthread(self):
print('main start')
self.server = MyThread()
self.server.start()
print('wait for win32event')
win32event.WaitForSingleObject(self.stopEvt, win32event.INFINITE)
self.server.exit()
print('wait for thread')
self.server.join()
print('main done')
# Wait for stopEvt event in loop.
def mainloop(self):
print('loop start')
rc = None
while rc != win32event.WAIT_OBJECT_0:
dummytask_once()
rc = win32event.WaitForSingleObject(self.stopEvt, 3000)
print('loop done')
if __name__ == '__main__':
SMWinservice.parse_command_line()
By far the best option nowadays would be using a maven container as a builder tool. A mvn.sh
script like this would be enough:
#!/bin/bash
docker run --rm -ti \
-v $(pwd):/opt/app \
-w /opt/app \
-e TERM=xterm \
-v $HOME/.m2:/root/.m2 \
maven mvn "$@"
The __doPostBack()
method works well.
Another solution (very hackish) is to simply add an invisible ASP button in your markup and click it with a JavaScript method.
<div style="display: none;">
<asp:Button runat="server" ... OnClick="ButtonClickHandlerMethod" />
</div>
From your JavaScript, retrieve the reference to the button using its ClientID and then call the .click() method on it.
var button = document.getElementById(/* button client id */);
button.click();
It might be the JavaScript check for some valid condition.
Two things you can perform a/c to your requirements:
String barcode="0000000047166";
WebElement strLocator = driver.findElement(By.xpath("//*[@id='div-barcode']"));
strLocator.sendKeys(barcode);
echo "<a href='index.php'>Index Page</a>";
if you wanna use html tag like anchor tag you have to put in echo
This should work (which you have tried)
$this->db->where_not_in('emailsToCampaigns.campaignId', $campaignId);
string id;
foreach (GridViewRow rows in grd.Rows)
{
TextBox lblStrucID = (TextBox)rows.FindControl("grdtext");
id=lblStrucID.Text
}
This should work. getElementsByClassName
returns an array Array-like object(see edit) of the elements matching the criteria.
var elements = document.getElementsByClassName("classname");
var myFunction = function() {
var attribute = this.getAttribute("data-myattribute");
alert(attribute);
};
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', myFunction, false);
}
jQuery does the looping part for you, which you need to do in plain JavaScript.
If you have ES6 support you can replace your last line with:
Array.from(elements).forEach(function(element) {
element.addEventListener('click', myFunction);
});
Note: Older browsers (like IE6, IE7, IE8) don´t support getElementsByClassName
and so they return undefined
.
EDIT : Correction
getElementsByClassName
doesnt return an array, but a HTMLCollection in most, or a NodeList in some browsers (Mozilla ref). Both of these types are Array-Like, (meaning that they have a length property and the objects can be accessed via their index), but are not strictly an Array or inherited from an Array. (meaning other methods that can be performed on an Array cannot be performed on these types)
Thanks to user @Nemo for pointing this out and having me dig in to fully understand.
For O(1) complexity of head,tail
operation you should use deque
however.
Following way:
from collections import deque
l = deque([1,2,3,4,5,6,7,8,9])
head, tail = l.popleft(), l
It's useful when you must iterate through all elements of the list. For example in naive merging 2 partitions in merge sort.
I think structuring the project by functionalities is a practical method. It makes the project scalable and maintainable easily. And it makes each part of the project working in a total autonomy. Let me know what you think about this structure below: ANGULAR TYPESCRIPT PROJECT STRUCTURE – ANGULAR 2
source : http://www.angulartypescript.com/angular-typescript-project-structure/
An explicit call to a parent class constructor is required any time the parent class lacks a no-argument constructor. You can either add a no-argument constructor to the parent class or explicitly call the parent class constructor in your child class.
In my instance, there was something completely odd that I'm not sure what the cause was. An entire folder was committed previously. I could see it in Git, Windows Explorer, and GitHub, but any changes I made to the folder itself and the files in it were ignored. Using git check-ignore
to see what was ignoring it, and attempting to remove it using git rm --cached
had no impact. The changes were not able to be staged.
I fixed it by:
And you should use neither if you have plenty of RAM. Redis and MongoDB come to the price of a general purpose tool. This introduce a lot of overhead.
There was the saying that Redis is 10 times faster than Mongo. That might not be that true anymore. MongoDB (if i remember correctly) claimed to beat memcache for storing and caching documents as long as the memory configurations are the same.
Anyhow. Redis good, MongoDB is good. If you care about substructures and need aggregation go for MongoDB. If storing keys and values is your main concern its all about Redis. (or any other key value store).
There you go:
timeout --signal=SIGINT 10 /path/to/slow command with options
you may change the SIGINT
and 10
as you desire ;)
ep = datetime.datetime(1970,1,1,0,0,0)
x = (datetime.datetime.utcnow()- ep).total_seconds()
This should be different from int(time.time())
, but it is safe to use something like x % (60*60*24)
datetime — Basic date and time types:
Unlike the time module, the datetime module does not support leap seconds.
I think you can find it usefull
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-two-datasources
It shows how to define multiple datasources & assign one of them as primary.
Here is a rather full example, also contains distributes transactions - if you need it.
What you need is to create 2 configuration classes, separate the model/repository packages etc to make the config easy.
Also, in above example, it creates the data sources manually. You can avoid this using the method on spring doc, with @ConfigurationProperties annotation. Here is an example of this:
http://xantorohara.blogspot.com.tr/2013/11/spring-boot-jdbc-with-multiple.html
Hope these helps.
For me it is an entirely different story.
Since this page has a good search engine ranking, I should add my case and the solution here too.
I built jquery
myself with webpack
picking only the modules I use. The ajax is always failed with "No Transport" message as the only clue.
After a long debugging, the problem turns out to be XMLHttpRequest
is pluggable in jquery
and it not include by default.
You have to explicitly include jquery/src/ajax/xhr
file in order to make the ajax working in browsers.
Use its name()
method:
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(Strings.ONE.name());
}
}
enum Strings {
ONE, TWO, THREE
}
yields ONE
.
@eOnOe has answered how we can change status bar tint through xml. But we can also change it dynamically in code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
View decor = getWindow().getDecorView();
if (shouldChangeStatusBarTintToDark) {
decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
} else {
// We want to change tint color to white again.
// You can also record the flags in advance so that you can turn UI back completely if
// you have set other flags before, such as translucent or full screen.
decor.setSystemUiVisibility(0);
}
}
PS
command prompt to appearNavigate to the directory where the script lives
PS> cd C:\my_path\yada_yada\ (enter)
Execute the script:
PS> .\run_import_script.ps1 (enter)
What am I missing??
Or: you can run the PowerShell script from cmd.exe
like this:
powershell -noexit "& ""C:\my_path\yada_yada\run_import_script.ps1""" (enter)
according to this blog post here
Or you could even run your PowerShell script from your C# application :-)
Asynchronously execute PowerShell scripts from your C# application
You have a numpy array of strings, not floats. This is what is meant by dtype('<U9')
-- a little endian encoded unicode string with up to 9 characters.
try:
return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))
However, you don't need numpy here at all. You can really just do:
return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)
Or if you're really set on using numpy.
return np.asarray(listOfEmb, dtype=float).mean()
Yeah, this is a general generics problem, not mockito-specific.
There is no class object for ArrayList<SomeType>
, and thus you can't type-safely pass such an object to a method requiring a Class<ArrayList<SomeType>>
.
You can cast the object to the right type:
Class<ArrayList<SomeType>> listClass =
(Class<ArrayList<SomeType>>)(Class)ArrayList.class;
ArgumentCaptor<ArrayList<SomeType>> argument = ArgumentCaptor.forClass(listClass);
This will give some warnings about unsafe casts, and of course your ArgumentCaptor can't really differentiate between ArrayList<SomeType>
and ArrayList<AnotherType>
without maybe inspecting the elements.
(As mentioned in the other answer, while this is a general generics problem, there is a Mockito-specific solution for the type-safety problem with the @Captor
annotation. It still can't distinguish between an ArrayList<SomeType>
and an ArrayList<OtherType>
.)
Take also a look at tenshis comment. You can change the original code from Paulo Ebermann to this (much simpler)
final ArgumentCaptor<List<SomeType>> listCaptor
= ArgumentCaptor.forClass((Class) List.class);
Make Enable32bit Application to TRUE in the IIS App pool which you are consuming
Git 2.6 (Sept/Oct 2015) will add the option --name-only
to simplify the output of a git config -l
:
See commit a92330d, commit f225987, commit 9f1429d (20 Aug 2015) by Jeff King (peff
).
See commit ebca2d4 (20 Aug 2015), and commit 905f203, commit 578625f (10 Aug 2015) by SZEDER Gábor (szeder
).
(Merged by Junio C Hamano -- gitster
-- in commit fc9dfda, 31 Aug 2015)
config
: add '--name-only
' option to list only variable names'
git config
' can only show values or name-value pairs, so if a shell script needs the names of set config variables it has to run 'git config --list
' or '--get-regexp
' and parse the output to separate config variable names from their values.
However, such a parsing can't cope with multi-line values.Though '
git config
' can produce null-terminated output for newline-safe parsing, that's of no use in such a case, because shells can't cope with null characters.Even our own bash completion script suffers from these issues.
Help the completion script, and shell scripts in general, by introducing the '
--name-only
' option to modify the output of '--list
' and '--get-regexp
' to list only the names of config variables, so they don't have to perform error-prone post processing to separate variable names from their values anymore.
If you look at either of the following keys:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\hivelist
You can find a list of the SIDs there with various values, including where their "home paths" which includes their usernames.
I'm not sure how dependable this is and I wouldn't recommend messing about with this unless you're really sure what you're doing.
Another option may be to have your fragment implement View.OnClickListener and override onClick(View v) within your fragment. If you need to have your fragment talk to the activity simply add an interface with desired method(s) and have the activity implement the interface and override its method(s).
public class FragName extends Fragment implements View.OnClickListener {
public FragmentCommunicator fComm;
public ImageButton res1, res2;
int c;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_test, container, false);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
fComm = (FragmentCommunicator) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement FragmentCommunicator");
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
res1 = (ImageButton) getActivity().findViewById(R.id.responseButton1);
res1.setOnClickListener(this);
res2 = (ImageButton) getActivity().findViewById(R.id.responseButton2);
res2.setOnClickListener(this);
}
public void onClick(final View v) { //check for what button is pressed
switch (v.getId()) {
case R.id.responseButton1:
c *= fComm.fragmentContactActivity(2);
break;
case R.id.responseButton2:
c *= fComm.fragmentContactActivity(4);
break;
default:
c *= fComm.fragmentContactActivity(100);
break;
}
public interface FragmentCommunicator{
public int fragmentContactActivity(int b);
}
public class MainActivity extends FragmentActivity implements FragName.FragmentCommunicator{
int a = 10;
//variable a is update by fragment. ex. use to change textview or whatever else you'd like.
public int fragmentContactActivity(int b) {
//update info on activity here
a += b;
return a;
}
}
http://developer.android.com/training/basics/firstapp/starting-activity.html http://developer.android.com/training/basics/fragments/communicating.html
I follow Kelsey's first set of steps to add the installer classes to my service project, but instead of creating an MSI or setup.exe installer I make the service self installing/uninstalling. Here's a bit of sample code from one of my services you can use as a starting point.
public static int Main(string[] args)
{
if (System.Environment.UserInteractive)
{
// we only care about the first two characters
string arg = args[0].ToLowerInvariant().Substring(0, 2);
switch (arg)
{
case "/i": // install
return InstallService();
case "/u": // uninstall
return UninstallService();
default: // unknown option
Console.WriteLine("Argument not recognized: {0}", args[0]);
Console.WriteLine(string.Empty);
DisplayUsage();
return 1;
}
}
else
{
// run as a standard service as we weren't started by a user
ServiceBase.Run(new CSMessageQueueService());
}
return 0;
}
private static int InstallService()
{
var service = new MyService();
try
{
// perform specific install steps for our queue service.
service.InstallService();
// install the service with the Windows Service Control Manager (SCM)
ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
}
catch (Exception ex)
{
if (ex.InnerException != null && ex.InnerException.GetType() == typeof(Win32Exception))
{
Win32Exception wex = (Win32Exception)ex.InnerException;
Console.WriteLine("Error(0x{0:X}): Service already installed!", wex.ErrorCode);
return wex.ErrorCode;
}
else
{
Console.WriteLine(ex.ToString());
return -1;
}
}
return 0;
}
private static int UninstallService()
{
var service = new MyQueueService();
try
{
// perform specific uninstall steps for our queue service
service.UninstallService();
// uninstall the service from the Windows Service Control Manager (SCM)
ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
}
catch (Exception ex)
{
if (ex.InnerException.GetType() == typeof(Win32Exception))
{
Win32Exception wex = (Win32Exception)ex.InnerException;
Console.WriteLine("Error(0x{0:X}): Service not installed!", wex.ErrorCode);
return wex.ErrorCode;
}
else
{
Console.WriteLine(ex.ToString());
return -1;
}
}
return 0;
}
@ECHO OFF
:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/
:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"
:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m
:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m
PAUSE
Since the assembly resides in a temporary cache, you should combine the path to get the dll's config:
var appConfig = ConfigurationManager.OpenExeConfiguration(
Path.Combine(Environment.CurrentDirectory, Assembly.GetExecutingAssembly().ManifestModule.Name));
The data.table
package has its IDate
class and functionalities similar to lubridate
or the zoo
package. You could do:
dt = data.table(
Name = c('Joe', 'Amy', 'John'),
JoiningDate = c('12/31/09', '10/28/09', '05/06/10'),
AmtPaid = c(1000, 100, 200)
)
require(data.table)
dt[ , JoiningDate := as.IDate(JoiningDate, '%m/%d/%y') ]
I think the only way to handle this is to use JavaScript
Try this Invert text color of a specific element
If you do this with css3 it's only compatible with the newest browser versions.
how can I fill a multidimensional array in Java without using a loop?
Multidimensional arrays are just arrays of arrays and fill(...)
doesn't check the type of the array and the value you pass in (this responsibility is upon the developer).
Thus you can't fill a multidimensional array reasonably well without using a loop.
Be aware of the fact that, unlike languages like C or C++, Java arrays are objects and in multidimensional arrays all but the last level contain references to other Array
objects. I'm not 100% sure about this, but most likely they are distributed in memory, thus you can't just fill a contiguous block without a loop, like C/C++ would allow you to do.
Permanent:
UPDATE
MyTable
SET
MyColumn = UPPER(MyColumn)
Temporary:
SELECT
UPPER(MyColumn) AS MyColumn
FROM
MyTable
Well to start with, you should only deal with them as strings when you have to. Most of the time you should work with them in a data type which actually describes the data you're working with.
I would recommend that you use Joda Time, which is a much better API than Date
/Calendar
. It sounds like you should use the LocalDate
type in this case. You can then use:
int days = Days.daysBetween(date1, date2).getDays();
I know my answer is not on time but this is purely code no xml
required.
This is for use in Activity
public void setTitle(String title){
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
TextView textView = new TextView(this);
textView.setText(title);
textView.setTextSize(20);
textView.setTypeface(null, Typeface.BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
textView.setTextColor(getResources().getColor(R.color.white));
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(textView);
}
This is for use in Fragment
public void setTitle(String title){
((AppCompatActivity)getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
TextView textView = new TextView(getActivity());
textView.setText(title);
textView.setTextSize(20);
textView.setTypeface(null, Typeface.BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
textView.setTextColor(getResources().getColor(R.color.white));
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
((AppCompatActivity)getActivity()).getSupportActionBar().setCustomView(textView);
}
'DD/MM/YYYY hh:mm A' => 12 hours 'DD/MM/YYYY HH:mm A' => 24 hours
Are you talking about getchar
function?
I found the below TSQL a fairly elegant solution (I don't have permissions to run functions). I found the DATEDIFF
ignores DATEFIRST
and I wanted my first day of the week to be a Monday. I also wanted the first working day to be set a zero and if it falls on a weekend Monday will be a zero. This may help someone who has a slightly different requirement :)
It does not handle bank holidays
SET DATEFIRST 1
SELECT
,(DATEDIFF(DD, [StartDate], [EndDate]))
-(DATEDIFF(wk, [StartDate], [EndDate]))
-(DATEDIFF(wk, DATEADD(dd,-@@DATEFIRST,[StartDate]), DATEADD(dd,-@@DATEFIRST,[EndDate]))) AS [WorkingDays]
FROM /*Your Table*/
create toggle_selector.xml in res/drawable
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/toggle_on" android:state_checked="true"/>
<item android:drawable="@drawable/toggle_off" android:state_checked="false"/>
</selector>
apply the selector to your toggle button
<ToggleButton
android:id="@+id/chkState"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/toggle_selector"
android:textOff=""
android:textOn=""/>
Note: for removing the text i used following in above code
textOff=""
textOn=""
For future reference, deleting nodes with SimpleXML can be a pain sometimes, especially if you don't know the exact structure of the document. That's why I have written SimpleDOM, a class that extends SimpleXMLElement to add a few convenience methods.
For instance, deleteNodes() will delete all nodes matching a XPath expression. And if you want to delete all nodes with the attribute "id" equal to "A5", all you have to do is:
// don't forget to include SimpleDOM.php
include 'SimpleDOM.php';
// use simpledom_load_string() instead of simplexml_load_string()
$data = simpledom_load_string(
'<data>
<seg id="A1"/>
<seg id="A5"/>
<seg id="A12"/>
<seg id="A29"/>
<seg id="A30"/>
</data>'
);
// and there the magic happens
$data->deleteNodes('//seg[@id="A5"]');
following lines works for me. I am using mac 10.7.2 .
sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
Try:
select id, game, min(point) from t
group by id
I have the current latest version of MySQL: 8.0.20
So my table name is visit, my column name is curdate.
alter table visit modify curdate date not null default (current_date);
This writes the default date value with no timestamp.
svn merge will merge revisions, not revert them. i.e. if you have some addition in your HEAD version then merge that with a previous revision, then the change will persist.
I use svn cat then redirect it into the file:
svn cat -r 851 l3toks.dtx > l3toks.dtx
Then you have the 851 content in that file and can check it back in.
It seems that you are looking to parse commandline arguments into your bash script. I have searched for this recently myself. I came across the following which I think will assist you in parsing the arguments:
http://rsalveti.wordpress.com/2007/04/03/bash-parsing-arguments-with-getopts/
I added the snippet below as a tl;dr
#using : after a switch variable means it requires some input (ie, t: requires something after t to validate while h requires nothing.
while getopts “ht:r:p:v” OPTION
do
case $OPTION in
h)
usage
exit 1
;;
t)
TEST=$OPTARG
;;
r)
SERVER=$OPTARG
;;
p)
PASSWD=$OPTARG
;;
v)
VERBOSE=1
;;
?)
usage
exit
;;
esac
done
if [[ -z $TEST ]] || [[ -z $SERVER ]] || [[ -z $PASSWD ]]
then
usage
exit 1
fi
./script.sh -t test -r server -p password -v
For starters:
<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.
This would be the optimal solution:
<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
create view view_clients_credit_usage as
select client_id, sum(credits_used) as credits_used
from credit_usage
group by client_id
create view view_credit_status as
select
credit_orders.client_id,
sum(credit_orders.number_of_credits) as purchased,
ifnull(t1.credits_used,0) as used
from credit_orders
left outer join view_clients_credit_usage as t1 on t1.client_id = credit_orders.client_id
where credit_orders.payment_status='Paid'
group by credit_orders.client_id)
I got the same exact error with In case it helps others .. documenting what worked for me useful for very latest (Jan 14, 2017) latest everything. Tried all the Invalidate, build clean, even deleting .gradle/, tweaking the support libs etc.. on multiple stack overflow answers.
I found that upgrading the settings.gradle gradle version fixed it (it was 2.1.3) something in gradle toolchain seems to classpath 'com.android.tools.build:gradle:2.2.3'
import java.io.*;
class Initials {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s;
char x;
int l;
System.out.print("Enter any sentence: ");
s = br.readLine();
s = " " + s; //adding a space infront of the inputted sentence or a name
s = s.toUpperCase(); //converting the sentence into Upper Case (Capital Letters)
l = s.length(); //finding the length of the sentence
System.out.print("Output = ");
for (int i = 0; i < l; i++) {
x = s.charAt(i); //taking out one character at a time from the sentence
if (x == ' ') //if the character is a space, printing the next Character along with a fullstop
System.out.print(s.charAt(i + 1) + ".");
}
}
}
use fs?path module can got the folder. this use Promise. If your will get the fill, your can change isDirectory() to isFile() Nodejs--fs--fs.Stats.At last, you can get the file'name file'extname and so on Nodejs---Path
var fs = require("fs"),
path = require("path");
//your <MyFolder> path
var p = "MyFolder"
fs.readdir(p, function (err, files) {
if (err) {
throw err;
}
//this can get all folder and file under <MyFolder>
files.map(function (file) {
//return file or folder path, such as **MyFolder/SomeFile.txt**
return path.join(p, file);
}).filter(function (file) {
//use sync judge method. The file will add next files array if the file is directory, or not.
return fs.statSync(file).isDirectory();
}).forEach(function (files) {
//The files is array, so each. files is the folder name. can handle the folder.
console.log("%s", files);
});
});
Swift 4
let tap = UITapGestureRecognizer(target: self, action: #selector(self.touchTapped(_:)))
self.view.addGestureRecognizer(tap)
@objc func touchTapped(_ sender: UITapGestureRecognizer) {
}
@UniqueConstraint this annotation is used for annotating single or multiple unique keys at the table level separated by comma, which is why you get an error. it will only work if you let JPA create your tables
Example
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Builder(builderClassName = "Builder", toBuilder = true)
@Entity
@Table(name = "users", uniqueConstraints = @UniqueConstraint(columnNames = {"person_id", "company_id"}))
public class AppUser extends BaseEntity {
@Column(name = "person_id")
private Long personId;
@ManyToOne
@JoinColumn(name = "company_id")
private Company company;
}
https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/UniqueConstraint.html
On the other hand To ensure a field value is unique you can write
@Column(unique=true)
String username;
I also encountered this exception with error message,
java.nio.charset.MalformedInputException: Input length = 1
at java.nio.charset.CoderResult.throwException(Unknown Source)
at sun.nio.cs.StreamEncoder.implWrite(Unknown Source)
at sun.nio.cs.StreamEncoder.write(Unknown Source)
at java.io.OutputStreamWriter.write(Unknown Source)
at java.io.BufferedWriter.flushBuffer(Unknown Source)
at java.io.BufferedWriter.write(Unknown Source)
at java.io.Writer.write(Unknown Source)
and found that some strange bug occurs when trying to use
BufferedWriter writer = Files.newBufferedWriter(Paths.get(filePath));
to write a String "orazg 54" cast from a generic type in a class.
//key is of generic type <Key extends Comparable<Key>>
writer.write(item.getKey() + "\t" + item.getValue() + "\n");
This String is of length 9 containing chars with the following code points:
111 114 97 122 103 9 53 52 10
However, if the BufferedWriter in the class is replaced with:
FileOutputStream outputStream = new FileOutputStream(filePath);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
it can successfully write this String without exceptions. In addition, if I write the same String create from the characters it still works OK.
String string = new String(new char[] {111, 114, 97, 122, 103, 9, 53, 52, 10});
BufferedWriter writer = Files.newBufferedWriter(Paths.get("a.txt"));
writer.write(string);
writer.close();
Previously I have never encountered any Exception when using the first BufferedWriter to write any Strings. It's a strange bug that occurs to BufferedWriter created from java.nio.file.Files.newBufferedWriter(path, options)
Personally, I use
if not (x is None):
which is understood immediately without ambiguity by every programmer, even those not expert in the Python syntax.
You can just use wildcards in the predicate (after IF, WHERE or ON):
@mainstring LIKE '%' + @substring + '%'
or in this specific case
' ' + @mainstring + ' ' LIKE '% ME[., ]%'
(Put the spaces in the quoted string if you're looking for the whole word, or leave them out if ME can be part of a bigger word).
Try this way, allow you even filter by other key
data:
var my_data = [{"name":"Lenovo Thinkpad 41A4298","website":"google"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"},
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},
{"name":"Lenovo Thinkpad 41A424448","website":"google"},
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}];
usage:
//We do that to ensure to get a correct JSON
var my_json = JSON.stringify(my_data)
//We can use {'name': 'Lenovo Thinkpad 41A429ff8'} as criteria too
var filtered_json = find_in_object(JSON.parse(my_json), {website: 'yahoo'});
filter function
function find_in_object(my_object, my_criteria){
return my_object.filter(function(obj) {
return Object.keys(my_criteria).every(function(c) {
return obj[c] == my_criteria[c];
});
});
}
Java doesn't have an analog to C++'s structs, but you can use classes with all public members.
Swift 4:
// Change status bar background color
let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView
statusBar?.backgroundColor = UIColor.red
I ended up doing this
typeof ($('#mySelector').data('events').click) == "object"
With the following you can insert multiple values and also have default values but you're creating a new dictionary.
d = {**{ key: value }, **default_values}
I've tested it with the most voted answer and on average this is faster as it can be seen in the following example, .
Speed test comparing a for loop based method with a dict comprehension with unpack operator method.
if no copy (d = default_vals.copy()
) is made on the first case then the most voted answer would be faster once we reach orders of magnitude of 10**5
and greater. Memory footprint of both methods are the same.
I think documentation has a great explanation of else, continue
[...] it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement."
$("#btnSubmit").click(function(){
alert("button");
});
In typescript it is possible to do an instanceof
check in an if statement and you will have access to the same variable with the Typed
properties.
So let's say MarkerSymbolInfo
has a property on it called marker
. You can do the following:
if (symbolInfo instanceof MarkerSymbol) {
// access .marker here
const marker = symbolInfo.marker
}
It's a nice little trick to get the instance of a variable using the same variable without needing to reassign it to a different variable name.
Check out these two resources for more information:
After a lot of search and tests i found the solution : if you are in windows :
1 - first you must found the PG databases directory execute the command as sql command in pgAdmin query tools
$ show data_directory;
result :
------------------------ - D:/PG_DATA/data - ------------------------
2 - go to the bin directory of postgres in my case it's located "c:/programms/postgresSql/bin"
and open a command prompt (CMD) and execute this command :
pg_ctl -D "D:\PSG_SQL\data" restart
This should do it.
The best way to deal with this in case of txt file which contains data for text mining (speech, newsletter, etc.) is to replace "\" with "/".
Example:
file<-Corpus(DirSource("C:/Users/PRATEEK/Desktop/training tool/Text Analytics/text_file_main"))
curl -K myconfig.txt -o output.txt
Writes the first output received in the file you specify (overwrites if an old one exists).
curl -K myconfig.txt >> output.txt
Appends all output you receive to the specified file.
Note: The -K is optional.
Depends on your needs, if you know what parent your looking for you can use the .parents() selector.
E.G: http://jsfiddle.net/HenryGarle/Kyp5g/2/
<div id="One">
<div id="Two">
<div id="Three">
<div id="Four">
</div>
</div>
</div>
</div>
var top = $("#Four").parents("#One");
alert($(top).html());
Example using index:
//First parent - 2 levels up from #Four
// I.e Selects div#One
var topTwo = $("#Four").parents().eq(2);
alert($(topTwo ).html());
You can do that, or you can use the readfile
function, which outputs it for you:
header('Content-Type: image/x-png'); //or whatever
readfile('thefile.png');
die();
Edit: Derp, fixed obvious glaring typo.
An important difference is that some UARTs (16550 notably) will stop receiving characters immediately if their host instructs them to set DSR to be inactive. In contrast, characters will still be received if CTS is inactive. I believe that the intention here is that DSR indicates that the device is no longer listening and so sending any further characters is pointless, while CTS indicates that a buffer is getting full; the latter allows for a certain amount of 'skid' where the flow control line changed state between the DTE sampling it and the next character being transmitted. In (relatively) later devices that support a hardware FIFO it's possible that a number of characters could be transmitted after the DCE has set CTS to be inactive.
Why is this still so complicated in 2021? For me I wanted to open in a new chrome window fullscreen so I used the below:
window.open("http://my.url.com", "", "fullscreen=yes");
This worked as exepected opening a new chrome window. Without the options at the end it will only open a new tab
Wikipedia, of all places, actually discusses this.
The idea is to make sure all package names are unique world-wide, by having authors use a variant of a DNS name they own to name the package. For example, the owners of the domain name joda.org
created a number of packages whose names begin with org.joda
, for example:
org.joda.time
org.joda.time.base
org.joda.time.chrono
org.joda.time.convert
org.joda.time.field
org.joda.time.format
If Paths is not available for JRE 1.5 runtime or maven plugin
package org.afc.util;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
public class FileUtil {
public static String getRelativePath(String basePath, String filePath) {
return getRelativePath(new File(basePath), new File(filePath));
}
public static String getRelativePath(File base, File file) {
List<String> bases = new LinkedList<String>();
bases.add(0, base.getName());
for (File parent = base.getParentFile(); parent != null; parent = parent.getParentFile()) {
bases.add(0, parent.getName());
}
List<String> files = new LinkedList<String>();
files.add(0, file.getName());
for (File parent = file.getParentFile(); parent != null; parent = parent.getParentFile()) {
files.add(0, parent.getName());
}
int overlapIndex = 0;
while (overlapIndex < bases.size() && overlapIndex < files.size() && bases.get(overlapIndex).equals(files.get(overlapIndex))) {
overlapIndex++;
}
StringBuilder relativePath = new StringBuilder();
for (int i = overlapIndex; i < bases.size(); i++) {
relativePath.append("..").append(File.separatorChar);
}
for (int i = overlapIndex; i < files.size(); i++) {
relativePath.append(files.get(i)).append(File.separatorChar);
}
relativePath.deleteCharAt(relativePath.length() - 1);
return relativePath.toString();
}
}
One trick is to create an interface that extends a generic base interface...
public interface LoadFutures extends Map<UUID, Future<LoadResult>> {}
Then you can check it with instanceof before the cast...
Object obj = context.getAttribute(FUTURES);
if (!(obj instanceof LoadFutures)) {
String format = "Servlet context attribute \"%s\" is not of type "
+ "LoadFutures. Its type is %s.";
String msg = String.format(format, FUTURES, obj.getClass());
throw new RuntimeException(msg);
}
return (LoadFutures) obj;
If you have floats you can write a function and then use that e.g.
#!/bin/bash
function float_gt() {
perl -e "{if($1>$2){print 1} else {print 0}}"
}
x=3.14
y=5.20
if [ $(float_gt $x $y) == 1 ] ; then
echo "do stuff with x"
else
echo "do stuff with y"
fi
Use the parseJSON
method:
var json = '["City1","City2","City3"]';
var arr = $.parseJSON(json);
Then you have an array with the city names.
If using Nginx
and getting a similar problem, then this might help:
Scan your domain on this sslTesturl, and see if the connection is allowed for your device version.
If lower version devices(like < Android 4.4.2 etc) are not able to connect due to TLS support, then try adding this to your Nginx config file,
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
I had a nice time creating an Custom Attribute for this:
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public sealed class DecimalPrecisionAttribute : Attribute
{
public DecimalPrecisionAttribute(byte precision, byte scale)
{
Precision = precision;
Scale = scale;
}
public byte Precision { get; set; }
public byte Scale { get; set; }
}
using it like this
[DecimalPrecision(20,10)]
public Nullable<decimal> DeliveryPrice { get; set; }
and the magic happens at model creation with some reflection
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
foreach (Type classType in from t in Assembly.GetAssembly(typeof(DecimalPrecisionAttribute)).GetTypes()
where t.IsClass && t.Namespace == "YOURMODELNAMESPACE"
select t)
{
foreach (var propAttr in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttribute<DecimalPrecisionAttribute>() != null).Select(
p => new { prop = p, attr = p.GetCustomAttribute<DecimalPrecisionAttribute>(true) }))
{
var entityConfig = modelBuilder.GetType().GetMethod("Entity").MakeGenericMethod(classType).Invoke(modelBuilder, null);
ParameterExpression param = ParameterExpression.Parameter(classType, "c");
Expression property = Expression.Property(param, propAttr.prop.Name);
LambdaExpression lambdaExpression = Expression.Lambda(property, true,
new ParameterExpression[]
{param});
DecimalPropertyConfiguration decimalConfig;
if (propAttr.prop.PropertyType.IsGenericType && propAttr.prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
MethodInfo methodInfo = entityConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[7];
decimalConfig = methodInfo.Invoke(entityConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
}
else
{
MethodInfo methodInfo = entityConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[6];
decimalConfig = methodInfo.Invoke(entityConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
}
decimalConfig.HasPrecision(propAttr.attr.Precision, propAttr.attr.Scale);
}
}
}
the first part is to get all classes in the model (my custom attribute is defined in that assembly so i used that to get the assembly with the model)
the second foreach gets all properties in that class with the custom attribute, and the attribute itself so i can get the precision and scale data
after that i have to call
modelBuilder.Entity<MODEL_CLASS>().Property(c=> c.PROPERTY_NAME).HasPrecision(PRECISION,SCALE);
so i call the modelBuilder.Entity() by reflection and store it in the entityConfig variable then i build the "c => c.PROPERTY_NAME" lambda expression
After that, if the decimal is nullable i call the
Property(Expression<Func<TStructuralType, decimal?>> propertyExpression)
method (i call this by the position in the array, it's not ideal i know, any help will be much appreciated)
and if it's not nullable i call the
Property(Expression<Func<TStructuralType, decimal>> propertyExpression)
method.
Having the DecimalPropertyConfiguration i call the HasPrecision method.
The new line separator is different for different OS-es - '\r\n' for Windows and '\n' for Linux.
To be safe, you can use regex pattern \R - the linebreak matcher introduced with Java 8:
String inlinedText = text.replaceAll("\\R", " ");
This post describes it very nicely.
In short: utf8_unicode_ci
uses the Unicode Collation Algorithm as defined in the Unicode standards, whereas utf8_general_ci
is a more simple sort order which results in "less accurate" sorting results.
First composer requires doctrine/dbal
, then:
$table->longText('column_name')->change();
Bootstrap 5
<div class="input-group">
<input type="text" class="form-control">
<button class="btn btn-outline-secondary" type="button">Go</button>
</div>
Bootstrap 3 & 4
you may use the input-group button property to apply the button direct to the input-field.
<div class="input-group">
<input type="text" class="form-control">
<span class="input-group-btn">
<button class="btn btn-default" type="button">Go!</button>
</span>
</div><!-- /input-group -->
Take a look at BS4 or BS5 Input-Group doc for many more examples.
import java.io.*;
public class CountChar
{
public static void main(String[] args) throws IOException
{
String ch;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the Statement:");
ch=br.readLine();
int count=0,len=0;
do
{
try
{
char name[]=ch.toCharArray();
len=name.length;
count=0;
for(int j=0;j<len;j++)
{
if((name[0]==name[j])&&((name[0]>=65&&name[0]<=91)||(name[0]>=97&&name[0]<=123)))
count++;
}
if(count!=0)
System.out.println(name[0]+" "+count+" Times");
ch=ch.replace(""+name[0],"");
}
catch(Exception ex){}
}
while(len!=1);
}
}
Output
Enter the Statement:asdf23123sfsdf
a 1 Times
s 3 Times
d 2 Times
f 3 Times
Always : If you always want vertical scrollbar, use overflow-y: scroll;
<div style="overflow-y: scroll;">
......
</div>
When needed: If you only want vertical scrollbar when needed, use overflow-y: auto;
(You need to specify a height in this case)
<div style="overflow-y: auto; height:150px; ">
....
</div>
I had forgot Minikube running in background and thats what always restarted them back up
thanks to @thusharaK I could reset the root password without knowing the old password.
On ubuntu I did the following:
sudo service mysql stop
sudo mysqld_safe --skip-grant-tables --skip-syslog --skip-networking
Then run mysql in a new terminal:
mysql -u root
And run the following queries to change the password:
UPDATE mysql.user SET authentication_string=PASSWORD('password') WHERE User='root';
FLUSH PRIVILEGES;
In MySQL 5.7, the password field in mysql.user table field was removed, now the field name is 'authentication_string'.
Quit the mysql safe mode and start mysql service by:
mysqladmin shutdown
sudo service mysql start
Here's are some examples:
var name = 'india';
alert(name);
var name = $("#txtname").val();
alert(name);
Taken from http://way2finder.blogspot.in/2013/09/how-to-create-variable-in-jquery.html
I got this on Firefox (FF58). I fixed this with:
dom.moduleScripts.enabled
in about:config
Source: Import page on mozilla (See Browser compatibility)
type="module"
to your script tag where you import the js file<script type="module" src="appthatimports.js"></script>
./
, /
, ../
or http://
before)import * from "./mylib.js"
For more examples, this blog post is good.
Doing
df.index = pd.to_datetime(df.index, errors='coerce')
the data type of the index has changed to
A worked, completed and simple example:
package io.github.baijifeilong.excel;
import lombok.SneakyThrows;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
/**
* Created by [email protected] at 2019/12/6 11:41
*/
public class ExcelBoldTextDemo {
@SneakyThrows
public static void main(String[] args) {
new XSSFWorkbook() {{
XSSFRow row = createSheet().createRow(0);
row.setRowStyle(createCellStyle());
row.getRowStyle().getFont().setBold(true);
row.createCell(0).setCellValue("Alpha");
row.createCell(1).setCellValue("Beta");
row.createCell(2).setCellValue("Gamma");
}}.write(new FileOutputStream("demo.xlsx"));
}
}
Here is a simple approach which will print the 2 different elapsed time for each query.
DECLARE @t1 DATETIME;
DECLARE @t2 DATETIME;
SET @t1 = GETDATE();
SELECT DISTINCT u.profession FROM users u; --Query with DISTINCT
SET @t2 = GETDATE();
PRINT 'Elapsed time (ms): ' + CAST(DATEDIFF(millisecond, @t1, @t2) AS varchar);
SET @t1 = GETDATE();
SELECT u.profession FROM users u GROUP BY u.profession; --Query with GROUP BY
SET @t2 = GETDATE();
PRINT 'Elapsed time (ms): ' + CAST(DATEDIFF(millisecond, @t1, @t2) AS varchar);
OR try SET STATISTICS TIME (Transact-SQL)
SET STATISTICS TIME ON;
SELECT DISTINCT u.profession FROM users u; --Query with DISTINCT
SELECT u.profession FROM users u GROUP BY u.profession; --Query with GROUP BY
SET STATISTICS TIME OFF;
It simply displays the number of milliseconds required to parse, compile, and execute each statement as below:
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 2 ms.
From iOS11 one can use the following property
let frameLayoutGuide: UILayoutGuide
If you set constraints for frameLayoutGuide.topAnchor and frameLayoutGuide.bottomAnchor to the same anchors of some subview of your scrollView then vertical scroll will be disabled and the height of the scrollView will be equal to the height of its subview.
It is stored in the heap referenced by the class definition. If you think about it, it has nothing to do with stack because there is no scope.
skip[1]
will skip second line, not the first one.
fp.read()
reads up to the end of the file, so after it's successfully finished you know the file is at EOF; there's no need to check. If it cannot reach EOF it will raise an exception.
When reading a file in chunks rather than with read()
, you know you've hit EOF when read
returns less than the number of bytes you requested. In that case, the following read
call will return the empty string (not None
). The following loop reads a file in chunks; it will call read
at most once too many.
assert n > 0
while True:
chunk = fp.read(n)
if chunk == '':
break
process(chunk)
Or, shorter:
for chunk in iter(lambda: fp.read(n), ''):
process(chunk)
In this case what you can do is : Go in developer options on the device Uncheck "USB Debugging" then check it again A confirmation box should then appear DvxWifiScan
public static void deleteLine(String line, String filePath) {
File file = new File(filePath);
File file2 = new File(file.getParent() + "\\temp" + file.getName());
PrintWriter pw = null;
Scanner read = null;
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel src = null;
FileChannel dest = null;
try {
pw = new PrintWriter(file2);
read = new Scanner(file);
while (read.hasNextLine()) {
String currline = read.nextLine();
if (line.equalsIgnoreCase(currline)) {
continue;
} else {
pw.println(currline);
}
}
pw.flush();
fis = new FileInputStream(file2);
src = fis.getChannel();
fos = new FileOutputStream(file);
dest = fos.getChannel();
dest.transferFrom(src, 0, src.size());
} catch (IOException e) {
e.printStackTrace();
} finally {
pw.close();
read.close();
try {
fis.close();
fos.close();
src.close();
dest.close();
} catch (IOException e) {
e.printStackTrace();
}
if (file2.delete()) {
System.out.println("File is deleted");
} else {
System.out.println("Error occured! File: " + file2.getName() + " is not deleted!");
}
}
}
You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);
, you just need to get rid of default sum(max_count)
. No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL
as the value for every cell in that column.
So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.
You also have the option to always COALESCE
the column to your desired default and leave it NULL
for now. This option fails when you want NULL
to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE
.
If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.
You are inside a namespace
so you should use \Exception
to specify the global namespace:
try {
$this->buildXMLHeader();
} catch (\Exception $e) {
return $e->getMessage();
}
In your code you've used catch (Exception $e)
so Exception
is being searched in/as:
App\Services\PayUService\Exception
Since there is no Exception
class inside App\Services\PayUService
so it's not being triggered. Alternatively, you can use a use
statement at the top of your class like use Exception;
and then you can use catch (Exception $e)
.
To set the build configuration to Debug or Release, choose 'Edit Scheme' from the 'Product' menu.
Then you see a clear choice.
The Apple Transition Guide mentions a button at the top left of the Xcode screen, but I cannot see it in Xcode 4.3.
If you receive multiple entries the correct method is called lists.
Word_relation::select('word_two')->where('word_one', $word_id)->lists('word_one')->toArray();
Another built-in command that's long been installed in Windows by default dating back to 2003 is Certutil, which of course can be invoked from PowerShell, too.
CertUtil -hashfile file.foo MD5
(Caveat: MD5 should be in all caps for maximum robustness)
You need to declare the type of the protocol as AnyObject
.
protocol ProtocolNameDelegate: AnyObject {
// Protocol stuff goes here
}
class SomeClass {
weak var delegate: ProtocolNameDelegate?
}
Using AnyObject
you say that only classes can conform to this protocol, whereas structs or enums can't.
I use the AbsoluteUri and you can get it like this:
string myURI = Request.Url.AbsoluteUri;
if (!WebSecurity.IsAuthenticated) {
Response.Redirect("~/Login?returnUrl="
+ Request.Url.AbsoluteUri );
Then after you login:
var returnUrl = Request.QueryString["returnUrl"];
if(WebSecurity.Login(username,password,true)){
Context.RedirectLocal(returnUrl);
It works well for me.
Change:
<!-- ANT4X -->
<dependency>
<groupId>net.sourceforge</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
To:
<!-- ANT4X -->
<dependency>
<groupId>net.sourceforge.ant4x</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
The groupId
of net.sourceforge
was incorrect. The correct value is net.sourceforge.ant4x
.
// iterate through key-value gracefully
const obj = { a: 5, b: 7, c: 9 };
for (const [key, value] of Object.entries(obj)) {
console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
}
Refer MDN
| 0000 0001 0010 0011 0100 0101 0110 0111 | ------> EAX
| 0100 0101 0110 0111 | ------> AX
| 0110 0111 | ------> AL
| 0100 0101 | ------> AH
I had similar issue due to a small mistake, when i was trying to convert a List to json. If a List is converted to json it will return JSONArray not JSONObject.
You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.*
function are thin wrappers that basically do gca().*
.
plt.subplot
returns an axes
object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.
import matplotlib.pyplot as plt
ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])
ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])
and so on for as many axes as you want.
or better, wrap it all up in a loop:
import matplotlib.pyplot as plt
DATA_x = ([1, 2],
[2, 3],
[3, 4])
DATA_y = DATA_x[::-1]
XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3
for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
ax = plt.subplot(1, 3, j + 1)
ax.scatter(x, y)
ax.set_xlim(xlim)
ax.set_ylim(ylim)
On Mac (on french keyboard its) cmd + shift + F
Is WebSockets over TCP a fast enough protocol to stream a video of, say, 30fps?
Yes.. it is, take a look at this project. Websockets can easily handle HD videostreaming.. However, you should go for Adaptive Streaming. I explain here how you could implement it.
Currently we're working on a webbased instant messaging application with chat, filesharing and video/webcam support. With some bits and tricks we got streaming media through websockets (used HTML5 Media Capture to get the stream from our webcams).
You need to build a stream API
and a Media Stream Transceiver
to control the related media processing and transport.
another way which can return the list of matching strings is
sample = "alexis has the control"
matched_strings = filter(sample.endswith, ["trol", "ol", "troll"])
print matched_strings
['trol', 'ol']
You could create an installer for you EXE file by:
1. Press WinKey + R
2. Type "iexpress" (without quotes) into the run window
3. Complete the wizard for creating the installation program.
4. Distribute the completed EXE.
I've always come back here for the answer so I wanted to make a short simple one to go to.
There are multiple ways of doing this:
Add Namespaces:
System.Windows.Interactivitiy
Microsoft.Expression.Interactions
XAML:
Use the EventName
to call the event you want then specify your Method
name in the MethodName
.
<Window>
xmlns:wi="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions">
<wi:Interaction.Triggers>
<wi:EventTrigger EventName="SelectionChanged">
<ei:CallMethodAction
TargetObject="{Binding}"
MethodName="ShowCustomer"/>
</wi:EventTrigger>
</wi:Interaction.Triggers>
</Window>
Code:
public void ShowCustomer()
{
// Do something.
}
Install GalaSoft NuGet package.
Get the namespaces:
System.Windows.Interactivity
GalaSoft.MvvmLight.Platform
XAML:
Use the EventName
to call the event you want then specify your Command
name in your binding. If you want to pass the arguments of the method, mark PassEventArgsToCommand
to true.
<Window>
xmlns:wi="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="http://www.galasoft.ch/mvvmlight">
<wi:Interaction.Triggers>
<wi:EventTrigger EventName="Navigated">
<cmd:EventToCommand Command="{Binding CommandNameHere}"
PassEventArgsToCommand="True" />
</wi:EventTrigger>
</wi:Interaction.Triggers>
</Window>
Code Implementing Delegates: Source
You must get the Prism MVVM NuGet package for this.
using Microsoft.Practices.Prism.Commands;
// With params.
public DelegateCommand<string> CommandOne { get; set; }
// Without params.
public DelegateCommand CommandTwo { get; set; }
public MainWindow()
{
InitializeComponent();
// Must initialize the DelegateCommands here.
CommandOne = new DelegateCommand<string>(executeCommandOne);
CommandTwo = new DelegateCommand(executeCommandTwo);
}
private void executeCommandOne(string param)
{
// Do something here.
}
private void executeCommandTwo()
{
// Do something here.
}
Code Without DelegateCommand
: Source
using GalaSoft.MvvmLight.CommandWpf
public MainWindow()
{
InitializeComponent();
CommandOne = new RelayCommand<string>(executeCommandOne);
CommandTwo = new RelayCommand(executeCommandTwo);
}
public RelayCommand<string> CommandOne { get; set; }
public RelayCommand CommandTwo { get; set; }
private void executeCommandOne(string param)
{
// Do something here.
}
private void executeCommandTwo()
{
// Do something here.
}
You'll have to download it's NuGet Package.
XAML
:
<i:Interaction.Behaviors>
<telerek:EventToCommandBehavior
Command="{Binding DropCommand}"
Event="Drop"
PassArguments="True" />
</i:Interaction.Behaviors>
Code:
public ActionCommand<DragEventArgs> DropCommand { get; private set; }
this.DropCommand = new ActionCommand<DragEventArgs>(OnDrop);
private void OnDrop(DragEventArgs e)
{
// Do Something
}
Simply put Middleware is a software component which provides services to integrate disparate systems together.
In an complex enterprise environment, there are a number of challenges when you need to integrate two or more enterprise systems together to talk to each other. Normally these systems do not understand each others language as they are developed on different platforms using different languages (like C++, Java, Cobol, etc.).
So here comes middleware software in picture which provides services like
A typical example of middleware is an ESB products like IBM message broker (WMB/IIB), WESB, Datapower XI50, Oracle Fusion, Mule and many others.
Therefore, middleware sits mostly in between the service consuming apps and services provider apps and help these apps to talk to each other.
header("Location: route_to_main_page");
I've encountered this problem while having a custom 404 error handling file. Instead of throwing some html content it was suppose to redirect to the main page url. It worked well.
Then I used this as a skeleton for a next project, therefore not changing the "route_to_main_page" actually on the new project (different URL) became a "route_to_external_url" so any 404 errors within your code (missing css stylesheets, js libraries) would return the "Uncaught SyntaxError: Unexpected token <".
According to Daniel Simmons:
Create a new ObjectContext instance in a Using statement for each service method so that it is disposed of before the method returns. This step is critical for scalability of your service. It makes sure that database connections are not kept open across service calls and that temporary state used by a particular operation is garbage collected when that operation is over. The Entity Framework automatically caches metadata and other information it needs in the app domain, and ADO.NET pools database connections, so re-creating the context each time is a quick operation.
This is from his comprehensive article here:
http://msdn.microsoft.com/en-us/magazine/ee335715.aspx
I believe this advice extends to HTTP requests, so would be valid for ASP.NET. A stateful, fat-client application such as a WPF application might be the only case for a "shared" context.
[i for i, v in enumerate(L) if v[0] == 53]
SELECT id, user_id, video_name
FROM sa_created_videos
ORDER BY LENGTH(id) ASC, LENGTH(user_id) DESC
As of Matplotlib 2.0, there is a reversed()
method for ListedColormap
and LinearSegmentedColorMap
objects, so you can just do
cmap_reversed = cmap.reversed()
Here is the documentation.
You have to load the url helper to access that function. Either you add
$this->load->helper('url');
somewhere in your controller.
Alternately, to have it be loaded automatically everywhere, make sure the line in application/config/autoload.php that looks like
$autoload['helper'] = array('url');
has 'url'
in that array (as shown above).
Adding on to Kalyoyan's answer, this subscription is tied to the router and will live until the page is fully refreshed. When subscribing to router events in a component, be sure to unsubscribe in ngOnDestroy:
import { OnDestroy } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { Subscription } from "rxjs/Rx";
class MyAppComponent implements OnDestroy {
private subscription: Subscription;
constructor(router: Router) {
this.subscription = router.events.subscribe(s => {
if (s instanceof NavigationEnd) {
const tree = router.parseUrl(router.url);
if (tree.fragment) {
const element = document.querySelector("#" + tree.fragment);
if (element) { element.scrollIntoView(element); }
}
}
});
}
public ngOnDestroy() {
this.subscription.unsubscribe();
}
}
window.localStorage.clear(); //try this to clear all local storage
Your current solution does not work because $time
is a string - it needs to be a Unix timestamp. You can do this instead:
$unix_time = strtotime('January 1 2010 '.$time); // create a unix timestamp
$startTime date( "H:i", strtotime('-30 minutes', $unix_time) );
$endTime date( "H:i", strtotime('+30 minutes', $unix_time) );
If you're like me and you don't like the idea of deleting things that were part of the standard system installation (which others have suggested) then you might like the solution I ended up using:
.profile
, or whatever is appropriate, and put /usr/local/bin
at the start
of your PATH
so that Homebrew binaries are found before system binariesbrew install python
- this installs a newer version of python in /usr/local
pip install pandas
This worked for me in OS X 10.8.2, and I can't see any reason it shouldn't work in 10.6.8.
GAC (Global Assembly Cache) is where all shared .NET assembly reside.
I just tried the same and came up with following solution:
public enum Countries {
TEXAS,
FLORIDA,
OKLAHOMA,
KENTUCKY;
private static Countries[] list = Countries.values();
public static Countries getCountry(int i) {
return list[i];
}
public static int listGetLastIndex() {
return list.length - 1;
}
}
The class has it's own values saved inside an array, and I use the array to get the enum at indexposition. As mentioned above arrays begin to count from 0, if you want your index to start from '1' simply change these two methods to:
public static String getCountry(int i) {
return list[(i - 1)];
}
public static int listGetLastIndex() {
return list.length;
}
Inside my Main I get the needed countries-object with
public static void main(String[] args) {
int i = Countries.listGetLastIndex();
Countries currCountry = Countries.getCountry(i);
}
which sets currCountry to the last country, in this case Countries.KENTUCKY.
Just remember this code is very affected by ArrayOutOfBoundsExceptions if you're using hardcoded indicies to get your objects.
Not quite sure why it's not mentioned more online (or on this thread), but the Babel package (and Django utilities) from the Edgewall guys is awesome for currency formatting (and lots of other i18n tasks). It's nice because it doesn't suffer from the need to do everything globally like the core Python locale module.
The example the OP gave would simply be:
>>> import babel.numbers
>>> import decimal
>>> babel.numbers.format_currency( decimal.Decimal( "188518982.18" ), "GBP" )
£188,518,982.18
While the proposed solutions work, I was trying to implement with Full Calendar and it would require over 90 database calls for each view (as it loads current, previous, and next month), which, I wasn't too thrilled about.
I found an recursion library https://github.com/tplaner/When where you simply store the rules in the database and one query to pull all the relevant rules.
Hopefully this will help someone else, as I spent so many hours trying to find a good solution.
Edit: This Library is for PHP
object[] newarray = new object[oldarray.Length-1];
for(int x=0; x < array.Length; x++)
{
if(!(array[x] == value_of_array_to_delete))
// if(!(x == array_index_to_delete))
{
newarray[x] = oldarray[x];
}
}
There is no way to downsize an array after it is created, but you can copy the contents to another array of a lesser size.
I haven't timed it but I suspect this would be pretty quick:
import numpy as np
list1=[1, 2, 3]
list2=[4, 5, 6]
list_sum = (np.add(list1, list2)).tolist()
[5, 7, 9]
This is an old post, but I though I should put a graphical answer here as the question is about viewing the SharedPreferences.xml
using Android Studio. So here it goes.
Go to the Tools -> Android Device Monitor. Open the device monitor by clicking it.
Then you need to select the File Explorer tab in the device monitor. Find the data folder and find another data folder inside it. It will contain a folder having the name of your application package and there will be the desired SharedPreferences.xml
.
Select the SharedPreferences.xml
file and then pull and save the file in your computer using the button marked at the top-right corner of the image above.
I've used a device emulator.
this is very similar to all of the answers, but why not use the !
operator twice so you can get a boolean:
jQuery.fn.exists = function(){return !!this.length};
if ($(selector).exists()) {
// the element exists, now what?...
}
A common solution is to make a base view model which contains the properties used in the layout file and then inherit from the base model to the models used on respective pages.
The problem with this approach is that you now have locked yourself into the problem of a model can only inherit from one other class, and maybe your solution is such that you cannot use inheritance on the model you intended anyways.
My solution also starts of with a base view model:
public class LayoutModel
{
public LayoutModel(string title)
{
Title = title;
}
public string Title { get;}
}
What I then use is a generic version of the LayoutModel which inherits from the LayoutModel, like this:
public class LayoutModel<T> : LayoutModel
{
public LayoutModel(T pageModel, string title) : base(title)
{
PageModel = pageModel;
}
public T PageModel { get; }
}
With this solution I have disconnected the need of having inheritance between the layout model and the model.
So now I can go ahead and use the LayoutModel in Layout.cshtml like this:
@model LayoutModel
<!doctype html>
<html>
<head>
<title>@Model.Title</title>
</head>
<body>
@RenderBody()
</body>
</html>
And on a page you can use the generic LayoutModel like this:
@model LayoutModel<Customer>
@{
var customer = Model.PageModel;
}
<p>Customer name: @customer.Name</p>
From your controller you simply return a model of type LayoutModel:
public ActionResult Page()
{
return View(new LayoutModel<Customer>(new Customer() { Name = "Test" }, "Title");
}
Prefix the call with Module2 (ex. Module2.IDLE
). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.
I think this is quite overkill for a dictionary semantics, since dictionary is by definition is a collection of keys and its respective values, just like the way we see a book of language dictionary that contains a word as the key and its descriptive meaning as the value.
But you can represent a dictionary that can contain collection of values, for example:
Dictionary<String,List<Customer>>
Or a dictionary of a key and the value as a dictionary:
Dictionary<Customer,Dictionary<Order,OrderDetail>>
Then you'll have a dictionary that can have multiple values.
If you want to select every element that has class attribute "myclass" use
$('#mydiv .myclass');
If you want to select only div elements that has class attribute "myclass" use
$("div#mydiv div.myclass");
find more about jquery selectors refer these articles
Epoch time (i.e. Unix Epoch time) is nearly always the number of seconds that have expired since 1st Jan 1970 00:00:00 (UTC time), not the number of milliseconds which some of the answers here have implied.
https://en.wikipedia.org/wiki/Unix_time
Therefore, if you have been given a Unix Epoch time value it will probably be in seconds, and will look something like 1547035195
. If you want to make this human readable in JavaScript, you need to convert the value to milliseconds, and pass that value into the Date(value)
constructor, e.g.:
const unixEpochTimeMS = 1547035195 * 1000;
const d = new Date(unixEpochTimeMS);
// Careful, the string output here can vary by implementation...
const strDate = d.toLocaleString();
You don't need to do the d.setUTCMilliseconds(0)
step in the accepted answer because the JavaScript Date(value)
constructor takes a UTC value in milliseconds (not a local time).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Syntax
Also note that you should avoid using the Date(...)
constructor that takes a string datetime representation, this is not recommended (see the link above).
this will do the magic
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var scrollpos = localStorage.getItem('scrollpos');
if (scrollpos) window.scrollTo(0, scrollpos);
});
window.onbeforeunload = function(e) {
localStorage.setItem('scrollpos', window.scrollY);
};
</script>
What type of authentication do you use? Send the credentials using the properties Ben said before and setup a cookie handler. You already allow redirection, check your webserver if any redirection occurs (NTLM auth does for sure). If there is a redirection you need to store the session which is mostly stored in a session cookie.
I use Enthought Canopy for my python, at first I used "pip install --upgrade pip", it showed a syntax error like yours, then I added a "!" in front of the pip, then it finally worked.
Packets and Frames are the names given to Protocol data units (PDUs) at different network layers
Segments/Datagrams are units of data in the Transport Layer.
In the case of the internet, the term Segment typically refers to TCP, while Datagram typically refers to UDP. However Datagram can also be used in a more general sense and refer to other layers (link):
Datagram
A self-contained, independent entity of data carrying sufficient information to be routed from the source to the destination computer without reliance on earlier exchanges between this source and destination computer andthe transporting network.
Packets are units of data in the Network Layer (IP in case of the Internet)
Frames are units of data in the Link Layer (e.g. Wifi, Bluetooth, Ethernet, etc).
You can check Visual Studio Downloads for available Visual Studio Community
, Visual Studio Professional
, Visual Studio Enterprise
and Visual Studio Code
download links.
Update!
There is no direct links of Visual Studio 2015
at Visual Studio Downloads anymore. but the below links still works.
OR simply click on direct links below (for .iso/.exe file):
VSCode area:
In windows OS do right click on task bar-->start task manager-->process then check java.exe or javaw is running if it is running,then click on it and do end process then restart your tom cat server.
System.out.println(new String(new byte[]{ (byte)0x63 }, "US-ASCII"));
Note especially that converting bytes to Strings always involves an encoding. If you do not specify it, you'll be using the platform default encoding, which means the code can break when running in different environments.