Write the following in linux terminal:
$ wget -r http://developer.android.com/reference/packages.html
Working example is given below,
MyService.class
public class MyService extends Service implements SpeechDelegate, Speech.stopDueToDelay {
public static SpeechDelegate delegate;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
try {
if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
((AudioManager) Objects.requireNonNull(
getSystemService(Context.AUDIO_SERVICE))).setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
} catch (Exception e) {
e.printStackTrace();
}
Speech.init(this);
delegate = this;
Speech.getInstance().setListener(this);
if (Speech.getInstance().isListening()) {
Speech.getInstance().stopListening();
} else {
System.setProperty("rx.unsafe-disable", "True");
RxPermissions.getInstance(this).request(permission.RECORD_AUDIO).subscribe(granted -> {
if (granted) { // Always true pre-M
try {
Speech.getInstance().stopTextToSpeech();
Speech.getInstance().startListening(null, this);
} catch (SpeechRecognitionNotAvailable exc) {
//showSpeechNotSupportedDialog();
} catch (GoogleVoiceTypingDisabledException exc) {
//showEnableGoogleVoiceTyping();
}
} else {
Toast.makeText(this, R.string.permission_required, Toast.LENGTH_LONG).show();
}
});
}
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
@Override
public void onStartOfSpeech() {
}
@Override
public void onSpeechRmsChanged(float value) {
}
@Override
public void onSpeechPartialResults(List<String> results) {
for (String partial : results) {
Log.d("Result", partial+"");
}
}
@Override
public void onSpeechResult(String result) {
Log.d("Result", result+"");
if (!TextUtils.isEmpty(result)) {
Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onSpecifiedCommandPronounced(String event) {
try {
if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
((AudioManager) Objects.requireNonNull(
getSystemService(Context.AUDIO_SERVICE))).setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
} catch (Exception e) {
e.printStackTrace();
}
if (Speech.getInstance().isListening()) {
Speech.getInstance().stopListening();
} else {
RxPermissions.getInstance(this).request(permission.RECORD_AUDIO).subscribe(granted -> {
if (granted) { // Always true pre-M
try {
Speech.getInstance().stopTextToSpeech();
Speech.getInstance().startListening(null, this);
} catch (SpeechRecognitionNotAvailable exc) {
//showSpeechNotSupportedDialog();
} catch (GoogleVoiceTypingDisabledException exc) {
//showEnableGoogleVoiceTyping();
}
} else {
Toast.makeText(this, R.string.permission_required, Toast.LENGTH_LONG).show();
}
});
}
}
@Override
public void onTaskRemoved(Intent rootIntent) {
//Restarting the service if it is removed.
PendingIntent service =
PendingIntent.getService(getApplicationContext(), new Random().nextInt(),
new Intent(getApplicationContext(), MyService.class), PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
assert alarmManager != null;
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, service);
super.onTaskRemoved(rootIntent);
}
}
For more details,
Hope this will help someone in future.
<offline> false </offline>
<localRepository>${user.home}/.m2/repository</localRepository>
to
<offline> true <offline>
<localRepository>${user.home}/.m2/repository</localRepository>
Change the offline tag from false to true .
will download from repo online
if(navigator.onLine){
alert('online');
} else {
alert('offline');
}
If all you want is the UNIX command line tools I'd suggest not installing Cygwin. Cygwin wants to turn your Windows PC into a UNIX Workstation which is why it likes to install all its packages.
Have a look at GnuWin32 instead. It's Windows ports of the command line tools and nothing else. Here is the installer for the GnuWin32 diff.exe
. There are offline installers for all the common tools.
(You asked for offline installers but in case you ever want one later there is a tool which will download and install everything for you.)
Method 2: make an offline install zip file for cygwin.
Don't mess with saving packages because the installed directory for cygwin can be canned in a zip file and expanded whenever you need it on any computer.
Download Cygwin installer
pick packages you want installed from gui.
hit install and wait a really long time for everything to download.
zip up the C:\Cygwin folder. Now you have your offline zip file for installing cygwin on any machine.
Unzip this file on whatever computer you like. set cmd.exe paths appropriately to point to cygwin bin directory under windows control panel.
It is possible to play a local video file.
<input type="file" accept="video/*"/>
<video controls autoplay></video>
When a file is selected via the input
element:
input.files
FileListvideo.src
propertyLean back and watch :)
http://jsfiddle.net/dsbonev/cCCZ2/embedded/result,js,html,css/
(function localFileVideoPlayer() {_x000D_
'use strict'_x000D_
var URL = window.URL || window.webkitURL_x000D_
var displayMessage = function(message, isError) {_x000D_
var element = document.querySelector('#message')_x000D_
element.innerHTML = message_x000D_
element.className = isError ? 'error' : 'info'_x000D_
}_x000D_
var playSelectedFile = function(event) {_x000D_
var file = this.files[0]_x000D_
var type = file.type_x000D_
var videoNode = document.querySelector('video')_x000D_
var canPlay = videoNode.canPlayType(type)_x000D_
if (canPlay === '') canPlay = 'no'_x000D_
var message = 'Can play type "' + type + '": ' + canPlay_x000D_
var isError = canPlay === 'no'_x000D_
displayMessage(message, isError)_x000D_
_x000D_
if (isError) {_x000D_
return_x000D_
}_x000D_
_x000D_
var fileURL = URL.createObjectURL(file)_x000D_
videoNode.src = fileURL_x000D_
}_x000D_
var inputNode = document.querySelector('input')_x000D_
inputNode.addEventListener('change', playSelectedFile, false)_x000D_
})()
_x000D_
video,_x000D_
input {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
input {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.info {_x000D_
background-color: aqua;_x000D_
}_x000D_
_x000D_
.error {_x000D_
background-color: red;_x000D_
color: white;_x000D_
}
_x000D_
<h1>HTML5 local video file player example</h1>_x000D_
<div id="message"></div>_x000D_
<input type="file" accept="video/*" />_x000D_
<video controls autoplay></video>
_x000D_
You can download visual studio community edition with /layout
switch.
But I prefer to use /layout
with /NoRefresh
for my low-speed internet connection that downloading long more than a day.
vs_community.exe /layout /NoRefresh
Every time that you run the installer it searches for new updates and if it finds updates, start downloading them and consume more time and more bandwidth!
The window.navigator.onLine
attribute and its associated events are currently unreliable on certain web browsers (especially Firefox desktop) as @Junto said, so I wrote a little function (using jQuery) that periodically checks the network connectivity status and raise the appropriate offline
and online
events:
// Global variable somewhere in your app to replicate the
// window.navigator.onLine variable (this last is not modifiable). It prevents
// the offline and online events to be triggered if the network
// connectivity is not changed
var IS_ONLINE = true;
function checkNetwork() {
$.ajax({
// Empty file in the root of your public vhost
url: '/networkcheck.txt',
// We don't need to fetch the content (I think this can lower
// the server's resources needed to send the HTTP response a bit)
type: 'HEAD',
cache: false, // Needed for HEAD HTTP requests
timeout: 2000, // 2 seconds
success: function() {
if (!IS_ONLINE) { // If we were offline
IS_ONLINE = true; // We are now online
$(window).trigger('online'); // Raise the online event
}
},
error: function(jqXHR) {
if (jqXHR.status == 0 && IS_ONLINE) {
// We were online and there is no more network connection
IS_ONLINE = false; // We are now offline
$(window).trigger('offline'); // Raise the offline event
} else if (jqXHR.status != 0 && !IS_ONLINE) {
// All other errors (404, 500, etc) means that the server responded,
// which means that there are network connectivity
IS_ONLINE = true; // We are now online
$(window).trigger('online'); // Raise the online event
}
}
});
}
You can use it like this:
// Hack to use the checkNetwork() function only on Firefox
// (http://stackoverflow.com/questions/5698810/detect-firefox-browser-with-jquery/9238538#9238538)
// (But it may be too restrictive regarding other browser
// who does not properly support online / offline events)
if (!(window.mozInnerScreenX == null)) {
window.setInterval(checkNetwork, 30000); // Check the network every 30 seconds
}
To listen to the offline and online events (with the help of jQuery):
$(window).bind('online offline', function(e) {
if (!IS_ONLINE || !window.navigator.onLine) {
alert('We have a situation here');
} else {
alert('Battlestation connected');
}
});
You can mimic the Ping command.
Use Ajax to request a timestamp to your own server, define a timer using setTimeout to 5 seconds, if theres no response it try again.
If there's no response in 4 attempts, you can suppose that internet is down.
So you can check using this routine in regular intervals like 1 or 3 minutes.
That seems a good and clean solution for me.
Just go to Google Fonts - http://www.google.com/fonts/ , add the font you like to your collection, and press the download button. And then just use the @fontface to connect this font to your web page. Btw, if you open the link you are using, you'll see an example of using @fontface
http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600,300
For an example
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 300;
src: local('Open Sans Light'), local('OpenSans-Light'), url(http://themes.googleusercontent.com/static/fonts/opensans/v6/DXI1ORHCpsQm3Vp6mXoaTaRDOzjiPcYnFooOUGCOsRk.woff) format('woff');
}
Just change the url address to the local link on the font file, you've downloaded.
You can do it even easier.
Just download the file, you've linked:
http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600,300
Name it opensans.css or so.
Then just change the links in url() to your path to font files.
And then replace your example string with:
<link href='opensans.css' rel='stylesheet' type='text/css'>
The solution of this problem is really very simple. actually Google start using a new authorization mechanism for its User.. you might have seen another line in debug console prompting you to log into your account using any browser.! this is because of new XOAUTH2 authentication mechanism which google start using since 2014. remember.. do not use the ssl over port 465, instead go for tls over 587. this is just because of XOAUTH2 authentication mechanism. if you use ssl over 465, your request will be bounced back.
what you really need to do is .. log into your google account and open up following address https://www.google.com/settings/security/lesssecureapps and check turn on . you have to do this for letting you to connect with the google SMTP because according to new authentication mechanism google bounce back all the requests from all those applications which does not follow any standard encryption technique.. after checking turn on.. you are good to go.. here is the code which worked fine for me..
require_once 'C:\xampp\htdocs\email\vendor\autoload.php';
define ('GUSER','[email protected]');
define ('GPWD','your password');
// make a separate file and include this file in that. call this function in that file.
function smtpmailer($to, $from, $from_name, $subject, $body) {
global $error;
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 2; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
$mail->SMTPAutoTLS = false;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->Username = GUSER;
$mail->Password = GPWD;
$mail->SetFrom($from, $from_name);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);
if(!$mail->Send()) {
$error = 'Mail error: '.$mail->ErrorInfo;
return false;
} else {
$error = 'Message sent!';
return true;
}
}
In one controller, you can do:
$rootScope.$broadcast('eventName', data);
and listen to the event in another:
$scope.$on('eventName', function (event, data) {...});
If you don't want to use a function constructor like in Brian's answer you can use Object.create() instead:-
var myVar = {
count: 0
}
myVar.init = function(n) {
this.count = n
this.newDiv()
}
myVar.newDiv = function() {
var newDiv = document.createElement("div")
var contents = document.createTextNode("Click me!")
var func = myVar.func(this)
newDiv.addEventListener ?
newDiv.addEventListener('click', func, false) :
newDiv.attachEvent('onclick', func)
newDiv.appendChild(contents)
document.getElementsByTagName("body")[0].appendChild(newDiv)
}
myVar.func = function (thys) {
return function() {
thys.clickme()
}
}
myVar.clickme = function () {
this.count += 1
alert(this.count)
}
myVar.init(2)
var myVar1 = Object.create(myVar)
myVar1.init(55)
var myVar2 = Object.create(myVar)
myVar2.init(150)
// etc
Strangely, I couldn't get the above to work using newDiv.onClick, but it works with newDiv.addEventListener / newDiv.attachEvent.
Since Object.create is newish, include the following code from Douglas Crockford for older browsers, including IE8.
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o
return new F()
}
}
Finally this is for Hibernate 5
in Tomcat
.
Compiled all the answers from the above and added my tips which works like a charm for Hibernate 5 and SQL Server 2014
.
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.SQLServerDialect
</property>
<property name="hibernate.connection.driver_class">
com.microsoft.sqlserver.jdbc.SQLServerDriver
</property>
<property name="hibernate.connection.url">
jdbc:sqlserver://localhost\ServerInstanceOrServerName:1433;databaseName=DATABASE_NAME
</property>
<property name="hibernate.default_schema">theSchemaNameUsuallydbo</property>
<property name="hibernate.connection.username">
YourUsername
</property>
<property name="hibernate.connection.password">
YourPasswordForMSSQL
</property>
This is the tutorial I used to get to darrinm's answer. It's updated for ios5/6 and really easy. When I'm popular enough I'll delete this and add it as a comment to his answer.
http://www.raywenderlich.com/5492/working-with-json-in-ios-5
http://www.touch-code-magazine.com/tutorial-fetch-and-parse-json-in-ios6/
This is because you DON'T associated the OnClickListener() on the button retrieve from the XML layout.
You don't need to create object because they are already created by the Android system when you inflate XML file (with the Activity.setContentLayout( int resourceLayoutId ) method).
Just retrieve them with the findViewById(...) method.
Depending on what style attributes you'd like to change you may be able to use the Paris library:
Button view = (Button) LayoutInflater.from(this).inflate(R.layout.section_button, null);
Paris.style(view).apply(R.style.YourStyle);
Many attributes like background, padding, textSize, textColor, etc. are supported.
Disclaimer: I authored the library.
I found that the only option that worked for me was
font-size:0;
I was also using overflow
and white-space: nowrap;
float: left;
seems to mess things up
If you have notepad++ installed in your pc, then you can copy text as RTF (Rich Text Format) and paste it in your outlook mail.
1) Paste you code snippet into notepad++
2) From Menu bar navigate to "Plugins -> NppExport -> Copy RTF to clipboard"
3) Paste into your email
4) Done
To save the Log cat content to the file, you need to redirect to the android sdk's platform tools folder and hit the below command
adb logcat > logcat.txt
In Android Studio, version 3.6RC1, file will be created of the name "logcat.txt" in respective project folder. you can change the name according to your interest. enjoy
Adding a new row in a DGV with no rows with Add() raises SelectionChanged event before you can insert any data (or bind an object in Tag property).
Create a clone row from RowTemplate is safer imho:
//assuming that you created columns (via code or designer) in myDGV
DataGridViewRow row = (DataGridViewRow) myDGV.RowTemplate.Clone();
row.CreateCells(myDGV, "cell1", "cell2", "cell3");
myDGV.Rows.Add(row);
There are several ways to do it This is the better way
res.download('/report-12345.pdf')
or in your case this might be
app.get('/download', function(req, res){
const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`;
res.download(file); // Set disposition and send it.
});
just do something like this:
ListIterator<String> it = list1.listIterator();
int index = -1;
while (it.hasNext()) {
index++;
String value = it.next();
//At this point the index can be checked for the current element.
}
In my case I just needed to remove Homebrew's executable using:
sudo rm -f `which brew`
Then reinstall Homebrew:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
This can be done with a single statement and some XML magic:
select table_name,
to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from '||owner||'.'||table_name)),'/ROWSET/ROW/C')) as count
from all_tables
where owner = 'FOOBAR'
Try this.
20 4 * * *
Check the below Screenshot
Referred URL - https://www.lenar.io/jenkins-schedule-build-periodically/
$('.launchConfirm').on('click', function (e) {
$('#confirm')
.modal({ backdrop: 'static', keyboard: false })
.one('click', '#delete', function (e) {
//delete function
});
});
For your button:
<button class='btn btn-danger btn-xs launchConfirm' type="button" name="remove_levels"><span class="fa fa-times"></span> delete</button></td>
TL;DR
You should use FLUSH PRIVILEGES;
only if you modify the grant tables directly using statements such as INSERT
, UPDATE
, or DELETE
.
Each computer where the common language runtime is installed has a machine-wide code cache called the global assembly cache. The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer.
You should share assemblies by installing them into the global assembly cache only when you need to. As a general guideline, keep assembly dependencies private, and locate assemblies in the application directory unless sharing an assembly is explicitly required. In addition, it is not necessary to install assemblies into the global assembly cache to make them accessible to COM interop or unmanaged code.
The things MSDN contains may surprise you... you can usually read it like an article. The straightforward and most important bits at the top, the intricate details deeper down. It certainly explains it better than I could.
Note that Visual Studio displays all the DLLs in the GAC in the .NET tab of the References window. (Right-click on a project in Solution Explorer and select Add Reference.) This should give you a more tangeable idea.
use copy() and unlink() function
$moveFile="path/filename";
if (copy($csvFile,$moveFile))
{
unlink($csvFile);
}
I solved it.
I used destroy instead close function (it doesn't make any sense), but it worked.
$(document).ready(function() {
$('#showTerms').click(function()
{
$('#terms').css('display','inline');
$('#terms').dialog({resizable: false,
modal: true,
width: 400,
height: 450,
overlay: { backgroundColor: "#000", opacity: 0.5 },
buttons:{ "Close": function() { $(this).dialog('**destroy**'); } },
close: function(ev, ui) { $(this).close(); },
});
});
$('#form1 input#calendarTEST').datepicker({ dateFormat: 'MM d, yy' });
});
The explanation for how it works:
JUnit wraps your test method in a Statement object so statement and Execute()
runs your test. Then instead of calling statement.Execute()
directly to run your test, JUnit passes the Statement to a TestRule with the @Rule
annotation. The TestRule's "apply" function returns a new Statement given the Statement with your test. The new Statement's Execute()
method can call the test Statement's execute method (or not, or call it multiple times), and do whatever it wants before and after
.
Now, JUnit has a new Statement that does more than just run the test, and it can again pass that to any more rules before finally calling Execute.
If you want to leave the original array intact,
you need a second array to contain the uniqe elements of the first-
Most browsers have Array.prototype.filter
:
var unique= array1.filter(function(itm, i){
return array1.indexOf(itm)== i;
// returns true for only the first instance of itm
});
//if you need a 'shim':
Array.prototype.filter= Array.prototype.filter || function(fun, scope){
var T= this, A= [], i= 0, itm, L= T.length;
if(typeof fun== 'function'){
while(i<L){
if(i in T){
itm= T[i];
if(fun.call(scope, itm, i, T)) A[A.length]= itm;
}
++i;
}
}
return A;
}
Array.prototype.indexOf= Array.prototype.indexOf || function(what, i){
if(!i || typeof i!= 'number') i= 0;
var L= this.length;
while(i<L){
if(this[i]=== what) return i;
++i;
}
return -1;
}
The first step is to make P2 reference P1 by doing the following
Next you'll need to make sure that the classes in P1 are accessible to P2. The easiest way is to make them public
.
public class MyType { ... }
Now you should be able to use them in P2 via their fully qualified name. Assuming the namespace of P1 is Project1 then the following would work
Project1.MyType obj = new Project1.MyType();
The preferred way though is to add a using for Project1
so you can use the types without qualification
using Project1;
...
public void Example() {
MyType obj = new MyType();
}
I tried everything said here without any luck, but found a workaround.
After running this command (and failing) : bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg
Go to the temporary directory the tool made (given in the output of the last command), then execute python setup.py bdist_wheel
. The .whl
file is in the dist
folder.
I use something like this function I created...
Object.getKeys = function(obj, add) {
if(obj === undefined || obj === null) {
return undefined;
}
var keys = [];
if(add !== undefined) {
keys = jQuery.merge(keys, add);
}
for(key in obj) {
if(obj.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys;
};
I think you could set obj to self or something better in the first test. It seems sometimes I'm checking if it's empty too so I did it that way. Also I don't think {} is Object.* or at least there's a problem finding the function getKeys on the Object that way. Maybe you're suppose to put prototype first, but that seems to cause a conflict with GreenSock etc.
They often forget that iterator
must convert to const_iterator
but not the other way around. Here is a way to do that:
template<class T, class Tag = void>
class IntrusiveSlistIterator
: public std::iterator<std::forward_iterator_tag, T>
{
typedef SlistNode<Tag> Node;
Node* node_;
public:
IntrusiveSlistIterator(Node* node);
T& operator*() const;
T* operator->() const;
IntrusiveSlistIterator& operator++();
IntrusiveSlistIterator operator++(int);
friend bool operator==(IntrusiveSlistIterator a, IntrusiveSlistIterator b);
friend bool operator!=(IntrusiveSlistIterator a, IntrusiveSlistIterator b);
// one way conversion: iterator -> const_iterator
operator IntrusiveSlistIterator<T const, Tag>() const;
};
In the above notice how IntrusiveSlistIterator<T>
converts to IntrusiveSlistIterator<T const>
. If T
is already const
this conversion never gets used.
Multiple statements are to be separated by a new line:
If SkyIsBlue Then
StartEngines
Pollute
ElseIf SkyIsRed Then
StopAttack
Vent
ElseIf SkyIsYellow Then
If Sunset Then
Sleep
ElseIf Sunrise or IsMorning Then
Smoke
GetCoffee
Else
Error
End If
Else
Joke
Laugh
End If
Another "finally" block emulation using C++11 lambda functions
template <typename TCode, typename TFinallyCode>
inline void with_finally(const TCode &code, const TFinallyCode &finally_code)
{
try
{
code();
}
catch (...)
{
try
{
finally_code();
}
catch (...) // Maybe stupid check that finally_code mustn't throw.
{
std::terminate();
}
throw;
}
finally_code();
}
Let's hope the compiler will optimize the code above.
Now we can write code like this:
with_finally(
[&]()
{
try
{
// Doing some stuff that may throw an exception
}
catch (const exception1 &)
{
// Handling first class of exceptions
}
catch (const exception2 &)
{
// Handling another class of exceptions
}
// Some classes of exceptions can be still unhandled
},
[&]() // finally
{
// This code will be executed in all three cases:
// 1) exception was not thrown at all
// 2) exception was handled by one of the "catch" blocks above
// 3) exception was not handled by any of the "catch" block above
}
);
If you wish you can wrap this idiom into "try - finally" macros:
// Please never throw exception below. It is needed to avoid a compilation error
// in the case when we use "begin_try ... finally" without any "catch" block.
class never_thrown_exception {};
#define begin_try with_finally([&](){ try
#define finally catch(never_thrown_exception){throw;} },[&]()
#define end_try ) // sorry for "pascalish" style :(
Now "finally" block is available in C++11:
begin_try
{
// A code that may throw
}
catch (const some_exception &)
{
// Handling some exceptions
}
finally
{
// A code that is always executed
}
end_try; // Sorry again for this ugly thing
Personally I don't like the "macro" version of "finally" idiom and would prefer to use pure "with_finally" function even though a syntax is more bulky in that case.
You can test the code above here: http://coliru.stacked-crooked.com/a/1d88f64cb27b3813
PS
If you need a finally block in your code, then scoped guards or ON_FINALLY/ON_EXCEPTION macros will probably better fit your needs.
Here is short example of usage ON_FINALLY/ON_EXCEPTION:
void function(std::vector<const char*> &vector)
{
int *arr1 = (int*)malloc(800*sizeof(int));
if (!arr1) { throw "cannot malloc arr1"; }
ON_FINALLY({ free(arr1); });
int *arr2 = (int*)malloc(900*sizeof(int));
if (!arr2) { throw "cannot malloc arr2"; }
ON_FINALLY({ free(arr2); });
vector.push_back("good");
ON_EXCEPTION({ vector.pop_back(); });
...
Here is a function to get the IP address using a filter for local and LAN IP addresses:
function get_IP_address()
{
foreach (array('HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR') as $key){
if (array_key_exists($key, $_SERVER) === true){
foreach (explode(',', $_SERVER[$key]) as $IPaddress){
$IPaddress = trim($IPaddress); // Just to be safe
if (filter_var($IPaddress,
FILTER_VALIDATE_IP,
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)
!== false) {
return $IPaddress;
}
}
}
}
}
Question has a good pagerank on google, so for anyone who's looking for answer to this question this might be helpful.
There is an extension in google chrome marketspace to do exactly that: https://chrome.google.com/webstore/detail/hccmhjmmfdfncbfpogafcbpaebclgjcp
Visibility is animatable. Check this blog post about it: http://www.greywyvern.com/?post=337
You can see it here too: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties
Let's say you have a menu that you want to fade-in and fade-out on mouse hover. If you use opacity:0
only, your transparent menu will still be there and it will animate when you hover the invisible area. But if you add visibility:hidden
, you can eliminate this problem:
div {_x000D_
width:100px;_x000D_
height:20px;_x000D_
}_x000D_
.menu {_x000D_
visibility:hidden;_x000D_
opacity:0;_x000D_
transition:visibility 0.3s linear,opacity 0.3s linear;_x000D_
_x000D_
background:#eee;_x000D_
width:100px;_x000D_
margin:0;_x000D_
padding:5px;_x000D_
list-style:none;_x000D_
}_x000D_
div:hover > .menu {_x000D_
visibility:visible;_x000D_
opacity:1;_x000D_
}
_x000D_
<div>_x000D_
<a href="#">Open Menu</a>_x000D_
<ul class="menu">_x000D_
<li><a href="#">Item</a></li>_x000D_
<li><a href="#">Item</a></li>_x000D_
<li><a href="#">Item</a></li>_x000D_
</ul>_x000D_
</div>
_x000D_
Read Google-gson
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
Add the following line to your MODULE LEVEL build.gradle
configuration:
dependencies {
implementation 'com.google.code.gson:gson:2.8.5' // Old 2.8.2
}
You have to be specific about the columns you are selecting. If your user
table had four columns id, name, username, opted_in
you must select exactly those four columns from the query. The syntax looks like:
INSERT INTO user (id, name, username, opted_in)
SELECT id, name, username, opted_in
FROM user LEFT JOIN user_permission AS userPerm ON user.id = userPerm.user_id
However, there does not appear to be any reason to join against user_permission
here, since none of the columns from that table would be inserted into user
. In fact, this INSERT
seems bound to fail with primary key uniqueness violations.
MySQL does not support inserts into multiple tables at the same time. You either need to perform two INSERT
statements in your code, using the last insert id from the first query, or create an AFTER INSERT
trigger on the primary table.
INSERT INTO user (name, username, email, opted_in) VALUES ('a','b','c',0);
/* Gets the id of the new row and inserts into the other table */
INSERT INTO user_permission (user_id, permission_id) VALUES (LAST_INSERT_ID(), 4)
Or using a trigger:
CREATE TRIGGER creat_perms AFTER INSERT ON `user`
FOR EACH ROW
BEGIN
INSERT INTO user_permission (user_id, permission_id) VALUES (NEW.id, 4)
END
UPDATE January, 2017:
According to Can I use, the user-select
is currently supported in all browsers except Internet Explorer 9 and earlier versions (but sadly still needs a vendor prefix).
All of the correct CSS variations are:
.noselect {_x000D_
-webkit-touch-callout: none; /* iOS Safari */_x000D_
-webkit-user-select: none; /* Safari */_x000D_
-khtml-user-select: none; /* Konqueror HTML */_x000D_
-moz-user-select: none; /* Firefox */_x000D_
-ms-user-select: none; /* Internet Explorer/Edge */_x000D_
user-select: none; /* Non-prefixed version, currently_x000D_
supported by Chrome and Opera */_x000D_
}
_x000D_
<p>_x000D_
Selectable text._x000D_
</p>_x000D_
<p class="noselect">_x000D_
Unselectable text._x000D_
</p>
_x000D_
Note that it's a non-standard feature (i.e. not a part of any specification). It is not guaranteed to work everywhere, and there might be differences in implementation among browsers and in the future browsers can drop support for it.
More information can be found in Mozilla Developer Network documentation.
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<form method="post" id="form_content" action="Javascript:void(0);">
<button id="desc" name="desc" value="desc" style="display:none;">desc</button>
<button id="asc" name="asc" value="asc">asc</button>
<input type='hidden' id='check' value=''/>
</form>
<div id="demoajax"></div>
<script>
numbers = '';
$('#form_content button').click(function(){
$('#form_content button').toggle();
numbers = this.id;
function_two(numbers);
});
function function_two(numbers){
if (numbers === '')
{
$('#check').val("asc");
}
else
{
$('#check').val(numbers);
}
//alert(sort_var);
$.ajax({
url: 'test.php',
type: 'POST',
data: $('#form_content').serialize(),
success: function(data){
$('#demoajax').show();
$('#demoajax').html(data);
}
});
return false;
}
$(document).ready(function_two());
</script>
The only way to retrieve the correct value in your context is to run $.ajax()
function synchronously (what actually contradicts to main AJAX idea). There is the special configuration attribute async
you should set to false
. In that case the main scope which actually contains $.ajax()
function call is paused until the synchronous function is done, so, the return
is called only after $.ajax()
.
function doSomething() {
var status = 0;
$.ajax({
url: 'action.php',
type: 'POST',
data: dataString,
async: false,
success: function (txtBack) {
if (txtBack == 1)
status = 1;
}
});
return status;
}
var response = doSomething();
The simple way:
$GET = array();
$key = 'one=1';
parse_str($key, $GET);
try this..
using System;
using System.Net.Mail;
public class Test
{
public static void Main()
{
SmtpClient client = new SmtpClient("smtphost", 25);
MailMessage msg = new MailMessage("[email protected]", "[email protected],[email protected]");
msg.Subject = "sdfdsf";
msg.Body = "sdfsdfdsfd";
client.UseDefaultCredentials = true;
client.Send(msg);
}
}
I actually got this error because I was checking InnerHtml for some content that was generated dynamically - i.e. a control that is runat=server.
To solve this I had to remove the "static" keyword on my method, and it ran fine.
C:\Users\*********\AppData\Local\Android\Sdk
Check whether the USERNAME
is correct, for me a new USERNAME
got created with my proxy extension.
New location for mysql config file is
/etc/mysql/mysql.conf.d/mysqld.cnf
You can use:
Insert into Event(Description,Date) values('teste', GETDATE());
Also, you can change your table so that 'Date' has a default, "GETDATE()"
Application is not the same as the Singleton.The reasons are:
Is better to use parse_url
to retrieve only the path, and then getting only the filename with the basename
. This way we also avoid query parameters.
<?php
// url to inspect
$url = 'http://www.example.com/image.jpg?q=6574&t=987';
// parsed path
$path = parse_url($url, PHP_URL_PATH);
// extracted basename
echo basename($path);
?>
Is somewhat similar to Sultan answer excepting that I'm using component
parse_url
parameter, to obtain only the path.
You are missing the std namespace reference in the cc file. You should also call nom.c_str()
because there is no implicit conversion from std::string
to const char *
expected by ifstream
's constructor.
Polygone::Polygone(std::string nom) {
std::ifstream fichier (nom.c_str(), std::ifstream::in);
// ...
}
Another reason the breakpoints can turn yellow is if the application binary you are debugging has been modified since it was first run. In my case, I added a folder to the application's Contents/Resources folder after having debugged the program once. On the debug run after adding the folder, the breakpoints turned yellow and were ignored. I modified my procedure: I did a clean, a build, added the folder, then ran, and all was well.
Perhaps Xcode (or OS X) creates and remembers its own digital signature of the application (which was not digitally signed) and then, sensing that the application was modified, refuses to try to set breakpoints. By making my mods before the first (debug) run of the application, the digital signature was made with my mods.
All this on OS X 10.6.8 using Xcode 3.2.2.
I think you want to take a look at jQuery since that Javascript library provides a lot of functionality you might want to use in this kind of cases. In your case you could write (or find one on the internet) a hasAttribute method, like so (not tested):
$.fn.hasAttribute = function(tagName, attrName){
var result = [];
$.each($(tagName), function(index, value) {
var attr = $(this).attr(attrName);
if (typeof attr !== 'undefined' && attr !== false)
result.push($(this));
});
return result;
}
Just drop them:
nms.dropna(thresh=2)
this will drop all rows where there are at least two non-NaN
.
Then you could then drop where name is NaN
:
In [87]:
nms
Out[87]:
movie name rating
0 thg John 3
1 thg NaN 4
3 mol Graham NaN
4 lob NaN NaN
5 lob NaN NaN
[5 rows x 3 columns]
In [89]:
nms = nms.dropna(thresh=2)
In [90]:
nms[nms.name.notnull()]
Out[90]:
movie name rating
0 thg John 3
3 mol Graham NaN
[2 rows x 3 columns]
EDIT
Actually looking at what you originally want you can do just this without the dropna
call:
nms[nms.name.notnull()]
UPDATE
Looking at this question 3 years later, there is a mistake, firstly thresh
arg looks for at least n
non-NaN
values so in fact the output should be:
In [4]:
nms.dropna(thresh=2)
Out[4]:
movie name rating
0 thg John 3.0
1 thg NaN 4.0
3 mol Graham NaN
It's possible that I was either mistaken 3 years ago or that the version of pandas I was running had a bug, both scenarios are entirely possible.
SELECT col1, col2, IF( action = 2 AND state = 0, 1, 0 ) AS state from tbl1;
OR
SELECT col1, col2, (case when (action = 2 and state = 0) then 1 else 0 end) as state from tbl1;
both results will same....
Turns out I don't have enough reputation to put this as a comment, which would be a more appropriate place for this:
Re. AllBlackt's answer, if you prefer Ansible's multiline format you need to adjust the quoting for state
(I spent a few minutes working this out, so hopefully this speeds someone else up),
- stat:
path: "/etc/nologin"
register: p
- name: create fake 'nologin' shell
file:
path: "/etc/nologin"
owner: root
group: sys
mode: 0555
state: '{{ "file" if p.stat.exists else "touch" }}'
I like the xargs
solution, but if it's important to not collapse spaces, then one might instead do:
sed ':b;$!{N;bb};s/\n/ /g'
That will replace newlines for spaces, without substituting the last line terminator like tr '\n' ' '
would.
This also allows you to use other joining strings besides a space, like a comma, etc, something that xargs
cannot do:
$ seq 1 5 | sed ':b;$!{N;bb};s/\n/,/g'
1,2,3,4,5
The correct syntax for adding column into table is:
ALTER TABLE table_name
ADD column_name column-definition;
In your case it will be:
ALTER TABLE Employees
ADD EmployeeID int NOT NULL IDENTITY (1, 1)
To add multiple columns use brackets:
ALTER TABLE table_name
ADD (column_1 column-definition,
column_2 column-definition,
...
column_n column_definition);
COLUMN
keyword in SQL SERVER is used only for altering:
ALTER TABLE table_name
ALTER COLUMN column_name column_type;
FOUND THE SOLUTION: I added an action listener before uploadingDialog.show() like this:
uploadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
public void onCancel(DialogInterface dialog) {
myTask.cancel(true);
//finish();
}
});
That way when I press the back button, the above OnCancelListener cancels both dialog and task. Also you can add finish() if you want to finish the whole activity on back pressed. Remember to declare your async task as a variable like this:
MyAsyncTask myTask=null;
and execute your async task like this:
myTask = new MyAsyncTask();
myTask.execute();
The correct answer is SYSDATE().
INSERT INTO servers (
server_name, online_status, exchange, disk_space,
network_shares, date_time
)
VALUES (
'm1', 'ONLINE', 'ONLINE', '100GB', 'ONLINE', SYSDATE()
);
We can change this behavior and make NOW()
behave in the same way as SYSDATE()
by setting sysdate_is_now command line argument to True
.
Note that NOW()
(which has CURRENT_TIMESTAMP()
as an alias), differs from SYSDATE()
in a subtle way:
SYSDATE() returns the time at which it executes. This differs from the behavior for NOW(), which returns a constant time that indicates the time at which the statement began to execute. (Within a stored function or trigger, NOW() returns the time at which the function or triggering statement began to execute.)
As indicated by Erandi, it is best to create your table with the DEFAULT
clause so that the column gets populated automatically with the timestamp when you insert a new row:
date_time datetime NOT NULL DEFAULT SYSDATE()
If you want the current date in epoch format, then you can use UNIX_TIMESTAMP(). For example:
select now(3), sysdate(3), unix_timestamp();
would yield
+-------------------------+-------------------------+------------------+
| now(3) | sysdate(3) | unix_timestamp() |
+-------------------------+-------------------------+------------------+
| 2018-11-27 01:40:08.160 | 2018-11-27 01:40:08.160 | 1543282808 |
+-------------------------+-------------------------+------------------+
Related:
TL;DR
The @Autowired
annotation spares you the need to do the wiring by yourself in the XML file (or any other way) and just finds for you what needs to be injected where and does that for you.
Full explanation
The @Autowired
annotation allows you to skip configurations elsewhere of what to inject and just does it for you. Assuming your package is com.mycompany.movies
you have to put this tag in your XML (application context file):
<context:component-scan base-package="com.mycompany.movies" />
This tag will do an auto-scanning. Assuming each class that has to become a bean is annotated with a correct annotation like @Component
(for simple bean) or @Controller
(for a servlet control) or @Repository
(for DAO
classes) and these classes are somewhere under the package com.mycompany.movies
, Spring will find all of these and create a bean for each one. This is done in 2 scans of the classes - the first time it just searches for classes that need to become a bean and maps the injections it needs to be doing, and on the second scan it injects the beans. Of course, you can define your beans in the more traditional XML file or with an @Configuration
class (or any combination of the three).
The @Autowired
annotation tells Spring where an injection needs to occur. If you put it on a method setMovieFinder
it understands (by the prefix set
+ the @Autowired
annotation) that a bean needs to be injected. In the second scan, Spring searches for a bean of type MovieFinder
, and if it finds such bean, it injects it to this method. If it finds two such beans you will get an Exception
. To avoid the Exception
, you can use the @Qualifier
annotation and tell it which of the two beans to inject in the following manner:
@Qualifier("redBean")
class Red implements Color {
// Class code here
}
@Qualifier("blueBean")
class Blue implements Color {
// Class code here
}
Or if you prefer to declare the beans in your XML, it would look something like this:
<bean id="redBean" class="com.mycompany.movies.Red"/>
<bean id="blueBean" class="com.mycompany.movies.Blue"/>
In the @Autowired
declaration, you need to also add the @Qualifier
to tell which of the two color beans to inject:
@Autowired
@Qualifier("redBean")
public void setColor(Color color) {
this.color = color;
}
If you don't want to use two annotations (the @Autowired
and @Qualifier
) you can use @Resource
to combine these two:
@Resource(name="redBean")
public void setColor(Color color) {
this.color = color;
}
The @Resource
(you can read some extra data about it in the first comment on this answer) spares you the use of two annotations and instead, you only use one.
I'll just add two more comments:
@Inject
instead of @Autowired
because it is not Spring-specific and is part of the JSR-330
standard.@Inject
/ @Autowired
on a constructor instead of a method. If you put it on a constructor, you can validate that the injected beans are not null and fail fast when you try to start the application and avoid a NullPointerException
when you need to actually use the bean.Update: To complete the picture, I created a new question about the @Configuration
class.
It's better to avoid unnecessary autoboxing for 2 reasons.
For one thing, it's a bit slower than int < int
, as you're (sometimes) creating an extra object;
void doSomethingWith(Integer integerObject){ ...
int i = 1000;
doSomethingWith(i);//gets compiled into doSomethingWith(Integer.valueOf(i));
The bigger issue is that hidden autoboxing can hide exceptions:
void doSomethingWith (Integer count){
if (count>0) // gets compiled into count.intValue()>0
Calling this method with null
will throw a NullPointerException
.
The split between primitives and wrapper objects in java was always described as a kludge for speed. Autoboxing almost hides this, but not quite - it's cleaner just to keep track of the type. So if you've got an Integer object, you can just call compare()
or intValue()
, and if you've got the primitive just check the value directly.
The bash script should be something like this:
#!/bin/bash
/usr/bin/php /path/to/php/file.php
You need the php executable (usually found in /usr/bin) and the path of the php script to be ran. Now you only have to put this bash script on crontab and you're done!
You should use UNION if you want to combine different resultsets. Try the following:
(SELECT *
FROM ( SELECT *
FROM orders_products
INNER JOIN orders ON orders_products.orders_id = orders.orders_id
WHERE products_id = 181) AS A)
UNION
(SELECT *
FROM ( SELECT *
FROM orders_products
INNER JOIN orders ON orders_products.orders_id = orders.orders_id
WHERE products_id = 180) AS B
ON A.orders_id=B.orders_id)
(The answer was heavily modified after clarifications to the original question)
After clarifications:
This cannot be done in xml only. It is not possible to scale both the image and the ImageView
so that image's one dimension would always be 250dp and the ImageView
would have the same dimensions as the image.
This code scales Drawable
of an ImageView
to stay in a square like 250dp x 250dp with one dimension exactly 250dp and keeping the aspect ratio. Then the ImageView
is resized to match the dimensions of the scaled image. The code is used in an activity. I tested it via button click handler.
Enjoy. :)
private void scaleImage(ImageView view) throws NoSuchElementException {
// Get bitmap from the the ImageView.
Bitmap bitmap = null;
try {
Drawable drawing = view.getDrawable();
bitmap = ((BitmapDrawable) drawing).getBitmap();
} catch (NullPointerException e) {
throw new NoSuchElementException("No drawable on given view");
} catch (ClassCastException e) {
// Check bitmap is Ion drawable
bitmap = Ion.with(view).getBitmap();
}
// Get current dimensions AND the desired bounding box
int width = 0;
try {
width = bitmap.getWidth();
} catch (NullPointerException e) {
throw new NoSuchElementException("Can't find bitmap on given view/drawable");
}
int height = bitmap.getHeight();
int bounding = dpToPx(250);
Log.i("Test", "original width = " + Integer.toString(width));
Log.i("Test", "original height = " + Integer.toString(height));
Log.i("Test", "bounding = " + Integer.toString(bounding));
// Determine how much to scale: the dimension requiring less scaling is
// closer to the its side. This way the image always stays inside your
// bounding box AND either x/y axis touches it.
float xScale = ((float) bounding) / width;
float yScale = ((float) bounding) / height;
float scale = (xScale <= yScale) ? xScale : yScale;
Log.i("Test", "xScale = " + Float.toString(xScale));
Log.i("Test", "yScale = " + Float.toString(yScale));
Log.i("Test", "scale = " + Float.toString(scale));
// Create a matrix for the scaling and add the scaling data
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
// Create a new bitmap and convert it to a format understood by the ImageView
Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
width = scaledBitmap.getWidth(); // re-use
height = scaledBitmap.getHeight(); // re-use
BitmapDrawable result = new BitmapDrawable(scaledBitmap);
Log.i("Test", "scaled width = " + Integer.toString(width));
Log.i("Test", "scaled height = " + Integer.toString(height));
// Apply the scaled bitmap
view.setImageDrawable(result);
// Now change ImageView's dimensions to match the scaled image
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
params.width = width;
params.height = height;
view.setLayoutParams(params);
Log.i("Test", "done");
}
private int dpToPx(int dp) {
float density = getApplicationContext().getResources().getDisplayMetrics().density;
return Math.round((float)dp * density);
}
The xml code for the ImageView
:
<ImageView a:id="@+id/image_box"
a:background="#ff0000"
a:src="@drawable/star"
a:layout_width="wrap_content"
a:layout_height="wrap_content"
a:layout_marginTop="20dp"
a:layout_gravity="center_horizontal"/>
Thanks to this discussion for the scaling code:
http://www.anddev.org/resize_and_rotate_image_-_example-t621.html
UPDATE 7th, November 2012:
Added null pointer check as suggested in comments
For Sybase ASE, sp_columns table_name will return all the table metadata you are looking for.
There are three possible ways to do that.
Option
SELECT lt.* FROM table_left lt
LEFT JOIN
table_right rt
ON rt.value = lt.value
WHERE rt.value IS NULL
Option
SELECT lt.* FROM table_left lt
WHERE lt.value NOT IN
(
SELECT value
FROM table_right rt
)
Option
SELECT lt.* FROM table_left lt
WHERE NOT EXISTS
(
SELECT NULL
FROM table_right rt
WHERE rt.value = lt.value
)
As others have mentioned, Google uses a homegrown solution called BigTable and they've released a few papers describing it out into the real world.
The Apache folks have an implementation of the ideas presented in these papers called HBase. HBase is part of the larger Hadoop project which according to their site "is a software platform that lets one easily write and run applications that process vast amounts of data." Some of the benchmarks are quite impressive. Their site is at http://hadoop.apache.org.
This is pretty easy to do with a double for loop.
function makeTableHTML(myArray) {
var result = "<table border=1>";
for(var i=0; i<myArray.length; i++) {
result += "<tr>";
for(var j=0; j<myArray[i].length; j++){
result += "<td>"+myArray[i][j]+"</td>";
}
result += "</tr>";
}
result += "</table>";
return result;
}
When I needed HTML to PDF conversion earlier this year, I tried the trial of Winnovative HTML to PDF converter (I think ExpertPDF is the same product, too). It worked great so we bought a license at that company. I don't go into it too in depth after that.
a very common try_files line which can be applied on your condition is
location / {
try_files $uri $uri/ /test/index.html;
}
you probably understand the first part, location /
matches all locations, unless it's matched by a more specific location, like location /test
for example
The second part ( the try_files
) means when you receive a URI that's matched by this block try $uri
first, for example http://example.com/images/image.jpg
nginx will try to check if there's a file inside /images
called image.jpg
if found it will serve it first.
Second condition is $uri/
which means if you didn't find the first condition $uri
try the URI as a directory, for example http://example.com/images/
, ngixn will first check if a file called images
exists then it wont find it, then goes to second check $uri/
and see if there's a directory called images
exists then it will try serving it.
Side note: if you don't have autoindex on
you'll probably get a 403 forbidden error, because directory listing is forbidden by default.
EDIT: I forgot to mention that if you have
index
defined, nginx will try to check if the index exists inside this folder before trying directory listing.
Third condition /test/index.html
is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html
inside the folder test
and serve it if it exists.
If the third condition fails too, then nginx will serve the 404 error page.
Also there's something called named locations, like this
location @error {
}
You can call it with try_files
like this
try_files $uri $uri/ @error;
TIP: If you only have 1 condition you want to serve, like for example inside folder images
you only want to either serve the image or go to 404 error, you can write a line like this
location /images {
try_files $uri =404;
}
which means either serve the file or serve a 404 error, you can't use only $uri
by it self without =404
because you need to have a fallback option.
You can also choose which ever error code you want, like for example:
location /images {
try_files $uri =403;
}
This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..
I prefer len([b for b in boollist if b is True])
(or the generator-expression equivalent), as it's quite self-explanatory. Less 'magical' than the answer proposed by Ignacio Vazquez-Abrams.
Alternatively, you can do this, which still assumes that bool is convertable to int, but makes no assumptions about the value of True:
ntrue = sum(boollist) / int(True)
try this:
ren "File 1-1" "File 1 - %date:/=-% %time::=-%"
All of the answers here are helpful, but if you're using a Spring application context XML to setup your session factory, setting the log4j SQL level variable only gets you part of the way there, you also have to set the hibernate.show_sql variable in the app context itself to get Hibernate to start actually showing the values.
ApplicationContext.xml has:
<property name="hibernateProperties">
<value>
hibernate.jdbc.batch_size=25
... <!-- Other parameter values here -->
hibernate.show_sql=true
</value>
</property>
And your log4j file needs
log4j.logger.org.hibernate.SQL=DEBUG
Here's another fix that works for me:
(event.target as HTMLInputElement).value
That should get rid of the error by letting TS know that event.target
is an HTMLInputElement
, which inherently has a value
. Before specifying, TS likely only knew that event
alone was an HTMLInputElement
, thus according to TS the keyed-in target
was some randomly mapped value that could be anything.
When using webview as a subview somewhere in scrollview, you can set height constraint to some constant value and later make outlet from it and use it like:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
webView.scrollView.scrollEnabled = NO;
_webViewHeight.constant = webView.scrollView.contentSize.height;
}
I came across this issue, however my inline function was withing an angularJS view. Therefore on the load i could not access the inline script to add the debug, as only the index.html was available in the sources tab of the debugger.
This meant that when i was opening the particular view with my inline (had no choice on this) it was not accessible.
The onlly way i was able to hit it was to put an erroneous function or call inside the inline JS function.
My solution included :
function doMyInline(data) {
//Throw my undefined error here.
$("select.Sel").debug();
//This is the real onclick i was passing to
angular.element(document.getElementById(data.id)).scope().doblablabla(data.id);
}
This mean when i clicked on my button, i was then prompted in the chrome consolse.
Uncaught TypeError: undefined is not a function
The important thing here was the source of this : VM5658:6
clicking on this allowed me to step through the inline and hold the break point there for later..
Extremely convoluted way of reaching it.. But it worked and might prove useful for when dealing with Single page apps which dynamically load your views.
The VM[n]
has no significant value, and the n
on equates to the script ID. This info can be found here : Chrome "[VM]"
we can create nested cte.please see the below cte in example
;with cte_data as
(
Select * from [HumanResources].[Department]
),cte_data1 as
(
Select * from [HumanResources].[Department]
)
select * from cte_data,cte_data1
Unfortunately, Date
object in javascript returns information about months only in numeric format. The faster thing you can do is to create an array of months (they are not supposed to change frequently!) and create a function which returns the name based on the number.
Something like this:
function getMonthNameByMonthNumber(mm) {
var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
return months[mm];
}
Your code therefore becomes:
var prnDt = "Printed on Thursday, " + now.getDate() + " " + getMonthNameByMonthNumber(now.getMonth) + " "+ now.getFullYear() + " at " + h + ":" + m + ":" s;
What the code does, is that the number 8000 is counting up from 0 to 8000. The problem is, that it is placed at the middle of quite long page, and once user scroll down and actually see the number, the animation is already dine. I would like to trigger the counter, once it appears in the viewport.
JS:
$('.count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
And HTML:
<span class="count">8000</span>
$(window).bind("load", function() {
// write your code here
});
Use the Bootstrap Customizer to generate a version of Bootstrap that has a taller navbar. The value you want to change is @navbar-height
in the Navbar section.
Inspect your current implementation to see how tall your navbar is with the 50px brand image, and use that calculated height in the Customizer.
Starting with .NET 4.5, TcpClient has a cool ConnectAsync method that we can use like this, so it's now pretty easy:
var client = new TcpClient();
if (!client.ConnectAsync("remotehost", remotePort).Wait(1000))
{
// connection failure
}
Just to add to all the conversation. Since arrays requires consecutive memory locations to store the item, so if we create an array of references then it's not guaranteed that they will be at consecutive memory location so accessing will be a problem and hence we can't even apply all the mathematical operations on array.
To clarify, a database created under SQL Server 2008 R2 was being opened in an instance of SQL Server 2008 (the version prior to R2). The solution for me was to simply perform an upgrade installation of SQL Server 2008 R2. I can only speak for the Express edition, but it worked.
Oddly, though, the Web Platform Installer indicated that I had Express R2 installed. The better way to tell is to ask the database server itself:
SELECT @@VERSION
instant/feasible/partial answer : https://stackoverflow.com/a/20130959/2584794
unlike from the previous answer where netstat -a -o -n was used incredibly long list was to be looked into without the name of application using those ports
It all depends on what you are trying to achieve with "saving locally". Do you want to allow the user to download the file? then <a download>
is the way to go. Do you want to save it locally, so you can restore your application state? Then you might want to look into the various options of WebStorage. Specifically localStorage or IndexedDB. The FilesystemAPI allows you to create local virtual file systems you can store arbitrary data in.
use the object to call...
<a href="#" onclick='$("#myModal").modal("show");'>Try This</a>
or if you using ajax to show that modal after get result, this is work for me...
$.ajax({ url: "YourUrl",
type: "POST", data: "x=1&y=2&z=3",
cache: false, success: function(result){
// Your Function here
$("#myModal").modal("show");
}
});
@Bobince is providing a really opaque answer.
Riffing off of Már Örlygsson's answer, Javascript is always single-threaded because of this simple fact: Everything in Javascript is executed along a single timeline.
That is the strict definition of a single-threaded programming language.
I done in this way
from keras.models import Sequential
from keras_contrib.losses import import crf_loss
from keras_contrib.metrics import crf_viterbi_accuracy
# To save model
model.save('my_model_01.hdf5')
# To load the model
custom_objects={'CRF': CRF,'crf_loss': crf_loss,'crf_viterbi_accuracy':crf_viterbi_accuracy}
# To load a persisted model that uses the CRF layer
model1 = load_model("/home/abc/my_model_01.hdf5", custom_objects = custom_objects)
In Eclipse using Subversive:
Right click your project > Team > Merge
In the merge window, select the revisions you want to revert as normally but also enable checkbox "Reversed merge".
Merge as normally.
TextBox2.Text = "Line 1" & Environment.NewLine & "Line 2"
or
TextBox2.Text = "Line 1"
TextBox2.Text += Environment.NewLine
TextBox2.Text += "Line 2"
This, is how it is done.
This piece of snippet is from c++ primer book. Although I am sure this is wrong.
Each type parameter must be preceded by the keyword class or typename:
// error: must precede U with either typename or class
template <typename T, U> T calc(const T&, const U&);
These keywords have the same meaning and can be used interchangeably inside a template parameter list. A template parameter list can use both keywords:
// ok: no distinction between typename and class in a template parameter list
template <typename T, class U> calc (const T&, const U&);
It may seem more intuitive to use the keyword typename rather than class to designate a template type parameter. After all, we can use built-in (nonclass) types as a template type argument. Moreover, typename more clearly indicates that the name that follows is a type name. However, typename was added to C++ after templates were already in widespread use; some programmers continue to use class exclusively
F:\PuppetLab\src\boxes>vagrant box add precise32 file:///F:/PuppetLab/src/boxes/precise32.box
==> box: Adding box 'precise32' (v0) for provider:
box: Downloading: file:///F:/PuppetLab/src/boxes/precise32.box
box: Progress: 100% (Rate: 1200k/s, Estimated time remaining: --:--:--)
==> box: Successfully added box 'precise32' (v0) for 'virtualbox'!
As other's have mentioned, PHP's cURL functions will allow you to perform advanced HTTP requests. You can also use file_get_contents
to access REST APIs:
$payload = file_get_contents('http://api.someservice.com/SomeMethod?param=value');
Starting with PHP 5 you can also create a stream context which will allow you to change headers or post data to the service.
the best way to do this is with:
<a href="#" onclick="someFunction(e)"></a>
The problem is that this WILL add a hash (#) to the end of the page's URL in the browser, thus requiring the user to click the back button twice to go to the page before yours. Considering this, you need to add some code to stop event propagation. Most javascript toolkits will already have a function for this. For example, the dojo toolkit uses
dojo.stopEvent(event);
to do so.
Addition to previous answer make sure that your curl installation supports https.
You can use curl --version
to get information about supported protocols.
If your curl supports https follow the previous answer.
curl --cert certificate_path:password https://www.example.com
If it does not support https, you need to install a cURL version that supports https.
Reading this original article on The Code Project will help you a lot: Visual Representation of SQL Joins.
Also check this post: SQL SERVER – Better Performance – LEFT JOIN or NOT IN?.
Find original one at: Difference between JOIN and OUTER JOIN in MySQL.
You perhaps use the wrong username.
I had a similar error. Ensure you're not using uppercase while logging into server.
Example: [email protected]
If you use ->setUsername('JacekPL')
, this can cause an error. Use ->setUsername('jacekpl')
instead. This solved my problem.
You can execute this command to enable nodejs:
scl enable rh-nodejs8 bash
Note: Check your node version.
Source: https://developers.redhat.com/products/softwarecollections/hello-world/
Your result is currently in string format, you need to parse it as json.
var obj = $.parseJSON(result);
alert(obj[0].category);
Additionally, if you set the dataType of the ajax call you are making to json
, you can skip the $.parseJSON()
step.
In the manual for GNU make, they talk about this specific example when describing the value
function:
The value function provides a way for you to use the value of a variable without having it expanded. Please note that this does not undo expansions which have already occurred; for example if you create a simply expanded variable its value is expanded during the definition; in that case the value function will return the same result as using the variable directly.
The syntax of the value function is:
$(value variable)
Note that variable is the name of a variable; not a reference to that variable. Therefore you would not normally use a ‘$’ or parentheses when writing it. (You can, however, use a variable reference in the name if you want the name not to be a constant.)
The result of this function is a string containing the value of variable, without any expansion occurring. For example, in this makefile:
FOO = $PATH all: @echo $(FOO) @echo $(value FOO)
The first output line would be ATH, since the “$P” would be expanded as a make variable, while the second output line would be the current value of your $PATH environment variable, since the value function avoided the expansion.
What you could also do is put a .htaccess file containing
RewriteEngine Off
In the folders you want to exclude from being rewritten (by the rules in a .htaccess file that's higher up in the tree). Simple but effective.
void Test(){
var obj = new{a="aaa", b="bbb"};
var val_a = obj.GetValObjDy("a"); //="aaa"
var val_b = obj.GetValObjDy("b"); //="bbb"
}
//create in a static class
static public object GetValObjDy(this object obj, string propertyName)
{
return obj.GetType().GetProperty(propertyName).GetValue(obj, null);
}
SELECT dateadd(dd,DAYS,'2013-09-07 00:00:00') DATES
INTO #TEMP1
FROM
(SELECT TOP 365 colorder - 1 AS DAYS from master..syscolumns
WHERE id = -519536829 order by colorder) a
WHERE datediff(dd,dateadd(dd,DAYS,'2013-09-07 00:00:00'),'2013-09-13 00:00:00' ) >= 0
AND dateadd(dd,DAYS,'2013-09-07 00:00:00') <= '2013-09-13 00:00:00'
SELECT * FROM #TEMP1
Yet another way to do this:
shopt -s extglob
selfpath=$0
selfdir=${selfpath%%+([!/])}
while [[ -L "$selfpath" ]];do
selfpath=$(readlink "$selfpath")
if [[ ! "$selfpath" =~ ^/ ]];then
selfpath=${selfdir}${selfpath}
fi
selfdir=${selfpath%%+([!/])}
done
echo $selfpath $selfdir
No, you can never instantiate an abstract class. That's the purpose of an abstract class. The getProvider
method you are referring to returns a specific implementation of the abstract class. This is the abstract factory pattern.
I have a huge database with no (separate) index.
Any time I query by the primary key the results are, for all intensive purposes, instant.
In the event someone needs a generic version of mattsven's answer (as I did), here it is:
$('select').each(function() {
$(this).data('lastSelected', $(this).find('option:selected'));
});
$('select').change(function() {
if(my_condition) {
$(this).data('lastSelected').attr('selected', true);
}
});
$('select').click(function() {
$(this).data('lastSelected', $(this).find('option:selected'));
});
I just tested the code at the bottom and it prints 16384
twice (I'm on Excel 2010) and the first row gets selected. Your problem seems to be somewhere else.
Have you tried to get rid of the selects:
Sheets("BOM").Rows(copyFromRow).Copy
With Sheets("Proposal")
.Paste Destination:=.Rows(copyToRow)
copyToRow = copyToRow + 1
Application.CutCopyMode = False
.Rows(copyToRow).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End With
Test code to get convinced that the problem does not seem to be what you think it is.
Sub test()
Dim r
Dim i As Long
i = 1
r = Rows(i & ":" & i)
Debug.Print UBound(r, 2)
r = Rows(i)
Debug.Print UBound(r, 2)
Rows(i).Select
End Sub
Try adding this to your where
clause:
dateadd(day, -30, getdate())
This answer works in SQL Server 2005, 2008, 2012.
At times the value has MANY single quotes. Rather than add a single quote next to each single quote as described above with 'John''s'
. And there are examples using the REPLACE
function to handle many single quotes in a value.
Try the following. This is an update statement but you can use it in an INSERT
statement as well.
SET QUOTED_IDENTIFIER OFF
DECLARE @s VARCHAR(1000)
SET @s = "SiteId:'1'; Rvc:'6'; Chk:'1832'; TrEmp:'150'; WsId:'81'; TtlDue:'-9.40'; TtlDsc:'0'; TtlSvc:'0'; TtlTax:'-0.88'; TtlPay:'0'; TipAmt:'0.00'; SvcSeq:'09'; ReTx:'N'; TraceId:'160110124347N091832';"
UPDATE TransactionPaymentPrompt
set PromptData = @s
from TransactionPaymentPrompt tpp with (nolock)
where tpp.TransactionID = '106627343'
As constraint has unpredictable name, you can write special script(DropConstraint) to remove it without knowing it's name (was tested at EF 6.1.3):
public override void Up()
{
DropConstraint();
AlterColumn("dbo.MyTable", "Rating", c => c.Double(nullable: false));
}
private void DropConstraint()
{
Sql(@"DECLARE @var0 nvarchar(128)
SELECT @var0 = name
FROM sys.default_constraints
WHERE parent_object_id = object_id(N'dbo.MyTable')
AND col_name(parent_object_id, parent_column_id) = 'Rating';
IF @var0 IS NOT NULL
EXECUTE('ALTER TABLE [dbo].[MyTable] DROP CONSTRAINT [' + @var0 + ']')");
}
public override void Down()
{
AlterColumn("dbo.MyTable", "Rating", c => c.Int(nullable: false));
}
my solution:
MOVE:
jQuery("#NodesToMove").detach().appendTo('#DestinationContainerNode')
COPY:
jQuery("#NodesToMove").appendTo('#DestinationContainerNode')
Note the usage of .detach(). When copying, be careful that you are not duplicating IDs.
First of all, you lack parentheses to call GetType. What you see is the MethodInfo describing the GetType method on [DayOfWeek]. To actually call GetType, you should do:
$a.GetType();
$b.GetType();
You should see that $a
is a [DayOfWeek], and $b
is a custom object generated by the Select-Object cmdlet to capture only the DayOfWeek property of a data object. Hence, it's an object with a DayOfWeek property only:
C:\> $b.DayOfWeek -eq $a
True
Just check if you are running different instances in eclipse. I quit all my other sessions, clean build fixed the problem
Lists themselves are thread-safe. In CPython the GIL protects against concurrent accesses to them, and other implementations take care to use a fine-grained lock or a synchronized datatype for their list implementations. However, while lists themselves can't go corrupt by attempts to concurrently access, the lists's data is not protected. For example:
L[0] += 1
is not guaranteed to actually increase L[0] by one if another thread does the same thing, because +=
is not an atomic operation. (Very, very few operations in Python are actually atomic, because most of them can cause arbitrary Python code to be called.) You should use Queues because if you just use an unprotected list, you may get or delete the wrong item because of race conditions.
First, Eloquent automatically converts it's timestamps (created_at
, updated_at
) into carbon objects. You could just use updated_at
to get that nice feature, or specify edited_at
in your model in the $dates
property:
protected $dates = ['edited_at'];
Now back to your actual question. Carbon has a bunch of comparison functions:
eq()
equalsne()
not equalsgt()
greater thangte()
greater than or equalslt()
less thanlte()
less than or equalsUsage:
if($model->edited_at->gt($model->created_at)){
// edited at is newer than created at
}
To make little more easy to understand use like below, which i prefer the most. Also it permits to call multiple function at once. Obviously
setTimeout(function(){
startTimer();
function2();
function3();
}, startInterval);
@ Original Poster - see inline comments.
public class demo
{
public static void main(String a[])
{
B b = (B) new A(); // compiles with the cast, but runtime exception - java.lang.ClassCastException
//- A subclass variable cannot hold a reference to a superclass variable. so, the above statement will not work.
//For downcast, what you need is a superclass ref containing a subclass object.
A superClassRef = new B();//just for the sake of illustration
B subClassRef = (B)superClassRef; // Valid downcast.
}
}
class A
{
public void draw()
{
System.out.println("1");
}
public void draw1()
{
System.out.println("2");
}
}
class B extends A
{
public void draw()
{
System.out.println("3");
}
public void draw2()
{
System.out.println("4");
}
}
Once I've seen such an interesting construction:
<Ids xmlns:id="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<id:int>1787</id:int>
</Ids>
For those like @sha1 wondering why the OP's code doesn't work -
OP's logic for deleting player at server side is in the handler for DelPlayer
event,
and the code that emits this event (DelPlayer
) is in inside disconnected
event callback of client.
The server side code that emits this disconnected
event is inside the disconnect
event callback which is fired when the socket loses connection. Since the socket already lost connection, disconnected
event doesn't reach the client.
Accepted solution executes the logic on disconnect
event at server side, which is fired when the socket disconnects, hence works.
I've done this with PDFBox. I suppose it works similarly to iTextSharp.
When asked:
Are you sure you want to continue connecting (yes/no)?
Type yes as the response
That is how I solved my issue. But if you try to just hit the enter button, it won't work!
Either I don't understand your question, or Enumerable#find is the thing you were looking for.
You need to put the directory that has php.exe
in you WAMP
installation into your PATH
. It is usually something like C:\wamp\xampp\php
In DOS/Windows Batch most commands return an exitCode, called "errorlevel", that is a value that customarily is equal to zero if the command ends correctly, or a number greater than zero if ends because an error, with greater numbers for greater errors (hence the name).
There are a couple methods to check that value, but the original one is:
IF ERRORLEVEL value command
Previous IF test if the errorlevel returned by the previous command was GREATER THAN OR EQUAL the given value and, if this is true, execute the command. For example:
verify bad-param
if errorlevel 1 echo Errorlevel is greater than or equal 1
echo The value of errorlevel is: %ERRORLEVEL%
Findstr command return 0 if the string was found and 1 if not:
CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat
IF ERRORLEVEL 1 XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y
Previous code will copy the file if the string was NOT found in the file.
CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat
IF NOT ERRORLEVEL 1 XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y
Previous code copy the file if the string was found. Try this:
findstr "string" file
if errorlevel 1 (
echo String NOT found...
) else (
echo String found
)
Just add the following code:
setIconImage(new ImageIcon(PathOfFile).getImage());
The only working solution I found was this one that uses reflection
/**
* Get external sd card path using reflection
* @param mContext
* @param is_removable is external storage removable
* @return
*/
private static String getExternalStoragePath(Context mContext, boolean is_removable) {
StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
Class<?> storageVolumeClazz = null;
try {
storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
Method getPath = storageVolumeClazz.getMethod("getPath");
Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
Object result = getVolumeList.invoke(mStorageManager);
final int length = Array.getLength(result);
for (int i = 0; i < length; i++) {
Object storageVolumeElement = Array.get(result, i);
String path = (String) getPath.invoke(storageVolumeElement);
boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
if (is_removable == removable) {
return path;
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
Please follow the way like below:
.selectParent {_x000D_
width:120px;_x000D_
overflow:hidden; _x000D_
}_x000D_
.selectParent select { _x000D_
display: block;_x000D_
width: 100%;_x000D_
padding: 2px 25px 2px 2px; _x000D_
border: none; _x000D_
background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
appearance: none; _x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
direction: rtl;_x000D_
padding: 2px 2px 2px 25px;_x000D_
background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
<select>_x000D_
<option value="1">Option 1</option>_x000D_
<option value="2">Option 2</option> _x000D_
</select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
<select>_x000D_
<option value="1">Option 1</option>_x000D_
<option value="2">Option 2</option> _x000D_
</select>_x000D_
</div>
_x000D_
Docker now recommends migrating towards using --mount
.
Multiple volume mounts are also explained in detail in the current Docker documentation.
From: https://docs.docker.com/storage/bind-mounts/
$ docker run -d \
-it \
--name devtest \
--mount type=bind,source="$(pwd)"/target,target=/app \
--mount type=bind,source="$(pwd)"/target,target=/app2,readonly,bind-propagation=rslave \
nginx:latest
Original older answer should still work; just trying to keep the answer aligned to current best known method.
Click on the drop down next to the Run button, After that choose Run Configuration, shows three option, for example i choose java application add class(Name of the class of your project) in that then Click on the ok button ...Run your application :)
Neeraj
I had this same issue in SQL Server and wrote this T-SQL script to automate the process (actually this is the watered-down version, mine wrote all the diff to a single table for easy reporting).
Update 'MyTable' and 'MyOtherTable' to the names of the tables you wish to compare.
DECLARE @ColName varchar(100)
DECLARE @Table1 varchar(100) = 'MyTable'
DECLARE @Table2 varchar(100) = 'MyOtherTable'
IF (OBJECT_ID('tempdb..#col') IS NOT NULL) DROP TABLE #col
SELECT IDENTITY(INT, 1, 1) RowNum , c.name
INTO #col
FROM SYS.Objects o
JOIN SYS.columns c on o.object_id = c.object_id
WHERE o.name = @Table1 AND NOT c.Name IN ('List','Columns','YouWantToIgnore')
DECLARE @Counter INT = (SELECT MAX(RowNum) FROM #col)
WHILE @Counter > 0
BEGIN
SET @ColName = (SELECT name FROM #Col WHERE RowNum= @Counter)
EXEC ('SELECT t1.Identifier
,t1.'+@ColName+' AS '+@Table1+@ColName+'
,t2.'+@ColName+' AS '+@Table2+@ColName+'
FROM '+@Table1+' t1
LEFT JOIN '+@Table2+' t2 ON t1.Identifier = t2.Identifier
WHERE t1.'+@ColName+' <> t2.'+@ColName)
SET @Counter = @Counter - 1
END
import threading
# global variable x
x = 0
def increment():
"""
function to increment global variable x
"""
global x
x += 1
def thread_task():
"""
task for thread
calls increment function 100000 times.
"""
for _ in range(100000):
increment()
def main_task():
global x
# setting global variable x as 0
x = 0
# creating threads
t1 = threading.Thread(target=thread_task)
t2 = threading.Thread(target=thread_task)
# start threads
t1.start()
t2.start()
# wait until threads finish their job
t1.join()
t2.join()
if __name__ == "__main__":
for i in range(10):
main_task()
print("Iteration {0}: x = {1}".format(i,x))
copy mysql-connector-java-5.1.24-bin.jar
Paste it into \Apache Software Foundation\Tomcat 6.0\lib\<--here-->
Restart Your Server from Eclipes.
Done
Basically speaking, the answer is: it depends. There are many many benchmarks focusing on different kinds of application.
My benchmark on my app is: gcc > icc > clang.
There are rare IO, but many CPU float and data structure operations.
compile flags is -Wall -g -DNDEBUG -O3.
https://github.com/zhangyafeikimi/ml-pack/blob/master/gbdt/profile/benchmark
If error is like Author=models.ForeignKey(User, related_names='blog_posts') TypeError:init() missing 1 required positional argument:'on_delete'
Then the solution will be like, you have to add one argument Author=models.ForeignKey(User, related_names='blog_posts', on_delete=models.DO_NOTHING)
On Requests 1.X, the connection is available on the response object:
r = requests.post("https://stream.twitter.com/1/statuses/filter.json",
data={'track': toTrack}, auth=('username', 'passwd'))
r.connection.close()
To logout from the app only but not the Gmail:
window.gapi.load('auth2', () => {
window.gapi.auth2
.init({
client_id:
'<Your client id configired on google console>'
})
.then(() => {
window.gapi.auth2
.getAuthInstance()
.signOut()
.then(function() {
console.log('User signed out.');
});
});
});
I'm using above in my ReactJs code.
Problem 1
You mentioned it was your private docker registry, so you probably need to check Registry API instead of Hub registry API doc, which is the link you provided.
Problem 2
docker registry API is a client/server protocol, it is up to the server's implementation on whether to remove the images in the back-end. (I guess)
DELETE /v1/repositories/(namespace)/(repository)/tags/(tag*)
Detailed explanation
Below I demo how it works now from your description as my understanding for your questions.
I run a private docker registry.
I use the default one, and listen on port 5000
.
docker run -d -p 5000:5000 registry
Then I tag the local image and push into it.
$ docker tag ubuntu localhost:5000/ubuntu
$ docker push localhost:5000/ubuntu
The push refers to a repository [localhost:5000/ubuntu] (len: 1)
Sending image list
Pushing repository localhost:5000/ubuntu (1 tags)
511136ea3c5a: Image successfully pushed
d7ac5e4f1812: Image successfully pushed
2f4b4d6a4a06: Image successfully pushed
83ff768040a0: Image successfully pushed
6c37f792ddac: Image successfully pushed
e54ca5efa2e9: Image successfully pushed
Pushing tag for rev [e54ca5efa2e9] on {http://localhost:5000/v1/repositories/ubuntu/tags/latest}
After that I can use Registry API to check it exists in your private docker registry
$ curl -X GET localhost:5000/v1/repositories/ubuntu/tags
{"latest": "e54ca5efa2e962582a223ca9810f7f1b62ea9b5c3975d14a5da79d3bf6020f37"}
Now I can delete the tag using that API !!
$ curl -X DELETE localhost:5000/v1/repositories/ubuntu/tags/latest
true
Check again, the tag doesn't exist in my private registry server
$ curl -X GET localhost:5000/v1/repositories/ubuntu/tags/latest
{"error": "Tag not found"}
Lot of answers seem to be overkill. FOR ME , this works
<a ng-href="#" ng-click="$event.preventDefault();vm.questionContainer($index)">{{question.Verbiage}}</a>
String url = "https://www.thandroid-mania.com/";
if (url.startsWith("https://") || url.startsWith("http://")) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}else{
Toast.makeText(mContext, "Invalid Url", Toast.LENGTH_SHORT).show();
}
That error occurred because of invalid URL, Android OS can't find action view for your data. So you have validate that the URL is valid or not.
You can also go to Notepad++ and do the following steps:
Edit->LineOperations-> Remove Empty Lines or Remove Empty Lines(Containing blank characters)
Dim resources As Object = My.Resources.ResourceManager
PictureBoxName.Image = resources.GetObject("Company_Logo")
You aren't doing anything with the return value of replace
. You'll need to assign the result of the method, which is the new String
:
sentence = sentence.replace("and", " ");
A String
is immutable in java. Methods like replace
return a new String
.
Your contains
test is unnecessary: replace
will just no-op if there aren't instances of the text to replace.
One way (2k8);
select 'abc_1_2_3_4.gif ' as img into #T
insert #T values ('zzz_12_3_3_45.gif')
;with T as (
select 0 as row, charindex('_', img) pos, img from #T
union all
select pos + 1, charindex('_', img, pos + 1), img
from T
where pos > 0
)
select
img, pos
from T
where pos > 0
order by img, pos
>>>>
img pos
abc_1_2_3_4.gif 4
abc_1_2_3_4.gif 6
abc_1_2_3_4.gif 8
abc_1_2_3_4.gif 10
zzz_12_3_3_45.gif 4
zzz_12_3_3_45.gif 7
zzz_12_3_3_45.gif 9
zzz_12_3_3_45.gif 11
Update
;with T(img, starts, pos) as (
select img, 1, charindex('_', img) from #t
union all
select img, pos + 1, charindex('_', img, pos + 1)
from t
where pos > 0
)
select
*, substring(img, starts, case when pos > 0 then pos - starts else len(img) end) token
from T
order by img, starts
>>>
img starts pos token
abc_1_2_3_4.gif 1 4 abc
abc_1_2_3_4.gif 5 6 1
abc_1_2_3_4.gif 7 8 2
abc_1_2_3_4.gif 9 10 3
abc_1_2_3_4.gif 11 0 4.gif
zzz_12_3_3_45.gif 1 4 zzz
zzz_12_3_3_45.gif 5 7 12
zzz_12_3_3_45.gif 8 9 3
zzz_12_3_3_45.gif 10 11 3
zzz_12_3_3_45.gif 12 0 45.gif
Filestash is the perfect tool for that:
Also Filestash is open source. (Disclaimer: I am the author)
Very informative answer from @stej, but here is a short answer: Among other options, you have 3 simple options to format [System.DateTime] stored in a variable:
Pass the variable to the Get-Date cmdlet:
Get-Date -Format "HH:mm" $date
Use toString() method:
$date.ToString("HH:mm")
Use Composite formatting:
"{0:HH:mm}" -f $date
Just Add HttpClientModule
in 'imports' array of app.module.ts
file.
...
import {HttpClientModule} from '@angular/common/http'; // add this line
@NgModule({
declarations: [
AppComponent,
HeaderComponent
],
imports: [
BrowserModule,
HttpClientModule, //add this line
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
and then you can use HttpClient
in your project through constructor injection
import {HttpClient} from '@angular/common/http';
export class Services{
constructor(private http: HttpClient) {}
Here is an alternative way to get an object's property value:
write-host $(get-something).SomeProp
Recently I had a deadlock problem because Sql Server locks more then necessary (page). You can't really do anything against it. Now we are catching deadlock exceptions... and I wish I had Oracle instead.
Edit: We are using snapshot isolation meanwhile, which solves many, but not all of the problems. Unfortunately, to be able to use snapshot isolation it must be allowed by the database server, which may cause unnecessary problems at customers site. Now we are not only catching deadlock exceptions (which still can occur, of course) but also snapshot concurrency problems to repeat transactions from background processes (which cannot be repeated by the user). But this still performs much better than before.
I wanted something a little more extensible/semantic than the given answers so I wrote a directive that takes a javascript object in a similar way to the built-in ngClass
:
<input key-bind="{ enter: 'go()', esc: 'clear()' }" type="text"></input>
The values of the object are evaluated in the context of the directive's scope - ensure they are encased in single quotes otherwise all of the functions will be executed when the directive is loaded(!)
So for example:
esc : 'clear()'
instead of esc : clear()
myModule
.constant('keyCodes', {
esc: 27,
space: 32,
enter: 13,
tab: 9,
backspace: 8,
shift: 16,
ctrl: 17,
alt: 18,
capslock: 20,
numlock: 144
})
.directive('keyBind', ['keyCodes', function (keyCodes) {
function map(obj) {
var mapped = {};
for (var key in obj) {
var action = obj[key];
if (keyCodes.hasOwnProperty(key)) {
mapped[keyCodes[key]] = action;
}
}
return mapped;
}
return function (scope, element, attrs) {
var bindings = map(scope.$eval(attrs.keyBind));
element.bind("keydown keypress", function (event) {
if (bindings.hasOwnProperty(event.which)) {
scope.$apply(function() {
scope.$eval(bindings[event.which]);
});
}
});
};
}]);
Here is a sample code
strFileName = "c:\test.xls"
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Add()
objWorkbook.SaveAs(strFileName)
objExcel.Quit
@Autowired
to autowire(or search) by-type
@Qualifier
to autowire(or search) by-name
Other alternate option for @Qualifier
is @Primary
@Component
@Qualifier("beanname")
public class A{}
public class B{
//Constructor
@Autowired
public B(@Qualifier("beanname")A a){...} // you need to add @autowire also
//property
@Autowired
@Qualifier("beanname")
private A a;
}
//If you don't want to add the two annotations, we can use @Resource
public class B{
//property
@Resource(name="beanname")
private A a;
//Importing properties is very similar
@Value("${property.name}") //@Value know how to interpret ${}
private String name;
}
more about @value
My /var/log/apache2 folder was 35g and some logs in /var/log totaled to be the other 5g of my 40g hard drive. I cleared out all the *.gz logs and after making sure the other logs werent going to do bad things if I messed with them, i just cleared them too.
echo "clear" > access.log
etc.
Actually, I found a somewhat quirky way to do this. Add the protocol to your web.config, but inside a location element. Specify the webservice location as the path attribute, like so:
<location path="YourWebservice.asmx">
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
</location>
Not what you asked but may be useful nevertheless.
Of course you can do the same thing with matrix formulas. Just read the result of the cell that contains:
Cell A1="Text to search"
Cells A2:C20=Range to search for
=COUNT(SEARCH(A1;A2:C20;1))
Remember that entering matrix formulas needs CTRL+SHIFT+ENTER, not just ENTER. After, it should look like :
{=COUNT(SEARCH(A1;A2:C20;1))}
Try the Terminal Services PowerShell Module:
Get-TSSession -ComputerName comp1 -UserName user1 | Stop-TSSession -Force
Generally, I agree with @kgrittn's advice. Go for it.
But to address your basic question about concat()
: The new function concat()
is useful if you need to deal with null values - and null has neither been ruled out in your question nor in the one you refer to.
If you can rule out null values, the good old (SQL standard) concatenation operator ||
is still the best choice, and @luis' answer is just fine:
SELECT col_a || col_b;
If either of your columns can be null, the result would be null in that case. You could defend with COALESCE
:
SELECT COALESCE(col_a, '') || COALESCE(col_b, '');
But that get tedious quickly with more arguments. That's where concat()
comes in, which never returns null, not even if all arguments are null. Per documentation:
NULL arguments are ignored.
SELECT concat(col_a, col_b);
The remaining corner case for both alternatives is where all input columns are null in which case we still get an empty string ''
, but one might want null instead (at least I would). One possible way:
SELECT CASE
WHEN col_a IS NULL THEN col_b
WHEN col_b IS NULL THEN col_a
ELSE col_a || col_b
END;
This gets more complex with more columns quickly. Again, use concat()
but add a check for the special condition:
SELECT CASE WHEN (col_a, col_b) IS NULL THEN NULL
ELSE concat(col_a, col_b) END;
How does this work?
(col_a, col_b)
is shorthand notation for a row type expression ROW (col_a, col_b)
. And a row type is only null if all columns are null. Detailed explanation:
Also, use concat_ws()
to add separators between elements (ws
for "with separator").
An expression like the one in Kevin's answer:
SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;
is tedious to prepare for null values in PostgreSQL 8.3 (without concat()
). One way (of many):
SELECT COALESCE(
CASE
WHEN $1.zipcode IS NULL THEN $1.city
WHEN $1.city IS NULL THEN $1.zipcode
ELSE $1.zipcode || ' - ' || $1.city
END, '')
|| COALESCE(', ' || $1.state, '');
STABLE
concat()
and concat_ws()
are STABLE
functions, not IMMUTABLE
because they can invoke datatype output functions (like timestamptz_out
) that depend on locale settings.
Explanation by Tom Lane.
This prohibits their direct use in index expressions. If you know that the result is actually immutable in your case, you can work around this with an IMMUTABLE
function wrapper. Example here:
Another solution that it is similar to those already exposed here is this one. Just before the closing body tag place this html:
<div id="resultLoading" style="display: none; width: 100%; height: 100%; position: fixed; z-index: 10000; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto;">
<div style="width: 340px; height: 200px; text-align: center; position: fixed; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto; z-index: 10; color: rgb(255, 255, 255);">
<div class="uil-default-css">
<img src="/images/loading-animation1.gif" style="max-width: 150px; max-height: 150px; display: block; margin-left: auto; margin-right: auto;" />
</div>
<div class="loader-text" style="display: block; font-size: 18px; font-weight: 300;"> </div>
</div>
<div style="background: rgb(0, 0, 0); opacity: 0.6; width: 100%; height: 100%; position: absolute; top: 0px;"></div>
</div>
Finally, replace .loader-text element's
content on the fly on every navigation event and turn on the #resultloading
div, note that it is initially hidden.
var showLoader = function (text) {
$('#resultLoading').show();
$('#resultLoading').find('.loader-text').html(text);
};
jQuery(document).ready(function () {
jQuery(window).on("beforeunload ", function () {
showLoader('Loading, please wait...');
});
});
This can be applied to any html based project with jQuery where you don't know which pages of your administration area will take too long to finish loading.
The gif image is 176x176px but you can use any transparent gif animation, please take into account that the image size is not important as it will be maxed to 150x150px.
Also, the function showLoader can be called on an element's click to perform an action that will further redirect the page, that is why it is provided ad an individual function. i hope this can also help anyone.
Oracle has a page for this issue with SQL and trouble shooting suggestions.
"Troubleshooting Open Cursor Issues" http://docs.oracle.com/cd/E40329_01/admin.1112/e27149/cursor.htm#OMADM5352
But you all forgot to mention, that if a variable table is used within a loop it will need emptying (delete @table) prior to loading with data again within a loop.
I had some more thoughts on this:
1) Remember that maps represent a physical organization. Store the latitude/longitude of every intersection. You don't need to check much beyond the points that lie in the direction of your target. Only if you find yourself blocked do you need to go beyond this. If you store an overlay of superior connections you can limit it even more--you will normally never go across one of those in a way that goes away from your final destination.
2) Divide up the world into a whole bunch of zones defined by limited connectivity, define all connectivity points between the zones. Find what zones your source and target are in, for the start and end zone route from your location to each connection point, for the zones between simply map between connection points. (I suspect a lot of the latter is already pre-calculated.)
Note that zones can be smaller than a metropolitan area. Any city with terrain features that divide it up (say, a river) would be multiple zones.
First thing, at the time the question was asked, uintptr_t
was not in C++. It's in C99, in <stdint.h>
, as an optional type. Many C++03 compilers do provide that file. It's also in C++11, in <cstdint>
, where again it is optional, and which refers to C99 for the definition.
In C99, it is defined as "an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer".
Take this to mean what it says. It doesn't say anything about size.
uintptr_t
might be the same size as a void*
. It might be larger. It could conceivably be smaller, although such a C++ implementation approaches perverse. For example on some hypothetical platform where void*
is 32 bits, but only 24 bits of virtual address space are used, you could have a 24-bit uintptr_t
which satisfies the requirement. I don't know why an implementation would do that, but the standard permits it.
Provide a format string:
date +"%H:%M"
Running man date
will give all the format options
%a locale's abbreviated weekday name (e.g., Sun)
%A locale's full weekday name (e.g., Sunday)
%b locale's abbreviated month name (e.g., Jan)
%B locale's full month name (e.g., January)
%c locale's date and time (e.g., Thu Mar 3 23:05:25 2005)
%C century; like %Y, except omit last two digits (e.g., 20)
%d day of month (e.g., 01)
%D date; same as %m/%d/%y
%e day of month, space padded; same as %_d
%F full date; same as %Y-%m-%d
%g last two digits of year of ISO week number (see %G)
%G year of ISO week number (see %V); normally useful only with %V
%h same as %b
%H hour (00..23)
%I hour (01..12)
%j day of year (001..366)
%k hour, space padded ( 0..23); same as %_H
%l hour, space padded ( 1..12); same as %_I
%m month (01..12)
%M minute (00..59)
%n a newline
%N nanoseconds (000000000..999999999)
%p locale's equivalent of either AM or PM; blank if not known
%P like %p, but lower case
%r locale's 12-hour clock time (e.g., 11:11:04 PM)
%R 24-hour hour and minute; same as %H:%M
%s seconds since 1970-01-01 00:00:00 UTC
%S second (00..60)
%t a tab
%T time; same as %H:%M:%S
%u day of week (1..7); 1 is Monday
%U week number of year, with Sunday as first day of week (00..53)
%V ISO week number, with Monday as first day of week (01..53)
%w day of week (0..6); 0 is Sunday
%W week number of year, with Monday as first day of week (00..53)
%x locale's date representation (e.g., 12/31/99)
%X locale's time representation (e.g., 23:13:48)
%y last two digits of year (00..99)
%Y year
%z +hhmm numeric time zone (e.g., -0400)
%:z +hh:mm numeric time zone (e.g., -04:00)
%::z +hh:mm:ss numeric time zone (e.g., -04:00:00)
%:::z numeric time zone with : to necessary precision (e.g., -04, +05:30)
%Z alphabetic time zone abbreviation (e.g., EDT)
I had a similar problem; the anchor text in my Bootstrap4 navbar wasn't centered. Simply added text-center
in the anchor's class.
Try http.sslCAPath
or http.sslCAInfo
. Adam Spiers's answer gives some great examples. This is the most secure solution to the question.
try passing -c
to git
with the proper config variable, or use Flow's answer:
git -c http.sslVerify=false clone https://example.com/path/to/git
If the repository is completely under your control, you can try:
git config --global http.sslVerify false
There are quite a few SSL configuration options in git
. From the man page of git config
:
http.sslVerify
Whether to verify the SSL certificate when fetching or pushing over HTTPS.
Can be overridden by the GIT_SSL_NO_VERIFY environment variable.
http.sslCAInfo
File containing the certificates to verify the peer with when fetching or pushing
over HTTPS. Can be overridden by the GIT_SSL_CAINFO environment variable.
http.sslCAPath
Path containing files with the CA certificates to verify the peer with when
fetching or pushing over HTTPS.
Can be overridden by the GIT_SSL_CAPATH environment variable.
A few other useful SSL configuration options:
http.sslCert
File containing the SSL certificate when fetching or pushing over HTTPS.
Can be overridden by the GIT_SSL_CERT environment variable.
http.sslKey
File containing the SSL private key when fetching or pushing over HTTPS.
Can be overridden by the GIT_SSL_KEY environment variable.
http.sslCertPasswordProtected
Enable git's password prompt for the SSL certificate. Otherwise OpenSSL will
prompt the user, possibly many times, if the certificate or private key is encrypted.
Can be overridden by the GIT_SSL_CERT_PASSWORD_PROTECTED environment variable.
Below the attached solution work over local machine and server.
public static string SendMail(string bodyContent)
{
string sendMail = "";
try
{
string fromEmail = "[email protected]";
MailMessage mailMessage = new MailMessage(fromEmail, "[email protected]", "Subject", body);
mailMessage.IsBodyHtml = true;
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential(fromEmail, frompassword);
smtpClient.Send(mailMessage);
}
catch (Exception ex)
{
sendMail = ex.Message.ToString();
Console.WriteLine(ex.ToString());
}
return sendMail;
}
You can first make a conditional selection, and sum up the results of the selection using the sum
function.
>> df = pd.DataFrame({'a': [1, 2, 3]})
>> df[df.a > 1].sum()
a 5
dtype: int64
Having more than one condition:
>> df[(df.a > 1) & (df.a < 3)].sum()
a 2
dtype: int64
In my case this worked.
@Override
public void onViewRecycled(MyViewHolder holder) {
holder.checkbox.setChecked(false); // - this line do the trick
super.onViewRecycled(holder);
}
if(isset($_POST['form_field_name'])) {
$variable_name = $_POST['form_field_name'];
}
Since the file will be larger, you don't have very much choice in how to do this. You cannot process the file in place since that will destroy the information you need to use. You have two options that I can see:
Of course, the whole point of streams is to avoid this sort of scenario. Instead of creating the content and stuffing it into a file stream, stuff it into a memory stream. Then encode that and only then save to disk.
You can put an apostrophe in a single quoted JavaScript string by escaping it with a backslash, like so:
theAnchorText = 'I\'m home';
I'm not posting this as an answer but a confirmation to Paresh's accepted answer. I recently updated SDK tools to Revision 22 and I noticed my code changes was not being affective on the device i'm testing at all. Such as the url I was using, I was getting errors for connection time out regarding the url I was "previously" using. Therefore I cleaned the project and built again only to find out that autogenerated R.java file is missing.
After reading Paresh's answer and checking what's going on with my sdk manager this is what I saw:
SDK Build-tools 17 was not installed and there was already a new update to SDK tools even though it does not mention any change related to this problem in the changelog, this update brought back my R.java file and the related problems were gone after an eclipse restart and final clean/rebuild on the project.
I apologize for promoting myself, but I have a jQuery plugin to launch native apps from web links https://github.com/eusonlito/jquery.applink
You can use it easy:
<script>
$('a[data-applink]').applink();
</script>
<a href="https://facebook.com/me" data-applink="fb://profile">My Facebook Profile</a>
Aggregating with $lookup
and subsequent $group
is pretty cumbersome, so if (and that's a medium if) you're using node & Mongoose or a supporting library with some hints in the schema, you could use a .populate()
to fetch those documents:
var mongoose = require("mongoose"),
Schema = mongoose.Schema;
var productSchema = Schema({ ... });
var orderSchema = Schema({
_id : Number,
products: [ { type: Schema.Types.ObjectId, ref: "Product" } ]
});
var Product = mongoose.model("Product", productSchema);
var Order = mongoose.model("Order", orderSchema);
...
Order
.find(...)
.populate("products")
...
Rotating the labels is certainly possible. Note though that doing so reduces the readability of the text. One alternative is to alternate label positions using a code like this:
import numpy as np
n=5
x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Long ticklabel %i' % i for i in range(n)]
fig, ax = plt.subplots()
ax.plot(x,y, 'o-')
ax.set_xticks(x)
labels = ax.set_xticklabels(xlabels)
for i, label in enumerate(labels):
label.set_y(label.get_position()[1] - (i % 2) * 0.075)
For more background and alternatives, see this post on my blog
Another method through re
module. It does the reverse operation of matching all the words instead of spitting the whole sentence by space.
>>> import re
>>> s = "many fancy word \nhello \thi"
>>> re.findall(r'\S+', s)
['many', 'fancy', 'word', 'hello', 'hi']
Above regex would match one or more non-space characters.
You need to use : "$@"
(WITH the quotes) or "${@}"
(same, but also telling the shell where the variable name starts and ends).
(and do NOT use : $@
, or "$*"
, or $*
).
ex:
#testscript1:
echo "TestScript1 Arguments:"
for an_arg in "$@" ; do
echo "${an_arg}"
done
echo "nb of args: $#"
./testscript2 "$@" #invokes testscript2 with the same arguments we received
I'm not sure I understood your other requirement ( you want to invoke './testscript2' in single quotes?) so here are 2 wild guesses (changing the last line above) :
'./testscript2' "$@" #only makes sense if "/path/to/testscript2" containes spaces?
./testscript2 '"some thing" "another"' "$var" "$var2" #3 args to testscript2
Please give me the exact thing you are trying to do
edit: after his comment saying he attempts tesscript1 "$1" "$2" "$3" "$4" "$5" "$6" to run : salt 'remote host' cmd.run './testscript2 $1 $2 $3 $4 $5 $6'
You have many levels of intermediate: testscript1 on host 1, needs to run "salt", and give it a string launching "testscrit2" with arguments in quotes...
You could maybe "simplify" by having:
#testscript1
#we receive args, we generate a custom script simulating 'testscript2 "$@"'
theargs="'$1'"
shift
for i in "$@" ; do
theargs="${theargs} '$i'"
done
salt 'remote host' cmd.run "./testscript2 ${theargs}"
if THAt doesn't work, then instead of running "testscript2 ${theargs}", replace THE LAST LINE above by
echo "./testscript2 ${theargs}" >/tmp/runtestscript2.$$ #generate custom script locally ($$ is current pid in bash/sh/...)
scp /tmp/runtestscript2.$$ user@remotehost:/tmp/runtestscript2.$$ #copy it to remotehost
salt 'remotehost' cmd.run "./runtestscript2.$$" #the args are inside the custom script!
ssh user@remotehost "rm /tmp/runtestscript2.$$" #delete the remote one
rm /tmp/runtestscript2.$$ #and the local one
Below code works for me
String xml1 = ...
String xml2 = ...
XMLUnit.setIgnoreWhitespace(true);
XMLUnit.setIgnoreAttributeOrder(true);
XMLAssert.assertXMLEqual(actualxml, xmlInDb);
This one worked for me on Chrome...
for some reason event.which
returns a capital S (83) for me, not sure why (regardless of the caps lock state) so I used fromCharCode
and toLowerCase
just to be on the safe side
$(document).keydown(function(event) {
//19 for Mac Command+S
if (!( String.fromCharCode(event.which).toLowerCase() == 's' && event.ctrlKey) && !(event.which == 19)) return true;
alert("Ctrl-s pressed");
event.preventDefault();
return false;
});
If anyone knows why I get 83 and not 115, I will be happy to hear, also if anyone tests this on other browsers I'll be happy to hear if it works or not
There are two way to do this first:
Use subquery to find the 2nd highest
SELECT MAX(salary) FROM employees
WHERE salary NOT IN (
SELECT MAX (salary) FROM employees)
But this solution is not much good as if you need to find out the 10 or 100th highest then you may be in trouble. So instead go for window function like
select * from
(
select salary,ROW_NUMBER() over(
order by Salary desc) as
rownum from employees
) as t where t.rownum=2
By using this method you can find out nth highest salary without any trouble.
Well, I made a simple two liner script for this, Its small and does what u want.
Check it http://jsfiddle.net/9RxLM/
Its a jquery solution :D
This was frustrating, most of the above answers are correct but they fail to mention you have to restart the database service before the changes in the pg_hba.conf file will take affect.
so if you make the changes as mentioned above:
local all postgres ident
then restart as root ( on centos its something like service service postgresql-9.2 restart ) now you should be able to access the db as the user postgres
$psql
psql (9.2.4)
Type "help" for help.
postgres=#
Hope this adds info for new postgres users
grant select on sys.external_tab$ to [myUser]; worked for me. thanx Codo
You can use Task Scheduler Managed Wrapper:
using System;
using Microsoft.Win32.TaskScheduler;
class Program
{
static void Main(string[] args)
{
// Get the service on the local machine
using (TaskService ts = new TaskService())
{
// Create a new task definition and assign properties
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Does something";
// Create a trigger that will fire the task at this time every other day
td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });
// Create an action that will launch Notepad whenever the trigger fires
td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));
// Register the task in the root folder
ts.RootFolder.RegisterTaskDefinition(@"Test", td);
// Remove the task we just created
ts.RootFolder.DeleteTask("Test");
}
}
}
Alternatively you can use native API or go for Quartz.NET. See this for details.
Something that works for me is this:
class C:
def __init__(self):
self._x=None
def g(self):
return self._x
def s(self, x):
self._x = x
def d(self):
del self._x
def s2(self,x):
self._x=x+x
x=property(g,s,d)
c = C()
c.x="a"
print(c.x)
C.x=property(C.g, C.s2)
C.x=C.x.deleter(C.d)
c2 = C()
c2.x="a"
print(c2.x)
Output
a
aa
Edit: Unfortunately, as of PHP 8.0, the answer is not "No, not anymore". This RFC was not accepted as I hoped, proposing to change T_PAAMAYIM_NEKUDOTAYIM
to T_DOUBLE_COLON
; but it was declined.
Note: I keep this answer for historical purposes. Actually, because of the creation of the RFC and the votes ratio at some point, I created this answer. Also, I keep this for hoping it to be accepted in the near future.
Here is the example:
document.getElementsByTagName("html").foo="bar"
Here is another example how to set custom attributes into body tag element:
document.getElementsByTagName('body')[0].dataset.attr1 = "foo";
document.getElementsByTagName('body')[0].dataset.attr2 = "bar";
Then read the attribute by:
attr1 = document.getElementsByTagName('body')[0].dataset.attr1
attr2 = document.getElementsByTagName('body')[0].dataset.attr2
You can test above code in Console in DevTools, e.g.
simple way :
-(void) viewDidLoad {
self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"background.png"]];
[super viewDidLoad];
}
My case is a bit different, since it is not a form but to return a view. Add method ->name('route')
.
MyView.blade.php
looks like this:
<a href="{{route('admin')}}">CATEGORIES</a>
And web.php
routes file is defined like this:
Route::view('admin', 'admin.index')->name('admin');
I solved this another way. Let's say you have your dependency.js
export const myFunction = () => { }
I create a depdency.mock.js file besides it with the following content:
export const mockFunction = jest.fn();
jest.mock('dependency.js', () => ({ myFunction: mockFunction }));
And in the test, before I import the file that has the dependency, I use:
import { mockFunction } from 'dependency.mock'
import functionThatCallsDep from './tested-code'
it('my test', () => {
mockFunction.returnValue(false);
functionThatCallsDep();
expect(mockFunction).toHaveBeenCalled();
})
To create list and list of lists use below syntax
x = [[] for i in range(10)]
this will create 1-d list and to initialize it put number in [[number] and set length of list put length in range(length)
x = [[[0] for i in range(3)] for i in range(10)]
this will initialize list of lists with 10*3 dimension and with value 0
x[1][5]=value
Installing the Chrome extension IE Tab did the job for me.
It has the ability to auto-detect URLs so whenever I browse to our SharePoint it emulates Internet Explorer. Finally I can open Office documents directly from Chrome.
You can install IETab for FireFox too.
Not only can you, but you have to make a special effort not to if you don't want to. :-)
When the browser encounters a classic script
tag when parsing the HTML, it stops parsing and hands over to the JavaScript interpreter, which runs the script. The parser doesn't continue until the script execution is complete (because the script might do document.write
calls to output markup that the parser should handle).
That's the default behavior, but you have a few options for delaying script execution:
Use JavaScript modules. A type="module"
script is deferred until the HTML has been fully parsed and the initial DOM created. This isn't the primary reason to use modules, but it's one of the reasons:
<script type="module" src="./my-code.js"></script>
<!-- Or -->
<script type="module">
// Your code here
</script>
The code will be fetched (if it's separate) and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. (If your module code is inline rather than in its own file, it is also deferred until HTML parsing is complete.)
This wasn't available when I first wrote this answer in 2010, but here in 2020, all major modern browsers support modules natively, and if you need to support older browsers, you can use bundlers like Webpack and Rollup.js.
Use the defer
attribute on a classic script tag:
<script defer src="./my-code.js"></script>
As with the module, the code in my-code.js
will be fetched and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. But, defer
doesn't work with inline script content, only with external files referenced via src
.
I don't think it's what you want, but you can use the async
attribute to tell the browser to fetch the JavaScript code in parallel with the HTML parsing, but then run it as soon as possible, even if the HTML parsing isn't complete. You can put it on a type="module"
tag, or use it instead of defer
on a classic script
tag.
Put the script
tag at the end of the document, just prior to the closing </body>
tag:
<!doctype html>
<html>
<!-- ... -->
<body>
<!-- The document's HTML goes here -->
<script type="module" src="./my-code.js"></script><!-- Or inline script -->
</body>
</html>
That way, even though the code is run as soon as its encountered, all of the elements defined by the HTML above it exist and are ready to be used.
It used to be that this caused an additional delay on some browsers because they wouldn't start fetching the code until the script
tag was encountered, but modern browsers scan ahead and start prefetching. Still, this is very much the third choice at this point, both modules and defer
are better options.
The spec has a useful diagram showing a raw script
tag, defer
, async
, type="module"
, and type="module" async
and the timing of when the JavaScript code is fetched and run:
Here's an example of the default behavior, a raw script
tag:
.found {_x000D_
color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script>_x000D_
if (typeof NodeList !== "undefined" && !NodeList.prototype.forEach) {_x000D_
NodeList.prototype.forEach = Array.prototype.forEach;_x000D_
}_x000D_
document.querySelectorAll("p").forEach(p => {_x000D_
p.classList.add("found");_x000D_
});_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
(See my answer here for details around that NodeList
code.)
When you run that, you see "Paragraph 1" in green but "Paragraph 2" is black, because the script ran synchronously with the HTML parsing, and so it only found the first paragraph, not the second.
In contrast, here's a type="module"
script:
.found {_x000D_
color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script type="module">_x000D_
document.querySelectorAll("p").forEach(p => {_x000D_
p.classList.add("found");_x000D_
});_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
Notice how they're both green now; the code didn't run until HTML parsing was complete. That would also be true with a defer
script
with external content (but not inline content).
(There was no need for the NodeList
check there because any modern browser supporting modules already has forEach
on NodeList
.)
In this modern world, there's no real value to the DOMContentLoaded
event of the "ready" feature that PrototypeJS, jQuery, ExtJS, Dojo, and most others provided back in the day (and still provide); just use modules or defer
. Even back in the day, there wasn't much reason for using them (and they were often used incorrectly, holding up page presentation while the entire jQuery library was loaded because the script
was in the head
instead of after the document), something some developers at Google flagged up early on. This was also part of the reason for the YUI recommendation to put scripts at the end of the body
, again back in the day.
I'm assuming that you wish to write software to do this. To do it naively you would just find lines and set the vectors. To do it intelligently, you attempt to fit shapes onto the drawing (model fitting). Additionally, you should attempt to ascertain bitmaped regions (regions you can't model through shames or applying textures. I would not recommend going this route as that it will take quite a bit of time and require a bit of graphics and computer vision knowledge. However, the output will much and scale much better than your original output.
Your question has already been answered, but IIRC you can replace lines like:
if d.has_key(scope_item):
with:
if scope_item in d:
That is, d
references d.keys()
in that construction. Sometimes defaultdict
isn't the best option (for example, if you want to execute multiple lines of code after the else
associated with the above if
), and I find the in
syntax easier to read.
Perhaps your main
function has been commented out because of e.g. preprocessing.
To learn what preprocessing is doing, try gcc -C -E es3.c > es3.i
then look with an editor into the generated file es3.i (and search main
inside it).
First, you should always (since you are a newbie) compile with
gcc -Wall -g -c es3.c
gcc -Wall -g es3.o -o es3
The -Wall
flag is extremely important, and you should always use it. It tells the compiler to give you (almost) all warnings. And you should always listen to the warnings, i.e. correct your source code file es3.C
till you got no more warnings.
The -g
flag is important also, because it asks gcc
to put debugging information in the object file and the executable. Then you are able to use a debugger (like gdb
) to debug your program.
To get the list of symbols in an object file or an executable, you can use nm
.
Of course, I'm assuming you use a GNU/Linux system (and I invite you to use GNU/Linux if you don't use it already).
NSDate *date = [NSDate date];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"]
NSString *dateString = [df stringFromDate:date];
[df setDateFormat:@"hh:mm:ss"];
NSString *hoursString = [df stringFromDate:date];
Thats it, you got it all you want.