you can use instead of click :
$('#whatever').on('touchstart click', function(){ /* do something... */ });
A great Spring MVC quickstart archetype is available on GitHub, courtesy of kolorobot. Good instructions are provided on how to install it to your local Maven repo and use it to create a new Spring MVC project. He’s even helpfully included the Tomcat 7 Maven plugin in the archetypical project so that the newly created Spring MVC can be run from the command line without having to manually deploy it to an application server.
Kolorobot’s example application includes the following:
Very nice solution by praneybehl, but if someone wants to save the data as a csv
file and using a blob
method then they can refer this:
function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
//This condition will generate the Label/Header
if (ShowLabel) {
var row = "";
//This loop will extract the label from 1st index of on array
for (var index in arrData[0]) {
//Now convert each value to string and comma-seprated
row += index + ',';
}
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";
//2nd loop will extract each column and convert it in string comma-seprated
for (var index in arrData[i]) {
row += '"' + arrData[i][index] + '",';
}
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
//this trick will generate a temp "a" tag
var link = document.createElement("a");
link.id = "lnkDwnldLnk";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
var csv = CSV;
blob = new Blob([csv], { type: 'text/csv' });
var csvUrl = window.webkitURL.createObjectURL(blob);
var filename = (ReportTitle || 'UserExport') + '.csv';
$("#lnkDwnldLnk")
.attr({
'download': filename,
'href': csvUrl
});
$('#lnkDwnldLnk')[0].click();
document.body.removeChild(link);
}
I was going insane trying to get my js files to refresh and I tried everything. Then I did a header check and remembered I was using Cloudflare!
In Cloudflare you can use dev mode to disable proxy.
check out lxml2json (disclosure: I wrote it)
https://github.com/rparelius/lxml2json
it's very fast, lightweight (only requires lxml), and one advantage is that you have control over whether certain elements are converted to lists or dicts
use:
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
it's not a RESTful approach anymore, but you can now call your actions by name (rather than let the Web API automatically determine one for you based on the verb) like this:
[POST] /api/VTRouting/TSPRoute
[POST] /api/VTRouting/Route
Contrary to popular belief, there is nothing wrong with this approach, and it's not abusing Web API. You can still leverage on all the awesome features of Web API (delegating handlers, content negotiation, mediatypeformatters and so on) - you just ditch the RESTful approach.
Try the Date
function. It will give you today's date in a MM/DD/YYYY format. If you're looking for today's date in the MM-DD-YYYY format try Date$
. Now()
also includes the current time (which you might not need). It all depends on what you need. :)
In general error is which nobody can control or guess when it occurs.Exception can be guessed and can be handled. In Java Exception and Error are sub class of Throwable.It is differentiated based on the program control.Error such as OutOfMemory Error which no programmer can guess and can handle it.It depends on dynamically based on architectire,OS and server configuration.Where as Exception programmer can handle it and can avoid application's misbehavior.For example if your code is looking for a file which is not available then IOException is thrown.Such instances programmer can guess and can handle it.
A more modern solution that utilises the URL
WebAPI:
(req, res) => {
const { pathname } = new URL(req.url || '', `https://${req.headers.host}`)
}
In order to execute multiple programs, I also needed a profiles
section:
<profiles>
<profile>
<id>traverse</id>
<activation>
<property>
<name>traverse</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<argument>org.dhappy.test.NeoTraverse</argument>
</arguments>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
This is then executable as:
mvn exec:exec -Ptraverse
The thing is that AsyncTask.cancel() call only calls the onCancel function in your task. This is where you want to handle the cancel request.
Here is a small task I use to trigger an update method
private class UpdateTask extends AsyncTask<Void, Void, Void> {
private boolean running = true;
@Override
protected void onCancelled() {
running = false;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
onUpdate();
}
@Override
protected Void doInBackground(Void... params) {
while(running) {
publishProgress();
}
return null;
}
}
The full list is:
DB, DW, DD, DQ, DT, DDQ, and DO (used to declare initialized data in the output file.)
See: http://www.tortall.net/projects/yasm/manual/html/nasm-pseudop.html
They can be invoked in a wide range of ways: (Note: for Visual-Studio - use "h" instead of "0x" syntax - eg: not 0x55 but 55h instead):
db 0x55 ; just the byte 0x55
db 0x55,0x56,0x57 ; three bytes in succession
db 'a',0x55 ; character constants are OK
db 'hello',13,10,'$' ; so are string constants
dw 0x1234 ; 0x34 0x12
dw 'A' ; 0x41 0x00 (it's just a number)
dw 'AB' ; 0x41 0x42 (character constant)
dw 'ABC' ; 0x41 0x42 0x43 0x00 (string)
dd 0x12345678 ; 0x78 0x56 0x34 0x12
dq 0x1122334455667788 ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
ddq 0x112233445566778899aabbccddeeff00
; 0x00 0xff 0xee 0xdd 0xcc 0xbb 0xaa 0x99
; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
do 0x112233445566778899aabbccddeeff00 ; same as previous
dd 1.234567e20 ; floating-point constant
dq 1.234567e20 ; double-precision float
dt 1.234567e20 ; extended-precision float
DT does not accept numeric constants as operands, and DDQ does not accept float constants as operands. Any size larger than DD does not accept strings as operands.
I have used following for the same:
<script type="application/javascript">
$('input[type="file"]').change(function(e){
var fileName = e.target.files[0].name;
$('.custom-file-label').html(fileName);
});
</script>
// Method inside the component
userClick(event){
let tag = event.currentTarget.dataset.tag;
console.log(tag); // should return Tagvalue
}
// when render element
<a data-tag="TagValue" onClick={this.userClick}>Click me</a>
If you want a list of lists:
>>> [list(t) for t in zip(*l)]
[[1, 3, 8], [2, 4, 9]]
If a list of tuples is OK:
>>> zip(*l)
[(1, 3, 8), (2, 4, 9)]
import React, {Component} from 'react';
import {StyleSheet, View} from 'react-native';
export default class App extends Component {
render() {
return (
<View>// you need to wrap the two Views an another View
<View style={styles.box1}></View>
<View style={styles.box2}></View>
</View>
);
}
}
const styles = StyleSheet.create({
box1:{
height:100,
width:100,
backgroundColor:'red'
},
box2:{
height:100,
width:100,
backgroundColor:'green',
position: 'absolute',
top:10,
left:30
},
});
So, static methods are the methods which can be called without creating the object of a class. For Example :-
@staticmethod
def add(a, b):
return a + b
b = A.add(12,12)
print b
In the above example method add
is called by the class name A
not the object name.
For cases of appending to end of existing string:
string = "Sec_"
string += "C_type"
print(string)
results in
Sec_C_type
Based on @AlecRust idea, I did an implementation of png text service.
The demo is here:
http://lingtalfi.com/services/pngtext?color=cc0000&size=10&text=Hello%20World
There are four parameters:
Please do not use this service directly (except for testing), but use the class I created that provides the service:
https://github.com/lingtalfi/WebBox/blob/master/Image/PngTextUtil.php
class PngTextUtil
{
/**
* Displays a png text.
*
* Note: this method is meant to be used as a webservice.
*
* Options:
* ------------
* - font: string = arial/Arial.ttf
* The font to use.
* If the path starts with a slash, it's an absolute path to the font file.
* Else if the path doesn't start with a slash, it's a relative path to the font directory provided
* by this class (the WebBox/assets/fonts directory in this repository).
* - fontSize: int = 12
* The font size.
* - color: string = 000000
* The color of the text in hexadecimal format (6 chars).
* This can optionally be prefixed with a pound symbol (#).
*
*
*
*
*
*
* @param string $text
* @param array $options
* @throws \Bat\Exception\BatException
* @throws WebBoxException
*/
public static function displayPngText(string $text, array $options = []): void
{
if (false === extension_loaded("gd")) {
throw new WebBoxException("The gd extension is not loaded!");
}
header("Content-type: image/png");
$font = $options['font'] ?? "arial/Arial.ttf";
$fontsize = $options['fontSize'] ?? 12;
$hexColor = $options['color'] ?? "000000";
if ('/' !== substr($font, 0, 1)) {
$fontDir = __DIR__ . "/../assets/fonts";
$font = $fontDir . "/" . $font;
}
$rgbColors = ConvertTool::convertHexColorToRgb($hexColor);
//--------------------------------------------
// GET THE TEXT BOX DIMENSIONS
//--------------------------------------------
$charWidth = $fontsize;
$charFactor = 1;
$textLen = mb_strlen($text);
$imageWidth = $textLen * $charWidth * $charFactor;
$imageHeight = $fontsize;
$logoimg = imagecreatetruecolor($imageWidth, $imageHeight);
imagealphablending($logoimg, false);
imagesavealpha($logoimg, true);
$col = imagecolorallocatealpha($logoimg, 255, 255, 255, 127);
imagefill($logoimg, 0, 0, $col);
$white = imagecolorallocate($logoimg, $rgbColors[0], $rgbColors[1], $rgbColors[2]); //for font color
$x = 0;
$y = $fontsize;
$angle = 0;
$bbox = imagettftext($logoimg, $fontsize, $angle, $x, $y, $white, $font, $text); //fill text in your image
$boxWidth = $bbox[4] - $bbox[0];
$boxHeight = $bbox[7] - $bbox[1];
imagedestroy($logoimg);
//--------------------------------------------
// CREATE THE PNG
//--------------------------------------------
$imageWidth = abs($boxWidth);
$imageHeight = abs($boxHeight);
$logoimg = imagecreatetruecolor($imageWidth, $imageHeight);
imagealphablending($logoimg, false);
imagesavealpha($logoimg, true);
$col = imagecolorallocatealpha($logoimg, 255, 255, 255, 127);
imagefill($logoimg, 0, 0, $col);
$white = imagecolorallocate($logoimg, $rgbColors[0], $rgbColors[1], $rgbColors[2]); //for font color
$x = 0;
$y = $fontsize;
$angle = 0;
imagettftext($logoimg, $fontsize, $angle, $x, $y, $white, $font, $text); //fill text in your image
imagepng($logoimg); //save your image at new location $target
imagedestroy($logoimg);
}
}
Note: if you don't use the universe framework, you will need to replace this line:
$rgbColors = ConvertTool::convertHexColorToRgb($hexColor);
With this code:
$rgbColors = sscanf($hexColor, "%02x%02x%02x");
In which case your hex color must be exactly 6 chars long (don't put the hash symbol (#) in front of it).
Note: in the end, I did not use this service, because I found that the font was ugly and worse: it was not possible to select the text. But for the sake of this discussion I thought this code was worth sharing...
Adding the data-position="fixed" and adding the below style in the css will fix the issue z-index: 1;
I had this problem before and to fix this, Just make sure :
My problem (before) :
I had class : Core, Router, Permissions and Render
Core include's the Router class, Router then calls Permissions class, then Router __destruct calls the Render class and the error "Cannot declare class because the name is already in use" appeared.
Solution :
I added __destruct on Permission class and the __destruct was empty and it's fixed...
Since C90, you can simply use:
dest_struct = source_struct;
as long as the string is memorized inside an array:
struct xxx {
char theString[100];
};
Otherwise, if it's a pointer, you'll need to copy it by hand.
struct xxx {
char* theString;
};
dest_struct = source_struct;
dest_struct.theString = malloc(strlen(source_struct.theString) + 1);
strcpy(dest_struct.theString, source_struct.theString);
Given that your strings are all fixed-length (presumably at compile-time?), you can do the following:
char (*orderedIds)[ID_LEN+1]
= malloc(variableNumberOfElements * sizeof(*orderedIds));
// Clear-up
free(orderedIds);
A more cumbersome, but more general, solution, is to assign an array of pointers, and psuedo-initialising them to point at elements of a raw backing array:
char *raw = malloc(variableNumberOfElements * (ID_LEN + 1));
char **orderedIds = malloc(sizeof(*orderedIds) * variableNumberOfElements);
// Set each pointer to the start of its corresponding section of the raw buffer.
for (i = 0; i < variableNumberOfElements; i++)
{
orderedIds[i] = &raw[i * (ID_LEN+1)];
}
...
// Clear-up pointer array
free(orderedIds);
// Clear-up raw array
free(raw);
Windows 7 isn't a supported platform as far as I know. I use the SDK on 64-bit Ubuntu 9.10 and it works fine, though I did have to install the ia32libs or libcurses bombed every time. That was Eclipse related.
The SDK sys reqs makes it clear whatever platform you run, you must be able to run 32-bit code.
The call to InitializeComponent()
(which is usually called in the default constructor of at least Window
and UserControl
) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).
This method locates a URI to the XAML for the Window
/UserControl
that is loading, and passes it to the System.Windows.Application.LoadComponent()
static method. LoadComponent()
loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.
In more detail, LoadComponent
creates an instance of the XamlParser
, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode()
. This gets passed to the BamlRecordWriter
class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.
Note: Interestingly, the InitializeComponent
is a method on the System.Windows.Markup.IComponentConnector
interface, of which Window
/UserControl
implement in the partial generated class.
Hope this helps!
max_allowed_packet
is set in mysql config, not on php side
[mysqld]
max_allowed_packet=16M
You can see it's curent value in mysql like this:
SHOW VARIABLES LIKE 'max_allowed_packet';
You can try to change it like this, but it's unlikely this will work on shared hosting:
SET GLOBAL max_allowed_packet=16777216;
You can read about it here http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html
EDIT
The [mysqld] is necessary to make the max_allowed_packet
working since at least mysql version 5.5.
Recently setup an instance on AWS EC2 with Drupal and Solr Search Engine, which required 32M max_allowed_packet
. It you set the value under [mysqld_safe]
(which is default settings came with the mysql installation) mode in /etc/my.cnf, it did no work. I did not dig into the problem. But after I change it to [mysqld]
and restarted the mysqld, it worked.
mysql> SHOW VARIABLES WHERE Variable_name = 'hostname';
+---------------+-----------+
| Variable_name | Value |
+---------------+-----------+
| hostname | karola-pc |
+---------------+-----------+
1 row in set (0.00 sec)
For Example in my case : karola-pc
is the host name of the box where my mysql is running. And it my local PC host name.
If it is romote box than you can ping that host directly if, If you are in network with that box you should be able to ping that host.
If it UNIX or Linux you can run "hostname" command
in terminal to check the host name.
if it is windows you can see same value in MyComputer-> right click -> properties ->Computer Name
you can see ( i.e System Properties)
Hope it will answer your Q.
I have a feeling that the username and password that you are sending should be part of the Authorization Header. So the code below shows you how to create the Base64 string of the username and password. I also included an example of sending the POST data. In my case it was a phone_number parameter.
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(_username + ":" + _password));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Request);
webRequest.Headers.Add("Authorization", string.Format("Basic {0}", credentials));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowAutoRedirect = true;
webRequest.Proxy = null;
string data = "phone_number=19735559042";
byte[] dataStream = Encoding.UTF8.GetBytes(data);
request.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();
setInterval and setTimeout create an automatically incrementing interval. Each time setTimeout or setInterval is called, this number goes up by one, so that if you call setTimeout, you'll get the current, highest value.
var currentInterval = 10000;
currentInterval += setTimeout( gotoHREF, 100 );
for( var i = 0; i < currentInterval; i++ ) top.clearInterval( i );
// Include setTimeout to avoid recursive functions.
for( i = 0; i < currentInterval; i++ ) top.clearTimeout( i );
function gotoHREF(){
top.location.href = "http://your.url.here";
}
Since it is almost unheard of for there to be 10000 simultaneous setIntervals and setTimeouts working, and since setTimeout returns "last interval or timeout created + 1", and since top.clearInterval is still accessible, this will defeat the black-hat attacks to frame websites which are described above.
alex,
I could be wrong here, but I suspect that multiple phones 'in the wild' have a bug that causes them to switch orientation on applications that are marked as statically oriented. This happens quite a bit on my personal phone, and on many of the test phones our group uses (including droid, n1, g1, hero). Typically an app marked as statically oriented (perhaps vertically) will lay itself out for a second or two using a horizontal orientation, and then immediately switch back. End result is that even though you don't want your app to switch orientation, you have to be prepared that it may. I don't know under what exact conditions this behavior can be reproduced, I don't know if it is specific to a version of Android. All I know is that I have seen it happen plenty of times :(
I would recommend using the solution provided in the link you posted that suggests overriding the Activity onCreateDialog method and letting the Android OS manage the lifecycle of your Dialogs. It looks to me like even though you don't want your activity to switch orientations, it is switching orientation somewhere. You can try to track down a method that will always prevent orientation switching, but I am trying to tell you that I personally don't believe there is a foolproof way that works on all current Android phones in the market.
You should group by the field you want the SUM apply to, and not include in SELECT any field other than multiple rows values, like COUNT, SUM, AVE, etc, because if you include Bill field like in this case, only the first value in the set of rows will be displayed, being almost meaningless and confusing.
This will return the sum of bills per account number:
SELECT SUM(Bill) FROM Table1 GROUP BY AccountNumber
You could add more clauses like WHERE, ORDER BY etc as needed.
I was getting this error for a different reason than those listed here, and could not find the solution easily, so I figured I would post here.
Hopefully this is helpful to someone.
My issue was with referencing files in the program. It was not able to find the file listed, because when I was coding it I had the file I wanted to reference in the top level directory and just called
"my_file.png"
when I was calling the files.
pyinstaller did not like this, because even when I was running it from the same folder, it was expecting a full path:
"C:\Files\my_file.png"
Once I changed all of my paths, to the full version of their path, it fixed this issue.
Not only is there a way to do this, there is more than one way to do this (which I concede is not very Pythonic, but then SQL*Developer is written in Java ).
I have a procedure with this signature: get_maxsal_by_dept( dno number, maxsal out number)
.
I highlight it in the SQL*Developer Object Navigator, invoke the right-click menu and chose Run. (I could use ctrl+F11.) This spawns a pop-up window with a test harness. (Note: If the stored procedure lives in a package, you'll need to right-click the package, not the icon below the package containing the procedure's name; you will then select the sproc from the package's "Target" list when the test harness appears.) In this example, the test harness will display the following:
DECLARE
DNO NUMBER;
MAXSAL NUMBER;
BEGIN
DNO := NULL;
GET_MAXSAL_BY_DEPT(
DNO => DNO,
MAXSAL => MAXSAL
);
DBMS_OUTPUT.PUT_LINE('MAXSAL = ' || MAXSAL);
END;
I set the variable DNO to 50 and press okay. In the Running - Log pane (bottom right-hand corner unless you've closed/moved/hidden it) I can see the following output:
Connecting to the database apc.
MAXSAL = 4500
Process exited.
Disconnecting from the database apc.
To be fair the runner is less friendly for functions which return a Ref Cursor, like this one: get_emps_by_dept (dno number) return sys_refcursor
.
DECLARE
DNO NUMBER;
v_Return sys_refcursor;
BEGIN
DNO := 50;
v_Return := GET_EMPS_BY_DEPT(
DNO => DNO
);
-- Modify the code to output the variable
-- DBMS_OUTPUT.PUT_LINE('v_Return = ' || v_Return);
END;
However, at least it offers the chance to save any changes to file, so we can retain our investment in tweaking the harness...
DECLARE
DNO NUMBER;
v_Return sys_refcursor;
v_rec emp%rowtype;
BEGIN
DNO := 50;
v_Return := GET_EMPS_BY_DEPT(
DNO => DNO
);
loop
fetch v_Return into v_rec;
exit when v_Return%notfound;
DBMS_OUTPUT.PUT_LINE('name = ' || v_rec.ename);
end loop;
END;
The output from the same location:
Connecting to the database apc.
name = TRICHLER
name = VERREYNNE
name = FEUERSTEIN
name = PODER
Process exited.
Disconnecting from the database apc.
Alternatively we can use the old SQLPLus commands in the SQLDeveloper worksheet:
var rc refcursor
exec :rc := get_emps_by_dept(30)
print rc
In that case the output appears in Script Output pane (default location is the tab to the right of the Results tab).
The very earliest versions of the IDE did not support much in the way of SQL*Plus. However, all of the above commands have been supported since 1.2.1. Refer to the matrix in the online documentation for more info.
"When I type just
var rc refcursor;
and select it and run it, I get this error (GUI):"
There is a feature - or a bug - in the way the worksheet interprets SQLPlus commands. It presumes SQLPlus commands are part of a script. So, if we enter a line of SQL*Plus, say var rc refcursor
and click Execute Statement
(or F9 ) the worksheet hurls ORA-900 because that is not an executable statement i.e. it's not SQL . What we need to do is click Run Script
(or F5 ), even for a single line of SQL*Plus.
"I am so close ... please help."
You program is a procedure with a signature of five mandatory parameters. You are getting an error because you are calling it as a function, and with just the one parameter:
exec :rc := get_account(1)
What you need is something like the following. I have used the named notation for clarity.
var ret1 number
var tran_cnt number
var msg_cnt number
var rc refcursor
exec :tran_cnt := 0
exec :msg_cnt := 123
exec get_account (Vret_val => :ret1,
Vtran_count => :tran_cnt,
Vmessage_count => :msg_cnt,
Vaccount_id => 1,
rc1 => :rc )
print tran_count
print rc
That is, you need a variable for each OUT or IN OUT parameter. IN parameters can be passed as literals. The first two EXEC statements assign values to a couple of the IN OUT parameters. The third EXEC calls the procedure. Procedures don't return a value (unlike functions) so we don't use an assignment syntax. Lastly this script displays the value of a couple of the variables mapped to OUT parameters.
First, keep in mind that, in its precise definition, a module is an object in the memory of a Python interpreter, often created by reading one or more files from disk. While we may informally call a disk file such as a/b/c.py
a "module," it doesn't actually become one until it's combined with information from several other sources (such as sys.path
) to create the module object.
(Note, for example, that two modules with different names can be loaded from the same file, depending on sys.path
and other settings. This is exactly what happens with python -m my.module
followed by an import my.module
in the interpreter; there will be two module objects, __main__
and my.module
, both created from the same file on disk, my/module.py
.)
A package is a module that may have submodules (including subpackages). Not all modules can do this. As an example, create a small module hierarchy:
$ mkdir -p a/b
$ touch a/b/c.py
Ensure that there are no other files under a
. Start a Python 3.4 or later interpreter (e.g., with python3 -i
) and examine the results of the following statements:
import a
a ? <module 'a' (namespace)>
a.b ? AttributeError: module 'a' has no attribute 'b'
import a.b.c
a.b ? <module 'a.b' (namespace)>
a.b.c ? <module 'a.b.c' from '/home/cjs/a/b/c.py'>
Modules a
and a.b
are packages (in fact, a certain kind of package called a "namespace package," though we wont' worry about that here). However, module a.b.c
is not a package. We can demonstrate this by adding another file, a/b.py
to the directory structure above and starting a fresh interpreter:
import a.b.c
? ImportError: No module named 'a.b.c'; 'a.b' is not a package
import a.b
a ? <module 'a' (namespace)>
a.__path__ ? _NamespacePath(['/.../a'])
a.b ? <module 'a.b' from '/home/cjs/tmp/a/b.py'>
a.b.__path__ ? AttributeError: 'module' object has no attribute '__path__'
Python ensures that all parent modules are loaded before a child module is loaded. Above it finds that a/
is a directory, and so creates a namespace package a
, and that a/b.py
is a Python source file which it loads and uses to create a (non-package) module a.b
. At this point you cannot have a module a.b.c
because a.b
is not a package, and thus cannot have submodules.
You can also see here that the package module a
has a __path__
attribute (packages must have this) but the non-package module a.b
does not.
Duration.ofMinutes( 260L )
.toString()
PT4H20M
… or …
LocalTime.MIN.plus(
Duration.ofMinutes( 260L )
).toString()
04:20
Duration
The java.time classes include a pair of classes to represent spans of time. The Duration
class is for hours-minutes-seconds, and Period
is for years-months-days.
Duration d = Duration.ofMinutes( 260L );
Duration
partsAccess each part of the Duration
by calling to…Part
. These methods were added in Java 9 and later.
long days = d.toDaysPart() ;
int hours = d.toHoursPart() ;
int minutes = d.toMinutesPart() ;
int seconds = d.toSecondsPart() ;
int nanos = d.toNanosPart() ;
You can then assemble your own string from those parts.
The ISO 8601 standard defines textual formats for date-time values. For spans of time unattached to the timeline, the standard format is PnYnMnDTnHnMnS
. The P
marks the beginning, and the T
separates the years-month-days from the hours-minutes-seconds. So an hour and a half is PT1H30M
.
The java.time classes use ISO 8601 formats by default for parsing and generating strings. The Duration
and Period
classes use this particular standard format. So simply call toString
.
String output = d.toString();
PT4H20M
For alternate formatting, build your own String in Java 9 and later (not in Java 8) with the Duration::to…Part
methods. Or see this Answer for using regex to manipulate the ISO 8601 formatted string.
LocalTime
I strongly suggest using the standard ISO 8601 format instead of the extremely ambiguous and confusing clock format of 04:20
. But if you insist, you can get this effect by hacking with the LocalTime
class. This works if your duration is not over 24 hours.
LocalTime hackUseOfClockAsDuration = LocalTime.MIN.plus( d );
String output = hackUseOfClockAsDuration.toString();
04:20
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Use the SimpleDateFormat
class parse()
method. This method will return a Date
object. You can then create a Calendar
object for this Date
and add 2 hours to it.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = formatter.parse(theDateToParse);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, 2);
cal.getTime(); // This will give you the time you want.
You mean you want to add a new row and only put data in a certain column? Try the following:
var row = dataTable.NewRow();
row[myColumn].Value = "my new value";
dataTable.Add(row);
As it is a data table, though, there will always be data of some kind in every column. It just might be DBNull.Value
instead of whatever data type you imagine it would be.
With Swift 4, you can use the code below to get your app's home directory. Your app's document directory is in there.
print(NSHomeDirectory())
I think you already know that your app's home directory is changeable, so if you don't want to add additional code to your codebase, SimPholder is a nice tool for you.
And further more, you may wonder is there a tool, that can help you save time from closing and reopening same SQLite database every time after your app's home directory be changed. And the answer is yes, a tool I know is SQLiteFlow. From it's document, it says that:
Handle database file name or directory changes. This makes SQLiteFlow can work friendly with your SQLite database in iOS simulator.
I figured out this workaround:
>>> p = subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=subprocess.PIPE)
>>> p.stdin.write(b'one\ntwo\nthree\nfour\nfive\nsix\n') #expects a bytes type object
>>> p.communicate()[0]
'four\nfive\n'
>>> p.stdin.close()
Is there a better one?
Yes, you can do this by creating a DoubleStream
from the array, filtering out the negatives, and converting the stream back to an array. Here is an example:
double[] d = {8, 7, -6, 5, -4};
d = Arrays.stream(d).filter(x -> x > 0).toArray();
//d => [8, 7, 5]
If you want to filter a reference array that is not an Object[]
you will need to use the toArray
method which takes an IntFunction
to get an array of the original type as the result:
String[] a = { "s", "", "1", "", "" };
a = Arrays.stream(a).filter(s -> !s.isEmpty()).toArray(String[]::new);
It is worth noting that the accepted answer will round small floats down to zero.
>>> import numpy as np
>>> arr = np.asarray([2.92290007e+00, -1.57376965e-03, 4.82011728e-08, 1.92896977e-12])
>>> print(arr)
[ 2.92290007e+00 -1.57376965e-03 4.82011728e-08 1.92896977e-12]
>>> np.round(arr, 2)
array([ 2.92, -0. , 0. , 0. ])
You can use set_printoptions
and a custom formatter to fix this and get a more numpy-esque printout with fewer decimal places:
>>> np.set_printoptions(formatter={'float': "{0:0.2e}".format})
>>> print(arr)
[2.92e+00 -1.57e-03 4.82e-08 1.93e-12]
This way, you get the full versatility of format
and maintain the full precision of numpy's datatypes.
Also note that this only affects printing, not the actual precision of the stored values used for computation.
Your first problem was you weren't using your compare symbols correctly.
< less than
> greater than
<= less than or equal to
>= greater than or equal to
To answer your other questions; get the condition to work on every cell in the column and what about blanks?
What about blanks?
Add an extra IF
condition to check if the cell is blank or not, if it isn't blank perform the check. =IF(B2="","",B2<=TODAY())
Condition on every cell in column
It seems your solution is not much ugly. You can use functions and make it proffesional like these ways
new.function <- function(filename){
readChar(filename, file.info(filename)$size)
}
new.function('foo.txt')
new.function <- function(){
filename <- 'foo.txt'
return (readChar(filename, file.info(filename)$size))
}
new.function()
Found a way to do this, simply add a querystring to load your components, like so:
@Component({
selector: 'some-component',
templateUrl: `./app/component/stuff/component.html?v=${new Date().getTime()}`,
styleUrls: [`./app/component/stuff/component.css?v=${new Date().getTime()}`]
})
This should force the client to load the server's copy of the template instead of the browser's. If you would like it to refresh only after a certain period of time you could use this ISOString instead:
new Date().toISOString() //2016-09-24T00:43:21.584Z
And substring some characters so that it will only change after an hour for example:
new Date().toISOString().substr(0,13) //2016-09-24T00
Hope this helps
SELECT (cast(timestamp_1 as bigint) - cast(timestamp_2 as bigint)) FROM table;
In case if someone is having an issue using extract.
You can add escaped double quotes like this: String name = "\"john\"";
Besides raise Exception("message")
and raise
Python 3 introduced a new form, raise Exception("message") from e
. It's called exception chaining, it allows you to preserve the original exception (the root cause) with its traceback.
It's very similar to inner exceptions from C#.
More info: https://www.python.org/dev/peps/pep-3134/
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
You can use this way, but be sure that there is no Page.Redirect()
is used.
If you want to redirect to another page then you can try this:
page.aspx:
<asp:Button AccessKey="S" ID="submitBtn" runat="server" OnClick="Submit" Text="Submit"
Width="90px" ValidationGroup="vg" CausesValidation="true" OnClientClick = "Confirm()" />
JavaScript code:
function Confirm()
{
if (Page_ClientValidate())
{
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Data has been Added. Do you wish to Continue ?"))
{
confirm_value.value = "Yes";
}
else
{
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
}
and this is your code behind snippet :
protected void Submit(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
Response.Redirect("~/AddData.aspx");
}
else
{
Response.Redirect("~/ViewData.aspx");
}
}
This will sure work.
I realize this is an old question, and the OP is talking about using custom gx that aren't necessary 'checkbox'-looking, but there is a fantastic resource for generating custom colored assets here: http://kobroor.pl/
Just give it the relevant details and it spits out graphics, complete with xml resources, that you can just drop right in.
You can use the JsonTextReader
to read the JSON and iterate over the tokens:
using (var reader = new JsonTextReader(new StringReader(jsonText)))
{
while (reader.Read())
{
Console.WriteLine("{0} - {1} - {2}",
reader.TokenType, reader.ValueType, reader.Value);
}
}
As of docker-compose file version 3.2, you can specify a volume mount of type "bind" (instead of the default type "volume") that allows you to mount a single file into the container. Search for "bind mount" in the docker-compose volume docs: https://docs.docker.com/compose/compose-file/#volumes
In my case, I was trying to mount a single ".secrets" file into my application that contained secrets for local development and testing only. In production, my application fetches these secrets from AWS instead.
If I mounted this file as a volume using the shorthand syntax:
volumes:
- ./.secrets:/data/app/.secrets
Docker would create a ".secrets" directory inside the container instead of mapping to the file outside of the container. My code would then raise an error like "IsADirectoryError: [Errno 21] Is a directory: '.secrets'".
I fixed this by using the long-hand syntax instead, specifying my secrets file using a read-only "bind" volume mount:
volumes:
- type: bind
source: ./.secrets
target: /data/app/.secrets
read_only: true
Now Docker correctly mounts my .secrets file into the container, creating a file inside the container instead of a directory.
In case you don't have Linq, I solved it the following way:
private T[] GetArray<T>(IList<T> iList) where T: new()
{
var result = new T[iList.Count];
iList.CopyTo(result, 0);
return result;
}
Hope it helps
in "from queue import Queue
" there is no module called queue
, instead multiprocessing
should be used. Therefore, it should look like "from multiprocessing import Queue
"
Here's another way through the GUI that does exactly what your script does even though it goes through Indexes (not Constraints) in the object explorer.
To get only empty values (and not null values):
SELECT * FROM myTable WHERE myColumn = ''
To get both null and empty values:
SELECT * FROM myTable WHERE myColumn IS NULL OR myColumn = ''
To get only null values:
SELECT * FROM myTable WHERE myColumn IS NULL
To get values other than null and empty:
SELECT * FROM myTable WHERE myColumn <> ''
And remember use LIKE phrases only when necessary because they will degrade performance compared to other types of searches.
Another reason why this exception occurs is if you call the configure method twice on a Configuration
or AnnotatedConfiguration
object like this -
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(MyClass.class);
//Use this if config files are in src folder
config.configure();
//Use this if config files are in a subfolder of src, such as "resources"
config.configure("/resources/hibernate.cfg.xml");
Btw, this project structure is inside eclipse.
One might also consider os.path.commonprefix
that works on characters and thus can be used for any strings.
import os
common = os.path.commonprefix(['apple pie available', 'apple pies'])
assert common == 'apple pie'
As the function name indicates, this only considers the common prefix of two strings.
By the way, if you are trying to find a way to send double quotes to the device, try the following:
adb shell input text '\"'
I'm not sure why there's no event code for quotes, but this workaround does the job. Also, if you're using MonkeyDevice (or ChimpChat) you should test each caracter before invoking monkeyDevice.type, otherwise you get nothing when you try to send "
import re
htmlString = '</dd><dt> Fine, thank you. </dt><dd> Molt bé, gràcies. (<i>mohl behh, GRAH-syuhs</i>)'
SearchStr = '(\<\/dd\>\<dt\>)+ ([\w+\,\.\s]+)([\&\#\d\;]+)(\<\/dt\>\<dd\>)+ ([\w\,\s\w\s\w\?\!\.]+) (\(\<i\>)([\w\s\,\-]+)(\<\/i\>\))'
Result = re.search(SearchStr.decode('utf-8'), htmlString.decode('utf-8'), re.I | re.U)
print Result.groups()
Works that way. The expression contains non-latin characters, so it usually fails. You've got to decode into Unicode and use re.U (Unicode) flag.
I'm a beginner too and I faced that issue a couple of times myself.
The var
keyword is used to declare variables in a class in PHP 4:
class Foo {
var $bar;
}
With PHP 5 property and method visibility (public
, protected
and private
) was introduced and thus var
is deprecated.
I had the same issue. I wanted to send data via POST. I used the following code:
URL url = new URL("http://example.com/getval.php");
Map<String,Object> params = new LinkedHashMap<>();
params.put("param1", param1);
params.put("param2", param2);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
String urlParameters = postData.toString();
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
String result = "";
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
result += line;
}
writer.close();
reader.close()
System.out.println(result);
I used Jsoup for parse:
Document doc = Jsoup.parseBodyFragment(value);
Iterator<Element> opts = doc.select("option").iterator();
for (;opts.hasNext();) {
Element item = opts.next();
if (item.hasAttr("value")) {
System.out.println(item.attr("value"));
}
}
last-child pseudo class does not work in IE
Here is an alternative way to get an object's property value:
write-host $(get-something).SomeProp
Use repr
and eval
:
>>> s = set([1,2,3])
>>> strs = repr(s)
>>> strs
'set([1, 2, 3])'
>>> eval(strs)
set([1, 2, 3])
Note that eval
is not safe if the source of string is unknown, prefer ast.literal_eval
for safer conversion:
>>> from ast import literal_eval
>>> s = set([10, 20, 30])
>>> lis = str(list(s))
>>> set(literal_eval(lis))
set([10, 20, 30])
help on repr
:
repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.
You may just without making the element hidden, simply make it transparent by making its opacity to 0.
Making the input file hidden will make it STOP working. So DON'T DO THAT..
Here you can find an example for a transparent Browse operation;
Have a look at Knockout-Validation which cleanly setups and uses what's described in the knockout documentation. Under: Live Example 1: Forcing input to be numeric
You can see it live in Fiddle
UPDATE: the fiddle has been updated to use the latest KO 2.0.3 and ko.validation 1.0.2 using the cloudfare CDN urls
To setup ko.validation:
ko.validation.rules.pattern.message = 'Invalid.';
ko.validation.configure({
registerExtenders: true,
messagesOnModified: true,
insertMessages: true,
parseInputAttributes: true,
messageTemplate: null
});
To setup validation rules, use extenders. For instance:
var viewModel = {
firstName: ko.observable().extend({ minLength: 2, maxLength: 10 }),
lastName: ko.observable().extend({ required: true }),
emailAddress: ko.observable().extend({ // custom message
required: { message: 'Please supply your email address.' }
})
};
In my case (IntelliJ 2020-02, Kotlin dev) JUnit library was already included by Create project wizard. I needed to enable JUnit plugin:
to get green Run test icons next to each test class and method:
and CTRL+Shift+R will run test under caret, and CTRL+shift+D to debug.
Does "pure HTML/CSS" exclude the use of tables? Because they will easily do what you want:
<table>
<tr>
<td valign="top"><img src="myImage.jpg" alt="" /></td>
<td valign="middle">This is my text!</td>
</tr>
</table>
Flame me all you like, but that works (and works in old, janky browsers).
read
with IFS
are perfect for this:
$ IFS=- read var1 var2 <<< ABCDE-123456
$ echo "$var1"
ABCDE
$ echo "$var2"
123456
Edit:
Here is how you can read each individual character into array elements:
$ read -a foo <<<"$(echo "ABCDE-123456" | sed 's/./& /g')"
Dump the array:
$ declare -p foo
declare -a foo='([0]="A" [1]="B" [2]="C" [3]="D" [4]="E" [5]="-" [6]="1" [7]="2" [8]="3" [9]="4" [10]="5" [11]="6")'
If there are spaces in the string:
$ IFS=$'\v' read -a foo <<<"$(echo "ABCDE 123456" | sed 's/./&\v/g')"
$ declare -p foo
declare -a foo='([0]="A" [1]="B" [2]="C" [3]="D" [4]="E" [5]=" " [6]="1" [7]="2" [8]="3" [9]="4" [10]="5" [11]="6")'
for anyone who's using react-moment
:
simply use format
prop to your needed format:
const now = new Date()
<Moment format="DD/MM/YYYY">{now}</Moment>
This may be useful to someone:
If you already got jQuery but still get this error, check you include jQuery before the js that uses it, specially if you use @RenderBody() in ASP.NET C#
You have to include jQuery before the @RenderBody() if you include the js inside the view that @RenderBody() calls.
If you are using Dot.Net then the code you need is
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache)
Click my name if you want the code to delete these files plus FireFox temp files and Flash shared object/Flash Cookies
I think it's a great way to do it. Not limited to express but I've seen quite a number of node.js projects on github doing the same thing. They take out the configuration parameters + smaller modules (in some cases every URI) are factored in separate files.
I would recommend going through express-specific projects on github to get an idea. IMO the way you are doing is correct.
You need a click listener which calls addActivityItem
if less than 2 options exist:
var activities = document.getElementById("activitySelector");
activities.addEventListener("click", function() {
var options = activities.querySelectorAll("option");
var count = options.length;
if(typeof(count) === "undefined" || count < 2)
{
addActivityItem();
}
});
activities.addEventListener("change", function() {
if(activities.value == "addNew")
{
addActivityItem();
}
});
function addActivityItem() {
// ... Code to add item here
}
A live demo is here on JSfiddle.
You don't apply a binary mask to an image. You (optionally) use a binary mask in a processing function call to tell the function which pixels of the image you want to process. If I'm completely misinterpreting your question, you should add more detail to clarify.
Man pages for diff
suggest no solution for colorization from within itself. Please consider using colordiff
. It's a wrapper around diff
that produces the same output as diff, except that it augments the output using colored syntax highlighting to increase readability:
diff old new | colordiff
or just:
colordiff old new
Installation:
sudo apt-get install colordiff
brew install colordiff
or port install colordiff
If you define your function to take argument of std::vector<int>& arr
and integer value, then you can use push_back
inside that function:
void do_something(int el, std::vector<int>& arr)
{
arr.push_back(el);
//....
}
usage:
std::vector<int> arr;
do_something(1, arr);
How to fix breakpoint error when debugging in Eclipse? Replace what you have with this lines only.
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.8
Since you are new to Android development you may not know about Content Providers, which are database abstractions. They may not be the right thing for your project, but you should check them out: http://developer.android.com/guide/topics/providers/content-providers.html
A very easy to understand description is the documentation of yuml, with examples for class diagrams, use cases, and activities.
id + runat="server" leads to accessible at the server
Give in the xml file of your layout android:scaleType="fitXY"
P.S : this applies to when the image is set with android:src="..."
rather than android:background="..."
as backgrounds are set by default to stretch and fit to the View.
From cran, you can install directly from a github repository address. So if you want the package at https://github.com/twitter/AnomalyDetection
:
library(devtools)
install_github("twitter/AnomalyDetection")
does the trick.
Simply remove the dot for the relative import and do:
from p_02_paying_debt_off_in_a_year import compute_balance_after
You can do following
<div id="circle"></div>
CSS
#circle {
width: 100px;
height: 100px;
background: red;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
}
Other shape SOURCE
It's even possible to restore without creating a blank database at all.
In Sql Server Management Studio, right click on Databases and select Restore Database...
In the Restore Database dialog, select the Source Database or Device as normal. Once the source database is selected, SSMS will populate the destination database name based on the original name of the database.
It's then possible to change the name of the database and enter a new destination database name.
With this approach, you don't even need to go to the Options tab and click the "Overwrite the existing database" option.
Also, the database files will be named consistently with your new database name and you still have the option to change file names if you want.
Suppose I have the following table T
:
a b
--------
1 abc
1 def
1 ghi
2 jkl
2 mno
2 pqr
And I do the following query:
SELECT a, b
FROM T
GROUP BY a
The output should have two rows, one row where a=1
and a second row where a=2
.
But what should the value of b show on each of these two rows? There are three possibilities in each case, and nothing in the query makes it clear which value to choose for b in each group. It's ambiguous.
This demonstrates the single-value rule, which prohibits the undefined results you get when you run a GROUP BY query, and you include any columns in the select-list that are neither part of the grouping criteria, nor appear in aggregate functions (SUM, MIN, MAX, etc.).
Fixing it might look like this:
SELECT a, MAX(b) AS x
FROM T
GROUP BY a
Now it's clear that you want the following result:
a x
--------
1 ghi
2 pqr
Sure, for windows
you can use:
$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("C:/path/to/php-win.exe -f C:/path/to/script.php", 0, false);
Note:
If you get a COM
error, add the extension to your php.ini
and restart apache
:
[COM_DOT_NET]
extension=php_com_dotnet.dll
I don't know if it is possible in Java, but in .NET the property StaticLogFileName on RollingFileAppender gives you what you want. The default is true.
<staticLogFileName value="false"/>
Full config:
<appender name="DefaultFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="application"/>
<staticLogFileName value="false"/>
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyy-MM-dd".log"" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
".log"
is for not letting the dateformat recognice the global date pattern 'g' in log.
You can use http_build_query()
to do that.
Generates a URL-encoded query string from the associative (or indexed) array provided.
You can change the size of the plot by adding this before you create the figure.
plt.rcParams["figure.figsize"] = [16,9]
you could use a cursor:
DECLARE @id int
DECLARE @pass varchar(100)
DECLARE cur CURSOR FOR SELECT Id, Password FROM @temp
OPEN cur
FETCH NEXT FROM cur INTO @id, @pass
WHILE @@FETCH_STATUS = 0 BEGIN
EXEC mysp @id, @pass ... -- call your sp here
FETCH NEXT FROM cur INTO @id, @pass
END
CLOSE cur
DEALLOCATE cur
It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.
In Web API, it's very simple to remember how parameter binding is happening.
POST
simple types, Web API tries to bind it from the URL if you POST
complex type, Web API tries to bind it from the body of
the request (this uses a media-type
formatter).
If you want to bind a complex type from the URL, you'll use [FromUri]
in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.
public IHttpActionResult Put([FromUri] ViewModel data) { ... }
If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.
public IHttpActionResult Put([FromBody] string name) { ... }
as a side note, say you are making a PUT
request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data
parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.
var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});
and your web api action will look something like below.
public IHttpActionResult Put([FromBody] string name){ ... }
This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
One more important thing needs to be highlighted. It's better to use params
because it is better for performance. When you call a method with params
argument and passed to it nothing:
public void ExampleMethod(params string[] args)
{
// do some stuff
}
call:
ExampleMethod();
Then a new versions of the .Net Framework do this (from .Net Framework 4.6):
ExampleMethod(Array.Empty<string>());
This Array.Empty
object can be reused by framework later, so there are no needs to do redundant allocations. These allocations will occur when you call this method like this:
ExampleMethod(new string[] {});
For whatever reason the above would not work for me. This is what did:
if (tabControl.SelectedTab.Name == "tabName" )
{
.. do stuff
}
where tabControl.SelectedTab.Name is the name attribute assigned to the page in the tabcontrol itself.
String arr= "[1,2]";
List<Integer> arrList= JSON.parseArray(arr,Integer.class).stream().collect(Collectors.toList());
Integer[] intArr = ArrayUtils.toObject(arrList.stream().mapToInt(Integer::intValue).toArray());
Cookies are passed as HTTP headers, both in the request (client -> server), and in the response (server -> client).
You can index and use a negative sign to drop the 3rd column:
data[,-3]
Or you can list only the first 2 columns:
data[,c("c1", "c2")]
data[,1:2]
Don't forget the comma and referencing data frames works like this: data[row,column]
As Already mentioned we have two ways!
And it's done interactively! And take effect immediately!
CTRL + A followed by : And we type scrollback 1000000
And hit ENTER
You detach from the screen and come back! It will be always the same.
You open another new screen! And the value is reset again to default! So it's not a global setting!
Which is done by adding defscrollback 1000000
to .screenrc
(in home)
defscrollback
and not scrollback
(def stand for default)
What you need to know is if the file is not created ! You create it !
> cd ~ && vim .screenrc
And you add defscrollback 1000000
to it!
Or in one command
> echo "defscrollback 1000000" >> .screenrc
(if not created already)
When you add the default to .screenrc
! The already running screen at re-attach will not take effect! The .screenrc
run at the screen creation! And it make sense! Just as with a normal console and shell launch!
And all the new created screens will have the set value!
To check type CTRL + A followed by i
And The result will be as
Importantly the buffer size is the number after the + sign
(in the illustration i set it to 1 000 000)
Note too that when you change it interactively! The effect is immediate and take over the default value!
CTRL+ A followed by ESC (to enter the copy mode).
Then navigate with Up,Down or PgUp PgDown
And ESC again to quit that mode.
(Extra info: to copy hit ENTER to start selecting! Then ENTER again to copy! Simple and cool)
Now the buffer is bigger!
And that's sum it up for the important details!
Turn off your firewall for port 80 from any address. Turn off 443 if you need https (SSL) access. Open the configuration file (http.conf
) and find the lines that say:
Allow from 127.0.0.1
Change them to read
Allow from all
Restart the wampserver. It will now work. Enjoy!!
You can use the standard HTTP_PROXY
environment var. Simply set it to the URL of your proxy. Many operating systems already set this variable for you.
Just export the variable, then you don't have to type it all the time.
export HTTP_PROXY="http://johndoeproxy.cu:8080"
Then you can do composer update
normally.
Using CSS you can just set display:none for the element in a CSS file or in a style attribute
#div { display:none; }
<div id="div"></div>
<div style="display:none"></div>
or having the js just after the div might be fast enough too, but not as clean
There are various ways to make it done, very simple technique with security peace in mind, here might help you
1. First you need to install Flask
pip install flask
in your command prompt, which is a python microframework, don't be afraid that you need to have another prior knowledge to learn that, it's really simple and just a few line of code.
If you wish you learn Flask quickly for complete novice here is the tutorial that I also learn from Flask Tutorial for beginner (YouTube)
2.Create a new folder
- 1st file will be
server.py
from flask import Flask, render_template_x000D_
app = Flask(__name__)_x000D_
_x000D_
@app.route('/')_x000D_
def index():_x000D_
return render_template('index.html')_x000D_
_x000D_
@app.route('/my-link/')_x000D_
def my_link():_x000D_
print ('I got clicked!')_x000D_
_x000D_
return 'Click.'_x000D_
_x000D_
if __name__ == '__main__':_x000D_
app.run(debug=True)
_x000D_
-2nd create another subfolder inside previous folder and name it as templates file will be your html file
index.html
<!doctype html>_x000D_
_x000D_
_x000D_
<head><title>Test</title> _x000D_
<meta charset=utf-8> </head>_x000D_
<body>_x000D_
<h1>My Website</h1>_x000D_
<form action="/my-link/">_x000D_
<input type="submit" value="Click me" />_x000D_
</form>_x000D_
_x000D_
<button> <a href="/my-link/">Click me</a></button>_x000D_
_x000D_
</body>
_x000D_
3.. To run, open command prompt to the New folder directory, type python server.py
to run the script, then go to browser type localhost:5000
, then you will see button. You can click and route to destination script file you created.
Hope this helpful. thank you.
edit your ~/.vimrc
$ vim ~/.vimrc
add following lines :
set tabstop=4
set shiftwidth=4
set softtabstop=4
set expandtab
Solution with awk:
awk '{if ($1 ~ /^all/) print $0, "anotherthing"; else print $0}' file
Simply: if the row starts with all
print the row plus "anotherthing", else print just the row.
If you didn't specify a different fileformat
intentionally (say, :e ++ff=unix
for a Windows file), it's likely that the target file has mixed EOLs.
For example, if a file has some lines with <CR><NL>
endings and others with
<NL>
endings, and fileformat
is set to unix
automatically by Vim when reading it, ^M (<CR>)
will appear.
In such cases, fileformats
(note: there's an extra s
) comes into play. See :help ffs
for the details.
Simple code please check
SELECT * FROM table_name WHERE created <= (NOW() - INTERVAL 1 MONTH)
$("a").click(function(){
alert('disabled');
return false;
});
There is no such functionality in jQuery. Use JSON.stringify
or alternatively any jQuery plugin with similar functionality (e.g jquery-json).
As this rightly stated
__proto__
is the actual object that is used in the lookup chain to resolve methods, etc. prototype is the object that is used to build__proto__
when you create an object with new:( new Foo ).__proto__ === Foo.prototype; ( new Foo ).prototype === undefined;
We can further note that __proto__
property of an object created using function constructor points towards the memory location pointed towards by prototype property of that respective constructor.
If we change the memory location of prototype of constructor function, __proto__
of derived object will still continue to point towards the original address space. Therefore to make common property available down the inheritance chain, always append property to constructor function prototype, instead of re-initializing it (which would change its memory address).
Consider the following example:
function Human(){
this.speed = 25;
}
var himansh = new Human();
Human.prototype.showSpeed = function(){
return this.speed;
}
himansh.__proto__ === Human.prototype; //true
himansh.showSpeed(); //25
//now re-initialzing the Human.prototype aka changing its memory location
Human.prototype = {lhs: 2, rhs:3}
//himansh.__proto__ will still continue to point towards the same original memory location.
himansh.__proto__ === Human.prototype; //false
himansh.showSpeed(); //25
expand
is a unix utility to convert tabs to spaces. If you do not want to set
anything in vim, you can use a shell command from vim:
:!% expand -t8
If you are using pip 19.0.3
and python 3.7.4
. Then go for pip list
command in your virtualenv. It will show all the installed packages with respective versions.
I spotted half of the problem: I can't use the 'indexer' notation to objects (my_object[0]). Is there a way to bypass it?
No; an object literal, as the name implies, is an object, and not an array, so you cannot simply retrieve a property based on an index, since there is no specific order of their properties. The only way to retrieve their values is by using the specific name:
var someVar = options.filters.firstName; //Returns 'abc'
Or by iterating over them using the for ... in
loop:
for(var p in options.filters) {
var someVar = options.filters[p]; //Returns the property being iterated
}
Try this simple select:
select *
from artists
where name like "a%"
You would use the focus
and blur
events of the window:
var interval_id;
$(window).focus(function() {
if (!interval_id)
interval_id = setInterval(hard_work, 1000);
});
$(window).blur(function() {
clearInterval(interval_id);
interval_id = 0;
});
To Answer the Commented Issue of "Double Fire" and stay within jQuery ease of use:
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
// do work
break;
case "focus":
// do work
break;
}
}
$(this).data("prevType", e.type);
})
Click to view Example Code Showing it working (JSFiddle)
We use Oracle PL/SQL Developer(Version 12.0.7). And we use F5 button to view the explain plan.
To change the default property for your entire MATLAB session, see the documentation on how default properties are handled.
As an example:
set(0,'DefaultAxesFontSize',22)
x=1:200; y=sin(x);
plot(x,y)
title('hello'); xlabel('x'); ylabel('sin(x)')
It worked for me, but the exe4j can leave a signature when you double click the .exe application
You can use csvreader api & download from following location:
http://sourceforge.net/projects/javacsv/files/JavaCsv/JavaCsv%202.1/javacsv2.1.zip/download
or
http://sourceforge.net/projects/javacsv/
Use the following code:
/ ************ For Reading ***************/
import java.io.FileNotFoundException;
import java.io.IOException;
import com.csvreader.CsvReader;
public class CsvReaderExample {
public static void main(String[] args) {
try {
CsvReader products = new CsvReader("products.csv");
products.readHeaders();
while (products.readRecord())
{
String productID = products.get("ProductID");
String productName = products.get("ProductName");
String supplierID = products.get("SupplierID");
String categoryID = products.get("CategoryID");
String quantityPerUnit = products.get("QuantityPerUnit");
String unitPrice = products.get("UnitPrice");
String unitsInStock = products.get("UnitsInStock");
String unitsOnOrder = products.get("UnitsOnOrder");
String reorderLevel = products.get("ReorderLevel");
String discontinued = products.get("Discontinued");
// perform program logic here
System.out.println(productID + ":" + productName);
}
products.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Write / Append to CSV file
Code:
/************* For Writing ***************************/
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import com.csvreader.CsvWriter;
public class CsvWriterAppendExample {
public static void main(String[] args) {
String outputFile = "users.csv";
// before we open the file check to see if it already exists
boolean alreadyExists = new File(outputFile).exists();
try {
// use FileWriter constructor that specifies open for appending
CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true), ',');
// if the file didn't already exist then we need to write out the header line
if (!alreadyExists)
{
csvOutput.write("id");
csvOutput.write("name");
csvOutput.endRecord();
}
// else assume that the file already has the correct header line
// write out a few records
csvOutput.write("1");
csvOutput.write("Bruce");
csvOutput.endRecord();
csvOutput.write("2");
csvOutput.write("John");
csvOutput.endRecord();
csvOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It's not clear what you want, or whether you want this trick to work with different targets, or whether you've defined these targets elsewhere, or what version of Make you're using, but what the heck, I'll go out on a limb:
ifeq (yes, ${TEST})
CXXFLAGS := ${CXXFLAGS} -DDESKTOP_TEST
test:
$(info ************ TEST VERSION ************)
else
release:
$(info ************ RELEASE VERSIOIN **********)
endif
Just add click event by jquery in $(document).ready() like :
$(document).ready(function(){
$('#YourControlID').click(function(){
if(Check your condtion)
{
$.messager.show({
title:'My Title',
msg:'The message content',
showType:'fade',
style:{
right:'',
bottom:''
}
});
}
});
});
Old question and all of that. But this is yet another way that offers some advantages.
On Windows, you could ask the task scheduler to start your app again for you. This has the advantage of waiting a specific amount of time before the app is restarted. You can go to task manager and delete the task and it stops repeating.
SimpleDateFormat hhmm = new SimpleDateFormat("kk:mm");
Calendar aCal = Calendar.getInstance();
aCal.add(Calendar.SECOND, 65);
String nextMinute = hhmm.format(aCal.getTime()); //Task Scheduler Doesn't accept seconds and won't do current minute.
String[] create = {"c:\\windows\\system32\\schtasks.exe", "/CREATE", "/F", "/TN", "RestartMyProg", "/SC", "ONCE", "/ST", nextMinute, "/TR", "java -jar c:\\my\\dev\\RestartTest.jar"};
Process proc = Runtime.getRuntime().exec(create, null, null);
System.out.println("Exit Now");
try {Thread.sleep(1000);} catch (Exception e){} // just so you can see it better
System.exit(0);
$('#usersSearch').keyup(function() { // handle keyup event on search input field
var key = e.which || e.keyCode; // store browser agnostic keycode
if(key == 13)
$(this).closest('form').submit(); // submit parent form
}
S3 doesn't have a folder structure, But there is something called as keys.
We can create /2013/11/xyz.xls
and will be shown as folder's in the console. But the storage part of S3 will take that as the file name.
Even when retrieving we observe that we can see files in particular folder (or keys) by using the ListObjects
method and using the Prefix
parameter.
So you are doing this a bit backwards. Typically you'd do something like this:
?<div class='article'>
Article 1
</div>
<div class='article'>
Article 2
</div>
<div class='article'>
Article 3
</div>?
And then in your jQuery:
$('.article').click(function(){
article = $(this).text(); //$(this) is what you clicked!
});?
When I see things like #search-item .search-article
, #search-item .search-article
, and #search-item .search-article
I sense you are overspecifying your CSS which makes writing concise jQuery very difficult. This should be avoided if at all possible.
The checked
and selected
attributes are allowed only two values, which are a copy of the attribute name and (from HTML 5 onwards) an empty string. Giving any other value is an error.
If you don't want to set the attribute, then the entire attribute must be omitted.
Note that in HTML 4 you may omit everything except the value. HTML 5 changed this to omit everything except the name (which makes no practical difference).
Thus, the complete (aside from variations in cAsE) set of valid representations of the attribute are:
<input ... checked="checked"> <!-- All versions of HTML / XHTML -->
<input ... checked > <!-- Only HTML 4.01 and earlier -->
<input ... checked > <!-- Only HTML 5 and later -->
<input ... checked="" > <!-- Only HTML 5 and later -->
Documents served as text/html (HTML or XHTML) will be fed through a tag soup parser, and the presence of a checked attribute (with any value) will be treated as "This element should be checked". Thus, while invalid, checked="true"
, checked="yes"
, and checked="false"
will all trigger the checked state.
I've not had any inclination to find out what error recovery mechanisms are in place for XML parsing mode should a different value be given to the attribute, but I would expect that the legacy of HTML and/or simple error recovery would treat it in the same way: If the attribute is there then the element is checked.
(And all the above applies equally to selected
as it does to checked
.)
I encountered this error when the JDK that I compiled the app under was different from the tomcat JVM. I verified that the Tomcat manager was running jvm 1.6.0 but the app was compiled under java 1.7.0.
After upgrading Java and changing JAVA_HOME in our startup script (/etc/init.d/tomcat) the error went away.
The reason it doesn't work because some value you passed to the function isn't correct. swift doesn't like Objective-C, you can put nil to arguments which are class type without any restriction(might be). Argument otherButtonTitles is defined as non-optional which its type do not have (?)at its end. so you must pass a concrete value to it.
In your Project properties(Right click on project, click on property button) ? Configuration Properties ? Build Events ? Post Build Events ? Command Line.
Edit and add one instruction to command line. for example copy botan.dll from source path to location where is being executed the program.
copy /Y "$(SolutionDir)ProjectDirs\x64\Botan\lib\botan.dll" "$(TargetDir)"
$alphabets = range('A', 'Z');
$doubleAlphabets = array();
$count = 0;
foreach($alphabets as $key => $alphabet)
{
$count++;
$letter = $alphabet;
while ($letter <= 'Z')
{
$doubleAlphabets[] = $letter;
++$letter;
}
}
return $doubleAlphabets;
Passing arguments between fragments.
This is a fairly late to answer this question but it could help someone!
Fragment_1.java
Bundle i = new Bundle();
i.putString("name", "Emmanuel");
Fragment_1 frag = new Fragment_1();
frag.setArguments(i);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new Fragment_2())
.commit();
Then in your Fragment_2.java
you can get the paramaters normally within your onActivityCreated
e.g
Intent intent = getActivity().getIntent();
if (intent.getExtras() != null) {
String name =intent.getStringExtra("name");
}
Using lapply and grep:
lst <- list(a = 1:4, b = 4:8, c = 8:10)
# say you want to remove a and c
toremove<-c("a","c")
lstnew<-lst[-unlist(lapply(toremove, function(x) grep(x, names(lst)) ) ) ]
#or
pattern<-"a|c"
lstnew<-lst[-grep(pattern, names(lst))]
Firstly, there is a difference. For numbers
> 2 == 2.0
True
> 2.Equals(2.0)
False
And for strings
> string x = null;
> x == null
True
> x.Equals(null)
NullReferenceException
In both cases, ==
behaves more usefully than .Equals
You could put static elements after the fields and show them, or you could inject the validation message dynamically. See the below example for how to inject dynamically.
This example also follows the best practice of setting focus to the blank field so user can easily correct the issue.
Note that you could easily genericize this to work with any label & field (for required fields anyway), instead of my example which specifically codes each validation.
Your fiddle is updated, see here: jsfiddle
The code:
$('form').on('submit', function (e) {
var focusSet = false;
if (!$('#email').val()) {
if ($("#email").parent().next(".validation").length == 0) // only add if not added
{
$("#email").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter email address</div>");
}
e.preventDefault(); // prevent form from POST to server
$('#email').focus();
focusSet = true;
} else {
$("#email").parent().next(".validation").remove(); // remove it
}
if (!$('#password').val()) {
if ($("#password").parent().next(".validation").length == 0) // only add if not added
{
$("#password").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter password</div>");
}
e.preventDefault(); // prevent form from POST to server
if (!focusSet) {
$("#password").focus();
}
} else {
$("#password").parent().next(".validation").remove(); // remove it
}
});
The CSS:
.validation
{
color: red;
margin-bottom: 20px;
}
Here is a sed solution:
sed '/19:55/{
N
N
N
N
N
s/\n/ /g
}' file.txt
$('#parent2').prepend($('#table1_length')).prepend($('#table1_filter'));
doesn't work for you? I think it should...
Best answer of that question I've seen is:
list(, $caller) = debug_backtrace(false);
Short and clean
Works for any number from 0 to 999999999.
This program gets a number from the user, divides it into three parts and stores them separately in an array. The three numbers are passed through a function that convert them into words. Then it adds "million" to the first part and "thousand" to the second part.
#include <iostream>
using namespace std;
int buffer = 0, partFunc[3] = {0, 0, 0}, part[3] = {0, 0, 0}, a, b, c, d;
long input, nFake = 0;
const char ones[][20] = {"", "one", "two", "three",
"four", "five", "six", "seven",
"eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"};
const char tens[][20] = {"", "ten", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"};
void convert(int funcVar);
int main() {
cout << "Enter the number:";
cin >> input;
nFake = input;
buffer = 0;
while (nFake) {
part[buffer] = nFake % 1000;
nFake /= 1000;
buffer++;
}
if (buffer == 0) {
cout << "Zero.";
} else if (buffer == 1) {
convert(part[0]);
} else if (buffer == 2) {
convert(part[1]);
cout << " thousand,";
convert(part[0]);
} else {
convert(part[2]);
cout << " million,";
if (part[1]) {
convert(part[1]);
cout << " thousand,";
} else {
cout << "";
}
convert(part[0]);
}
system("pause");
return (0);
}
void convert(int funcVar) {
buffer = 0;
if (funcVar >= 100) {
a = funcVar / 100;
b = funcVar % 100;
if (b)
cout << " " << ones[a] << " hundred and";
else
cout << " " << ones[a] << " hundred ";
if (b < 20)
cout << " " << ones[b];
else {
c = b / 10;
cout << " " << tens[c];
d = b % 10;
cout << " " << ones[d];
}
} else {
b = funcVar;
if (b < 20)
cout << ones[b];
else {
c = b / 10;
cout << tens[c];
d = b % 10;
cout << " " << ones[d];
}
}
}
You can easily write the method to do that :
public static String toCamelCase(final String init) {
if (init == null)
return null;
final StringBuilder ret = new StringBuilder(init.length());
for (final String word : init.split(" ")) {
if (!word.isEmpty()) {
ret.append(Character.toUpperCase(word.charAt(0)));
ret.append(word.substring(1).toLowerCase());
}
if (!(ret.length() == init.length()))
ret.append(" ");
}
return ret.toString();
}
jQuery.post(post_url,{ content: "John" } )_x000D_
.done(function( data ) {_x000D_
_x000D_
_x000D_
});_x000D_
_x000D_
I used the technique what u have replied above, it works fine but my problem is i need to generate a pdf conent using john as text . I have been able to echo the passed data. but getting empty in when generating pdf uisng below content ples check
ob_start();_x000D_
_x000D_
include_once(JPATH_SITE .'/components/com_gaevents/pdfgenerator.php');_x000D_
$content = ob_get_clean();_x000D_
_x000D_
_x000D_
_x000D_
$test = $_SESSION['content'] ;_x000D_
_x000D_
require_once(JPATH_SITE.'/html2pdf/html2pdf.class.php');_x000D_
$html2pdf = new HTML2PDF('P', 'A4', 'en', true, 'UTF-8',0 ); _x000D_
$html2pdf->setDefaultFont('Arial');_x000D_
$html2pdf->WriteHTML($test);
_x000D_
For example, say you were creating a web application to list and display recipes. You might want your customers to be able to sort the list, display features of the recipes, and so on before they choose the recipe to open. In order to do this, you need to associate things like cooking time, primary ingredient, meal position, and so on right inside the list elements for the recipes.
<li><a href="recipe1.html">Borscht</a></li>
<li><a href="recipe2.html">Chocolate Mousse</a></li>
<li><a href="recipe3.html">Almond Radiccio Salad</a></li>
<li><a href="recipe4.html">Deviled Eggs</a></li>
In order to get that information into the page, you could do many different things. You could add comments to each LI element, you could add rel attributes to the list items, you could place all the recipes in separate folders based on time, meal, and ingredient (i.e. ). The solution that most developers took was to use class attributes to store information about the current element. This has several advantages:
But there are some major drawbacks to this method:
All the other methods I suggested had these problems as well as others. But since it was the only way to quickly and easily include data, that’s what we did. HTML5 Data Attributes to the Rescue
HTML5 added a new type of attribute to any element—the custom data element (data-*). These are custom (denoted by the *) attributes that you can add to your HTML elements to define any type of data you want. They consist of two parts:
Attribute Name This is the name of the attribute. It must be at least one lowercase character and have the prefix data-. For example: data-main-ingredient, data-cooking-time, data-meal. This is the name of your data.
Attribute Vaule Like any other HTML attribute, you include the data itself in quotes separated by an equal sign. This data can be any string that is valid on a web page. For example: data-main-ingredient="chocolate".
You can then apply these data attributes to any HTML element you want. For example, you could define the information in the example list above:
<li data-main-ingredient="beets" data-cooking-time="1 hour" data-meal="dinner"><a href="recipe1.html">Borscht</a></li>
<li data-main-ingredient="chocolate" data-cooking-time="30 minutes" data-meal="dessert"><a href="recipe2.html">Chocolate Mousse</a></li>
<li data-main-ingredient="radiccio" data-cooking-time="20 minutes" data-meal="dinner"><a href="recipe1.html">Almond Radiccio Salad</a></li>
<li data-main-ingredient="eggs" data-cooking-time="15 minutes" data-meal="appetizer"><a href="recipe1.html">Deviled Eggs</a></li>
Once you have that information in your HTML, you will be able to access it with JavaScript and manipulate the page based on that data.
try with:
div.myclass { margin-top: 100%; }
try changing the % to fix it. Example: 120% or 90% ...etc.
You should install IIS sub components from
Control Panel
-> Programs and Features
-> Turn Windows features on or off
Internet Information Services
has subsection World Wide Web Services
/ Application Development Features
There you must check ASP.NET
(.NET Extensibility
, ISAPI Extensions
, ISAPI Filters
will be selected automatically). Double check that specific versions are checked. Under Windows Server 2012 R2, these options are split into 4 & 4.5.
Run from cmd
:
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir
Finally check in IIS manager, that your application uses application pool with .NET framework version v4.0.
Also, look at this answer.
In addition to bchhun's great answer, if you want absoulte positioning, you can do this
var options = {
placement: function (context, source) {
setTimeout(function () {
$(context).css('top',(source.getBoundingClientRect().top+ 500) + 'px')
},0)
return "top";
},
trigger: "click"
};
$(".infopoint").popover(options);
a = ''
b = ' '
a.isspace() -> False
b.isspace() -> True
Chrome, Safari, and IE 8+ come with built-in consoles (as part of a larger set of development tools). If you're using Firefox, getfirebug.com.
When you reference Range like that it's called an unqualified reference because you don't specifically say which sheet the range is on. Unqualified references are handled by the "_Global" object that determines which object you're referring to and that depends on where your code is.
If you're in a standard module, unqualified Range will refer to Activesheet. If you're in a sheet's class module, unqualified Range will refer to that sheet.
inputTemplateContent is a variable that contains a reference to a range, probably a named range. If you look at the RefersTo property of that named range, it likely points to a sheet other than the Activesheet at the time the code executes.
The best way to fix this is to avoid unqualified Range references by specifying the sheet. Like
With ThisWorkbook.Worksheets("Template")
.Range(inputTemplateHeader).Value = NO_ENTRY
.Range(inputTemplateContent).Value = NO_ENTRY
End With
Adjust the workbook and worksheet references to fit your particular situation.
IDE: The MS Office of Programming. It's where you type your code, plus some added features to make you a happier programmer. (e.g. Eclipse, Netbeans). Car body: It's what you really touch, see and work on.
Library: A library is a collection of functions, often grouped into multiple program files, but packaged into a single archive file. This contains programs created by other folks, so that you don't have to reinvent the wheel. (e.g. junit.jar, log4j.jar). A library generally has a key role, but does all of its work behind the scenes, it doesn't have a GUI. Car's engine.
API: The library publisher's documentation. This is how you should use my library. (e.g. log4j API, junit API). Car's user manual - yes, cars do come with one too!
What is a kit? It's a collection of many related items that work together to provide a specific service. When someone says medicine kit, you get everything you need for an emergency: plasters, aspirin, gauze and antiseptic, etc.
SDK: McDonald's Happy Meal. You have everything you need (and don't need) boxed neatly: main course, drink, dessert and a bonus toy. An SDK is a bunch of different software components assembled into a package, such that they're "ready-for-action" right out of the box. It often includes multiple libraries and can, but may not necessarily include plugins, API documentation, even an IDE itself. (e.g. iOS Development Kit).
Toolkit: GUI. GUI. GUI. When you hear 'toolkit' in a programming context, it will often refer to a set of libraries intended for GUI development. Since toolkits are UI-centric, they often come with plugins (or standalone IDE's) that provide screen-painting utilities. (e.g. GWT)
Framework: While not the prevalent notion, a framework can be viewed as a kit. It also has a library (or a collection of libraries that work together) that provides a specific coding structure & pattern (thus the word, framework). (e.g. Spring Framework)
Use:
SELECT *
FROM `table`
WHERE INSTR(`column`, '{$needle}') > 0
Reference:
to clarify your question:
From Python Source code to Java source code? (I don't think so)
.. or from Python source code to Java Bytecode? (Jython does this under the hood)
Add style="width:100%; height:100%;"
to the div see what that does
not to the #map_canvas
but the main div
example
<body>
<div style="height:100%; width:100%;">
<div id="map-canvas"></div>
</div>
</body>
There are some other answers on here the explain why this is necessary
If you are not using redux-form and you are using local state for changes then your react-select component might look like this:
class MySelect extends Component {
constructor() {
super()
}
state = {
selectedValue: 'default' // your default value goes here
}
render() {
<Select
...
value={this.state.selectedValue}
...
/>
)}
Frustratingly the Numpy package published to PyPI won't install on most Windows computers https://github.com/numpy/numpy/issues/5479
Instead:
pip install numpy-1.10.2+mkl-cp35-none-win_amd64.whl
You need to specify the path where your chromedriver is located.
Place chromedriver on your system path, or where your code is.
If not using a system path, link your chromedriver.exe
(For non-Windows users, it's just called chromedriver
):
browser = webdriver.Chrome(executable_path=r"C:\path\to\chromedriver.exe")
(Set executable_path
to the location where your chromedriver is located.)
If you've placed chromedriver on your System Path, you can shortcut by just doing the following:
browser = webdriver.Chrome()
If you're running on a Unix-based operating system, you may need to update the permissions of chromedriver after downloading it in order to make it executable:
chmod +x chromedriver
That's all. If you're still experiencing issues, more info can be found on this other StackOverflow article: Can't use chrome driver for Selenium
You can do it compactly like this:
string abc = abc.Replace(abc.Substring(abc.IndexOf("me"), (abc.IndexOf("is", abc.IndexOf("me")) + 1) - abc.IndexOf("size")), string.Empty);
Executing programs through the shell means that all user input passed to the program is interpreted according to the syntax and semantic rules of the invoked shell. At best, this only causes inconvenience to the user, because the user has to obey these rules. For instance, paths containing special shell characters like quotation marks or blanks must be escaped. At worst, it causes security leaks, because the user can execute arbitrary programs.
shell=True
is sometimes convenient to make use of specific shell features like word splitting or parameter expansion. However, if such a feature is required, make use of other modules are given to you (e.g. os.path.expandvars()
for parameter expansion or shlex
for word splitting). This means more work, but avoids other problems.
In short: Avoid shell=True
by all means.
var a;
alert(a); //Value is undefined
var b = "Volvo";
alert(b); //Value is Volvo
var c = null;
alert(c); //Value is null
If working on EJB client library:
You need to mention the argument for getting the initial context.
InitialContext ctx = new InitialContext();
If you do not, it will look in the project folder for properties file. Also you can include the properties credentials or values in your class file itself as follows:
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
props.put(Context.PROVIDER_URL, "jnp://localhost:1099");
InitialContext ctx = new InitialContext(props);
URL_PKG_PREFIXES: Constant that holds the name of the environment property for specifying the list of package prefixes to use when loading in URL context factories.
The EJB client library is the primary library to invoke remote EJB components.
This library can be used through the InitialContext. To invoke EJB components the library creates an EJB client context via a URL context factory. The only necessary configuration is to parse the value org.jboss.ejb.client.naming for the java.naming.factory.url.pkgs property to instantiate an InitialContext.
If you want a separate .js file to better organize your routes, just create a variable in the app.js
file pointing to its location in the filesystem:
var wf = require(./routes/wf);
then,
app.get('/wf', wf.foo );
where .foo
is some function declared in your wf.js
file. e.g
// wf.js file
exports.foo = function(req,res){
console.log(` request object is ${req}, response object is ${res} `);
}
ViewController.h
@protocol NameDelegate <NSObject>
-(void)delegateMEthod: (ArgType) arg;
@end
@property id <NameDelegate> delegate;
ViewController.m
[self.delegate delegateMEthod: argument];
MainViewController.m
ViewController viewController = [ViewController new];
viewController.delegate = self;
Method:
-(void)delegateMEthod: (ArgType) arg{
}
Add your test.js file after the jQuery libraries. This way your test.js file can use the libraries.
It's a bit ugly but because the NULL
s have a special meaning to you, this is the cleanest way I can think to do it:
SELECT recordid, MIN(startdate),
CASE WHEN MAX(CASE WHEN enddate IS NULL THEN 1 ELSE 0 END) = 0
THEN MAX(enddate)
END
FROM tmp GROUP BY recordid
That is, if any row has a NULL
, we want to force that to be the answer. Only if no rows contain a NULL
should we return the MIN
(or MAX
).
CSS
input[type="date"] {position: relative;}_x000D_
input[type="date"]:before {_x000D_
position: absolute;left: 0px;top: 0px;_x000D_
content: "Enter DOB";_x000D_
color: #999;_x000D_
width: 100%;line-height: 32px;_x000D_
}_x000D_
input[type="date"]:valid:before {display: none;}
_x000D_
<input type="date" required />
_x000D_
If data already exists in the column you should do:
ALTER TABLE tbl_name ALTER COLUMN col_name TYPE integer USING col_name::integer;
As pointed out by @nobu and @jonathan-porter in comments to @derek-kromm's answer.
You can use lookups in Ansible in order to get the contents of a file, e.g.
user_data: "{{ lookup('file', user_data_file) }}"
Caveat: This lookup will work with local files, not remote files.
Here's a complete example from the docs:
- hosts: all
vars:
contents: "{{ lookup('file', '/etc/foo.txt') }}"
tasks:
- debug: msg="the value of foo.txt is {{ contents }}"
For me the Target > Build Settings > Packaging > Product Name was set to the same thing as another value referenced in a .plist file which was custom to my app. Eventually due to our build process this creates duplicate files.
First of all - this is a bad idea, in general, something wrong going with your app architecture, but, sh..t happens
, if so, you can try to make something like below:
final class OrientationController {
static private (set) var allowedOrientation:UIInterfaceOrientationMask = [.all]
// MARK: - Public
class func lockOrientation(_ orientationIdiom: UIInterfaceOrientationMask) {
OrientationController.allowedOrientation = [orientationIdiom]
}
class func forceLockOrientation(_ orientation: UIInterfaceOrientation) {
var mask:UIInterfaceOrientationMask = []
switch orientation {
case .unknown:
mask = [.all]
case .portrait:
mask = [.portrait]
case .portraitUpsideDown:
mask = [.portraitUpsideDown]
case .landscapeLeft:
mask = [.landscapeLeft]
case .landscapeRight:
mask = [.landscapeRight]
}
OrientationController.lockOrientation(mask)
UIDevice.current.setValue(orientation.rawValue, forKey: "orientation")
}
}
Than, in AppDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// do stuff
OrientationController.lockOrientation(.portrait)
return true
}
// MARK: - Orientation
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return OrientationController.allowedOrientation
}
And whenever you want to change orientation do as:
OrientationController.forceLockOrientation(.landscapeRight)
Note: Sometimes, device may not update from such call, so you may need to do as follow
OrientationController.forceLockOrientation(.portrait)
OrientationController.forceLockOrientation(.landscapeRight)
That's all
You can try this:
var driveName = "C:\\";
var freeSpace = DriveInfo.GetDrives().Where(x => x.Name == driveName && x.IsReady).FirstOrDefault().TotalFreeSpace;
Good luck
$ svn copy http://svn.example.com/repos/calc/trunk@192 \
http://svn.example.com/repos/calc/branches/my-calc-branch \
-m "Creating a private branch of /calc/trunk."
Where 192 is the revision you specify
You can find this information from the SVN Book, specifically here on the page about svn copy
None of the other answers worked for me but this did:
SELECT CONCAT(Cust_First, ' ', Cust_Last) AS CustName FROM customer
Simple thing i did to get it working:
Went in eclipse > Window > Preferences
(Optional)typed in the search box "file" to help trim the tree of options. Went to General > Editors > File associations.
Clicked the ".class" type. Below there were 2 editors present, i clicked on the "Class File Editor" - the one with the icon from JD, clicked the "Default" button on the right.
Done. Now all ur class are belong to us.
The UIButtonTypeCustom is a clickable label if you don't set any images for it.
If it's only about changing the color of the Navbar my suggestion would be to use: Bootstrap Magic. You can change the values for different properties of the Navbar and see a preview.
Download the result as a custom CSS style sheet or as a Less variables file. You can change values with input fields and color pickers.
You can't target the last instance of the class name in your list without JS.
However, you may not be entirely out-of-css-luck, depending on what you are wanting to achieve. For example, by using the next sibling selector, I have added a visual divider after the last of your .list
elements here: http://jsbin.com/vejixisudo/edit?html,css,output
In GNU find
you can use -printf
parameter for that, e.g.:
find /dir1 -type f -printf "%f\n"
In Windows for Git 1.7.9+, run the following command on the command prompt to open the configuration file in a text editor:
git config --global --edit
Then in the file, add the following block if not present or edit it accordingly:
[credential "https://giturl.com"]
username = <user id>
helper = wincred
Save and close the file. You will need to provide the credentials only once after the above change.
For those who want some background info, here's a short article explaining why overflow: hidden
works. It has to do with the so-called block formatting context. This is part of W3C's spec (ie is not a hack) and is basically the region occupied by an element with a block-type flow.
Every time it is applied, overflow: hidden
creates a new block formatting context. But it's not the only property capable of triggering that behaviour. Quoting a presentation by Fiona Chan from Sydney Web Apps Group:
- float: left / right
- overflow: hidden / auto / scroll
- display: table-cell and any table-related values / inline-block
- position: absolute / fixed
I assume you are using Series.plot() to plot your data. If you look at the docs for Series.plot() here:
http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.plot.html
there is no color parameter listed where you might be able to set the colors for your bar graph.
However, the Series.plot() docs state the following at the end of the parameter list:
kwds : keywords
Options to pass to matplotlib plotting method
What that means is that when you specify the kind argument for Series.plot() as bar, Series.plot() will actually call matplotlib.pyplot.bar(), and matplotlib.pyplot.bar() will be sent all the extra keyword arguments that you specify at the end of the argument list for Series.plot().
If you examine the docs for the matplotlib.pyplot.bar() method here:
http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar
..it also accepts keyword arguments at the end of it's parameter list, and if you peruse the list of recognized parameter names, one of them is color, which can be a sequence specifying the different colors for your bar graph.
Putting it all together, if you specify the color keyword argument at the end of your Series.plot() argument list, the keyword argument will be relayed to the matplotlib.pyplot.bar() method. Here is the proof:
import pandas as pd
import matplotlib.pyplot as plt
s = pd.Series(
[5, 4, 4, 1, 12],
index = ["AK", "AX", "GA", "SQ", "WN"]
)
#Set descriptions:
plt.title("Total Delay Incident Caused by Carrier")
plt.ylabel('Delay Incident')
plt.xlabel('Carrier')
#Set tick colors:
ax = plt.gca()
ax.tick_params(axis='x', colors='blue')
ax.tick_params(axis='y', colors='red')
#Plot the data:
my_colors = 'rgbkymc' #red, green, blue, black, etc.
pd.Series.plot(
s,
kind='bar',
color=my_colors,
)
plt.show()
Note that if there are more bars than colors in your sequence, the colors will repeat.
Also, check if the user does not select anything.
var radioanswer = 'none';
if ($('input[name=myRadio]:checked').val() != null) {
radioanswer = $('input[name=myRadio]:checked').val();
}
I found a method using fseek and ftell and a thread with this question with answers that it can't be done in just C in another way.
You could use a portability library like NSPR (the library that powers Firefox).
Without jQuery:
document.getElementById('file').onchange = function(){
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent){
// Entire file
console.log(this.result);
// By lines
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
console.log(lines[line]);
}
};
reader.readAsText(file);
};
HTML:
<input type="file" name="file" id="file">
Remember to put your javascript code after the file field is rendered.
After some research on managing configs for development and builds etc, I decided to roll my own, I have made it available on bitbucket at: https://bitbucket.org/brightertools/contemplate/wiki/Home
This multiple configuration files for multiple environments, its a basic configuration entry replacement tool that will work with any text based file format.
Hope this helps.
Variation on the builder pattern, using call():
function asyncMethod(arg) {
function innerPromise() { return new Promise((...)=> {...}) }
innerPromise().then(result => {
this.setStuff(result);
}
}
const getInstance = async (arg) => {
let instance = new Instance();
await asyncMethod.call(instance, arg);
return instance;
}
Map implicitly returns while forEach does not.
This is why when you're coding a JSX application, you almost always use map instead of forEach to display content in React.
In case if you are developing your own framework:
WHY is this happening?
If any of the public header files you have mentioned in your module.modulemap have import statements that are not mentioned in modulemap, this will give you the error. Since it tries to import some header that is not declared as modular (in module.modulemap), it breaks the modularity of the framework.
HOW can I fix it?
Just include the header that gave the error to your module.modulemap and build again!
WHY NOT just set allow non-modular to YES?
Because it's not really a solution here, with that you tell your project "this framework was supposed to be modular but it's not. Use it somehow, I don't care." This doesn't fix your library's modularity problem.
For more information check this archived blog post or refer to clang docs.
Any line starting with a "REM" is treated as a comment, nothing is executed including the redirection.
Also, the %date% variable may contain "/" characters which are treated as path separator characters, leading to the system being unable to create the desired log file.
w+
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "w+"); //write and read mode
fprintf(fp, "This is testing for fprintf...\n");
rewind(fp); //rewind () function moves file pointer position to the beginning of the file.
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf...
w and r to form w+
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "w"); //only write mode
fprintf(fp, "This is testing for fprintf...\n");
fclose(fp);
fp = fopen("test.txt", "r");
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf...
r+
test.txt
This is testing for fprintf...
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "r+"); //read and write mode
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
rewind(fp); //rewind () function moves file pointer position to the beginning of the file.
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf again...
r and w to form r+
test.txt
This is testing for fprintf...
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "r");
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
fp=fopen("test.txt","w");
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf again...
a+
test.txt
This is testing for fprintf...
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "a+"); //append and read mode
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
rewind(fp); //rewind () function moves file pointer position to the beginning of the file.
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf...
This is testing for fprintf again...
a and r to form a+
test.txt
This is testing for fprintf...
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "a"); //append and read mode
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
fp=fopen("test.txt","r");
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf...
This is testing for fprintf again...
You can use spacing for Bootstrap and no need for any additional CSS. Just add the classes to your buttons. This is for version 4.
The more efficient (less obtrusive) way of doing this is through custom formatting.
Note that this does not actually change the value of the cell. It only displays the leading zeroes in the worksheet.
This example might help you. by using simple casting you can get code behind urdu character.
string str = "?????";
char ch = ' ';
int number = 0;
for (int i = 0; i < str.Length; i++)
{
ch = str[i];
number = (int)ch;
Console.WriteLine(number);
}
i have the same problem on ubuntu 15.10. Please try download plugin locally e.g. https://github.com/lmenezes/elasticsearch-kopf/archive/master.zip and install with this command:
sudo /usr/share/elasticsearch/bin/plugin install file:/home/dev/Downloads/elasticsearch-kopf-master.zip
Path maybe different depending on your environment.
Regards.
I am using Intellij Idea 2017 and I got into the same problem. What solved the problem for me was to simply
Try:
if($("option[value='parcel']").is(":checked"))
$('#row_dim').show();
Or even:
$(function() {
$('#type').change(function(){
$('#row_dim')[ ($("option[value='parcel']").is(":checked"))? "show" : "hide" ]();
});
});
JSFiddle: http://jsfiddle.net/3w5kD/
Yes I think this would be quicker.
Get-ChildItem $folder | Sort-Object -Descending -Property LastWriteTime -Top 1
At the first site is a dropdown field to select the language of phpmyadmin.
In the config.inc.php you can set:
$cfg['Lang'] = '';
More details you can find in the documentation: http://www.phpmyadmin.net/documentation/
Although it might be heresy in today's world - in the past you would do the following non-css code. This works in everything up to and including today's browsers but - as I have said - it is heresy in today's world:
<center>
<table>
...
</table>
</center>
What you need is some way to tell that you want to center a table and the person is using an older browser. Then insert the "<center>" commands around the table. Otherwise - use css.
Surprisingly - if you want to center everything in the BODY area - you just can use the standard
text-align: center;
css command and in IE8 (at least) it will center everything on the page including tables.
if you want to obtain it right within the container, you can try
ip a | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b" | grep 172.17
Well, why do you have %20
url-quoting escapes in a formatting string in first place? Ideally you'd do the interpolation formatting first:
formatting_template = 'Hello World%s'
text = '!'
full_string = formatting_template % text
Then you url quote it afterwards:
result = urllib.quote(full_string)
That is better because it would quote all url-quotable things in your string, including stuff that is in the text
part.
//XAML Code
// ViewModel code
private CategoryModel _SelectedCategory;
public CategoryModel SelectedCategory
{
get { return _SelectedCategory; }
set
{
_SelectedCategory = value;
OnPropertyChanged("SelectedCategory");
}
}
private ObservableCollection<CategoryModel> _Categories;
public ObservableCollection<CategoryModel> Categories
{
get { return _Categories; }
set
{
_Categories = value;
_Categories.Insert(0, new CategoryModel()
{
CategoryId = 0,
CategoryName = " -- Select Category -- "
});
SelectedCategory = _Categories[0];
OnPropertyChanged("Categories");
}
}
You can use anycache to do the job for you. Assuming you have a function myfunc
which creates the instance:
from anycache import anycache
class Fruits:pass
@anycache(cachedir='/path/to/your/cache')
def myfunc()
banana = Fruits()
banana.color = 'yellow'
banana.value = 30
return banana
Anycache calls myfunc
at the first time and pickles the result to a
file in cachedir
using an unique identifier (depending on the the function name and the arguments) as filename.
On any consecutive run, the pickled object is loaded.
If the cachedir
is preserved between python runs, the pickled object is taken from the previous python run.
The function arguments are also taken into account. A refactored implementation works likewise:
from anycache import anycache
class Fruits:pass
@anycache(cachedir='/path/to/your/cache')
def myfunc(color, value)
fruit = Fruits()
fruit.color = color
fruit.value = value
return fruit