Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.
So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.
Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.
If the database is InnoDB then it might be a better idea to use foreign keys and cascade on delete, this would do what you want and also result in no redundant data being stored.
For this example however I don't think you need the first s:
DELETE s
FROM spawnlist AS s
INNER JOIN npc AS n ON s.npc_templateid = n.idTemplate
WHERE n.type = "monster";
It might be a better idea to select the rows before deleting so you are sure your deleting what you wish to:
SELECT * FROM spawnlist
INNER JOIN npc ON spawnlist.npc_templateid = npc.idTemplate
WHERE npc.type = "monster";
You can also check the MySQL delete syntax here: http://dev.mysql.com/doc/refman/5.0/en/delete.html
Something like this substitutions will be needed for your tables and field names.
Declare @TableUsers Table (User_ID, MyRowCount Int Identity(1,1)
Declare @i Int, @MaxI Int, @UserID nVarchar(50)
Insert into @TableUser
Select User_ID
From Users
Where (My Criteria)
Select @MaxI = @@RowCount, @i = 1
While @i <= @MaxI
Begin
Select @UserID = UserID from @TableUsers Where MyRowCount = @i
Exec prMyStoredProc @UserID
Select
@i = @i + 1, @UserID = null
End
Back in New Zealand I knew someone who had macular degeneration, so was partially sighted. He's a very talented programmer and wound up using Delphi because he could work by recognizing word shapes This was easier to do with a Pascal-like syntax than a C-ish squiggly bracket one. He has a web site, but doesn't seem to mention macular degeneration at all, so I won't name him.
final Properties properties = new Properties();
try (final InputStream stream =
this.getClass().getResourceAsStream("foo.properties")) {
properties.load(stream);
/* or properties.loadFromXML(...) */
}
You can also try executing the 'convert' utility that comes with imagemagick.
exec("convert pdf_doc.pdf image.jpg");
echo 'image-0.jpg';
string[] MultiEmails = email.Split(',');
foreach (string ToEmail in MultiEmails)
{
message.To.Add(new MailAddress(ToEmail)); //adding multiple email addresses
}
Here is an example of a drawable that will be white by default, black when pressed:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape>
<solid
android:color="#1E669B"/>
<stroke
android:width="2dp"
android:color="#1B5E91"/>
<corners
android:radius="6dp"/>
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp"/>
</shape>
</item>
<item>
<shape>
<gradient
android:angle="270"
android:endColor="#1E669B"
android:startColor="#1E669B"/>
<stroke
android:width="4dp"
android:color="#1B5E91"/>
<corners
android:radius="7dp"/>
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp"/>
</shape>
</item>
</selector>
I updated my android SDK to the latest version (API 19). When I tried to run the emulator with phonegap 3, the build was successful but it ran the same issue.
In the AVD manager there was an existent device, nevertheless, its parameters were all unknown. Surely this occurs because I uninstalled the old sdk version (API 17) that returns a second error while attempting to remove the device. With the message: "device is already running"
To solve the issue, I went to the AVD's location in ~/.android/avd/ and removed manually the device directory.avd and device.ini file. Finally, in the the device manager I created a new AVD provided by the newest API.
This allowed phonegap to build and run the emulator succesfully
I hope this helps
Good day
optimized from spacedrop answer ...
ls $(pwd)/*
and you can use ls options
ls -alrt $(pwd)/*
Default Export (export default
)
// MyClass.ts -- using default export
export default class MyClass { /* ... */ }
The main difference is that you can only have one default export per file and you import it like so:
import MyClass from "./MyClass";
You can give it any name you like. For example this works fine:
import MyClassAlias from "./MyClass";
Named Export (export
)
// MyClass.ts -- using named exports
export class MyClass { /* ... */ }
export class MyOtherClass { /* ... */ }
When you use a named export, you can have multiple exports per file and you need to import the exports surrounded in braces:
import { MyClass } from "./MyClass";
Note: Adding the braces will fix the error you're describing in your question and the name specified in the braces needs to match the name of the export.
Or say your file exported multiple classes, then you could import both like so:
import { MyClass, MyOtherClass } from "./MyClass";
// use MyClass and MyOtherClass
Or you could give either of them a different name in this file:
import { MyClass, MyOtherClass as MyOtherClassAlias } from "./MyClass";
// use MyClass and MyOtherClassAlias
Or you could import everything that's exported by using * as
:
import * as MyClasses from "./MyClass";
// use MyClasses.MyClass and MyClasses.MyOtherClass here
Which to use?
In ES6, default exports are concise because their use case is more common; however, when I am working on code internal to a project in TypeScript, I prefer to use named exports instead of default exports almost all the time because it works very well with code refactoring. For example, if you default export a class and rename that class, it will only rename the class in that file and not any of the other references in other files. With named exports it will rename the class and all the references to that class in all the other files.
It also plays very nicely with barrel files (files that use namespace exports—export *
—to export other files). An example of this is shown in the "example" section of this answer.
Note that my opinion on using named exports even when there is only one export is contrary to the TypeScript Handbook—see the "Red Flags" section. I believe this recommendation only applies when you are creating an API for other people to use and the code is not internal to your project. When I'm designing an API for people to use, I'll use a default export so people can do import myLibraryDefaultExport from "my-library-name";
. If you disagree with me about doing this, I would love to hear your reasoning.
That said, find what you prefer! You could use one, the other, or both at the same time.
Additional Points
A default export is actually a named export with the name default
, so if the file has a default export then you can also import by doing:
import { default as MyClass } from "./MyClass";
And take note these other ways to import exist:
import MyDefaultExportedClass, { Class1, Class2 } from "./SomeFile";
import MyDefaultExportedClass, * as Classes from "./SomeFile";
import "./SomeFile"; // runs SomeFile.js without importing any exports
Well, any specific reason to not make Proxy its own struct?
Anyway you have 2 options:
The proper way, simply move proxy to its own struct, for example:
type Configuration struct {
Val string
Proxy Proxy
}
type Proxy struct {
Address string
Port string
}
func main() {
c := &Configuration{
Val: "test",
Proxy: Proxy{
Address: "addr",
Port: "port",
},
}
fmt.Println(c)
fmt.Println(c.Proxy.Address)
}
The less proper and ugly way but still works:
c := &Configuration{
Val: "test",
Proxy: struct {
Address string
Port string
}{
Address: "addr",
Port: "80",
},
}
It might be a good practice to define variables like below:
v_departmentid departments.department_id%TYPE;
NOT like below:
v_departmentid NUMBER(4)
You can also "fix" this by replacing the image with its inline Base64 representation:
Useful, when you do not intend to publish the page on the web, but instead use it on local machines only. img.src= "data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==";
I assume you're seeing this in a React component's render
method, like this (edit: your edited question does indeed show that):
class Example extends React.Component {_x000D_
render() {_x000D_
return <div>_x000D_
<div>Children ({this.props.children.length}):</div>_x000D_
{this.props.children}_x000D_
</div>;_x000D_
}_x000D_
}_x000D_
_x000D_
class Widget extends React.Component {_x000D_
render() {_x000D_
return <div>_x000D_
<div>First <code>Example</code>:</div>_x000D_
<Example>_x000D_
<div>1</div>_x000D_
<div>2</div>_x000D_
<div>3</div>_x000D_
</Example>_x000D_
<div>Second <code>Example</code> with different children:</div>_x000D_
<Example>_x000D_
<div>A</div>_x000D_
<div>B</div>_x000D_
</Example>_x000D_
</div>;_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
<Widget/>,_x000D_
document.getElementById("root")_x000D_
);
_x000D_
<div id="root"></div>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
_x000D_
children
is a special property of React components which contains any child elements defined within the component, e.g. the divs
inside Example
above. {this.props.children}
includes those children in the rendered result.
...what are the situations to use the same
You'd do it when you want to include the child elements in the rendered output directly, unchanged; and not if you didn't.
A callback is commonly used in asynchronous programming, so you could create a method which handles the response from a web service. When you call the web service, you could pass the method to it so that when the web service responds, it call's the method you told it ... it "calls back".
In Java this can commonly be done through implementing an interface and passing an object (or an anonymous inner class) that implements it. You find this often with transactions and threading - such as the Futures API.
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Future.html
I have found the answer and solution to this problem. Before, I did not know that php.ini resides where in wordpress files. Now I have found that file in wp-admin directory where I placed the code
post_max_size 33M
upload_max_filesize 32M
then it worked. It increases the upload file size for my worpdress website. But, it is the same 2M as was before on cPanel.
According the MDN custom headers are not exposed by default. The server admin need to expose them using "Access-Control-Expose-Headers" in the same fashion they deal with "access-control-allow-origin"
See this MDN link for confirmation [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers]
I run into same problem.
What I found from documentation, we should use namedspace.
in your case {% url login:login_view %}
CSS 3
divContainer input[type="text"] {
width:150px;
}
CSS2 add a class "text" to the text inputs then in your css
.divContainer.text{
width:150px;
}
Just for completion:
I wanted to kill all processes connected to a specific port but not the process listening
the command (in cmd shell) for the port 9001 is:
FOR /F "tokens=5 delims= " %P IN ('netstat -ano ^| findstr -rc:":9001[ ]*ESTA"') DO TaskKill /F /PID %P
findstr:
netstat:
It works because netstat prints out the source port then destination port and then ESTABLISHED
You get this warning message when the servlet api jar file has already been loaded in the container and you try to load it once again from lib
directory.
The Servlet specs say you are not allowed to have servlet.jar in your webapps
lib
directory.
servlet.jar
from your lib
directory.lib
directory scan for your build path and remove the jar.C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\project\WEB-INF\lib
If you are running a maven project, change the javax.servlet-api
dependency to scope provided
in you pom.xml since the container already provided the servlet jar in itself.
use Arrays.equals(ary1,ary2);
// returns boolean value
EDIT
you can use Arrays.deepEquals(ary1,ary2)
to compare 2D arrays as well
also check this link for comparision comparision between Arrays.equls(ar1,ar2)
and Arrays.deepEquals(ar1,ar2)
Java Arrays.equals() returns false for two dimensional arrays
EDIT 2
if you dont want to use these library methods then you can easily implement your method like this:
public static boolean ArrayCompare(int[] a, int[] a2) {
if (a==a2) // checks for same array reference
return true;
if (a==null || a2==null) // checks for null arrays
return false;
int length = a.length;
if (a2.length != length) // arrays should be of equal length
return false;
for (int i=0; i<length; i++) // compare array values
if (a[i] != a2[i])
return false;
return true;
}
I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.
//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
"ln": {c.ln},
"ip": {c.ip},
"ua": {c.ua}})
//okay, moving on...
if err != nil {
//handle postform error
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
//handle read response error
}
fmt.Printf("%s\n", string(body))
a tiny improvement for the answer from interjay, to make the result as a flatten list.
>>> list3 = [zip(x,list2) for x in itertools.permutations(list1,len(list2))]
>>> import itertools
>>> chain = itertools.chain(*list3)
>>> list4 = list(chain)
[('a', 1), ('b', 2), ('a', 1), ('c', 2), ('b', 1), ('a', 2), ('b', 1), ('c', 2), ('c', 1), ('a', 2), ('c', 1), ('b', 2)]
reference from this link
You can use:
for (int x = 0; x < 10; x++) {
if (x == 5) { // If x is 5, then break it.
break;
}
}
You can use the Bean Comparator to sort on any property in your custom class.
As in the docs, if you are on windows you can use hyperv drivers.
Docker for Windows - You can use
docker-machine
create with thehyperv
driver to create additional local machines.
var counts = {};
your_array.forEach(function(x) { counts[x] = (counts[x] || 0)+1; });
Foreign keys are almost always "Allow Duplicates," which would make them unsuitable as Primary Keys.
Instead, find a field that uniquely identifies each record in the table, or add a new field (either an auto-incrementing integer or a GUID) to act as the primary key.
The only exception to this are tables with a one-to-one relationship, where the foreign key and primary key of the linked table are one and the same.
Shift
+ Alt
+ F
indents the whole file.
Here is the directive I use. It automatically cleans itself up when the form is unloaded. If you want to prevent the prompt from firing (e.g. because you successfully saved the form), call $scope.FORMNAME.$setPristine(), where FORMNAME is the name of the form you want to prevent from prompting.
.directive('dirtyTracking', [function () {
return {
restrict: 'A',
link: function ($scope, $element, $attrs) {
function isDirty() {
var formObj = $scope[$element.attr('name')];
return formObj && formObj.$pristine === false;
}
function areYouSurePrompt() {
if (isDirty()) {
return 'You have unsaved changes. Are you sure you want to leave this page?';
}
}
window.addEventListener('beforeunload', areYouSurePrompt);
$element.bind("$destroy", function () {
window.removeEventListener('beforeunload', areYouSurePrompt);
});
$scope.$on('$locationChangeStart', function (event) {
var prompt = areYouSurePrompt();
if (!event.defaultPrevented && prompt && !confirm(prompt)) {
event.preventDefault();
}
});
}
};
}]);
To convert a NSDictionary to a NSString:
NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:myDictionary options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
Use this, modified from https://stephenhaunts.com/2014/09/25/remove-the-close-button-from-a-wpf-window :
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
namespace Whatever
{
public partial class MainMenu : Window
{
private const int GWL_STYLE = -16;
private const int WS_SYSMENU = 0x00080000;
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLongPtr(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
public MainMenu()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Window_Loaded);
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var hwnd = new WindowInteropHelper(this).Handle;
SetWindowLongPtr(hwnd, GWL_STYLE, GetWindowLongPtr(hwnd, GWL_STYLE) & ~WS_SYSMENU);
}
}
}
If there are true answers to those questions, it would be different per software vendor and would be defined by the vendor. I don't know of any true industry standards that are followed with regards to this matter.
Historically with Microsoft, they'll mark something as deprecated and state they'll remove it in a future version. That can be several versions before they actually get rid of it though.
This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.
However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.
In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.
Here is a simple example based on a SAP system I have access to.
Public Sub SimpleSAPExport()
Set SapGuiAuto = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI
Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
Set session = SAPCon.Children(0) 'Get the first session (window) on that connection
'Start the transaction to view a table
session.StartTransaction "SE16"
'Select table T001
session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
session.findById("wnd[0]/tbar[1]/btn[7]").Press
'Set our selection criteria
session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
session.findById("wnd[0]/tbar[1]/btn[8]").press
'Click the export to file button
session.findById("wnd[0]/tbar[1]/btn[45]").press
'Choose the export format
session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
session.findById("wnd[1]/tbar[0]/btn[0]").press
'Choose the export filename
session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"
'Export the file
session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub
To help find the names of elements such aswnd[1]/tbar[0]/btn[0]
you can use script recording.
Click the customize local layout button, it probably looks a bit like this:
Then find the Script Recording and Playback menu item.
Within that the More
button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.
The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI")
defines the SapGuiAuto object.
If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx
in the SAP GUI installation folder.
Try this:
$old_date = Date_create("2010-04-19 18:31:27");
$new_date = Date_format($old_date, "d/m/Y");
I create a library RMMapper (https://github.com/roomorama/RMMapper) to help save custom object into NSUserDefaults easier and more convenient, because implementing encodeWithCoder and initWithCoder is super boring!
To mark a class as archivable, just use: #import "NSObject+RMArchivable.h"
To save a custom object into NSUserDefaults:
#import "NSUserDefaults+RMSaveCustomObject.h"
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults rm_setCustomObject:user forKey:@"SAVED_DATA"];
To get custom obj from NSUserDefaults:
user = [defaults rm_customObjectForKey:@"SAVED_DATA"];
- http://dev.mysql.com/doc/refman/5.0/en/char.html
Values in VARCHAR columns are variable-length strings. The length can be specified as a value from 0 to 255 before MySQL 5.0.3, and 0 to 65,535 in 5.0.3 and later versions. The effective maximum length of a VARCHAR in MySQL 5.0.3 and later is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used.
- So ...
< MySQL 5.0.3 use TEXT
or
>= MySQL 5.0.3 use VARCHAR(2083)
Well, putting together every working approach will result in this (also dealing with deprecated GpsStatus.Listener
):
private GnssStatus.Callback mGnssStatusCallback;
@Deprecated private GpsStatus.Listener mStatusListener;
private LocationManager mLocationManager;
@Override
public void onCreate() {
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (checkPermission()) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, GPS_UPDATE_INTERVAL, MIN_DISTANCE, this);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mGnssStatusCallback = new GnssStatus.Callback() {
@Override
public void onSatelliteStatusChanged(GnssStatus status) {
satelliteStatusChanged();
}
@Override
public void onFirstFix(int ttffMillis) {
gpsFixAcquired();
}
};
mLocationManager.registerGnssStatusCallback(mGnssStatusCallback);
} else {
mStatusListener = new GpsStatus.Listener() {
@Override
public void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
satelliteStatusChanged();
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
// Do something.
gpsFixAcquired();
break;
}
}
};
mLocationManager.addGpsStatusListener(mStatusListener);
}
}
private void gpsFixAcquired() {
// Do something.
isGPSFix = true;
}
private void satelliteStatusChanged() {
if (mLastLocation != null)
isGPSFix = (SystemClock.elapsedRealtime() - mLastLocationMillis) < (GPS_UPDATE_INTERVAL * 2);
if (isGPSFix) { // A fix has been acquired.
// Do something.
} else { // The fix has been lost.
// Do something.
}
}
@Override
public void onLocationChanged(Location location) {
if (location == null) return;
mLastLocationMillis = SystemClock.elapsedRealtime();
mLastLocation = location;
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
Note: this answer is a combination of the answers above.
When reading the strtok documentation, I see you need to pass in a NULL pointer after the first "initializing" call. Maybe you didn't do that. Just a guess of course.
From the documentation for ast.literal_eval()
:
Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
Decimal
isn't on the list of things allowed by ast.literal_eval()
.
def get_true_text(tag):
children = tag.find_elements_by_xpath('*')
original_text = tag.text
for child in children:
original_text = original_text.replace(child.text, '', 1)
return original_text
~/In_ProjectDirectory $ g++ coordin_main.cpp coordin_func.cpp coordin.h
~/In_ProjectDirectory $ ./a.out
... Worked!!
Using Linux Mint with Geany IDE
When I saved each file to the same directory, one file was not saved correctly within the directory; the coordin.h file. So, rechecked and it was saved there as coordin.h, and not incorrectly as -> coordin.h.gch. The little stuff. Arg!!
You have to iterate through the document childNodes and getting the outerHTML content.
in VBA it looks like this
For Each e In document.ChildNodes
Put ff, , e.outerHTML & vbCrLf
Next e
using this, allows you to get all elements of the web page including < !DOCTYPE > node if it exists
In addition to T.J. Crowders answer, I have added some more handlers - including the newer .on(...)
handler to the snippet so you can see which events are being hidden and which ones not.
What I also found is that .live()
is not only deprecated, but was deleted since jQuery 1.9.x. But the other ones, i.e. .click
, .delegate
/.undelegate
and .on
/.off
are still there.
Also note there is more discussion about this topic here on Stackoverflow.
If you need to fix legacy code that is relying on .live, but you require to use a new version of jQuery (> 1.8.3), you can fix it with this snippet:
// fix if legacy code uses .live, but you want to user newer jQuery library
if (!$.fn.live) {
// in this case .live does not exist, emulate .live by calling .on
$.fn.live = function(events, handler) {
$(this).on(events, null, {}, handler);
};
}
The intention of the snippet below, which is an extension of T.J.'s script, is that you can try out by yourself instantly what happens if you bind multiple handlers - so please run the snippet and click on the texts below:
jQuery(function($) {_x000D_
_x000D_
// .live connects function with all spans_x000D_
$('span').live('click', function() {_x000D_
display("<tt>live</tt> caught a click!");_x000D_
});_x000D_
_x000D_
// --- catcher1 events ---_x000D_
_x000D_
// .click connects function with id='catcher1'_x000D_
$('#catcher1').click(function() {_x000D_
display("Click Catcher1 caught a click and prevented <tt>live</tt> from seeing it.");_x000D_
return false;_x000D_
});_x000D_
_x000D_
// --- catcher2 events ---_x000D_
_x000D_
// .click connects function with id='catcher2'_x000D_
$('#catcher2').click(function() {_x000D_
display("Click Catcher2 caught a click and prevented <tt>live</tt>, <tt>delegate</tt> and <tt>on</tt> from seeing it.");_x000D_
return false;_x000D_
});_x000D_
_x000D_
// .delegate connects function with id='catcher2'_x000D_
$(document).delegate('#catcher2', 'click', function() {_x000D_
display("Delegate Catcher2 caught a click and prevented <tt>live</tt> from seeing it.");_x000D_
return false;_x000D_
});_x000D_
_x000D_
// .on connects function with id='catcher2'_x000D_
$(document).on('click', '#catcher2', {}, function() {_x000D_
display("On Catcher2 caught a click and prevented <tt>live</tt> from seeing it.");_x000D_
return false;_x000D_
});_x000D_
_x000D_
// --- catcher3 events ---_x000D_
_x000D_
// .delegate connects function with id='catcher3'_x000D_
$(document).delegate('#catcher3', 'click', function() {_x000D_
display("Delegate Catcher3 caught a click and <tt>live</tt> and <tt>on</tt> can see it.");_x000D_
return false;_x000D_
});_x000D_
_x000D_
// .on connects function with id='catcher3'_x000D_
$(document).on('click', '#catcher3', {}, function() {_x000D_
display("On Catcher3 caught a click and and <tt>live</tt> and <tt>delegate</tt> can see it.");_x000D_
return false;_x000D_
});_x000D_
_x000D_
function display(msg) {_x000D_
$("<p>").html(msg).appendTo(document.body);_x000D_
}_x000D_
_x000D_
});
_x000D_
<!-- with JQuery 1.8.3 it still works, but .live was removed since 1.9.0 -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">_x000D_
</script>_x000D_
_x000D_
<style>_x000D_
span.frame {_x000D_
line-height: 170%; border-style: groove;_x000D_
}_x000D_
</style>_x000D_
_x000D_
<div>_x000D_
<span class="frame">Click me</span>_x000D_
<span class="frame">or me</span>_x000D_
<span class="frame">or me</span>_x000D_
<div>_x000D_
<span class="frame">I'm two levels in</span>_x000D_
<span class="frame">so am I</span>_x000D_
</div>_x000D_
<div id='catcher1'>_x000D_
<span class="frame">#1 - I'm two levels in AND my parent interferes with <tt>live</tt></span>_x000D_
<span class="frame">me too</span>_x000D_
</div>_x000D_
<div id='catcher2'>_x000D_
<span class="frame">#2 - I'm two levels in AND my parent interferes with <tt>live</tt></span>_x000D_
<span class="frame">me too</span>_x000D_
</div>_x000D_
<div id='catcher3'>_x000D_
<span class="frame">#3 - I'm two levels in AND my parent interferes with <tt>live</tt></span>_x000D_
<span class="frame">me too</span>_x000D_
</div>_x000D_
</div>
_x000D_
No. Scroll speed is determined by the browser (and usually directly by the settings on the computer/device). CSS and Javascript don't (or shouldn't) have any way to affect system settings.
That being said, there are likely a number of ways you could try to fake a different scroll speed by moving your own content around in such a way as to counteract scrolling. However, I think doing so is a HORRIBLE idea in terms of usability, accessibility, and respect for your users, but I would start by finding events that your target browsers fire that indicate scrolling.
Once you can capture the scroll event (assuming you can), then you would be able to adjust your content dynamically so that the portion you want is visible.
Another approach would be to deal with this in Flash, which does give you at least some level of control over scrolling events.
Install nmap,
sudo apt-get install nmap
then
nmap -sP 192.168.1.*
or more commonly
nmap -sn 192.168.1.0/24
will scan the entire .1 to .254 range
This does a simple ping scan in the entire subnet to see which hosts are online.
git tag -l --format='%(contents)'
or
git for-each-ref refs/tags/ --format='%(contents)'
will output full annotation message for every tag (including signature if its signed).
%(contents:subject)
will output only first line%(contents:body)
will output annotation without first line and signature (useful text only)%(contents:signature)
will output only PGP-signatureSee more in man git-for-each-ref
“Field names” section.
It's in VS2012 - Specifically the 2-Arrow icon at the top of the solution explorer (Left/Right arrows, one above the other). This automatically jumps to the current file.
This icon is only visible if you've got Track Active Item in Solution Explorer
disabled.
I was having your problem, and this is how I fixed it. The following steps are a working way to add a library. I had done the first two steps right, but I hadn't done the last one by dragging the ".jar" file direct from the file system into the "lib" folder on my eclipse project. Additionally, I had to remove the previous version of the library from both the build path and the "lib" folder.
I had the same issue as @Kos had, only for some reason I had to modify the gulp-sass package from the old package.json
file I had. It then installed the dependencies currently and now it finally works!
REST is a software design pattern typically used for web applications. In layman's terms this means that it is a commonly used idea used in many different projects. It stands for REpresentational State Transfer. The basic idea of REST is treating objects on the server-side (as in rows in a database table) as resources than can be created or destroyed.
The most basic way of thinking about REST is as a way of formatting the URLs of your web applications. For example, if your resource was called "posts", then:
/posts
Would be how a user would access ALL the posts, for displaying.
/posts/:id
Would be how a user would access and view an individual post, retrieved based on their unique id.
/posts/new
Would be how you would display a form for creating a new post.
Sending a POST request to /users
would be how you would actually create a new post on the database level.
Sending a PUT request to /users/:id
would be how you would update the attributes of a given post, again identified by a unique id.
Sending a DELETE request to /users/:id
would be how you would delete a given post, again identified by a unique id.
As I understand it, the REST pattern was mainly popularized (for web apps) by the Ruby on Rails framework, which puts a big emphasis on RESTful routes. I could be wrong about that though.
I may not be the most qualified to talk about it, but this is how I've learned it (specifically for Rails development).
When someone refers to a "REST api," generally what they mean is an api that uses RESTful urls for retrieving data.
CouchDB and MySQL are two very different beasts. JSON is the native way to store stuff in CouchDB. In MySQL, the best you could do is store JSON data as text in a single field. This would entirely defeat the purpose of storing it in an RDBMS and would greatly complicate every database transaction.
Don't.
Having said that, FriendFeed seemed to use an extremely custom schema on top of MySQL. It really depends on what exactly you want to store, there's hardly one definite answer on how to abuse a database system so it makes sense for you. Given that the article is very old and their main reason against Mongo and Couch was immaturity, I'd re-evaluate these two if MySQL doesn't cut it for you. They should have grown a lot by now.
From char and varchar (Transact-SQL)
varchar [ ( n | max ) ]
Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The ISO synonyms for varchar are char varying or character varying.
Looking at the code below, I tried it and found:
Instead of writing DBCon = DBConnection.Instance();
you should put DBConnection DBCon - new DBConnection();
(That worked for me)
and instead of MySqlComman cmd = new MySqlComman(query, DBCon.GetConnection());
you should put MySqlCommand cmd = new MySqlCommand(query, DBCon.GetConnection());
(it's missing the d)
Both these work for me. Maybe post a complete example?
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class PaneBackgroundTest extends Application {
@Override
public void start(Stage primaryStage) {
BorderPane root = new BorderPane();
VBox vbox = new VBox();
root.setCenter(vbox);
ToggleButton toggle = new ToggleButton("Toggle color");
HBox controls = new HBox(5, toggle);
controls.setAlignment(Pos.CENTER);
root.setBottom(controls);
// vbox.styleProperty().bind(Bindings.when(toggle.selectedProperty())
// .then("-fx-background-color: cornflowerblue;")
// .otherwise("-fx-background-color: white;"));
vbox.backgroundProperty().bind(Bindings.when(toggle.selectedProperty())
.then(new Background(new BackgroundFill(Color.CORNFLOWERBLUE, CornerRadii.EMPTY, Insets.EMPTY)))
.otherwise(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY))));
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Generally, you can use the func(*tuple)
syntax. You can even pass a part of the tuple, which seems like what you're trying to do here:
t = (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(*t[0:7])
This is called unpacking a tuple, and can be used for other iterables (such as lists) too. Here's another example (from the Python tutorial):
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]
Really all sql dates should be in yyyy-MM-dd format for the most accurate results.
Let me try to make it simple, suppose URL of the site is www.example.com and you need to sign up by filling username and password, so we go to the login page say http://www.example.com/login.php now and view it's source code and search for the action URL it will be in form tag something like
<form name="loginform" method="post" action="userinfo.php">
now take userinfo.php to make absolute URL which will be 'http://example.com/userinfo.php', now run a simple python script
import requests
url = 'http://example.com/userinfo.php'
values = {'username': 'user',
'password': 'pass'}
r = requests.post(url, data=values)
print r.content
I Hope that this helps someone somewhere someday.
I was searching for similar solution. The replies here and the Tutorial on top is informative. I studied posts/blogs referred here to build mine successful. I am posting complete CMakeLists.txt worked for me. I guess, this would be helpful as a basic template for beginners.
"CMakeLists.txt"
cmake_minimum_required(VERSION 3.10.2)
# Target Project
project (ClientProgram)
# Begin: Including Sources and Headers
include_directories(include)
file (GLOB SOURCES "src/*.c")
# End: Including Sources and Headers
# Begin: Generate executables
add_executable (ClientProgram ${SOURCES})
# End: Generate executables
# This Project Depends on External Project(s)
include (ExternalProject)
# Begin: External Third Party Library
set (libTLS ThirdPartyTlsLibrary)
ExternalProject_Add (${libTLS}
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/${libTLS}
# Begin: Download Archive from Web Server
URL http://myproject.com/MyLibrary.tgz
URL_HASH SHA1=<expected_sha1sum_of_above_tgz_file>
DOWNLOAD_NO_PROGRESS ON
# End: Download Archive from Web Server
# Begin: Download Source from GIT Repository
# GIT_REPOSITORY https://github.com/<project>.git
# GIT_TAG <Refer github.com releases -> Tags>
# GIT_SHALLOW ON
# End: Download Source from GIT Repository
# Begin: CMAKE Comamnd Argiments
CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_CURRENT_BINARY_DIR}/${libTLS}
CMAKE_ARGS -DUSE_SHARED_LIBRARY:BOOL=ON
# End: CMAKE Comamnd Argiments
)
# The above ExternalProject_Add(...) construct wil take care of \
# 1. Downloading sources
# 2. Building Object files
# 3. Install under DCMAKE_INSTALL_PREFIX Directory
# Acquire Installation Directory of
ExternalProject_Get_Property (${libTLS} install_dir)
# Begin: Importing Headers & Library of Third Party built using ExternalProject_Add(...)
# Include PATH that has headers required by Target Project
include_directories (${install_dir}/include)
# Import librarues from External Project required by Target Project
add_library (lmytls SHARED IMPORTED)
set_target_properties (lmytls PROPERTIES IMPORTED_LOCATION ${install_dir}/lib/libmytls.so)
add_library (lmyxdot509 SHARED IMPORTED)
set_target_properties(lmyxdot509 PROPERTIES IMPORTED_LOCATION ${install_dir}/lib/libmyxdot509.so)
# End: Importing Headers & Library of Third Party built using ExternalProject_Add(...)
# End: External Third Party Library
# Begin: Target Project depends on Third Party Component
add_dependencies(ClientProgram ${libTLS})
# End: Target Project depends on Third Party Component
# Refer libraries added above used by Target Project
target_link_libraries (ClientProgram lmytls lmyxdot509)
If you really wanted to store it in a column and have it queryable a lot of databases support XML now. If not querying you can store them as comma separated values and parse them out with a function when you need them separated. I agree with everyone else though if you are looking to use a relational database a big part of normalization is the separating of data like that. I am not saying that all data fits a relational database though. You could always look into other types of databases if a lot of your data doesn't fit the model.
I did mine using regular expressions, since I wanted to preserve a relative path and not use add the addClass function. I just wanted to make it convoluted, lol.
$(".travelinfo-btn").click(
function() {
$("html, body").animate({scrollTop: $(this).offset().top}, 200);
var bgImg = $(this).css('background-image')
var bgPath = bgImg.substr(0, bgImg.lastIndexOf('/')+1)
if(bgImg.match(/collapse/)) {
$(this).stop().css('background-image', bgImg.replace(/collapse/,'expand'));
$(this).next(".travelinfo-item").stop().slideToggle(400);
} else {
$(this).stop().css('background-image', bgImg.replace(/expand/,'collapse'));
$(this).next(".travelinfo-item").stop().slideToggle(400);
}
}
);
In case you have already installed the TortoiseSVN GUI and wondering how to upgrade to command line tools, here are the steps...
Refer to this image for further steps.
After completion of the command line client tools, open a command prompt and type svn help
to check the successful install.
In addition to the accepted answer I would like to give an answer that shows how to iterate directly over the Newtonsoft collections. It uses less code and I'm guessing its more efficient as it doesn't involve converting the collections.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//Parse the data
JObject my_obj = JsonConvert.DeserializeObject<JObject>(your_json);
foreach (KeyValuePair<string, JToken> sub_obj in (JObject)my_obj["ADDRESS_MAP"])
{
Console.WriteLine(sub_obj.Key);
}
I started doing this myself because JsonConvert automatically deserializes nested objects as JToken (which are JObject, JValue, or JArray underneath I think).
I think the parsing works according to the following principles:
Every object is abstracted as a JToken
Cast to JObject where you expect a Dictionary
Cast to JValue if the JToken represents a terminal node and is a value
Cast to JArray if its an array
JValue.Value gives you the .NET type you need
Also try to update your browser because Angular need latest browser. check: https://angular.io/guide/browser-support
I fixed console.log issue after updating latest browser.
falsetru's solution is nice, but has a little bug:
Suppose original 'id' length was larger than 5 characters. When we then dump with the new 'id' (134 with only 3 characters) the length of the string being written from position 0 in file is shorter than the original length. Extra chars (such as '}') left in file from the original content.
I solved that by replacing the original file.
import json
import os
filename = 'data.json'
with open(filename, 'r') as f:
data = json.load(f)
data['id'] = 134 # <--- add `id` value.
os.remove(filename)
with open(filename, 'w') as f:
json.dump(data, f, indent=4)
bash has a builtin
pushd SOME_PATH
run_stuff
...
...
popd
Canvas does not using .png file as background image. changing to other file extensions like gif or jpg works fine.
You can use conda remove --force
.
The documentation says:
--force Forces removal of a package without removing packages
that depend on it. Using this option will usually
leave your environment in a broken and inconsistent
state
The @Url.Action()
method is proccess on the server-side
, so you cannot pass a client-side
value to this function as a parameter. You can concat the client-side
variables with the server-side
url generated by this method, which is a string on the output. Try something like this:
var firstname = "abc";
var username = "abcd";
location.href = '@Url.Action("Display", "Customer")?uname=' + firstname + '&name=' + username;
The @Url.Action("Display", "Customer")
is processed on the server-side
and the rest of the string is processed on the client-side
, concatenating the result of the server-side
method with the client-side
.
NOTE -- As of 2020 you should not be using .utcnow()
or .utcfromtimestamp(xxx)
. As you've presumably moved on to python3,you should be using timezone aware datetime objects.
>>> from datetime import timezone
>>> dt_now = datetime.now(tz=timezone.utc)
>>> dt_ts = datetime.fromtimestamp(1571595618.0, tz=timezone.utc)
for details see: see: https://blog.ganssle.io/articles/2019/11/utcnow.html
The datetime module's utcnow() function can be used to obtain the current UTC time.
>>> import datetime
>>> utc_datetime = datetime.datetime.utcnow()
>>> utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2010-02-01 06:59:19'
As the link mentioned above by Tom: http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/ says:
UTC is a timezone without daylight saving time and still a timezone without configuration changes in the past.
Always measure and store time in UTC.
If you need to record where the time was taken, store that separately. Do not store the local time + timezone information!
NOTE - If any of your data is in a region that uses DST, use pytz
and take a look at John Millikin's answer.
If you want to obtain the UTC time from a given string and your lucky enough to be in a region in the world that either doesn't use DST, or you have data that is only offset from UTC without DST applied:
--> using local time as the basis for the offset value:
>>> # Obtain the UTC Offset for the current system:
>>> UTC_OFFSET_TIMEDELTA = datetime.datetime.utcnow() - datetime.datetime.now()
>>> local_datetime = datetime.datetime.strptime("2008-09-17 14:04:00", "%Y-%m-%d %H:%M:%S")
>>> result_utc_datetime = local_datetime + UTC_OFFSET_TIMEDELTA
>>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2008-09-17 04:04:00'
--> Or, from a known offset, using datetime.timedelta():
>>> UTC_OFFSET = 10
>>> result_utc_datetime = local_datetime - datetime.timedelta(hours=UTC_OFFSET)
>>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2008-09-17 04:04:00'
UPDATE:
Since python 3.2 datetime.timezone
is available. You can generate a timezone aware datetime object with the command below:
import datetime
timezone_aware_dt = datetime.datetime.now(datetime.timezone.utc)
If your ready to take on timezone conversions go read this:
If you can use Guava library, since version 21, you can use
Streams.stream(iterable)
You Can simply Use One Jsp Page To accomplish the task.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String username=request.getParameter("user_name");
String password=request.getParameter("password");
String role=request.getParameter("role");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
Statement st=con.createStatement();
String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
ResultSet rs=st.executeQuery(query);
while(rs.next())
{
session.setAttribute( "user_name",rs.getString(2));
session.setMaxInactiveInterval(3000);
response.sendRedirect("homepage.jsp");
}
%>
<%}
catch(Exception e)
{
out.println(e);
}
%>
</body>
I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.
I want to post this link as it may help further for peeps checking this answer and looking for more java style convention
Java Programming Style Guidelines
Item "2.13 is prefix should be used for boolean variables and methods." is specifically relevant and suggests the is prefix.
The style guide goes on to suggest:
There are a few alternatives to the is prefix that fits better in some situations. These are has, can and should prefixes:
boolean hasLicense();
boolean canEvaluate();
boolean shouldAbort = false;
If you follow the Guidelines I believe the appropriate method would be named:
shouldCreateFreshSnapshot()
'OR 1=1
is an attempt to make a query succeed no matter what
The /*
is an attempt to start a multiline comment so the rest of the query is ignored.
An example would be
SELECT userid
FROM users
WHERE username = ''OR 1=1/*'
AND password = ''
AND domain = ''
As you can see if you were to populate the username field without escaping the '
no matter what credentials the user passes in the query would return all userids in the system likely granting access to the attacker (possibly admin access if admin is your first user). You will also notice the remainder of the query would be commented out because of the /*
including the real '
.
The fact that you can see the value in your database means that it was escaped and that particular attack did not succeed. However, you should investigate if any other attempts were made.
Form data (for GET or POST) is usually encoded as application/x-www-form-urlencoded
: this specifies +
for spaces.
URLs are encoded as RFC 1738 which specifies %20
.
In theory I think you should have %20 before the ?
and + after:
example.com/foo%20bar?foo+bar
here is my implementation
public static byte[] intToByteArray(int a) {
return BigInteger.valueOf(a).toByteArray();
}
public static int byteArrayToInt(byte[] b) {
return new BigInteger(b).intValue();
}
The substring method allows you to specify start and end index:
var str = "xxx_456";
var subStr = str.substring(str.length - 3, str.length);
The accounts property is defined like this:
"accounts":{"github":"sergiotapia"}
Your POCO states this:
public List<Account> Accounts { get; set; }
Try using this Json:
"accounts":[{"github":"sergiotapia"}]
An array of items (which is going to be mapped to the list) is always enclosed in square brackets.
Edit: The Account Poco will be something like this:
class Account {
public string github { get; set; }
}
and maybe other properties.
Edit 2: To not have an array use the property as follows:
public Account Accounts { get; set; }
with something like the sample class I've posted in the first edit.
The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).
WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.
For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:
ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.
Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.
In the scenarios listed below you should go for WCF:
WEB API is a framework for developing RESTful/HTTP services.
There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.
HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.
void NumericTextBoxInput(object sender, TextCompositionEventArgs e)
{
TextBox txt = (TextBox)sender;
var regex = new Regex(@"^[0-9]*(?:\.[0-9]{0,1})?$");
string str = txt.Text + e.Text.ToString();
int cntPrc = 0;
if (str.Contains('.'))
{
string[] tokens = str.Split('.');
if (tokens.Count() > 0)
{
string result = tokens[1];
char[] prc = result.ToCharArray();
cntPrc = prc.Count();
}
}
if (regex.IsMatch(e.Text) && !(e.Text == "." && ((TextBox)sender).Text.Contains(e.Text)) && (cntPrc < 3))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
Quick guide to setup a cron job
Create a new text file, example: mycronjobs.txt
For each daily job (00:00, 03:45), save the schedule lines in mycronjobs.txt
00 00 * * * ruby path/to/your/script.rb
45 03 * * * path/to/your/script2.sh
Send the jobs to cron (everytime you run this, cron deletes what has been stored and updates with the new information in mycronjobs.txt)
crontab mycronjobs.txt
Extra Useful Information
See current cron jobs
crontab -l
Remove all cron jobs
crontab -r
function wait(time)
local duration = os.time() + time
while os.time() < duration do end
end
This is probably one of the easiest ways to add a wait/sleep function to your script
If you really only want to use bash (and sed), then I would go through each of your environment variables (as returned by set
in posix mode) and build a bunch of -e 'regex'
for sed from that, terminated by a -e 's/\$[a-zA-Z_][a-zA-Z0-9_]*//g'
, then pass all that to sed.
Perl would do a nicer job though, you have access to the environment vars as an array and you can do executable replacements so you only match any environment variable once.
In my case I had to add FormsModule
and ReactiveFormsModule
to the shared.module.ts
too:
(thanks to @Undrium for the code example):
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; @NgModule({ imports: [ CommonModule, ReactiveFormsModule ], declarations: [], exports: [ CommonModule, FormsModule, ReactiveFormsModule ] }) export class SharedModule { }
There begin to appear some answers that assume you want to get all <td>
elements from #table
. If so, the simplest cross-browser way how to do this is document.getElementById('table').getElementsByTagName('td')
. This works because getElementsByTagName
doesn't return only immediate children. No loops are needed.
It could be to do with the package you have it in. I had a similar problem:
Description:
Field userRepo in com.App.AppApplication required a bean of type 'repository.UserRepository' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'repository.UserRepository
' in your configuration.
"
Solved it by put the repository files into a package with standardised naming convention:
e.g. com.app.Todo (for main domain files)
and
com.app.Todo.repository (for repository files)
That way, spring knows where to go looking for the repositories, else things get confusing really fast. :)
Hope this helps.
Mine is installed under /usr/share/jenkins I thought it was installed via apt-get so might want to check there as well.
Ubuntu 12.04.1
#!/usr/bin/expect -f
# connect via scp
spawn scp "[email protected]:/home/santhosh/file.dmp" /u01/dumps/file.dmp
#######################
expect {
-re ".*es.*o.*" {
exp_send "yes\r"
exp_continue
}
-re ".*sword.*" {
exp_send "PASSWORD\r"
}
}
interact
http://blogs.oracle.com/SanthoshK/entry/automate_linux_scp_command
You can use
<iframe src="your_pdf_file_path" height="100%" width="100%" scrolling="auto"></iframe>
Or, if you want to make it take up the whole page:
<a href="your_pdf_file_path">Link</a>
from datetime import datetime
from dateutil.relativedelta import relativedelta
d = datetime.now()
date = datetime.isoformat(d).split('.')[0]
d_month = datetime.today() + relativedelta(months=1)
next_month = datetime.isoformat(d_month).split('.')[0]
You're now able to do:
var e = $.Event("keydown", {keyCode: 64});
As suggested, I edited this message to place a proper answer.
The 'physical' location of the mysql databases are under /usr/local/mysql
the mysql is a symlink to the current active mysql installation, in my case the exact folder is mysql-5.6.10-osx10.7-x86_64.
Inside that folder you'll see another data folder, inside it are RESTRICTED folders with your databases.
You can't actually see the size of your databases (that was my issue) from the Finder because the folder are protected, you can though see from the terminal with sudo du -sh /usr/local/mysql/data/{your-database-name}
and like this you'll get a nice formatted output with the size.
In those folder you have different files with all the folders present in your database, so it's safer to check the db's folder to get a size.
That's it. Enjoy!
That won't work if the string contains more than one match... try this:
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo " $0) }'
or better (if the echo
isn't a placeholder for something else):
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'
In your case you want to make a copy of the value before changing it:
echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'
You can create a DIV
component using the <h:panelGroup/>
.
By default, the <h:panelGroup/>
will generate a SPAN in the HTML code.
However, if you specify layout="block"
, then the component will be a DIV
in the generated HTML code.
<h:panelGroup layout="block"/>
Another easier way to do it is to upload your file to google sheets, then add a pivot, for the columns and rows select the same as you would with Excel, however, for values select Calculated Field and then in the formula type in =
To really convert from a string to a number properly, you need to use an instance of NSNumberFormatter
configured for the locale from which you're reading the string.
Different locales will format numbers differently. For example, in some parts of the world, COMMA
is used as a decimal separator while in others it is PERIOD
— and the thousands separator (when used) is reversed. Except when it's a space. Or not present at all.
It really depends on the provenance of the input. The safest thing to do is configure an NSNumberFormatter
for the way your input is formatted and use -[NSFormatter numberFromString:]
to get an NSNumber
from it. If you want to handle conversion errors, you can use -[NSFormatter getObjectValue:forString:range:error:]
instead.
Yes it is possible depending on what css you have, you simply just declare the same thing with a different background like this
ul li {
background: none !important;
}
ul li{
background: blue !important;
}
But you have to make sure the declaration comes after the first one seeing as it is cascading.
You can also create a style tag in jQuery like this
$('head').append('<style> #an-element li { background: inherit !important;} </style>');
You cannot see any changes because it's not inheriting any background but it is overwriting the background: none;
This kind of code perhaps should work for You
SELECT
*,
CASE
WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
ELSE '00'
END AS modifiedpvc
FROM my_table;
gid | datepose | pvc | modifiedpvc
-----+----------+-----+-------------
1 | 1961 | 01 | 00
2 | 1949 | | 01
3 | 1990 | 02 | 00
1 | 1981 | | 02
1 | | 03 | 00
1 | | | 03
(6 rows)
By default, MomentJS parses in local time. If only a date string (with no time) is provided, the time defaults to midnight.
In your code, you create a local date and then convert it to the UTC timezone (in fact, it makes the moment instance switch to UTC mode), so when it is formatted, it is shifted (depending on your local time) forward or backwards.
If the local timezone is UTC+N (N being a positive number), and you parse a date-only string, you will get the previous date.
Here are some examples to illustrate it (my local time offset is UTC+3 during DST):
>>> moment('07-18-2013', 'MM-DD-YYYY').utc().format("YYYY-MM-DD HH:mm")
"2013-07-17 21:00"
>>> moment('07-18-2013 12:00', 'MM-DD-YYYY HH:mm').utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 09:00"
>>> Date()
"Thu Jul 25 2013 14:28:45 GMT+0300 (Jerusalem Daylight Time)"
If you want the date-time string interpreted as UTC, you should be explicit about it:
>>> moment(new Date('07-18-2013 UTC')).utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"
or, as Matt Johnson mentions in his answer, you can (and probably should) parse it as a UTC date in the first place using moment.utc()
and include the format string as a second argument to prevent ambiguity.
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"
To go the other way around and convert a UTC date to a local date, you can use the local()
method, as follows:
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').local().format("YYYY-MM-DD HH:mm")
"2013-07-18 03:00"
parseInt((new Date('2012.08.10').getTime() / 1000).toFixed(0))
It's important to add the toFixed(0)
to remove any decimals when dividing by 1000 to convert from milliseconds to seconds.
The .getTime()
function returns the timestamp in milliseconds, but true unix timestamps are always in seconds.
Here's the code I wrote to find the only visible among a few similar elements, and return the value of its "class" attribute without jQuery:
// Build a NodeList:
var nl = document.querySelectorAll('.myCssSelector');
// convert it to array:
var myArray = [];for(var i = nl.length; i--; myArray.unshift(nl[i]));
// now find the visible (= with offsetWidth more than 0) item:
for (i =0; i < myArray.length; i++){
var curEl = myArray[i];
if (curEl.offsetWidth !== 0){
return curEl.getAttribute("class");
}
}
Your proposed doCalculationsAndUpdateUIs
does data processing and dispatches UI updates to the main queue. I presume that you have dispatched doCalculationsAndUpdateUIs
to a background queue when you first called it.
While technically fine, that's a little fragile, contingent upon your remembering to dispatch it to the background every time you call it: I would, instead, suggest that you do your dispatch to the background and dispatch back to the main queue from within the same method, as it makes the logic unambiguous and more robust, etc.
Thus it might look like:
- (void)doCalculationsAndUpdateUIs {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, NULL), ^{
// DATA PROCESSING 1
dispatch_async(dispatch_get_main_queue(), ^{
// UI UPDATION 1
});
/* I expect the control to come here after UI UPDATION 1 */
// DATA PROCESSING 2
dispatch_async(dispatch_get_main_queue(), ^{
// UI UPDATION 2
});
/* I expect the control to come here after UI UPDATION 2 */
// DATA PROCESSING 3
dispatch_async(dispatch_get_main_queue(), ^{
// UI UPDATION 3
});
});
}
In terms of whether you dispatch your UI updates asynchronously with dispatch_async
(where the background process will not wait for the UI update) or synchronously with dispatch_sync
(where it will wait for the UI update), the question is why would you want to do it synchronously: Do you really want to slow down the background process as it waits for the UI update, or would you like the background process to carry on while the UI update takes place.
Generally you would dispatch the UI update asynchronously with dispatch_async
as you've used in your original question. Yes, there certainly are special circumstances where you need to dispatch code synchronously (e.g. you're synchronizing the updates to some class property by performing all updates to it on the main queue), but more often than not, you just dispatch the UI update asynchronously and carry on. Dispatching code synchronously can cause problems (e.g. deadlocks) if done sloppily, so my general counsel is that you should probably only dispatch UI updates synchronously if there is some compelling need to do so, otherwise you should design your solution so you can dispatch them asynchronously.
In answer to your question as to whether this is the "best way to achieve this", it's hard for us to say without knowing more about the business problem being solved. For example, if you might be calling this doCalculationsAndUpdateUIs
multiple times, I might be inclined to use my own serial queue rather than a concurrent global queue, in order to ensure that these don't step over each other. Or if you might need the ability to cancel this doCalculationsAndUpdateUIs
when the user dismisses the scene or calls the method again, then I might be inclined to use a operation queue which offers cancelation capabilities. It depends entirely upon what you're trying to achieve.
But, in general, the pattern of asynchronously dispatching a complicated task to a background queue and then asynchronously dispatching the UI update back to the main queue is very common.
I only needed to parse IP v4 addresses. My solution based on Chills strategy follows:
def getIP():
valid = False
while not valid :
octets = raw_input( "Remote Machine IP Address:" ).strip().split(".")
try: valid=len( filter( lambda(item):0<=int(item)<256, octets) ) == 4
except: valid = False
return ".".join( octets )
You can use the instanceof
operator for this. From MDN:
The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.
If you don't know what prototypes and prototype chains are I highly recommend looking it up. Also here is a JS (TS works similar in this respect) example which might clarify the concept:
class Animal {_x000D_
name;_x000D_
_x000D_
constructor(name) {_x000D_
this.name = name;_x000D_
}_x000D_
}_x000D_
_x000D_
const animal = new Animal('fluffy');_x000D_
_x000D_
// true because Animal in on the prototype chain of animal_x000D_
console.log(animal instanceof Animal); // true_x000D_
// Proof that Animal is on the prototype chain_x000D_
console.log(Object.getPrototypeOf(animal) === Animal.prototype); // true_x000D_
_x000D_
// true because Object in on the prototype chain of animal_x000D_
console.log(animal instanceof Object); _x000D_
// Proof that Object is on the prototype chain_x000D_
console.log(Object.getPrototypeOf(Animal.prototype) === Object.prototype); // true_x000D_
_x000D_
console.log(animal instanceof Function); // false, Function not on prototype chain_x000D_
_x000D_
_x000D_
The prototype chain in this example is:
animal > Animal.prototype > Object.prototype
In my case, I was using Laravel 5 and I had forgotten to change the mail globals in the .env file that is located in your directory root folder (these variables override your mail configuration)
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=yourpassword
by default, the mailhost is:
MAIL_HOST=mailtraper.io
I was getting the same error but that worked for me.
<?php
$url=parse_url("http://domain.com/site/gallery/1?user=12#photo45 ");
echo $url["fragment"]; //This variable contains the fragment
?>
This is should work
Flatmap and Map both transforms the collection.
Difference:
map(func)
Return a new distributed dataset formed by passing each element of the source through a function func.
flatMap(func)
Similar to map, but each input item can be mapped to 0 or more output items (so func should return a Seq rather than a single item).
The transformation function:
map: One element in -> one element out.
flatMap: One element in -> 0 or more elements out (a collection).
You can make an extension method specially dedicated to this:
public static class EnumerableExtensions {
public static bool IsLast<T>(this List<T> items, T item)
{
if (items.Count == 0)
return false;
T last = items[items.Count - 1];
return item.Equals(last);
}
}
and you can use it like this:
foreach (Item result in Model.Results)
{
if(Model.Results.IsLast(result))
{
//do something in the code
}
}
It actually works now from bower.
bower install material-design-icons --save
It downloads 37.1 KBs. Then it extracts and installs. You will see a folder called material-design-icons in bower_components folder. The total size is around 299KBs
The declaration for Sleep in kernel32.dll won't work in 64-bit Excel. This would be a little more general:
#If VBA7 Then
Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#Else
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If
Is there a way to set the session timeout programatically
There are basically three ways to set the session timeout value:
session-timeout
in the standard web.xml
file ~or~session-timeout
value (and thus configuring it at the server level) ~or~HttpSession. setMaxInactiveInterval(int seconds)
method in your Servlet or JSP. But note that the later option sets the timeout value for the current session, this is not a global setting.
Since you don't call Num.__init__
, the field "n1" never gets created. Call it and then it will be there.
Using System.Web.HttpContext.Current.User.Identity.Name
should work.
Please check the IIS Site settings on the server that is hosting your site by doing the following:
Go to IIS ? Sites ? Your Site ? Authentication
Now check that Anonymous Access is Disabled & Windows Authentication is Enabled.
Now System.Web.HttpContext.Current.User.Identity.Name
should return something like this:
domain\username
I got the same error but from a backend job (SSIS job). Upon checking the database's Log file growth setting, the log file was limited growth of 1GB. So what happened is when the job ran and it asked SQL server to allocate more log space, but the growth limit of the log declined caused the job to failed. I modified the log growth and set it to grow by 50MB and Unlimited Growth and the error went away.
The jsfiddle link to where i tried out your query http://jsfiddle.net/A8Dnv/1/ its working fine @Imrul as mentioned you are using C# on server side and you dont mind that either: http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape.aspx
None of the above worked for me but the below did:
sudo chown -R user: /Library/Frameworks/Python.framework/Versions/3.9/share/jupyter/
Where user is your username.
This is worked for me.
#_account_id{
display: none;
}
label[for="_account_id"] { display: none !important; }
According to the HTML5 Spec:
A valid browsing context name is any string with at least one character that does not start with a U+005F LOW LINE character. (Names starting with an underscore are reserved for special keywords.)
A valid browsing context name or keyword is any string that is either a valid browsing context name or that is an ASCII case-insensitive match for one of: _blank, _self, _parent, or _top." - Source
That means that there is no such keyword as _new
in HTML5, and not in HTML4 (and consequently XHTML) either. That means, that there will be no consistent behavior whatsoever if you use this as a value for the target attribute.
As Daniel and Michael have pointed out in the comments, when using target _blank
pointing to an untrusted website, you should, in addition, set rel="noopener"
. This prevents the opening site to mess with the opener via JavaScript. See this post for more information.
Please explain your problem. You say:
But this involves adding character " to the string.
What problem is that? You can't type string foo = "Foo"bar"";
, because that'll invoke a compile error. As for the adding part, in string size terms that is not true:
@"""".Length == "\"".Length == 1
Color picker plugin for Interface Builder
There's a nice color picker from Panic which works well with IB: http://panic.com/~wade/picker/
Xcode plugin
This one gives you a GUI for choosing colors: http://www.youtube.com/watch?v=eblRfDQM0Go
Objective-C
UIColor *color = [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1.0];
Swift
let color = UIColor(red: 160/255, green: 97/255, blue: 5/255, alpha: 1.0)
Pods and libraries
There's a nice pod named MPColorTools
: https://github.com/marzapower/MPColorTools
I recently came across this and didn't really like the solutions so I tried experimenting.
.mydivclass {inline-block; vertical-align: middle; width: 33%;}
Does it matter which I use?
Yes! The second is vastly more readable. You are trading one line which concisely expresses what you want against nine lines of effectively clutter.
Which is faster?
Neither.
Is it a better practice to use the shortest code whenever possible?
Not “whenever possible” but certainly whenever possible without detriment effects. Shorter code is at least potentially more readable since it focuses on the relevant part rather than on incidental effects (“boilerplate code”).
Guys let's understand the syntax of it.
If class file is present in the Current Dir.
java -cp . fileName
If class file is present within the Dir. Go to the Parent Dir and enter below cmd.
java -cp . dir1.dir2.dir3.fileName
If there is a dependency on external jars then,
java -cp .:./jarName1:./jarName2 fileName
Hope this helps.
You can add account in the preference -> Accounts setting.
It seems that you already configure xCode4, then I think you can select your certificates for compiling in project-> Building Setting directly since your certificates are already in your keychain.
To solve the issue try to repair the .net framework 4 and then run the command
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
I just now faced this issue while trying to restart XAMPP Apache.
What you can do to solve this is:
Hope my solution solves your problem.
Thank You!
You can simply add @HostBinding('class') class = 'someClass';
inside your @Component class.
Example:
@Component({
selector: 'body',
template: 'app-element'
})
export class App implements OnInit {
@HostBinding('class') class = 'someClass';
constructor() {}
ngOnInit() {}
}
Try this from the box you are pushing from
ssh [email protected]
You should then get a welcome response from github and will be fine to then push.
CREATE FUNCTION [dbo].[_ICAN_FN_IntToTime](@Num INT)
RETURNS NVARCHAR(13)
AS
-------------------------------------------------------------------------------------------------------------------
--INVENTIVE:Keyvan ARYAEE-MOEEN
-------------------------------------------------------------------------------------------------------------------
BEGIN
DECLARE @Hour VARCHAR(10)=CAST(@Num/3600 AS VARCHAR(2))
DECLARE @Minute VARCHAR(10)=CAST((@Num-@Hour*3600)/60 AS VARCHAR(2))
DECLARE @Time VARCHAR(13)=CASE WHEN @Hour<10 THEN '0'+@Hour ELSE @Hour END+':'+CASE WHEN @Minute<10 THEN '0'+@Minute ELSE @Minute END+':00.000'
RETURN @Time
END
-------------------------------------------------------------------------------------------------------------------
--SELECT dbo._ICAN_FN_IntToTime(25500)
-------------------------------------------------------------------------------------------------------------------
json
seems faster than simplejson
in both cases of loads and dumps in latest version
Tested versions:
Results:
>>> def test(obj, call, data, times):
... s = datetime.now()
... print("calling: ", call, " in ", obj, " ", times, " times")
... for _ in range(times):
... r = getattr(obj, call)(data)
... e = datetime.now()
... print("total time: ", str(e-s))
... return r
>>> test(json, "dumps", data, 10000)
calling: dumps in <module 'json' from 'C:\\Users\\jophine.antony\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\json\\__init__.py'> 10000 times
total time: 0:00:00.054857
>>> test(simplejson, "dumps", data, 10000)
calling: dumps in <module 'simplejson' from 'C:\\Users\\jophine.antony\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\site-packages\\simplejson\\__init__.py'> 10000 times
total time: 0:00:00.419895
'{"1": 100, "2": "acs", "3.5": 3.5567, "d": [1, "23"], "e": {"a": "A"}}'
>>> test(json, "loads", strdata, 1000)
calling: loads in <module 'json' from 'C:\\Users\\jophine.antony\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\json\\__init__.py'> 1000 times
total time: 0:00:00.004985
{'1': 100, '2': 'acs', '3.5': 3.5567, 'd': [1, '23'], 'e': {'a': 'A'}}
>>> test(simplejson, "loads", strdata, 1000)
calling: loads in <module 'simplejson' from 'C:\\Users\\jophine.antony\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\site-packages\\simplejson\\__init__.py'> 1000 times
total time: 0:00:00.040890
{'1': 100, '2': 'acs', '3.5': 3.5567, 'd': [1, '23'], 'e': {'a': 'A'}}
For versions:
json was faster than simplejson during dumps operation but both maintained the same speed during loads operations
You can also use eye function of numpy:
numpy.eye(number of classes)[vector containing the labels]
Parse timespan to DateTime. For Example.
//The time will be "8.30 AM" or "10.00 PM" or any time like this format.
public TimeSpan GetTimeSpanValue(string displayValue)
{
DateTime dateTime = DateTime.Now;
if (displayValue.StartsWith("10") || displayValue.StartsWith("11") || displayValue.StartsWith("12"))
dateTime = DateTime.ParseExact(displayValue, "hh:mm tt", CultureInfo.InvariantCulture);
else
dateTime = DateTime.ParseExact(displayValue, "h:mm tt", CultureInfo.InvariantCulture);
return dateTime.TimeOfDay;
}
It is possible by using the legend tag. Refer to http://www.w3schools.com/html5/tag_legend.asp
Here is a working and tested solution. You can control the depth of the mapping in the class hierarchy.
public class FieldMapper {
public static void copy(Object from, Object to) throws Exception {
FieldMapper.copy(from, to, Object.class);
}
public static void copy(Object from, Object to, Class depth) throws Exception {
Class fromClass = from.getClass();
Class toClass = to.getClass();
List<Field> fromFields = collectFields(fromClass, depth);
List<Field> toFields = collectFields(toClass, depth);
Field target;
for (Field source : fromFields) {
if ((target = findAndRemove(source, toFields)) != null) {
target.set(to, source.get(from));
}
}
}
private static List<Field> collectFields(Class c, Class depth) {
List<Field> accessibleFields = new ArrayList<>();
do {
int modifiers;
for (Field field : c.getDeclaredFields()) {
modifiers = field.getModifiers();
if (!Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers)) {
accessibleFields.add(field);
}
}
c = c.getSuperclass();
} while (c != null && c != depth);
return accessibleFields;
}
private static Field findAndRemove(Field field, List<Field> fields) {
Field actual;
for (Iterator<Field> i = fields.iterator(); i.hasNext();) {
actual = i.next();
if (field.getName().equals(actual.getName())
&& field.getType().equals(actual.getType())) {
i.remove();
return actual;
}
}
return null;
}
}
Try PyPDF2.
There is a good tutorial here: https://automatetheboringstuff.com/chapter13/
You can filter for HTTP POST requests with the Chrome DevTools. Just do the following:
method:POST
Screenshot
Tested with Chrome Version 53.
Funkodebat posted a great solution which I have referenced many times. Still, I find myself writing my own working model each time I need this. So, here is my working model... with some added clarity.
First of all, the height of the text is equal to the pixel font size. Now, this was something I read a while ago, and it has worked out in my calculations. I'm not sure if this works with all fonts, but it seems to work with Arial, sans-serif.
Also, to make sure that you fit all of the text in your canvas (and don't trim the tails off of your "p"'s) you need to set context.textBaseline*.
You will see in the code that we are rotating the text about its center. To do this, we need to set context.textAlign = "center" and the context.textBaseline to bottom, otherwise, we trim off parts of our text.
Why resize the canvas?
I usually have a canvas that isn't appended to the page. I use it to draw all of my rotated text, then I draw it onto another canvas which I display.
For example, you can use this canvas to draw all of the labels for a chart (one by one) and draw the hidden canvas onto the chart canvas where you need the label (context.drawImage(hiddenCanvas, 0, 0);
).
IMPORTANT NOTE: Set your font before measuring your text, and re-apply all of your styling to the context after resizing your canvas. A canvas's context is completely reset when the canvas is resized.
Hope this helps!
var c = document.getElementById("myCanvas");_x000D_
var ctx = c.getContext("2d");_x000D_
var font, text, x, y;_x000D_
_x000D_
text = "Mississippi";_x000D_
_x000D_
//Set font size before measuring_x000D_
font = 20;_x000D_
ctx.font = font + 'px Arial, sans-serif';_x000D_
//Get width of text_x000D_
var metrics = ctx.measureText(text);_x000D_
//Set canvas dimensions_x000D_
c.width = font;//The height of the text. The text will be sideways._x000D_
c.height = metrics.width;//The measured width of the text_x000D_
//After a canvas resize, the context is reset. Set the font size again_x000D_
ctx.font = font + 'px Arial';_x000D_
//Set the drawing coordinates_x000D_
x = font/2;_x000D_
y = metrics.width/2;_x000D_
//Style_x000D_
ctx.fillStyle = 'black';_x000D_
ctx.textAlign = 'center';_x000D_
ctx.textBaseline = "bottom";_x000D_
//Rotate the context and draw the text_x000D_
ctx.save();_x000D_
ctx.translate(x, y);_x000D_
ctx.rotate(-Math.PI / 2);_x000D_
ctx.fillText(text, 0, font / 2);_x000D_
ctx.restore();
_x000D_
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
_x000D_
You can also manually change the time part of date and format in "dd/mm/yyyy" pattern according to your requirement.
public static Date getZeroTimeDate(Date changeDate){
Date returnDate=new Date(changeDate.getTime()-(24*60*60*1000));
return returnDate;
}
If the return value is not working then check for the context parameter in web.xml. eg.
<context-param>
<param-name>javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE</param-name>
<param-value>true</param-value>
</context-param>
I am set Tooltips On My Working Project That Is 100% Working
<!DOCTYPE html>_x000D_
<html>_x000D_
<style>_x000D_
.tooltip {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
border-bottom: 1px dotted black;_x000D_
}_x000D_
_x000D_
.tooltip .tooltiptext {_x000D_
visibility: hidden;_x000D_
width: 120px;_x000D_
background-color: black;_x000D_
color: #fff;_x000D_
text-align: center;_x000D_
border-radius: 6px;_x000D_
padding: 5px 0;_x000D_
_x000D_
/* Position the tooltip */_x000D_
position: absolute;_x000D_
z-index: 1;_x000D_
}_x000D_
_x000D_
.tooltip:hover .tooltiptext {_x000D_
visibility: visible;_x000D_
}_x000D_
.size_of_img{_x000D_
width:90px}_x000D_
</style>_x000D_
_x000D_
<body style="text-align:center;">_x000D_
_x000D_
<p>Move the mouse over the text below:</p>_x000D_
_x000D_
<div class="tooltip"><img class="size_of_img" src="https://babeltechreviews.com/wp-content/uploads/2018/07/rendition1.img_.jpg" alt="Image 1" /><span class="tooltiptext">grewon.pdf</span></div>_x000D_
_x000D_
<p>Note that the position of the tooltip text isn't very good. Check More Position <a href="https://www.w3schools.com/css/css_tooltip.asp">GO</a></p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
SELECT cols
FROM table
WHERE cols IS NULL
Step #1: Wrap whatever it is you want centered on the screen in a full-screen RelativeLayout
.
Step #2: Give that child view (the one, which you want centered inside the RelativeLayout
) the android:layout_centerInParent="true"
attribute.
This can be done by using intents too:
final Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(
"http://maps.google.com/maps?" +
"saddr="+YOUR_START_LONGITUDE+","+YOUR_START_LATITUDE+"&daddr="YOUR_END_LONGITUDE+","+YOUR_END_LATITUDE));
intent.setClassName(
"com.google.android.apps.maps",
"com.google.android.maps.MapsActivity");
startActivity(intent);
In simple terms, the reasons are as follows.
Object
has monitors.Object
. Only one thread can hold object monitor at a time for synchronized
methods/blocks.wait(), notify() and notifyAll()
method being in Object
class allows all the threads created on that object
to communicate with othersynchronized or Lock
API) and Communication (wait() and notify()
) are two different concepts. If Thread
class contains wait(), notify() and notifyAll()
methods, then it will create below problems:
Thread
communication problemSynchronization
on object won’t be possible. If each thread will have monitor, we won’t have any way of achieving synchronizationInconsistency
in state of object Refer to this article for more details.
in this example we run 2 line insert into query and if all of them true it run but if not no run anything and ROLLBACK
DECLARE @rowcount int set @rowcount = 0 ;
BEGIN TRANSACTION [Tran1]
BEGIN TRY
insert into [database].[dbo].[tbl1] (fld1) values('1') ;
set @rowcount = (@rowcount + @@ROWCOUNT);
insert into [database].[dbo].[tbl2] (fld1) values('2') ;
set @rowcount = (@rowcount + @@ROWCOUNT);
IF @rowcount = 2
COMMIT TRANSACTION[Tran1]
ELSE
ROLLBACK TRANSACTION[Tran1]
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION[Tran1]
END CATCH
The problem is GROUP BY
- if you group results by Locus, you only get one result per locus.
Try:
SELECT * FROM Genes WHERE Locus = '3' AND Chromosome = '10';
If you prefer using HAVING
syntax, then GROUP BY id
or something that is not repeating in the result set.
Try the net use command
I took Stano's excellent answer and wrapped it in a promise. This might be useful if you don't have an option like node or webpack to fall back on to load a json file from the file system:
// wrapped XMLHttpRequest in a promise
const readFileP = (file, options = {method:'get'}) =>
new Promise((resolve, reject) => {
let request = new XMLHttpRequest();
request.onload = resolve;
request.onerror = reject;
request.overrideMimeType("application/json");
request.open(options.method, file, true);
request.onreadystatechange = () => {
if (request.readyState === 4 && request.status === "200") {
resolve(request.responseText);
}
};
request.send(null);
});
You can call it like this:
readFileP('<path to file>')
.then(d => {
'<do something with the response data in d.srcElement.response>'
});
You can use text property in your xml file for particular Edittext fields. For example :
<EditText
android:id="@+id/ET_User"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yourusername"/>
like this all Edittext fields contains text whatever u want,if user wants to change particular Edittext field he remove older text and enter his new text.
In Another way just you get the particular Edittext field id in activity class and set text to that one.
Another way = programmatically
Example:
EditText username=(EditText)findViewById(R.id.ET_User);
username.setText("jack");
For concatenating selectors together when nesting, you need to use the parent selector (&
):
.class {
margin:20px;
&:hover {
color:yellow;
}
}
I've got the same problem in Docker.
In Docker I keep trained LightGBM
model + Flask
serving requests. As HTTP server I used gunicorn 19.9.0
. When I run my code locally on my Mac laptop everything worked just perfect, but when I ran the app in Docker my POST JSON requests were freezing for some time, then gunicorn
worker had been failing with [CRITICAL] WORKER TIMEOUT
exception.
I tried tons of different approaches, but the only one solved my issue was adding worker_class=gthread
.
Here is my complete config:
import multiprocessing
workers = multiprocessing.cpu_count() * 2 + 1
accesslog = "-" # STDOUT
access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(q)s" "%(D)s"'
bind = "0.0.0.0:5000"
keepalive = 120
timeout = 120
worker_class = "gthread"
threads = 3
In Xcode 8 beta 4 does not work...
Use:
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
print("Are we there yet?")
}
for async two ways:
DispatchQueue.main.async {
print("Async1")
}
DispatchQueue.main.async( execute: {
print("Async2")
})
I had a related issue working within Spyder, but the problem seems to be the relationship between the escape character ( "\") and the "\" in the path name Here's my illustration and solution (note single \ vs double \\ ):
path = 'C:\Users\myUserName\project\subfolder'
path # 'C:\\Users\\myUserName\\project\subfolder'
os.listdir(path) # gives windows error
path = 'C:\\Users\\myUserName\\project\\subfolder'
os.listdir(path) # gives expected behavior
Query for just a single known column:
session.query(MyTable.col1).count()
You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.
$("button").click(function() {
var $btn = $(this);
$btn.button('loading');
// simulating a timeout
setTimeout(function () {
$btn.button('reset');
}, 1000);
});
Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.
found = binarySearch(first, last, search4, &random);
Notice the &
.
Consider supplementing, not replacing, MSTest with another testing framework. You can keep Visual Studio MSTest integration while getting the benefits of a more full-featured testing framework.
For example, i use xUnit with MSTest. Add a reference to the xUnit.dll assembly, and just do something like this. Suprisingly, it just works!
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Assert = Xunit.Assert; // <-- Aliasing the Xunit namespace is key
namespace TestSample
{
[TestClass]
public class XunitTestIntegrationSample
{
[TestMethod]
public void TrueTest()
{
Assert.True(true); // <-- this is the Xunit.Assert class
}
[TestMethod]
public void FalseTest()
{
Assert.False(true);
}
}
}
I had a run in with the same problem. My application was also a Silverlight application and the service was being called from a class library with a custom UserControl that was being used in it.
The solution is simple. Copy the endpoint definitions from the config file (e.g. ServiceReferences.ClientConfig) of the class library to the config file of the silverlight application. I know you'd expect it to work without having to do this, but apparently someone in Redmond had a vacation that day.
My need was to get keys of an interface as an array of strings to simplify mocha/chai scripting. Not concerned about using in the app (yet), so didn't need the ts files to be created. Thanks to ford04 for the assistance, his solution above was a huge help and it works perfectly, NO compiler hacks. Here's the modified code:
npm install --save-dev ts-morph
NOTE: this assumes all ts files are located in the root of ./src and there are no subfolders, adjust accordingly
import {
Project,
VariableDeclarationKind,
InterfaceDeclaration,
} from "ts-morph";
// initName is name of the interface file below the root, ./src is considered the root
const Keys = (intName: string): string[] => {
const project = new Project();
const sourceFile = project.addSourceFileAtPath(`./src/${intName}.ts`);
const node = sourceFile.getInterface(intName)!;
const allKeys = node.getProperties().map((p) => p.getName());
return allKeys;
};
export default Keys;
import keys from "./keys";
const myKeys = keys("MyInterface") //ts file name without extension
console.log(myKeys)
instance.__class__.__name__
example:
>>> class A():
pass
>>> a = A()
>>> a.__class__.__name__
'A'
For Java 8 and above, it's easy:
when(mock.process(Matchers.anyList()));
For Java 7 and below, the compiler needs a bit of help. Use anyListOf(Class<T> clazz)
:
when(mock.process(Matchers.anyListOf(Bar.class)));
You can add the model error on any property of your model, I suggest if there is nothing related to create a new property.
As an exemple we check if the email is already in use in DB and add the error to the Email property in the action so when I return the view, they know that there's an error and how to show it up by using
<%: Html.ValidationSummary(true)%>
<%: Html.ValidationMessageFor(model => model.Email) %>
and
ModelState.AddModelError("Email", Resources.EmailInUse);
My privilege prevents me making my comment on the first post so it will have to go here.
Consideration should be taken into account of 2038 unix bug when setting 20 years in advance from the current date which is suggest as the correct answer above.
Your cookie on January 19, 2018 + (20 years) could well hit 2038 problem depending on the browser and or versions you end up running on.
You could try BeeWare - as described on their website:
Write your apps in Python and release them on iOS, Android, Windows, MacOS, Linux, Web, and tvOS using rich, native user interfaces. One codebase. Multiple apps.
Gives you want you want now to write Android Apps in Python, plus has the advantage that you won't need to learn yet another framework in future if you end up also wanting to do something on one of the other listed platforms.
Here's the Tutorial for Android Apps.
In my case it was - no disk space left on the web server.
You need to contain the three divs. Here is an example:
CSS
div.contain
{
margin:3%;
border: none;
height: auto;
width: auto;
float: left;
}
div.contain div
{
display:inline;
width:200px;
height:300px;
padding: 15px;
margin: auto;
border:1px solid red;
background-color:#fffff7;
-moz-border-radius:25px; /* Firefox */
border-radius:25px;
}
Note: border-radius attributes are optional and only work in CSS3 compliant browsers.
HTML
<div class="contain">
<div>Foo</div>
</div>
<div class="contain">
<div>Bar</div>
</div>
<div class="contain">
<div>Baz</div>
</div>
Note that the divs 'foo' 'bar' and 'baz' are each held within the 'contain' div.
The easiest way to achieve this is with a negative margin.
const deviceWidth = RN.Dimensions.get('window').width
a: {
alignItems: 'center',
backgroundColor: 'blue',
width: deviceWidth,
},
b: {
marginTop: -16,
marginStart: 20,
},
xhr.file = file;
; the file object is not supposed to be attached this way.xhr.send(file)
doesn't send the file. You have to use the FormData
object to wrap the file into a multipart/form-data
post data object:
var formData = new FormData();
formData.append("thefile", file);
xhr.send(formData);
After that, the file can be access in $_FILES['thefile']
(if you are using PHP).
Remember, MDC and Mozilla Hack demos are your best friends.
EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.
Option 1
In your index.js
file (i.e. webpack entry) add a require to your index.html
via file-loader plugin, e.g.:
require('file-loader?name=[name].[ext]!../index.html');
Once you build your project with webpack, index.html
will be in the output folder.
Option 2
Use html-webpack-plugin to avoid having an index.html at all. Simply have webpack generate the file for you.
In this case if you want to keep your own index.html
file as template, you may use this configuration:
{
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html'
})
]
}
See the docs for more information.
This is more predictable then "line-height"
.loginBtn {_x000D_
background:url(images/loginBtn-center.jpg) repeat-x;_x000D_
width:175px;_x000D_
height:65px;_x000D_
margin:20px auto;_x000D_
border-radius:10px;_x000D_
-webkit-border-radius:10px;_x000D_
box-shadow:0 1px 2px #5e5d5b;_x000D_
}_x000D_
_x000D_
.loginBtn span {_x000D_
display: block;_x000D_
padding-top: 22px;_x000D_
text-align: center;_x000D_
line-height: 1em;_x000D_
}
_x000D_
<div id="loginBtn" class="loginBtn"><span>Log in</span></div>
_x000D_
.loginBtn {
display: flex;
align-items: center;
justify-content: center;
}
sys.exit()
raises a SystemExit
exception which you are probably assuming as some error. If you want your program not to raise SystemExit but return gracefully, you can wrap your functionality in a function and return from places you are planning to use sys.exit
For Windows 7: c:\users\all users\MySql\MySql Server x.x\Data\
Where x.x is the version number of the sql server installed in your machine.
Fidel
Below code can be used to Remove New Line and Table Space in text column
Select replace(replace(TEXT,char(10),''),char(13),'')
Here is a great chrome extension to bulk delete your slack channel/group/im messages - https://slackext.com/deleter , where you can filter the messages by star, time range, or users. BTW, it also supports load all messages in recent version, then you can load your ~8k messages as you need.
Given the code you provided in comments, I assume you want to do this:
>>> dateList = "Thu Sep 16 13:14:15 CDT 2010".split()
>>> sdateList = "Thu Sep 16 14:14:15 CDT 2010".split()
>>> dateList == sdataList
false
The split
-method of the string returns a list. A list in Python is very different from an array. ==
in this case does an element-wise comparison of the two lists and returns if all their elements are equal and the number and order of the elements is the same. Read the documentation.
As Kristian has pointed out, good control over z-values will often solve your problems.
If that does not work you can take a look at CSS Box Shadow Bottom Only on using overflow hidden to hide excess shadow.
I would also have in mind that the box-shadow property can accept a comma-separated list of shadows like this:
box-shadow: 0px 10px 5px #888, 0px -10px 5px #888;
This will give you some control over the "amount" of shadow in each direction.
Have a look at http://www.css3.info/preview/box-shadow/ for more information about box-shadow.
Hope this was what you were looking for!
Since Java 6 there is also non-blocking thread-safe alternative to TreeMap. See ConcurrentSkipListMap.
Let see mounted()
I think it is help
Another thing to keep in mind is there are two different CASEs with MySQL: one like what @cdhowie and others describe here (and documented here: http://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#operator_case) and something which is called a CASE, but has completely different syntax and completely different function, documented here: https://dev.mysql.com/doc/refman/5.0/en/case.html
Invariably, I first use one when I want the other.
You can try:
<VirtualHost myvhost:80>
php_value error_log "/var/log/httpd/vhost_php_error_log"
</Virtual Host>
But I'm not sure if it is going to work. I tried on my sites with no success.
Use DISTINCT
if you just want to remove duplicates. Use GROUPY BY
if you want to apply aggregate operators (MAX
, SUM
, GROUP_CONCAT
, ..., or a HAVING
clause).
I am surprised there is no mention yet of this book: Starting Forth, by Leo Brodie. After all Forth, being a stack-based language, should fit the audience on this site...
Admittedly, Forth is a weird language and not very popular these days. But this book is a joy to read. And it has cartoons! The book, as well as Brodie's other book, Thinking Forth, are both available free on the web.
Use StringBuilder
class. It is more efficient at what you are trying to do.
The two functions do vastly different things!
The resize()
method (and passing argument to constructor is equivalent to that) will insert or delete appropriate number of elements to the vector to make it given size (it has optional second argument to specify their value). It will affect the size()
, iteration will go over all those elements, push_back will insert after them and you can directly access them using the operator[]
.
The reserve()
method only allocates memory, but leaves it uninitialized. It only affects capacity()
, but size()
will be unchanged. There is no value for the objects, because nothing is added to the vector. If you then insert the elements, no reallocation will happen, because it was done in advance, but that's the only effect.
So it depends on what you want. If you want an array of 1000 default items, use resize()
. If you want an array to which you expect to insert 1000 items and want to avoid a couple of allocations, use reserve()
.
EDIT: Blastfurnace's comment made me read the question again and realize, that in your case the correct answer is don't preallocate manually. Just keep inserting the elements at the end as you need. The vector will automatically reallocate as needed and will do it more efficiently than the manual way mentioned. The only case where reserve()
makes sense is when you have reasonably precise estimate of the total size you'll need easily available in advance.
EDIT2: Ad question edit: If you have initial estimate, then reserve()
that estimate. If it turns out to be not enough, just let the vector do it's thing.
For those looking for the shortex mutex example:
#include <mutex>
int main() {
std::mutex m;
m.lock();
// do thread-safe stuff
m.unlock();
}
If you use another view
make sure to use view.getContext()
instead of this
or getApplicationContext()
There have been methodologies in all languages advocating for use of a single return statement in any function. However impossible it may be in certain code, some people do strive for that, however, it may end up making your code more complex (as in more lines of code), but on the other hand, somewhat easier to follow (as in logic flow).
This will not mess up garbage collection in any way!!
The better way to do it is to set a boolean value, if you want to listen to him.
boolean flag = false;
for(int i=0; i<array.length; ++i){
if(array[i] == valueToFind) {
flag = true;
break;
}
}
return flag;
Another modification:
function update() {
$.get("response.php", function(data) {
$("#some_div").html(data);
window.setTimeout(update, 10000);
});
}
The difference with this is that it waits 10 seconds AFTER the ajax call is one. So really the time between refreshes is 10 seconds + length of ajax call. The benefit of this is if your server takes longer than 10 seconds to respond, you don't get two (and eventually, many) simultaneous AJAX calls happening.
Also, if the server fails to respond, it won't keep trying.
I've used a similar method in the past using .ajax to handle even more complex behaviour:
function update() {
$("#notice_div").html('Loading..');
$.ajax({
type: 'GET',
url: 'response.php',
timeout: 2000,
success: function(data) {
$("#some_div").html(data);
$("#notice_div").html('');
window.setTimeout(update, 10000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#notice_div").html('Timeout contacting server..');
window.setTimeout(update, 60000);
}
}
This shows a loading message while loading (put an animated gif in there for typical "web 2.0" style). If the server times out (in this case takes longer than 2s) or any other kind of error happens, it shows an error, and it waits for 60 seconds before contacting the server again.
This can be especially beneficial when doing fast updates with a larger number of users, where you don't want everyone to suddenly cripple a lagging server with requests that are all just timing out anyways.
Since there are limited real answers I'll share this workaround. For really simple cases like your example you do it backwards...
From this
1
2
3
4
5
Replace \r\n
with " />\r\n<row id="
and you'll get 90% of the way there
1" />
<row id="2" />
<row id="3" />
<row id="4" />
<row id="5
Or is a similar fashion you can hack about data with excel/spreadsheet. Just split your original data into columns and manipulate values as you require.
| <row id=" | 1 | " /> |
| <row id=" | 1 | " /> |
| <row id=" | 1 | " /> |
| <row id=" | 1 | " /> |
| <row id=" | 1 | " /> |
Obvious stuff but it may help someone doing the odd one-off hack job to save a few key strokes.
By using ''.join
list1 = ['1', '2', '3']
str1 = ''.join(list1)
Or if the list is of integers, convert the elements before joining them.
list1 = [1, 2, 3]
str1 = ''.join(str(e) for e in list1)
full cases (rgb, rgba, transparent...etc) solution (coffeeScript)
rgb2hex: (rgb, transparentDefault=null)->
return null unless rgb
return rgb if rgb.indexOf('#') != -1
return transparentDefault || 'transparent' if rgb == 'rgba(0, 0, 0, 0)'
rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
hex = (x)->
("0" + parseInt(x).toString(16)).slice(-2)
'#' + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3])
Firstly uninstall Android Studio from control panel using program and features. Later you also need to enable displaying of hidden files and folders and delete the following:
users/${yourUserName}/appData/Local/Android
I previously had the same issue, but I realized that I didn't include the "app.js
" (the main application) inside my main page (index.html
).
So even when you include all the dependencies required by AngularJS, you might end up with that error in the console. So always make sure to include the necessary files inside your main page and you shouldn't have that issue.
Hope this helps.
Instead of
cmd = new OracleCommand("ProcName", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
You can also use this syntax:
cmd = new OracleCommand("BEGIN ProcName(:p0); END;", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
Note, if you set cmd.BindByName = False
(which is the default) then you have to add the parameters in the same order as they are written in your command string, the actual names are not relevant. For cmd.BindByName = True
the parameter names have to match, the order does not matter.
In case of a function call the command string would be like this:
cmd = new OracleCommand("BEGIN :ret := ProcName(:ParName); END;", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("ret", OracleDbType.RefCursor, ParameterDirection.ReturnValue);
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
// cmd.ExecuteNonQuery(); is not needed, otherwise the function is executed twice!
var da = new OracleDataAdapter(cmd);
da.Fill(dt);
For those wondering why ipairs doesn't print all the values of the table all the time, here's why (I would comment this, but I don't have enough good boy points).
The function ipairs only works on tables which have an element with the key 1. If there is an element with the key 1, ipairs will try to go as far as it can in a sequential order, 1 -> 2 -> 3 -> 4 etc until it cant find an element with a key that is the next in the sequence. The order of the elements does not matter.
Tables that do not meet those requirements will not work with ipairs, use pairs instead.
Examples:
ipairsCompatable = {"AAA", "BBB", "CCC"}
ipairsCompatable2 = {[1] = "DDD", [2] = "EEE", [3] = "FFF"}
ipairsCompatable3 = {[3] = "work", [2] = "does", [1] = "this"}
notIpairsCompatable = {[2] = "this", [3] = "does", [4] = "not"}
notIpairsCompatable2 = {[2] = "this", [5] = "doesn't", [24] = "either"}
ipairs will go as far as it can with it's iterations but won't iterate over any other element in the table.
kindofIpairsCompatable = {[2] = 2, ["cool"] = "bro", [1] = 1, [3] = 3, [5] = 5 }
When printing these tables, these are the outputs. I've also included pairs outputs for comparison.
ipairs + ipairsCompatable
1 AAA
2 BBB
3 CCC
ipairs + ipairsCompatable2
1 DDD
2 EEE
3 FFF
ipairs + ipairsCompatable3
1 this
2 does
3 work
ipairs + notIpairsCompatable
pairs + notIpairsCompatable
2 this
3 does
4 not
ipairs + notIpairsCompatable2
pairs + notIpairsCompatable2
2 this
5 doesnt
24 either
ipairs + kindofIpairsCompatable
1 1
2 2
3 3
pairs + kindofIpairsCompatable
1 1
2 2
3 3
5 5
cool bro
If we are use chosen dropdown list, then we can use below css(No JS/JQuery require)
<select chosen="{width: '100%'}" ng-
model="modelName" class="form-control input-
sm"
ng-
options="persons.persons as
persons.persons for persons in
jsonData"
ng-
change="anyFunction(anyParam)"
required>
<option value=""> </option>
</select>
<style>
.chosen-container .chosen-drop {
border-bottom: 0;
border-top: 1px solid #aaa;
top: auto;
bottom: 40px;
}
.chosen-container.chosen-with-drop .chosen-single {
border-top-left-radius: 0px;
border-top-right-radius: 0px;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
background-image: none;
}
.chosen-container.chosen-with-drop .chosen-drop {
border-bottom-left-radius: 0px;
border-bottom-right-radius: 0px;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
box-shadow: none;
margin-bottom: -16px;
}
</style>