Using OKIO
public static String readJsonFromAssets(Context context, String filePath) {
try {
InputStream input = context.getAssets().open(filePath);
BufferedSource source = Okio.buffer(Okio.source(input));
return source.readByteString().string(Charset.forName("utf-8"));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
and then...
String data = readJsonFromAssets(context, "json/some.json"); //here is my file inside the folder assets/json/some.json
Type reviewType = new TypeToken<List<Object>>() {}.getType();
if (data != null) {
Object object = new Gson().fromJson(data, reviewType);
}
In addition to setting USB connection/storage mode to "Camera (PTP)", I also had to enable developer mode, which has been hidden since 4.2.
asort()
- Maintains key association: yes.
sort()
- Maintains key association: no.
Use the pre-compiled SDL2main.lib and SDL.lib for your VS2015 project's library : https://buildbot.libsdl.org/sdl-builds/sdl-visualstudio/sdl-visualstudio-2225.zip
Use this function:
function adjustHeight(el){
el.style.height = (el.scrollHeight > el.clientHeight) ? (el.scrollHeight)+"px" : "60px";
}
Use this html:
<textarea onkeyup="adjustHeight(this)"></textarea>
And finally use this css:
textarea {
min-height: 60px;
overflow-y: auto;
word-wrap:break-word
}
The solution simply is letting the scrollbar appears to detect that height needs to be adjusted, and whenever the scrollbar appears in your text area, it adjusts the height just as much as to hide the scrollbar again.
_
has 3 main conventional uses in Python:
To hold the result of the last executed expression(/statement) in an interactive interpreter session (see docs). This precedent was set by the standard CPython interpreter, and other interpreters have followed suit
For translation lookup in i18n (see the gettext documentation for example), as in code like
raise forms.ValidationError(_("Please enter a correct username"))
As a general purpose "throwaway" variable name:
To indicate that part of a function result is being deliberately ignored (Conceptually, it is being discarded.), as in code like:
label, has_label, _ = text.partition(':')
As part of a function definition (using either def
or lambda
), where
the signature is fixed (e.g. by a callback or parent class API), but
this particular function implementation doesn't need all of the
parameters, as in code like:
def callback(_):
return True
[For a long time this answer didn't list this use case, but it came up often enough, as noted here, to be worth listing explicitly.]
This use case can conflict with the translation lookup use case, so it is necessary to avoid using _
as a throwaway variable in any code block that also uses it for i18n translation (many folks prefer a double-underscore, __
, as their throwaway variable for exactly this reason).
Linters often recognize this use case. For example year, month, day = date()
will raise a lint warning if day
is not used later in the code. The fix, if day
is truly not needed, is to write year, month, _ = date()
. Same with lambda functions, lambda arg: 1.0
creates a function requiring one argument but not using it, which will be caught by lint. The fix is to write lambda _: 1.0
. An unused variable is often hiding a bug/typo (e.g. set day
but use dya
in the next line).
the command to get the effective push remote for the branch, e.g., master, is:
git config branch.master.pushRemote || git config remote.pushDefault || git config branch.master.remote
Here's why (from the "man git config" output):
branch.name.remote [...] tells git fetch and git push which remote to fetch from/push to [...] [for push] may be overridden with remote.pushDefault (for all branches) [and] for the current branch [..] further overridden by branch.name.pushRemote [...]
For some reason, "man git push" only tells about branch.name.remote (even though it has the least precedence of the three) + erroneously states that if it is not set, push defaults to origin - it does not, it's just that when you clone a repo, branch.name.remote is set to origin, but if you remove this setting, git push will fail, even though you still have the origin remote
Try Like this.
tv1.setText(" " + Integer.toString(X[i]) + "\n" + "+" + " " + Integer.toString(Y[i]));
background-image: url("/your-dir/your_image.jpg");
min-height: 100%;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: cover;}
I also want to do the same thing: migrate a db from a standalone redis instance to a another redis instances(redis sentinel).
Because the data is not critical(session data), i will give https://github.com/yaauie/redis-copy a try.
Best way is to use lifecycle rule to delete whole bucket contents. Programmatically you can use following code (PHP) to PUT lifecycle rule.
$expiration = array('Date' => date('U', strtotime('GMT midnight')));
$result = $s3->putBucketLifecycle(array(
'Bucket' => 'bucket-name',
'Rules' => array(
array(
'Expiration' => $expiration,
'ID' => 'rule-name',
'Prefix' => '',
'Status' => 'Enabled',
),
),
));
In above case all the objects will be deleted starting Date - "Today GMT midnight".
You can also specify Days as follows. But with Days it will wait for at least 24 hrs (1 day is minimum) to start deleting the bucket contents.
$expiration = array('Days' => 1);
Just delete the whole directory. This will delete all the projects but also the Eclipse cache and settings for the workspace. These are kept in the .metadata
folder of an Eclipse workspace. Note that you can configure Eclipse to use project folders that are outside the workspace folder as well, so you may want to verify the location of each of the projects.
You can remove the workspace from the suggested workspaces by going into the General/Startup and Shutdown/Workspaces section of the preferences (via Preferences > General > Startup & Shudown > Workspaces > [Remove] ). Note that this does not remove the files itself. For old versions of Eclipse you will need to edit the org.eclipse.ui.ide.prefs
file in the configuration/.settings
directory under your installation directory (or in ~/.eclipse
on Unix, IIRC).
Listview lv = (ListView) findViewById(R.id.previewlist);
final BaseAdapter adapter = new PreviewAdapter(this, name, age);
confirm.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
View view = null;
String value;
for (int i = 0; i < adapter.getCount(); i++) {
view = adapter.getView(i, view, lv);
Textview et = (TextView) view.findViewById(R.id.passfare);
value=et.getText().toString();
Toast.makeText(getApplicationContext(), value,
Toast.LENGTH_SHORT).show();
}
}
});
In excel, hide the workbooks, and save them as hidden. When your app loads them they will not be shown.
Edit: upon re-reading, it became clear that these workbooks are not part of your application. Such a solution would be inappropriate for user workbooks.
if you try with lubridate:
library(lubridate)
lubridate::week(ymd("2014-03-16", "2014-03-17","2014-03-18", '2014-01-01'))
[1] 11 11 12 1
The pattern is the same. Try isoweek
lubridate::isoweek(ymd("2014-03-16", "2014-03-17","2014-03-18", '2014-01-01'))
[1] 11 12 12 1
I think you should be able to follow the method used in this post. It looks really ugly, but I would think you could do it twice and get the result you want.
I wonder if this is actually a case where you'd be better off using DataContext.ExecuteCommand(...)
instead of converting to linq.
You could replace something in there by getting the index along with the item.
>>> foo = ['a', 'b', 'c', 'A', 'B', 'C']
>>> for index, item in enumerate(foo):
... print(index, item)
...
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'A')
(4, 'B')
(5, 'C')
>>> for index, item in enumerate(foo):
... if item in ('a', 'A'):
... foo[index] = 'replaced!'
...
>>> foo
['replaced!', 'b', 'c', 'replaced!', 'B', 'C']
Note that if you want to remove something from the list you have to iterate over a copy of the list, else you will get errors since you're trying to change the size of something you are iterating over. This can be done quite easily with slices.
Wrong:
>>> foo = ['a', 'b', 'c', 1, 2, 3]
>>> for item in foo:
... if isinstance(item, int):
... foo.remove(item)
...
>>> foo
['a', 'b', 'c', 2]
The 2 is still in there because we modified the size of the list as we iterated over it. The correct way would be:
>>> foo = ['a', 'b', 'c', 1, 2, 3]
>>> for item in foo[:]:
... if isinstance(item, int):
... foo.remove(item)
...
>>> foo
['a', 'b', 'c']
Public variable declarations in classes is the easiest way:
On target class:
public class MyFragment extends Fragment {
public MyCallerFragment caller; // Declare the caller var
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Do what you want with the vars
caller.str = "I changed your value!";
caller.i = 9999;
...
return inflater.inflate(R.layout.my_fragment, container, false);
}
...
}
On caller class:
public class MyCallerFragment extends Fragment {
public Integer i; // Declared public var
public String str; // Declared public var
...
FragmentManager fragmentManager = getParentFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
myFragment = new MyFragment();
myFragment.caller = this;
transaction.replace(R.id.nav_host_fragment, myFragment)
.addToBackStack(null).commit();
...
}
If you want to use the main activity it is easy too:
On main activity class:
public class MainActivity extends AppCompatActivity {
public String str; // Declare public var
public EditText myEditText; // You can declare public elements too.
// Taking care that you have it assigned
// correctly.
...
}
On called class:
public class MyFragment extends Fragment {
private MainActivity main; // Declare the activity var
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Assign the main activity var
main = (MainActivity) getActivity();
// Do what you want with the vars
main.str = "I changed your value!";
main.myEditText.setText("Wow I can modify the EditText too!");
...
return inflater.inflate(R.layout.my_fragment, container, false);
}
...
}
Note: Take care when using events (onClick, onChanged, etc) because you can be on a "fighting" situation where more than one assign a variable. The result will be that the variable sometimes does not will change or will return to the last value magically.
For more combinations use your creativity. :)
You don't need a plugin (including the Remote System View plugin), you can do this with the basic platform. You just create an external tool configuration. I've added an image to demonstrate.
Orange Arrows: Use the external tool button on the toolbar and select External Tools Configuration...
. Click on Program
then up above click on the New launch configuration
icon.
Green Arrows: Use the Name
field and name your new tool something clever like "Launch Shell". In the Location
area enter a shell command e.g. /bin/bash
. A more generic approach would be to use ${env_var:SHELL}
which under the Mac (and I hope Linux) launches the default shell. Then in the Working Directory
you can use the variable ${project_loc}
to set the default directory to your current project location. This will mean that when you launch the tool, you have to make sure you have your cursor in an active project on the explorer or in an appropriate editor window. Under the Arguments
area use -i
for interactive mode.
Blue arrows: Switch to the Build
tab and uncheck Build before launch
. Then switch to the Common
tab and click to add your command to the favorites menu. Now click Apply
and Close
. Make sure the console view is showing (Window->Show View->Console
). Click on a project in the Package or Project Explorer or click in an editor window that has code for a project of interest. Then click on the external tool icon and select Launch Shell
, you now have an interactive shell window in the console view.
In the lower left of the image you can see the tcsh shell in action.
Windows Note:
This also works in Windows but you use ${env_var:ComSpec}
in the location field and you can leave the arguments field blank.
Check out the Image drag and drop uploader with image preview using dropper jquery plugin.
HTML
<div class="target" width="78" height="100"><img /></div>
JS
$(".target").dropper({
action: "upload.php",
}).on("start.dropper", onStart);
function onStart(e, files){
console.log(files[0]);
image_preview(files[0].file).then(function(res){
$('.dropper-dropzone').empty();
//$('.dropper-dropzone').css("background-image",res.data);
$('#imgPreview').remove();
$('.dropper-dropzone').append('<img id="imgPreview"/><span style="display:none">Drag and drop files or click to select</span>');
var widthImg=$('.dropper-dropzone').attr('width');
$('#imgPreview').attr({width:widthImg});
$('#imgPreview').attr({src:res.data});
})
}
function image_preview(file){
var def = new $.Deferred();
var imgURL = '';
if (file.type.match('image.*')) {
//create object url support
var URL = window.URL || window.webkitURL;
if (URL !== undefined) {
imgURL = URL.createObjectURL(file);
URL.revokeObjectURL(file);
def.resolve({status: 200, message: 'OK', data:imgURL, error: {}});
}
//file reader support
else if(window.File && window.FileReader)
{
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = function () {
imgURL = reader.result;
def.resolve({status: 200, message: 'OK', data:imgURL, error: {}});
}
}
else {
def.reject({status: 1001, message: 'File uploader not supported', data:imgURL, error: {}});
}
}
else
def.reject({status: 1002, message: 'File type not supported', error: {}});
return def.promise();
}
$('.dropper-dropzone').mouseenter(function() {
$( '.dropper-dropzone>span' ).css("display", "block");
});
$('.dropper-dropzone').mouseleave(function() {
$( '.dropper-dropzone>span' ).css("display", "none");
});
CSS
.dropper-dropzone{
width:78px;
padding:3px;
height:100px;
position: relative;
}
.dropper-dropzone>img{
width:78px;
height:100px;
margin-top=0;
}
.dropper-dropzone>span {
position: absolute;
right: 10px;
top: 20px;
color:#ccc;
}
.dropper .dropper-dropzone{
padding:3px !important
}
You can simply concatnate two lists, e.g:
list1 = [0, 1]
list2 = [2, 3]
list3 = list1 + list2
print(list3)
>> [0, 1, 2, 3]
JQUERY INR v1.2
A simple jQuery plug-in for convert Rs. to standard Indian rupee symbol through out the web page. Simple to use and simple instillation
The Indian Rupee sign is the currency sign: ? for the Indian Rupee, the official currency of India. Designed by D. Udaya Kumar, it was presented to the public by the Government of India on 15 July 2010,[1] following its selection through an “open” competition among Indian residents. Before its adoption, the most commonly used symbols for the rupee were Rs, Re or, if the text was in an Indian language, an appropriate abbreviation in that language. The new sign relates solely to the Indian rupee; other countries that use a rupee, such as Sri Lanka, Pakistan and Nepal, still use the generic U+20A8 ? rupee sign character. The design resembles both the Devanagari letter "?" (ra) and the Latin capital letter "R", with a double horizontal line at the top.
Instillation:
Include jQuery min and jQuery Ui to your page first
eg: NB: use jQuery stable version only
include the “indianRupee_v1.2.js” and “indianRupee_ctrl.js” after the jQuery library eg:
Use Span tag to wrap Rs through out the web it will replace with the symbol eg: Rs 1280000/-
Source:
Pay Him Rs 1280000/-
Pay Him Rs 528500/-
Pay Him Rs 1250/-
Result:
http://romy.theqtl.com/rupeePlugin/
Plug-in Options:
$("body").indianRupee({ targets:"span",// use as default we can also use [p, div, h1 , li etc...] vector:"on"//[on/off] of [true/false] NB: {vector not support in Internet Explore } });
You can disable a button when you construct the dialog:
$(function() {_x000D_
$("#dialog").dialog({_x000D_
modal: true,_x000D_
buttons: [_x000D_
{ text: "Confirm", click: function() { $(this).dialog("close"); }, disabled: true },_x000D_
{ text: "Cancel", click: function() { $(this).dialog("close"); } }_x000D_
]_x000D_
});_x000D_
});
_x000D_
@import url("https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css");
_x000D_
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>_x000D_
_x000D_
<div id="dialog" title="Confirmation">_x000D_
<p>Proceed?</p>_x000D_
</div>
_x000D_
Or you can disable it anytime after the dialog is created:
$(function() {_x000D_
$("#dialog").dialog({_x000D_
modal: true,_x000D_
buttons: [_x000D_
{ text: "Confirm", click: function() { $(this).dialog("close"); }, "class": "confirm" },_x000D_
{ text: "Cancel", click: function() { $(this).dialog("close"); } }_x000D_
]_x000D_
});_x000D_
setTimeout(function() {_x000D_
$("#dialog").dialog("widget").find("button.confirm").button("disable");_x000D_
}, 2000);_x000D_
});
_x000D_
@import url("https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css");
_x000D_
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>_x000D_
_x000D_
<div id="dialog" title="Confirmation">_x000D_
<p>Button will disable after two seconds.</p>_x000D_
</div>
_x000D_
Given
volumes:
- /dir/on/host:/var/www/html
if /dir/on/host
doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html
. Whatever content you had before in /var/www/html
inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.
If you used read.table()
(or one of it's ilk, e.g. read.csv()
) then the easy fix is to change the call to:
read.table(file = "foo.txt", row.names = 1, ....)
where ....
are the other arguments you needed/used. The row.names
argument takes the column number of the data file from which to take the row names. It need not be the first column. See ?read.table
for details/info.
If you already have the data in R and can't be bothered to re-read it, or it came from another route, just set the rownames
attribute and remove the first variable from the object (assuming obj
is your object)
rownames(obj) <- obj[, 1] ## set rownames
obj <- obj[, -1] ## remove the first variable
num_rows on your COUNT() query will literally ALWAYS be 1. It is an aggregate function without a GROUP BY clause, so all rows are grouped together into one. If you want the value of the count, you should give it an identifier SELECT COUNT(*) as myCount ...
, then use your normal method of accessing a result (the first, only result) and get it's 'myCount' property.
<!--[if lt IE 8]><![endif]-->
The lt in the above statement means less than, so 'if less than IE 8'.
For all versions of IE you can just use
<!--[if IE]><![endif]-->
or for all versions above ie 6 for example.
<!--[if gt IE 6]><![endif]-->
Where gt is 'greater than'
If you would like to write specific styles for versions below and including IE8 you can write
<!--[if lte IE 8]><![endif]-->
where lte is 'less than and equal' to
As an .htaccess file, a good option is to use the one provided by the Kohana Framework:
# Turn on URL rewriting
RewriteEngine On
# Installation directory
RewriteBase /
# Protect hidden files from being viewed
<Files .*>
Order Deny,Allow
Deny From All
</Files>
# Protect application and system files from being viewed
RewriteRule ^(?:application|system)\b.* index.php/$0 [L]
# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php/$0 [PT]
It's a well thought out .htaccess that just works.
Arrays.fill works with single dimensional array, so to fill two dimensional array we can do below
for (int i = 0, len = arr.length; i < len; i++)
Arrays.fill(arr[i], 0);
You may be looking for auto-fill
:
grid-template-columns: repeat(auto-fill, 186px);
Demo: http://codepen.io/alanbuchanan/pen/wJRMox
To use up the available space more efficiently, you could use minmax
, and pass in auto
as the second argument:
grid-template-columns: repeat(auto-fill, minmax(186px, auto));
Demo: http://codepen.io/alanbuchanan/pen/jBXWLR
If you don't want the empty columns, you could use auto-fit
instead of auto-fill
.
If strMyString.Tostring.Contains("Something") or strMyString.Tostring.Contains("Something2") Then
End if
Three ways to pass model data to partial view (there may be more)
This is view page
Method One Populate at view
@{
PartialViewTestSOl.Models.CountryModel ctry1 = new PartialViewTestSOl.Models.CountryModel();
ctry1.CountryName="India";
ctry1.ID=1;
PartialViewTestSOl.Models.CountryModel ctry2 = new PartialViewTestSOl.Models.CountryModel();
ctry2.CountryName="Africa";
ctry2.ID=2;
List<PartialViewTestSOl.Models.CountryModel> CountryList = new List<PartialViewTestSOl.Models.CountryModel>();
CountryList.Add(ctry1);
CountryList.Add(ctry2);
}
@{
Html.RenderPartial("~/Views/PartialViewTest.cshtml",CountryList );
}
Method Two Pass Through ViewBag
@{
var country = (List<PartialViewTestSOl.Models.CountryModel>)ViewBag.CountryList;
Html.RenderPartial("~/Views/PartialViewTest.cshtml",country );
}
Method Three pass through model
@{
Html.RenderPartial("~/Views/PartialViewTest.cshtml",Model.country );
}
Yes, use the rendered
attribute.
<h:form rendered="#{some boolean condition}">
You usually tie it to the model rather than letting the model grab the component and manipulate it.
E.g.
<h:form rendered="#{bean.booleanValue}" />
<h:form rendered="#{bean.intValue gt 10}" />
<h:form rendered="#{bean.objectValue eq null}" />
<h:form rendered="#{bean.stringValue ne 'someValue'}" />
<h:form rendered="#{not empty bean.collectionValue}" />
<h:form rendered="#{not bean.booleanValue and bean.intValue ne 0}" />
<h:form rendered="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />
Note the importance of keyword based EL operators such as gt
, ge
, le
and lt
instead of >
, >=
, <=
and <
as angle brackets <
and >
are reserved characters in XML. See also this related Q&A: Error parsing XHTML: The content of elements must consist of well-formed character data or markup.
As to your specific use case, let's assume that the link is passing a parameter like below:
<a href="page.xhtml?form=1">link</a>
You can then show the form as below:
<h:form rendered="#{param.form eq '1'}">
(the #{param}
is an implicit EL object referring to a Map
representing the request parameters)
Its very easy to create procedure in Mysql. Here, in my example I am going to create a procedure which is responsible to fetch all data from student table according to supplied name.
DELIMITER //
CREATE PROCEDURE getStudentInfo(IN s_name VARCHAR(64))
BEGIN
SELECT * FROM student_database.student s where s.sname = s_name;
END//
DELIMITER;
In the above example ,database and table names are student_database and student respectively. Note: Instead of s_name, you can also pass @s_name as global variable.
How to call procedure? Well! its very easy, simply you can call procedure by hitting this command
$mysql> CAll getStudentInfo('pass_required_name');
Simply u can add this to jquery.validationEngine-en.js file
"onlyLetterNumberSp": {
"regex": ^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$,
"alertText": "* No special characters allowed"
},
and call it in text field as
<input type="text" class="form-control validate[required,custom[onlyLetterNumberSp]]" id="title" name="title" placeholder="Title"/>
You can do it using just css without using any jQiuery.
<a class="tooltips">
Hover Me
<span>My Tooltip Text</span>
</a>
<style>
a.tooltips {
position: relative;
display: inline;
}
a.tooltips span {
position: absolute;
width: 200px;
color: #FFFFFF;
background: #000000;
height: 30px;
line-height: 30px;
text-align: center;
visibility: hidden;
border-radius: 6px;
}
a.tooltips span:after {
content: '';
position: absolute;
top: 100%;
left: 35%;
margin-left: -8px;
width: 0;
height: 0;
border-top: 8px solid #000000;
border-right: 8px solid transparent;
border-left: 8px solid transparent;
}
a:hover.tooltips span {
visibility: visible;
opacity: 0.8;
bottom: 30px;
left: 50%;
margin-left: -76px;
z-index: 999;
}
</style>
I've published a NameValuePair
class in GlobalMentor's core library, available in Maven. This is an ongoing project with a long history, so please submit any request for changes or improvements.
UIImage
contains a CGImage
as its main content member as well as scaling and orientation factors. Since CGImage
and its various functions are derived from OSX, it expects a coordinate system that is upside down compared to the iPhone. When you create a UIImage
, it defaults to an upside-down orientation to compensate (you can change this!). Use the .CGImage
property to access the very powerful CGImage
functions, but drawing onto the iPhone screen etc. is best done with the UIImage
methods.
First you have to deactivate your environment before removing it. You can remove conda environment by using the following command
Suppose your environment name is "sample_env" , you can remove this environment by using
source deactivate
conda remove -n sample_env --all
'--all' will be used to remove all the dependencies
it doesn't work from XML with maxLenght I used this code, you can limit the number of characters
String editorName = mEditorNameNd.getText().toString().substring(0, Math.min(mEditorNameNd.length(), 15));
You didn't say on which event.Just use below on your event listener.Or in your page load
$('#models').empty()
Then to repopulate
$.getJSON('@Url.Action("YourAction","YourController")',function(data){
var dropdown=$('#models');
dropdown.empty();
$.each(data, function (index, item) {
dropdown.append(
$('<option>', {
value: item.valueField,
text: item.DisplayField
}, '</option>'))
}
)});
There appears to be two common causes for this error, one is to do with the server configuration and the session.save_path and the other is the browser cache.
If you encounter this error try using a different browser or machine before you attempt to alter your Apache and PHP configurations on the server!
Note that clearing the Cookies for the server is not enough, you need to clear the cache.
In Firefox clearing all history and cookies is easy, but you may not want to get rid of everything. Clearing the cache is hidden away in Firefox:
Tools > Options > Advanced > Network: Cached Web Content - Clear Now
I was having this problem as well but following Farhan's lead of using setContentView()
I did just that. using setContentView()
by itself was not enough however. I found that I had to repopulate all of my views with information. To fix this I just pulled all of that code out to another method (I called it build) and in my onCreate
method I just call that build. Now whenever my event occurs that I want my activity to "refresh" I just call build, give it the new information (which I pass in as parameters to build) and I have a refreshed activity.
Just don't perform e.preventDefault();
, or perform it conditionally.
You certainly can't alter when the original event action occurs.
If you want to "recreate" the original UI event some time later (say, in the callback for an AJAX request) then you'll just have to fake it some other way (like in vzwick's answer)... though I'd question the usability of such an approach.
I have this code snippet run from the ENTRYPOINT
in my docker file:
while true
do
echo "Press [CTRL+C] to stop.."
sleep 1
done
Run the built docker image as:
docker run -td <image name>
Log in to the container shell:
docker exec -it <container id> /bin/bash
Let us say your jsfunctions.js file has a function "display" and this file is stored in C:/Scripts/Jsfunctions.js
jsfunctions.js
var display = function(name) {
print("Hello, I am a Javascript display function",name);
return "display function return"
}
Now, in your java code, I would recommend you to use Java8 Nashorn. In your java class,
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
class Test {
public void runDisplay() {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
try {
engine.eval(new FileReader("C:/Scripts/Jsfunctions.js"));
Invocable invocable = (Invocable) engine;
Object result;
result = invocable.invokeFunction("display", helloWorld);
System.out.println(result);
System.out.println(result.getClass());
} catch (FileNotFoundException | NoSuchMethodException | ScriptException e) {
e.printStackTrace();
}
}
}
Note: Get the absolute path of your javascript file and replace in FileReader() and run the java code. It should work.
Works for me in the same way:
...
<MyComponent {...this.props}>
<Route path="path1" name="pname1" component="FirstPath">
...
</MyComponent>
...
And then, I can access "this.props.location.pathname" in the MyComponent function.
I forgot that it was I am...))) Following link describes more for make navigation bar etc.: react router this.props.location
If you change from using a lambda with one argument to a function with one argument, you will get this error.
For example:
You had:
foobar = lambda do |baz|
puts baz
end
and you changed the definition to
def foobar(baz)
puts baz
end
And you left your invocation as:
foobar.call(baz)
And then you got the message
ArgumentError: wrong number of arguments (0 for 1)
when you really meant:
foobar(baz)
(?<!1\.2\.3\.4).*Has exploded
You need to run this with -P to have negative lookbehind (Perl regular expression), so the command is:
grep -P '(?<!1\.2\.3\.4).*Has exploded' test.log
Try this. It uses negative lookbehind to ignore the line if it is preceeded by 1.2.3.4
. Hope that helps!
In addition to the accepted answer, I would like to add one info, that NuGet packages in Visual Studio 2017 are located in the project file itself. I.e., right click on the project -> edit, to find all package reference entries.
You can create an alias in .bashrc file as follows
alias vg='valgrind --leak-check=full -v --track-origins=yes --log-file=vg_logfile.out'
So whenever you want to check memory leaks, just do simply
vg ./<name of your executable> <command line parameters to your executable>
This will generate a Valgrind log file in the current directory.
The basic problem here is that the bash developer(s) that designed/implemented arrays really screwed the pooch. They decided that ${array}
was just short hand for ${array[0]}
, which was a bad mistake. Especially when you consider that ${array[0]}
has no meaning and evaluates to the empty string if the array type is associative.
Assigning an array takes the form array=(value1 ... valueN)
where value has the syntax [subscript]=string
, thereby assigning a value directly to a particular index in the array. This makes it so there can be two types of arrays, numerically indexed and hash indexed (called associative arrays in bash parlance). It also makes it so that you can create sparse numerically indexed arrays. Leaving off the [subscript]=
part is short hand for a numerically indexed array, starting with the ordinal index of 0 and incrementing with each new value in the assignment statement.
Therefore, ${array}
should evaluate to the entire array, indexes and all. It should evaluate to the inverse of the assignment statement. Any third year CS major should know that. In that case, this code would work exactly as you might expect it to:
declare -A foo bar
foo=${bar}
Then, passing arrays by value to functions and assigning one array to another would work as the rest of the shell syntax dictates. But because they didn't do this right, the assignment operator =
doesn't work for arrays, and arrays can't be passed by value to functions or to subshells or output in general (echo ${array}
) without code to chew through it all.
So, if it had been done right, then the following example would show how the usefulness of arrays in bash could be substantially better:
simple=(first=one second=2 third=3)
echo ${simple}
the resulting output should be:
(first=one second=2 third=3)
Then, arrays could use the assignment operator, and be passed by value to functions and even other shell scripts. Easily stored by outputting to a file, and easily loaded from a file into a script.
declare -A foo
read foo <file
Alas, we have been let down by an otherwise superlative bash development team.
As such, to pass an array to a function, there is really only one option, and that is to use the nameref feature:
function funky() {
local -n ARR
ARR=$1
echo "indexes: ${!ARR[@]}"
echo "values: ${ARR[@]}"
}
declare -A HASH
HASH=([foo]=bar [zoom]=fast)
funky HASH # notice that I'm just passing the word 'HASH' to the function
will result in the following output:
indexes: foo zoom
values: bar fast
Since this is passing by reference, you can also assign to the array in the function. Yes, the array being referenced has to have a global scope, but that shouldn't be too big a deal, considering that this is shell scripting. To pass an associative or sparse indexed array by value to a function requires throwing all the indexes and the values onto the argument list (not too useful if it's a large array) as single strings like this:
funky "${!array[*]}" "${array[*]}"
and then writing a bunch of code inside the function to reassemble the array.
Make sure there are no spaces in your Xcode application name (can happen if you keep older versions around - for example renaming it 'Xcode 4.app'); build tools will be referenced within the Xcode bundle paths, and many scripts can't handle references with spaces properly.
SOAP -> SOAP(Simple object access protocal) is the application level protocal created for machine to machine interaction. Protocol defines standard rules. All the parties who are using the particular protocol should adhere to the protocol rules. Like TCP, It unwinds at transport layer, The SOAP protocol will be understood by Application layer( any application which supports SOAP - Axis2, .Net).
WSDL -> SOAP message consist of SoapEnevelope->SoapHeader and SoapBody. It doesn't define what would be message format? what are all the transports(HTTP,JMS) it supports? without this info, It is hard for any client who wants to consume the particular web service to construct the SOAP message. Even if they do, they won't be sure, it'll work all the time. WSDL is the rescue. WSDL (Web Service description Language) defines the operations, message formats and transport details for the SOAP message.
REST -> REST(Representational state transfer) is based on the Transport. Unlike SOAP which targets the actions, REST concerns more on the resources. REST locates the resources by using URL (example -http://{serverAddress}/employees/employeeNumber/12345) and it depends on the transport protocol( with HTTP - GET,POST, PUT, DELETE,...) for the actions to be performed on the resources. The REST service locates the resource based on the URL and perform the action based on the transport action verb. It is more of architectural style and conventions based.
There is no "second property" -- when you say var obj = { ... }
, the properties inside the braces are unordered. Even a 'for' loop walking through them might return them in different orders on different JavaScript implementations.
We should first know what is Pull to refresh layout in android . we can call pull to refresh in android as swipe-to-refresh. when you swipe screen from top to bottom it will do some action based on setOnRefreshListener.
Here's tutorial that demonstrate about how to implement android pull to refresh. I hope this helps.
One other option would be to use something like this
SELECT *
FROM table t INNER JOIN
(
SELECT 'Text%' Col
UNION SELECT 'Link%'
UNION SELECT 'Hello%'
UNION SELECT '%World%'
) List ON t.COLUMN LIKE List.Col
As it is a multi-class problem, you have to use the categorical_crossentropy, the binary cross entropy will produce bogus results, most likely will only evaluate the first two classes only.
50% for a multi-class problem can be quite good, depending on the number of classes. If you have n classes, then 100/n is the minimum performance you can get by outputting a random class.
If you are using Spring as Back-End server and especially using Spring Security then i found a solution by putting http.cors();
in the configure
method. The method looks like that:
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests() // authorize
.anyRequest().authenticated() // all requests are authenticated
.and()
.httpBasic();
http.cors();
}
I generally agree with solutions given above. Namely with:
for
-loop (2 and more lines)while
counter (3 and more lines)__nonzero__
implementation (many more lines) If one is to define an object as in #3 I would recommend implementing protocol for with keyword or apply contextlib.
Further I propose yet another solution. It is a 3 liner and is not of supreme elegance, but it uses itertools package and thus might be of an interest.
from itertools import (chain, repeat)
times = chain(repeat(True, 2), repeat(False))
while next(times):
print 'do stuff!'
In these example 2 is the number of times to iterate the loop. chain is wrapping two repeat iterators, the first being limited but the second is infinite. Remember that these are true iterator objects, hence they do not require infinite memory. Obviously this is much slower then solution #1. Unless written as a part of a function it might require a clean up for times variable.
As @Jono points out in @OneOfOne's answer, the correct answer should take into account the duration of a nanosecond. Eg:
func makeTimestamp() int64 {
return time.Now().UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}
OneOfOne's answer works because time.Nanosecond
happens to be 1
, and dividing by 1 has no effect. I don't know enough about go to know how likely this is to change in the future, but for the strictly correct answer I would use this function, not OneOfOne's answer. I doubt there is any performance disadvantage as the compiler should be able to optimize this perfectly well.
See https://en.wikipedia.org/wiki/Dimensional_analysis
Another way of looking at this is that both time.Now().UnixNano()
and time.Millisecond
use the same units (Nanoseconds). As long as that is true, OneOfOne's answer should work perfectly well.
You can set the line-height
in pixels instead of percentage. Is that what you mean?
I think you don't need to update only some specific field. Just update whole data.
@Update query
It is a given query basically. No need to make some new query.
@Dao
interface MemoDao {
@Insert
suspend fun insert(memo: Memo)
@Delete
suspend fun delete(memo: Memo)
@Update
suspend fun update(memo: Memo)
}
Memo.class
@Entity
data class Memo (
@PrimaryKey(autoGenerate = true) val id: Int,
@ColumnInfo(name = "title") val title: String?,
@ColumnInfo(name = "content") val content: String?,
@ColumnInfo(name = "photo") val photo: List<ByteArray>?
)
Only thing you need to know is 'id'. For instance, if you want to update only 'title', you can reuse 'content' and 'photo' from already inserted data. In real code, use like this
val memo = Memo(id, title, content, byteArrayList)
memoViewModel.update(memo)
You may like to first create a dialogue by right clicking the project in solution explorer and in the code file type
dialogue1.show()
that's all !!!
It appears to me that you have two issues here. One is that JFrame does not have a close
method, which has been addressed in the other answers.
The other is that you're having trouble referencing your JFrame. Within actionPerformed
, super
refers to ActionListener. To refer to the JFrame instance there, use MyExtendedJFrame.super
instead (you should also be able to use MyExtendedJFrame.this
, as I see no reason why you'd want to override the behaviour of dispose
or setVisible
).
psql -U username -d mydatabase -c 'SELECT * FROM mytable'
If you're new to postgresql and unfamiliar with using the command line tool psql
then there is some confusing behaviour you should be aware of when you've entered an interactive session.
For example, initiate an interactive session:
psql -U username mydatabase
mydatabase=#
At this point you can enter a query directly but you must remember to terminate the query with a semicolon ;
For example:
mydatabase=# SELECT * FROM mytable;
If you forget the semicolon then when you hit enter you will get nothing on your return line because psql
will be assuming that you have not finished entering your query. This can lead to all kinds of confusion. For example, if you re-enter the same query you will have most likely create a syntax error.
As an experiment, try typing any garble you want at the psql prompt then hit enter. psql
will silently provide you with a new line. If you enter a semicolon on that new line and then hit enter, then you will receive the ERROR:
mydatabase=# asdfs
mydatabase=# ;
ERROR: syntax error at or near "asdfs"
LINE 1: asdfs
^
The rule of thumb is:
If you received no response from psql
but you were expecting at least SOMETHING, then you forgot the semicolon ;
use jQuery's $.getJSON
$.getJSON('mydata.json', function(data) {
//do stuff with your data here
});
In addition to the answers above. You can do it programmatically by implementing the TrustManager:
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {}
}
};
SSLContext sc=null;
try {
sc = SSLContext.getInstance("SSL");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
sc.init(null, trustAllCerts, new java.security.SecureRandom());
} catch (KeyManagementException e) {
e.printStackTrace();
}
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier validHosts = new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
};
// All hosts will be valid
HttpsURLConnection.setDefaultHostnameVerifier(validHosts);
However this is not a good practice for production.
This example on How to disable SSL certificat validation in Java contains a utility class you can copy in your project.
Do it like this...
if (!Array.prototype.indexOf) {
}
As recommended compatibility by MDC.
In general, browser detection code is a big no-no.
For several cases, or even just a few cases involving a lot of criteria, consider using a switch.
switch( true ){
case ( !empty($youtube) && !empty($link) ):{
// Nothing is empty...
break;
}
case ( !empty($youtube) && empty($link) ):{
// One is empty...
break;
}
case ( empty($youtube) && !empty($link) ):{
// The other is empty...
break;
}
case ( empty($youtube) && empty($link) ):{
// Everything is empty
break;
}
default:{
// Even if you don't expect ever to use it, it's a good idea to ALWAYS have a default.
// That way if you change it, or miss a case, you have some default handler.
break;
}
}
If you have multiple cases that require the same action, you can stack them and omit the break; to flowthrough. Just maybe put a comment like /*Flowing through*/ so you're explicit about doing it on purpose.
Note that the { } around the cases aren't required, but they are nice for readability and code folding.
More about switch: http://php.net/manual/en/control-structures.switch.php
A global declaration provides this functionality. In the example below (python 3.5 or greater to use the "f"), the counter variable is defined outside of the function. Defining it as global in the function signifies that the "global" version outside of the function should be made available to the function. So each time the function runs, it modifies the value outside the function, preserving it beyond the function.
counter = 0
def foo():
global counter
counter += 1
print("counter is {}".format(counter))
foo() #output: "counter is 1"
foo() #output: "counter is 2"
foo() #output: "counter is 3"
The working solution listed are great, but the problem occurs when you want multiple default home for your git-bash.
A simple workaround is to start git-bash using bat script.
cd C:\xampp\htdocs
"C:\Program Files\Git\git-bash.exe"
The above of course assume git-bash is installed at C:\Program Files\Git\git-bash.exe
You can create multiple .bat
file so your git-bash can start where it want to be
I have faced same type of issue and followed the below steps to resolved the issue
Go to Tools --> Library Package Manager --> Package Manager Console and run the below command
Install-Package Microsoft.ASPNet.WebAPI -pre
Indeed there is an API to search google programmatically. The API is called google custom search. For using this API, you will need an Google Developer API key and a cx key. A simple procedure for accessing google search from java program is explained in my blog.
Now dead, here is the Wayback Machine link.
You can use a list comprehension:
>>> s = 'hi'
>>> [ord(c) for c in s]
[104, 105]
No, I don't believe there is any way to forward-declare a function in Python.
Imagine you are the Python interpreter. When you get to the line
print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)])
either you know what cmp_configs is or you don't. In order to proceed, you have to know cmp_configs. It doesn't matter if there is recursion.
My PHP is a little rusty, but I believe you're looking for indexed assignment. Simply use:
$catList[$row["datasource_id"]] = $row["title"];
In PHP arrays are actually maps, where the keys can be either integers or strings. Check out PHP: Arrays - Manual for more information.
"Not Possible". You can use a function instead of the stored procedure.
As mentioned in the question, there is the clip
css property, although it does require that the element being clipped is position: absolute;
(which is a shame):
.container {_x000D_
position: relative;_x000D_
}_x000D_
#clip {_x000D_
position: absolute;_x000D_
clip: rect(0, 100px, 200px, 0);_x000D_
/* clip: shape(top, right, bottom, left); NB 'rect' is the only available option */_x000D_
}
_x000D_
<div class="container">_x000D_
<img src="http://lorempixel.com/200/200/nightlife/3" />_x000D_
</div>_x000D_
<div class="container">_x000D_
<img id="clip" src="http://lorempixel.com/200/200/nightlife/3" />_x000D_
</div>
_x000D_
JS Fiddle demo, for experimentation.
To supplement the original answer – somewhat belatedly – I'm editing to show the use of clip-path
, which has replaced the now-deprecated clip
property.
The clip-path
property allows a range of options (more-so than the original clip
), of:
inset
— rectangular/cuboid shapes, defined with four values as 'distance-from' (top right bottom left)
.circle
— circle(diameter at x-coordinate y-coordinate)
.ellipse
— ellipse(x-axis-length y-axis-length at x-coordinate y-coordinate)
.polygon
— defined by a series of x
/y
coordinates in relation to the element's origin of the top-left corner. As the path is closed automatically the realistic minimum number of points for a polygon should be three, any fewer (two) is a line or (one) is a point: polygon(x-coordinate1 y-coordinate1, x-coordinate2 y-coordinate2, x-coordinate3 y-coordinate3, [etc...])
.url
— this can be either a local URL (using a CSS id-selector) or the URL of an external file (using a file-path) to identify an SVG, though I've not experimented with either (as yet), so I can offer no insight as to their benefit or caveat.div.container {_x000D_
display: inline-block;_x000D_
}_x000D_
#rectangular {_x000D_
-webkit-clip-path: inset(30px 10px 30px 10px);_x000D_
clip-path: inset(30px 10px 30px 10px);_x000D_
}_x000D_
#circle {_x000D_
-webkit-clip-path: circle(75px at 50% 50%);_x000D_
clip-path: circle(75px at 50% 50%)_x000D_
}_x000D_
#ellipse {_x000D_
-webkit-clip-path: ellipse(75px 50px at 50% 50%);_x000D_
clip-path: ellipse(75px 50px at 50% 50%);_x000D_
}_x000D_
#polygon {_x000D_
-webkit-clip-path: polygon(50% 0, 100% 38%, 81% 100%, 19% 100%, 0 38%);_x000D_
clip-path: polygon(50% 0, 100% 38%, 81% 100%, 19% 100%, 0 38%);_x000D_
}
_x000D_
<div class="container">_x000D_
<img id="control" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
<img id="rectangular" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
<img id="circle" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
<img id="ellipse" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
<img id="polygon" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>
_x000D_
JS Fiddle demo, for experimentation.
References:
clip
clip-path
(MDN).clip-path
(W3C).From client side, I cant solve this problem. From nodejs express side, you can use cors module to handle it.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var cors = require('cors');
var port = 3000;
var ip = '127.0.0.1';
app.use('*/myapi',
cors(), // with this row OPTIONS has handled
bodyParser.text({type:'text/*'}),
function( req, res, next ){
console.log( '\n.----------------' + req.method + '------------------------' );
console.log( '| prot:'+req.protocol );
console.log( '| host:'+req.get('host') );
console.log( '| url:'+req.originalUrl );
console.log( '| body:',req.body );
//console.log( '| req:',req );
console.log( '.----------------' + req.method + '------------------------' );
next();
});
app.listen(port, ip, function() {
console.log('Listening to port: ' + port );
});
console.log(('dir:'+__dirname ));
console.log('The server is up and running at http://'+ip+':'+port+'/');
Without cors() this OPTIONS has appears before POST.
.----------------OPTIONS------------------------
| prot:http
| host:localhost:3000
| url:/myapi
| body: {}
.----------------OPTIONS------------------------
.----------------POST------------------------
| prot:http
| host:localhost:3000
| url:/myapi
| body: <SOAP-ENV:Envelope .. P-ENV:Envelope>
.----------------POST------------------------
The ajax call:
$.ajax({
type: 'POST',
contentType: "text/xml; charset=utf-8",
// these does not works
//beforeSend: function(request) {
// request.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
// request.setRequestHeader('Accept', 'application/vnd.realtime247.sct-giro-v1+cms');
// request.setRequestHeader('Access-Control-Allow-Origin', '*');
// request.setRequestHeader('Access-Control-Allow-Methods', 'POST, GET');
// request.setRequestHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type');
//},
//headers: {
// 'Content-Type': 'text/xml; charset=utf-8',
// 'Accept': 'application/vnd.realtime247.sct-giro-v1+cms',
// 'Access-Control-Allow-Origin': '*',
// 'Access-Control-Allow-Methods': 'POST, GET',
// 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type'
//},
url: 'http://localhost:3000/myapi',
data: '<SOAP-ENV:Envelope .. P-ENV:Envelope>',
success: function( data ) {
console.log(data.documentElement.innerHTML);
},
error: function(jqXHR, textStatus, err) {
console.log( jqXHR,'\n', textStatus,'\n', err )
}
});
I encountered a similar issue recently. In my case the versions of cffi
and cryptography
written in requirements.txt weren't compatible (cffi==1.8.9 and cryptography==1.9). I solved updating cffi
with the last available version.
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
Another use of in_array in_array() with an array as needle
<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');
if (in_array(array('p', 'h'), $a)) {
echo "'ph' was found\n";
}
if (in_array(array('f', 'i'), $a)) {
echo "'fi' was found\n";
}
if (in_array('o', $a)) {
echo "'o' was found\n";
}
?>
SSL certificates are bound to a 'common name', which is usually a fully qualified domain name but can be a wildcard name (eg. *.domain.com) or even an IP address, but it usually isn't.
In your case, you are accessing your LDAP server by a hostname and it sounds like your two LDAP servers have different SSL certificates installed. Are you able to view (or download and view) the details of the SSL certificate? Each SSL certificate will have a unique serial numbers and fingerprint which will need to match. I assume the certificate is being rejected as these details don't match with what's in your certificate store.
Your solution will be to ensure that both LDAP servers have the same SSL certificate installed.
BTW - you can normally override DNS entries on your workstation by editing a local 'hosts' file, but I wouldn't recommend this.
Other than using time/datetime package, pandas can also be used to solve the same problem.Here is how we can use pandas to convert timestamp to readable date:
Timestamps can be in two formats:
13 digits(milliseconds) - To convert milliseconds to date, use:
import pandas
result_ms=pandas.to_datetime('1493530261000',unit='ms')
str(result_ms)
Output: '2017-04-30 05:31:01'
10 digits(seconds) - To convert seconds to date, use:
import pandas
result_s=pandas.to_datetime('1493530261',unit='s')
str(result_s)
Output: '2017-04-30 05:31:01'
First, Mv = numpy.asarray(M.T)
, which gives you a 4x1 but 2D array.
Then, perform A = Mv[0,:]
, which gives you what you want. You could put them together, as numpy.asarray(M.T)[0,:]
.
. ~/.bashrc
source ~/.bashrc
exec bash
exec
command replaces the shell with a given program... – WhoSayIn
I had the same problem and it works you just have to declare the i
outside of the loop:
int i;
for(i = low; i <= high; ++i)
{
res = runalg(i);
if (res > highestres)
{
highestres = res;
}
}
I think I can illustrate this quite nicely. Since nextTick
is called at the end of the current operation, calling it recursively can end up blocking the event loop from continuing. setImmediate
solves this by firing in the check phase of the event loop, allowing event loop to continue normally.
+-----------------------+
+->¦ timers ¦
¦ +-----------------------+
¦ +-----------------------+
¦ ¦ I/O callbacks ¦
¦ +-----------------------+
¦ +-----------------------+
¦ ¦ idle, prepare ¦
¦ +-----------------------+ +---------------+
¦ +-----------------------+ ¦ incoming: ¦
¦ ¦ poll ¦<-----¦ connections, ¦
¦ +-----------------------+ ¦ data, etc. ¦
¦ +-----------------------+ +---------------+
¦ ¦ check ¦
¦ +-----------------------+
¦ +-----------------------+
+--¦ close callbacks ¦
+-----------------------+
source: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/
Notice that the check phase is immediately after the poll phase. This is because the poll phase and I/O callbacks are the most likely places your calls to setImmediate
are going to run. So ideally most of those calls will actually be pretty immediate, just not as immediate as nextTick
which is checked after every operation and technically exists outside of the event loop.
Let's take a look at a little example of the difference between setImmediate
and process.nextTick
:
function step(iteration) {
if (iteration === 10) return;
setImmediate(() => {
console.log(`setImmediate iteration: ${iteration}`);
step(iteration + 1); // Recursive call from setImmediate handler.
});
process.nextTick(() => {
console.log(`nextTick iteration: ${iteration}`);
});
}
step(0);
Let's say we just ran this program and are stepping through the first iteration of the event loop. It will call into the step
function with iteration zero. It will then register two handlers, one for setImmediate
and one for process.nextTick
. We then recursively call this function from the setImmediate
handler which will run in the next check phase. The nextTick
handler will run at the end of the current operation interrupting the event loop, so even though it was registered second it will actually run first.
The order ends up being: nextTick
fires as current operation ends, next event loop begins, normal event loop phases execute, setImmediate
fires and recursively calls our step
function to start the process all over again. Current operation ends, nextTick
fires, etc.
The output of the above code would be:
nextTick iteration: 0
setImmediate iteration: 0
nextTick iteration: 1
setImmediate iteration: 1
nextTick iteration: 2
setImmediate iteration: 2
nextTick iteration: 3
setImmediate iteration: 3
nextTick iteration: 4
setImmediate iteration: 4
nextTick iteration: 5
setImmediate iteration: 5
nextTick iteration: 6
setImmediate iteration: 6
nextTick iteration: 7
setImmediate iteration: 7
nextTick iteration: 8
setImmediate iteration: 8
nextTick iteration: 9
setImmediate iteration: 9
Now let's move our recursive call to step
into our nextTick
handler instead of the setImmediate
.
function step(iteration) {
if (iteration === 10) return;
setImmediate(() => {
console.log(`setImmediate iteration: ${iteration}`);
});
process.nextTick(() => {
console.log(`nextTick iteration: ${iteration}`);
step(iteration + 1); // Recursive call from nextTick handler.
});
}
step(0);
Now that we have moved the recursive call to step
into the nextTick
handler things will behave in a different order. Our first iteration of the event loop runs and calls step
registering a setImmedaite
handler as well as a nextTick
handler. After the current operation ends our nextTick
handler fires which recursively calls step
and registers another setImmediate
handler as well as another nextTick
handler. Since a nextTick
handler fires after the current operation, registering a nextTick
handler within a nextTick
handler will cause the second handler to run immediately after the current handler operation finishes. The nextTick
handlers will keep firing, preventing the current event loop from ever continuing. We will get through all our nextTick
handlers before we see a single setImmediate
handler fire.
The output of the above code ends up being:
nextTick iteration: 0
nextTick iteration: 1
nextTick iteration: 2
nextTick iteration: 3
nextTick iteration: 4
nextTick iteration: 5
nextTick iteration: 6
nextTick iteration: 7
nextTick iteration: 8
nextTick iteration: 9
setImmediate iteration: 0
setImmediate iteration: 1
setImmediate iteration: 2
setImmediate iteration: 3
setImmediate iteration: 4
setImmediate iteration: 5
setImmediate iteration: 6
setImmediate iteration: 7
setImmediate iteration: 8
setImmediate iteration: 9
Note that had we not interrupted the recursive call and aborted it after 10 iterations then the nextTick
calls would keep recursing and never letting the event loop continue to the next phase. This is how nextTick
can become blocking when used recursively whereas setImmediate
will fire in the next event loop and setting another setImmediate
handler from within one won't interrupt the current event loop at all, allowing it to continue executing phases of the event loop as normal.
Hope that helps!
PS - I agree with other commenters that the names of the two functions could easily be swapped since nextTick
sounds like it's going to fire in the next event loop rather than the end of the current one, and the end of the current loop is more "immediate" than the beginning of the next loop. Oh well, that's what we get as an API matures and people come to depend on existing interfaces.
@media all and (orientation:portrait) {
/* Style adjustments for portrait mode goes here */
}
@media all and (orientation:landscape) {
/* Style adjustments for landscape mode goes here */
}
but it still looks like you have to experiment
I just add a static method to call it like a MessageBox:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
x:Class="utils.PromptDialog"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
WindowStartupLocation="CenterScreen"
SizeToContent="WidthAndHeight"
MinWidth="300"
MinHeight="100"
WindowStyle="SingleBorderWindow"
ResizeMode="CanMinimize">
<StackPanel Margin="5">
<TextBlock Name="txtQuestion" Margin="5"/>
<TextBox Name="txtResponse" Margin="5"/>
<PasswordBox Name="txtPasswordResponse" />
<StackPanel Orientation="Horizontal" Margin="5" HorizontalAlignment="Right">
<Button Content="_Ok" IsDefault="True" Margin="5" Name="btnOk" Click="btnOk_Click" />
<Button Content="_Cancel" IsCancel="True" Margin="5" Name="btnCancel" Click="btnCancel_Click" />
</StackPanel>
</StackPanel>
</Window>
And the code behind:
public partial class PromptDialog : Window
{
public enum InputType
{
Text,
Password
}
private InputType _inputType = InputType.Text;
public PromptDialog(string question, string title, string defaultValue = "", InputType inputType = InputType.Text)
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(PromptDialog_Loaded);
txtQuestion.Text = question;
Title = title;
txtResponse.Text = defaultValue;
_inputType = inputType;
if (_inputType == InputType.Password)
txtResponse.Visibility = Visibility.Collapsed;
else
txtPasswordResponse.Visibility = Visibility.Collapsed;
}
void PromptDialog_Loaded(object sender, RoutedEventArgs e)
{
if (_inputType == InputType.Password)
txtPasswordResponse.Focus();
else
txtResponse.Focus();
}
public static string Prompt(string question, string title, string defaultValue = "", InputType inputType = InputType.Text)
{
PromptDialog inst = new PromptDialog(question, title, defaultValue, inputType);
inst.ShowDialog();
if (inst.DialogResult == true)
return inst.ResponseText;
return null;
}
public string ResponseText
{
get
{
if (_inputType == InputType.Password)
return txtPasswordResponse.Password;
else
return txtResponse.Text;
}
}
private void btnOk_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
Close();
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
Close();
}
}
So you can call it like:
string repeatPassword = PromptDialog.Prompt("Repeat password", "Password confirm", inputType: PromptDialog.InputType.Password);
My problem was eventually solved when I looked at the IIS Express registry key:
HKEY_CURRENT_USER\Software\Microsoft\IISExpress
I had an entry CustomUserHome
pointing to My Web Sites which was causing havoc.
Once an update is committed you can't rollback just the single update. Your best bet is to roll back to a previous backup of the database.
As other answers have mentioned, the &&
token in this context is new to C++0x (the next C++ standard) and represent an "rvalue reference".
Rvalue references are one of the more important new things in the upcoming standard; they enable support for 'move' semantics on objects and permit perfect forwarding of function calls.
It's a rather complex topic - one of the best introductions (that's not merely cursory) is an article by Stephan T. Lavavej, "Rvalue References: C++0x Features in VC10, Part 2"
Note that the article is still quite heavy reading, but well worthwhile. And even though it's on a Microsoft VC++ Blog, all (or nearly all) the information is applicable to any C++0x compiler.
Actually Im agree with MikeW (+1) it's better to use profiler for this case.
Anyway, if you really need to grab all (n)varchar columns in db and make a search. See below. I suppose to use INFORMATION_SCHEMA.Tables + dynamic SQL. The plain search:
DECLARE @SearchText VARCHAR(100)
SET @SearchText = '12'
DECLARE @Tables TABLE(N INT, TableName VARCHAR(100), ColumnNamesCSV VARCHAR(2000), SQL VARCHAR(4000))
INSERT INTO @Tables (TableName, ColumnNamesCSV)
SELECT T.TABLE_NAME AS TableName,
( SELECT C.Column_Name + ','
FROM INFORMATION_SCHEMA.Columns C
WHERE T.TABLE_NAME = C.TABLE_NAME
AND C.DATA_TYPE IN ('nvarchar','varchar')
FOR XML PATH('')
)
FROM INFORMATION_SCHEMA.Tables T
DELETE FROM @Tables WHERE ColumnNamesCSV IS NULL
INSERT INTO @Tables (N, TableName, ColumnNamesCSV)
SELECT ROW_NUMBER() OVER(ORDER BY TableName), TableName, ColumnNamesCSV
FROM @Tables
DELETE FROM @Tables WHERE N IS NULL
UPDATE @Tables
SET ColumnNamesCSV = SUBSTRING(ColumnNamesCSV, 0, LEN(ColumnNamesCSV))
UPDATE @Tables
SET SQL = 'SELECT * FROM ['+TableName+'] WHERE '''+@SearchText+''' IN ('+ColumnNamesCSV+')'
DECLARE @C INT,
@I INT,
@SQL VARCHAR(4000)
SELECT @I = 1,
@C = COUNT(1)
FROM @Tables
WHILE @I <= @C BEGIN
SELECT @SQL = SQL FROM @Tables WHERE N = @I
SET @I = @I+1
EXEC(@SQL)
END
and one with LIKE clause:
DECLARE @SearchText VARCHAR(100)
SET @SearchText = '12'
DECLARE @Tables TABLE(N INT, TableName VARCHAR(100), ColumnNamesCSVLike VARCHAR(2000), LIKESQL VARCHAR(4000))
INSERT INTO @Tables (TableName, ColumnNamesCSVLike)
SELECT T.TABLE_NAME AS TableName,
( SELECT C.Column_Name + ' LIKE ''%'+@SearchText+'%'' OR '
FROM INFORMATION_SCHEMA.Columns C
WHERE T.TABLE_NAME = C.TABLE_NAME
AND C.DATA_TYPE IN ('nvarchar','varchar')
FOR XML PATH(''))
FROM INFORMATION_SCHEMA.Tables T
DELETE FROM @Tables WHERE ColumnNamesCSVLike IS NULL
INSERT INTO @Tables (N, TableName, ColumnNamesCSVLike)
SELECT ROW_NUMBER() OVER(ORDER BY TableName), TableName, ColumnNamesCSVLike
FROM @Tables
DELETE FROM @Tables WHERE N IS NULL
UPDATE @Tables
SET ColumnNamesCSVLike = SUBSTRING(ColumnNamesCSVLike, 0, LEN(ColumnNamesCSVLike)-2)
UPDATE @Tables SET LIKESQL = 'SELECT * FROM ['+TableName+'] WHERE '+ColumnNamesCSVLike
DECLARE @C INT,
@I INT,
@LIKESQL VARCHAR(4000)
SELECT @I = 1,
@C = COUNT(1)
FROM @Tables
WHILE @I <= @C BEGIN
SELECT @LIKESQL = LIKESQL FROM @Tables WHERE N = @I
SET @I = @I +1
EXEC(@LIKESQL)
END
Thanks resources present in Stackoverflow
in helping me to find this answer.
You can find your remotely Android crash reports directly into your email. remmember you have to put your email inside CustomExceptionHandler class.
public static String sendErrorLogsTo = "[email protected]" ;
Steps required :
1st) in onCreate of your activity use this section of your code.
if(!(Thread.getDefaultUncaughtExceptionHandler() instanceof CustomExceptionHandler)) {
Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(this));
}
2nd) use this overridden version of CustomExceptionHandler class of ( rrainn ), according to my phpscript.
package com.vxmobilecomm.activity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.util.Log;
public class CustomExceptionHandler implements UncaughtExceptionHandler {
private UncaughtExceptionHandler defaultUEH;
public static String sendErrorLogsTo = "[email protected]" ;
Activity activity;
public CustomExceptionHandler(Activity activity) {
this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
this.activity = activity;
}
public void uncaughtException(Thread t, Throwable e) {
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
e.printStackTrace(printWriter);
String stacktrace = result.toString();
printWriter.close();
String filename = "error" + System.nanoTime() + ".stacktrace";
Log.e("Hi", "url != null");
sendToServer(stacktrace, filename);
StackTraceElement[] arr = e.getStackTrace();
String report = e.toString() + "\n\n";
report += "--------- Stack trace ---------\n\n";
for (int i = 0; i < arr.length; i++) {
report += " " + arr[i].toString() + "\n";
}
report += "-------------------------------\n\n";
report += "--------- Cause ---------\n\n";
Throwable cause = e.getCause();
if (cause != null) {
report += cause.toString() + "\n\n";
arr = cause.getStackTrace();
for (int i = 0; i < arr.length; i++) {
report += " " + arr[i].toString() + "\n";
}
}
report += "-------------------------------\n\n";
defaultUEH.uncaughtException(t, e);
}
private void sendToServer(String stacktrace, String filename) {
AsyncTaskClass async = new AsyncTaskClass(stacktrace, filename,
getAppLable(activity));
async.execute("");
}
public String getAppLable(Context pContext) {
PackageManager lPackageManager = pContext.getPackageManager();
ApplicationInfo lApplicationInfo = null;
try {
lApplicationInfo = lPackageManager.getApplicationInfo(
pContext.getApplicationInfo().packageName, 0);
} catch (final NameNotFoundException e) {
}
return (String) (lApplicationInfo != null ? lPackageManager
.getApplicationLabel(lApplicationInfo) : "Unknown");
}
public class AsyncTaskClass extends AsyncTask<String, String, InputStream> {
InputStream is = null;
String stacktrace;
final String filename;
String applicationName;
AsyncTaskClass(final String stacktrace, final String filename,
String applicationName) {
this.applicationName = applicationName;
this.stacktrace = stacktrace;
this.filename = filename;
}
@Override
protected InputStream doInBackground(String... params)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://suo-yang.com/books/sendErrorLog/sendErrorLogs.php?");
Log.i("Error", stacktrace);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
6);
nameValuePairs.add(new BasicNameValuePair("data", stacktrace));
nameValuePairs.add(new BasicNameValuePair("to",sendErrorLogsTo));
nameValuePairs.add(new BasicNameValuePair("subject",applicationName));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity1 = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(
entity1);
is = bufHttpEntity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
@Override
protected void onPostExecute(InputStream result) {
super.onPostExecute(result);
Log.e("Stream Data", getStringFromInputStream(is));
}
}
// convert InputStream to String
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}
According to the latest documentation
from selenium import webdriver
PROXY = "<HOST:PORT>"
webdriver.DesiredCapabilities.FIREFOX['proxy'] = {
"httpProxy": PROXY,
"ftpProxy": PROXY,
"sslProxy": PROXY,
"proxyType": "MANUAL",
}
with webdriver.Firefox() as driver:
# Open URL
driver.get("https://selenium.dev")
For fadeIn and fadeOut, only add this after super.onCreate(savedInstanceState) in your new Activity class. You don't need to create something else (No XML, no anim folder, no extra function).
overridePendingTransition(R.anim.abc_fade_in,R.anim.abc_fade_out);
Just need to change one letter:), rename 640x360.ogv to 640x360.ogg, it will work for all the 3 browers.
Using Thread.interrupt()
is a perfectly acceptable way of doing this. In fact, it's probably preferrable to a flag as suggested above. The reason being that if you're in an interruptable blocking call (like Thread.sleep
or using java.nio Channel operations), you'll actually be able to break out of those right away.
If you use a flag, you have to wait for the blocking operation to finish and then you can check your flag. In some cases you have to do this anyway, such as using standard InputStream
/OutputStream
which are not interruptable.
In that case, when a thread is interrupted, it will not interrupt the IO, however, you can easily do this routinely in your code (and you should do this at strategic points where you can safely stop and cleanup)
if (Thread.currentThread().isInterrupted()) {
// cleanup and stop execution
// for example a break in a loop
}
Like I said, the main advantage to Thread.interrupt()
is that you can immediately break out of interruptable calls, which you can't do with the flag approach.
You can use yahoo to get daily data (a much more managable dataset) but you have to structure the urls. See this link. You are not making lots of little requests you are making a fewer large requests. Lot of free software uses this so they shouldn't shut you down.
EDIT: This guy does it, maybe you can have a look at the calls his software makes.
On Windows, you can also use the Win32 File Namespace prefixed with \\?\
to refer to your local directories:
\\?\C:\my_dir
I'm listing out the differences below:
A function declaration can be placed anywhere in the code. Even if it is invoked before the definition appears in code, it gets executed as function declaration is committed to memory or in a way it is hoisted up, before any other code in the page starts execution.
Take a look at the function below:
function outerFunction() {
function foo() {
return 1;
}
return foo();
function foo() {
return 2;
}
}
alert(outerFunction()); // Displays 2
This is because, during execution, it looks like:-
function foo() { // The first function declaration is moved to top
return 1;
}
function foo() { // The second function declaration is moved to top
return 2;
}
function outerFunction() {
return foo();
}
alert(outerFunction()); //So executing from top to bottom,
//the last foo() returns 2 which gets displayed
A function expression, if not defined before calling it, will result in an error. Also, here the function definition itself is not moved to the top or committed to memory like in the function declarations. But the variable to which we assign the function gets hoisted up and undefined gets assigned to it.
Same function using function expressions:
function outerFunction() {
var foo = function() {
return 1;
}
return foo();
var foo = function() {
return 2;
}
}
alert(outerFunction()); // Displays 1
This is because during execution, it looks like:
function outerFunction() {
var foo = undefined;
var foo = undefined;
foo = function() {
return 1;
};
return foo ();
foo = function() { // This function expression is not reachable
return 2;
};
}
alert(outerFunction()); // Displays 1
It is not safe to write function declarations in non-function blocks like if because they won't be accessible.
if (test) {
function x() { doSomething(); }
}
Named function expression like the one below, may not work in Internet Explorer browsers prior to version 9.
var today = function today() {return new Date()}
The GNU Coding Standard is a good reference for things like this. This section deals with the output of --help
. In this case it is not very specific. You probably can't go wrong with printing a table showing the short and long options and a succinct description. Try to get the spacing between all arguments right for readability. You probably want to provide a man
page (and possibly an info
manual) for your tool to provide a more elaborate explanation.
Alternative iterative solution:
def myprint(d):
stack = d.items()
while stack:
k, v = stack.pop()
if isinstance(v, dict):
stack.extend(v.iteritems())
else:
print("%s: %s" % (k, v))
You can use this code to add placeholder attr for every TextInput field in you form. Text for placeholders will be taken from model field labels.
class PlaceholderDemoForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(PlaceholderDemoForm, self).__init__(*args, **kwargs)
for field_name in self.fields:
field = self.fields.get(field_name)
if field:
if type(field.widget) in (forms.TextInput, forms.DateInput):
field.widget = forms.TextInput(attrs={'placeholder': field.label})
class Meta:
model = DemoModel
You could make a helper method. Something like:
public bool IsNumeric(string input) {
int test;
return int.TryParse(input, out test);
}
If you truly want to confirm that a variable is not null and not an empty string specifically, you would write:
if(data !== null && data !== '') {
// do something
}
Notice that I changed your code to check for type equality (!==
|===
).
If, however you just want to make sure, that a code will run only for "reasonable" values, then you can, as others have stated already, write:
if (data) {
// do something
}
Since, in javascript, both null values, and empty strings, equals to false (i.e. null == false
).
The difference between those 2 parts of code is that, for the first one, every value that is not specifically null or an empty string, will enter the if
. But, on the second one, every true-ish value will enter the if
: false
, 0
, null
, undefined
and empty strings, would not.
My simple solution which is based on the default value of function parameters.
def getSystemContext(contextObjList=[]):
if len( contextObjList ) == 0:
contextObjList.append( Context() )
pass
return contextObjList[0]
class Context(object):
# Anything you want here
If you don't care about a minimum width for the div and really just don't want the div to expand across the whole container, you can float it left -- floated divs by default expand to support their contents, like so:
<form>
<div style="float: left; background-color: blue">
<input type="button" name="blah" value="lots and lots of characters"/>
<input type="button" name="blah2" value="some characters"/>
</div>
</form>
If the content is loaded via ajax anyway, use javascript to manipulate the placeholder. Every css approach is hack-isch anyway.
E.g. with jQuery:
$('#myFieldId').attr('placeholder', 'Search for Stuff');
If you don't care about the data, you can drop database first and then recreate it:
DROP DATABASE IF EXISTS dbname;
CREATE DATABASE dbname;
I spent a lot of time solving this.
Eventually what worked was going to project settings in android studio, sdk tools, uncheck hide obsolete packages and install sdk tools obsolete package.
Then run flutter doctor --android-licenses and then flutter doctor showed a green tick on my android toolchain.
Hope this helps someone.
I ran into this problem as well, it ended up that I had two postgres servers running at the same time. I uninstalled one of them and changed the port back to 5432 and works fine now.
You're making an HTTP POST, but trying to pass parameters with the GET query string syntax. In a POST, the data are passed as named parameters and do not use the param=value&foo=bar
syntax. Using jQuery's ajax method lets you create a javascript object with the named parameters, like so:
$.ajax({
url: '/Home/SaveChart',
type: 'POST',
async: false,
dataType: 'text',
processData: false,
data: {
input: JSON.stringify(IVRInstant.data),
name: $("#wrkname").val()
},
success: function (data) { }
});
If you need Date Object
Passing only date string Date assumes time to be 00:00 shifted by time zone:
new Date('2019-03-11')
Sun Mar 10 2019 18:00:00 GMT-0600 (Central Standard Time)
If you add current hours and minutes you get proper date:
new Date('2019-03-11 ' + new Date().getHours() + ':' + new Date().getMinutes())
Mon Mar 11 2019 04:36:00 GMT-0600 (Central Standard Time)
The simplest and most fun way (imo) is glob
foreach (glob("*.*") as $filename) {
echo $filename."<br />";
}
But the standard way is to use the directory functions.
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: .".$file."<br />";
}
closedir($dh);
}
}
There are also the SPL DirectoryIterator methods. If you are interested
I'm adding this answer because I don't see it here.
One way is to put a '+' character in front of the value
example:
var x = +'11.5' + +'3.5'
x === 15
I have found this to be the simplest way
In this case, the line:
dots = document.getElementById("txt").value;
could be changed to
dots = +(document.getElementById("txt").value);
to force it to a number
NOTE:
+'' === 0
+[] === 0
+[5] === 5
+['5'] === 5
After installing Free BitDefender AntiVirus the services related to the AntiVirus used about 80 MB of my computer's Memory. I also noticed that after installing BitDefender the service related to windows Presentation Font Cache was also installed: "WPFFontCache_v0300.exe". I disabled the service from stating automatically and now BitDefender Free AntiVirus use only 15-20 MB (!!!) of my computer's Memory! As far as I concern, this service affected negatively the memory usage of my PC inother services. I recommend you to disable it.
This wasn't available when this question was answered, but you can also use the live() method to enable/disable events.
$('#myimage:not(.disabled)').live('click', myclickevent);
$('#mydisablebutton').click( function () { $('#myimage').addClass('disabled'); });
What will happen with this code is that when you click #mydisablebutton, it will add the class disabled to the #myimage element. This will make it so that the selector no longer matches the element and the event will not be fired until the 'disabled' class is removed making the .live() selector valid again.
This has other benefits by adding styling based on that class as well.
You could also a for loop to do so:
#!/bin/bash
for i in *.sql
do
echo "Importing: $i"
mysql your_db_name < $i
wait
done
In case you're interested in a solution using Java 7 and NIO.2, it could go like this:
private static class DirectoriesFilter implements Filter<Path> {
@Override
public boolean accept(Path entry) throws IOException {
return Files.isDirectory(entry);
}
}
try (DirectoryStream<Path> ds = Files.newDirectoryStream(FileSystems.getDefault().getPath(root), new DirectoriesFilter())) {
for (Path p : ds) {
System.out.println(p.getFileName());
}
} catch (IOException e) {
e.printStackTrace();
}
Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding. When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system) or larger. Data alignment means putting the data at a memory address equal to some multiple of the word size, which increases the system’s performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.
You can derive a class from Runnable, and during the construction (say) pass the parameter in.
Then launch it using Thread.start(Runnable r);
If you mean whilst the thread is running, then simply hold a reference to your derived object in the calling thread, and call the appropriate setter methods (synchronising where appropriate)
a {
outline: 0;
}
But read this before change it:
This is not a precise answer for the question but may help in finding a workaround for it.
I had an image I was hiding on page load and displaying when waiting on an AJAX call then hiding again however...
I found the only way to display my image when loading the page then make it disappear and be able to click things where the image was located before hiding it was to put the image into a DIV, make the size of the DIV 10x10 pixels or small enough to prevent it causing an issue then hiding the containing div. This allowed the image to overflow the div while visible and when the div was hidden, only the divs area was affected by inability to click objects beneath and not the whole size of the image the DIV contained and was displaying.
I tried all the methods to hide the image including CSS display=none/block, opacity=0, hiding the image with hidden=true. All of them resulted in my image being hidden but the area where it was displayed to act like there was a cover over the stuff underneath so clicks and so on wouldn't act on the underlying objects. Once the image was inside a tiny DIV and I hid the tiny DIV, the entire area occupied by the image was clear and only the tiny area under the DIV I hid was affected but as I made it small enough (10x10 pixels), the issue was fixed (sort of).
I found this to be a dirty workaround for what should be a simple issue but I was not able to find any way to hide the object in its native format without a container. My object was in the form of etc. If anyone has a better way, please let me know.
You can use text-overflow: ellipsis; which according to caniuse is supported by all the major browsers.
Here's a demo on jsbin.
.cut-text {
text-overflow: ellipsis;
overflow: hidden;
width: 160px;
height: 1.2em;
white-space: nowrap;
}
_x000D_
<div class="cut-text">
I like big butts and I can not lie.
</div>
_x000D_
EX:
<input type="textbox" ondrop="return false;" onpaste="return false;">
Use these attributes in the required textbox in HTML. Now the drag-and-drop and the paste functionality are disabled.
I've resorted to
df[ (df[column_name].notnull()) & (df[column_name]!=u'') ].index
lately. That gets both null and empty-string cells in one go.
Use a named fifo.
#!/bin/sh
mkfifo trigger
while true; do
read < trigger
long_running_task
done
Then whenever you want to start the long running task, simply write a newline (nonblocking to the trigger file.
As long as your input is smaller than PIPE_BUF
and it's a single write()
operation, you can write arguments into the fifo and have them show up as $REPLY
in the script.
In OS X Mavericks running Sublime Text 2 the following worked for me.
sudo ln -s /Applications/Sublime\ Text\ 2.app/Contents/SharedSupport/bin/subl /usr/bin/subl
Its handy to locate the file in the finder and drag and drop that into the terminal window so you can be sure the path is the correct one, I'm not a huge terminal user so this was more comfortable for me. then you can go to the start of the path and start adding in the other parts like the shorthand UNIX commands. Hope this helps
To find a very long list of words in big files, it can be more efficient to use egrep:
remove the last \n of A
$ tr '\n' '|' < A > A_regex
$ egrep -f A_regex B
Raphael is not supported on pre 3.0 Android browsers, that's what your problem is. They have no support for SVG graphics. It does have support for canvas though. If you don't need to animate it, you could render the graphics with canvg:
http://code.google.com/p/canvg/
That's how we got around this issue for rendering SVG icons in the default Android browser.
HTML
<input type="checkbox" id="checkme"/><input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />
JS
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
checker.onchange = function() {
sendbtn.disabled = !!this.checked;
};
This is caused by the limited support for the MP4 format within the video tag in Firefox. Support was not added until Firefox 21, and it is still limited to Windows 7 and above. The main reason for the limited support revolves around the royalty fee attached to the mp4 format.
Check out Supported media formats and Media formats supported by the audio and video elements directly from the Mozilla crew or the following blog post for more information:
http://pauljacobson.org/2010/01/22/2010122firefox-and-its-limited-html-5-video-support-html/
Building on Vitaliy's CSS and Mehmet's jQuery, I changed the a
tags to span
tags and incorporated some Glyphicons and badging into my take on a Bootstrap tree widget.
Example:
For extra credit, I've created a GitHub project to host the jQuery and LESS code that goes into adding this tree component to Bootstrap. Please see the project documentation at http://jhfrench.github.io/bootstrap-tree/docs/example.html.
Alternately, here is the LESS source to generate that CSS (the JS can be picked up from the jsFiddle):
@import "../../../external/bootstrap/less/bootstrap.less"; /* substitute your path to the bootstrap.less file */
@import "../../../external/bootstrap/less/responsive.less"; /* optional; substitute your path to the responsive.less file */
/* collapsable tree */
.tree {
.border-radius(@baseBorderRadius);
.box-shadow(inset 0 1px 1px rgba(0,0,0,.05));
background-color: lighten(@grayLighter, 5%);
border: 1px solid @grayLight;
margin-bottom: 10px;
max-height: 300px;
min-height: 20px;
overflow-y: auto;
padding: 19px;
a {
display: block;
overflow: hidden;
text-overflow: ellipsis;
width: 90%;
}
li {
list-style-type: none;
margin: 0px 0;
padding: 4px 0px 0px 2px;
position: relative;
&::before, &::after {
content: '';
left: -20px;
position: absolute;
right: auto;
}
&::before {
border-left: 1px solid @grayLight;
bottom: 50px;
height: 100%;
top: 0;
width: 1px;
}
&::after {
border-top: 1px solid @grayLight;
height: 20px;
top: 13px;
width: 23px;
}
span {
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border: 1px solid @grayLight;
border-radius: 5px;
display: inline-block;
line-height: 14px;
padding: 2px 4px;
text-decoration: none;
}
&.parent_li > span {
cursor: pointer;
/*Time for some hover effects*/
&:hover, &:hover+ul li span {
background: @grayLighter;
border: 1px solid @gray;
color: #000;
}
}
/*Remove connectors after last child*/
&:last-child::before {
height: 30px;
}
}
/*Remove connectors before root*/
> ul > li::before, > ul > li::after {
border: 0;
}
}
to export
mongodump -d <database name> <backup-folder>
to import
mongorestore -d <database name> <backup-folder>
you might want to try this. Seems to be pretty easy and works on IE6 and Moz atleast.
<div id ="show" style="background-color:Silver;width:100px;height:100px;visibility:visible;border-bottom:outset 1px black;border-right:outset 1px black;" ></div>
The general syntax is : border-[postion]:[border-style] [border-width] [border-color] | inherit
The list of available [border-style]s are :
Backticks in JavaScript is a feature which is introduced in ECMAScript 6 // ECMAScript 2015 for making easy dynamic strings. This ECMAScript 6 feature is also named template string literal. It offers the following advantages when compared to normal strings:
''
or ""
) are not allowed to have linebreaks.${myVariable}
syntax.const name = 'Willem';_x000D_
const age = 26;_x000D_
_x000D_
const story = `_x000D_
My name is: ${name}_x000D_
And I'm: ${age} years old_x000D_
`;_x000D_
_x000D_
console.log(story);
_x000D_
Template string literal are natively supported by all major browser vendors (except Internet Explorer). So it is pretty save to use in your production code. A more detailed list of the browser compatibilities can be found here.
I had a similar problem in spring tool suite(sts). THE .m2 repository was not completely downloaded in the local system which is the reason why I was getting this error. So I reinstalled sts and deleted the old .m2 repository from the system and created a new maven project in sts which downloaded the complete .m2 repository. It worked for me.
According to the documentation for that plugin, .visible()
returns a boolean indicating if the element is visible. So you'd use it like this:
if ($('#element').visible(true)) {
// The element is visible, do something
} else {
// The element is NOT visible, do something else
}
reload()
is supposed to accept an argument which tells it to do a hard reload, ie, ignoring the cache:
location.reload(true);
I can't vouch for its reliability, you may want to investigate this further.
If you don't want to pass the clicked on element to the function through a parameter, then you need to access the event object that is happening, and get the target from that object. This is most easily done if you bind the click event like this:
$('#sendButton').click(function(e){
var SendButton = $(e.target);
var TheForm = SendButton.parents('form');
TheForm.submit();
return false;
});
I've been using an Evaluation copy of Sublime Text
. What's good is it doesn't really expire.
It's been good so far and was really easy to get started with.
Try this:
case $VAR in
normal)
echo "This doesn't do fallthrough"
;;
special)
echo -n "This does "
;&
fallthrough)
echo "fall-through"
;;
esac
Default arguments get evaluated at the time the function is compiled into a function object. When used by the function, multiple times by that function, they are and remain the same object.
When they are mutable, when mutated (for example, by adding an element to it) they remain mutated on consecutive calls.
They stay mutated because they are the same object each time.
Since the list is bound to the function when the function object is compiled and instantiated, this:
def foo(mutable_default_argument=[]): # make a list the default argument
"""function that uses a list"""
is almost exactly equivalent to this:
_a_list = [] # create a list in the globals
def foo(mutable_default_argument=_a_list): # make it the default argument
"""function that uses a list"""
del _a_list # remove globals name binding
Here's a demonstration - you can verify that they are the same object each time they are referenced by
example.py
print('1. Global scope being evaluated')
def create_list():
'''noisily create a list for usage as a kwarg'''
l = []
print('3. list being created and returned, id: ' + str(id(l)))
return l
print('2. example_function about to be compiled to an object')
def example_function(default_kwarg1=create_list()):
print('appending "a" in default default_kwarg1')
default_kwarg1.append("a")
print('list with id: ' + str(id(default_kwarg1)) +
' - is now: ' + repr(default_kwarg1))
print('4. example_function compiled: ' + repr(example_function))
if __name__ == '__main__':
print('5. calling example_function twice!:')
example_function()
example_function()
and running it with python example.py
:
1. Global scope being evaluated
2. example_function about to be compiled to an object
3. list being created and returned, id: 140502758808032
4. example_function compiled: <function example_function at 0x7fc9590905f0>
5. calling example_function twice!:
appending "a" in default default_kwarg1
list with id: 140502758808032 - is now: ['a']
appending "a" in default default_kwarg1
list with id: 140502758808032 - is now: ['a', 'a']
This order of execution is frequently confusing to new users of Python. If you understand the Python execution model, then it becomes quite expected.
But this is why the usual instruction to new users is to create their default arguments like this instead:
def example_function_2(default_kwarg=None):
if default_kwarg is None:
default_kwarg = []
This uses the None singleton as a sentinel object to tell the function whether or not we've gotten an argument other than the default. If we get no argument, then we actually want to use a new empty list, []
, as the default.
As the tutorial section on control flow says:
If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:
def f(a, L=None): if L is None: L = [] L.append(a) return L
I have suffered the same issue and was able to solve it by simply changing on my Android device (Nexus 5X) in Developer options > Select USB Configuration to RNDIS (USB Ethernet)
To check if variable is null or empty use this:
IF LEN(ISNULL(@var, '')) = 0
-- Is empty or NULL
ELSE
-- Is not empty and is not NULL
Another alternative is
npm install react-favicon
And in your application you would just do:
import Favicon from 'react-favicon';
//other codes
ReactDOM.render(
<div>
<Favicon url="/path/to/favicon.ico"/>
// do other stuff here
</div>
, document.querySelector('.react'));
__new__
is static class method, while __init__
is instance method.
__new__
has to create the instance first, so __init__
can initialize it. Note that __init__
takes self
as parameter. Until you create instance there is no self
.
Now, I gather, that you're trying to implement singleton pattern in Python. There are a few ways to do that.
Also, as of Python 2.6, you can use class decorators.
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
@singleton
class MyClass:
...
If you find by alphabet in plist, it should be "Application supports iTunes file sharing".
You need to run Set-ExecutionPolicy
:
Set-ExecutionPolicy Restricted <-- Will not allow any powershell scripts to run. Only individual commands may be run.
Set-ExecutionPolicy AllSigned <-- Will allow signed powershell scripts to run.
Set-ExecutionPolicy RemoteSigned <-- Allows unsigned local script and signed remote powershell scripts to run.
Set-ExecutionPolicy Unrestricted <-- Will allow unsigned powershell scripts to run. Warns before running downloaded scripts.
Set-ExecutionPolicy Bypass <-- Nothing is blocked and there are no warnings or prompts.
Use this function to regain the utf-8 characters
function decode_utf8(s) {
return decodeURIComponent(escape(s));
}
Example: var new_Str=decode_utf8(str);
I think this other Stack Overflow answer would solve your problem: How do I run a bat file in the background from another bat file?
Basically, you use the /B
and /C
options:
START /B CMD /C CALL "foo.bat" [args [...]] >NUL 2>&1
Yes the tab character is one character. You can match it in java with "\t".
It takes some time to return results, easily many tens of seconds, but wmic works well and can be scripted:
wmic product where "Name like '%Word%'" get Name, Version, IdentifyingNumber
result:
IdentifyingNumber Name Version
{90140000-001B-0409-0000-0000000FF1CE} Microsoft Office Word MUI (English) 2010 14.0.6029.1000
The IdentifingNumber
is the ProductCode. I didn't see a property for UpgradeCode, but perhaps it might be buried under something else. See http://quux.wiki.zoho.com/WMIC-Snippets.html for many other examples, including uninstall:
wmic path win32_product where "name = 'HP Software Update'" call Uninstall
Setting a width of 100% is the full width of the div it's in, not the original full-sized image. There is no way to do that without JavaScript or some other scripting language that can measure the image. If you can have a fixed width or fixed height of the div (like 200px wide) then it shouldn't be too hard to give the image a range to fill. But if you put a 20x20 pixel image in a 200x300 pixel box it will still be distorted.
I had different version of annotations jar. Changed all 3 jars to use SAME version of databind,annotations and core jackson jars
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.6</version>
</dependency>
So before I found this post, I successfully found this to work.
Model._meta.fields
It works equally as
Model._meta.get_fields()
I'm not sure what the difference is in the results, if there is one. I ran this loop and got the same output.
for field in Model._meta.fields:
print(field.name)
Html.Label
gives you a label for an input whose name matches the specified input text (more specifically, for the model property matching the string expression):
// Model
public string Test { get; set; }
// View
@Html.Label("Test")
// Output
<label for="Test">Test</label>
Html.LabelFor
gives you a label for the property represented by the provided expression (typically a model property):
// Model
public class MyModel
{
[DisplayName("A property")]
public string Test { get; set; }
}
// View
@model MyModel
@Html.LabelFor(m => m.Test)
// Output
<label for="Test">A property</label>
Html.LabelForModel
is a bit trickier. It returns a label whose for
value is that of the parameter represented by the model object. This is useful, in particular, for custom editor templates. For example:
// Model
public class MyModel
{
[DisplayName("A property")]
public string Test { get; set; }
}
// Main view
@Html.EditorFor(m => m.Test)
// Inside editor template
@Html.LabelForModel()
// Output
<label for="Test">A property</label>
In the repository, click Admin
, then go to the Collaborators
tab.
To be on the safe side use
os.getenv('FOO') or 'bar'
A corner case with the above answers is when the environment variable is set but is empty
For this special case you get
print(os.getenv('FOO', 'bar'))
# prints new line - though you expected `bar`
or
if "FOO" in os.environ:
print("FOO is here")
# prints FOO is here - however its not
To avoid this just use or
os.getenv('FOO') or 'bar'
Then you get
print(os.getenv('FOO') or 'bar')
# bar
When do we have empty environment variables?
You forgot to set the value in the .env
file
# .env
FOO=
or exported as
$ export FOO=
or forgot to set it in settings.py
# settings.py
os.environ['FOO'] = ''
Update: if in doubt, check out these one-liners
>>> import os; os.environ['FOO'] = ''; print(os.getenv('FOO', 'bar'))
$ FOO= python -c "import os; print(os.getenv('FOO', 'bar'))"
From my experience, you don't need to do anything particular about file fields, you just tell it to make use of the file field:
from rest_framework import routers, serializers, viewsets
class Photo(django.db.models.Model):
file = django.db.models.ImageField()
def __str__(self):
return self.file.name
class PhotoSerializer(serializers.ModelSerializer):
class Meta:
model = models.Photo
fields = ('id', 'file') # <-- HERE
class PhotoViewSet(viewsets.ModelViewSet):
queryset = models.Photo.objects.all()
serializer_class = PhotoSerializer
router = routers.DefaultRouter()
router.register(r'photos', PhotoViewSet)
api_urlpatterns = ([
url('', include(router.urls)),
], 'api')
urlpatterns += [
url(r'^api/', include(api_urlpatterns)),
]
and you're ready to upload files:
curl -sS http://example.com/api/photos/ -F 'file=@/path/to/file'
Add -F field=value
for each extra field your model has. And don't forget to add authentication.
If you want your JTextField
to be focused when your GUI shows up, you can use this:
in = new JTextField(40);
f.addWindowListener( new WindowAdapter() {
public void windowOpened( WindowEvent e ){
in.requestFocus();
}
});
Where f
would be your JFrame
and in
is your JTextField
.
It means that you're trying to insert into table2
a UserID
value that doesn't exist in table1
.
Working on the same idea as above , but generalizing a bit . Since the backspace should work fine on the input elements , but should not work if the focus is a paragraph or something , since it is there where the page tends to go back to the previous page in history .
$('html').on('keydown' , function(event) {
if(! $(event.target).is('input')) {
console.log(event.which);
//event.preventDefault();
if(event.which == 8) {
// alert('backspace pressed');
return false;
}
}
});
returning false => both event.preventDefault and event.stopPropagation are in effect .
We can define user defined comparator: .The code below can be helpful for you.
#include<bits/stdc++.h>
using namespace std;
struct man
{
string name;
int priority;
};
class comparator
{
public:
bool operator()(const man& a, const man& b)
{
return a.priority<b.priority;
}
};
int main()
{
man arr[5];
priority_queue<man, vector<man>, comparator> pq;
for(int i=0; i<3; i++)
{
cin>>arr[i].name>>arr[i].priority;
pq.push(arr[i]);
}
while (!pq.empty())
{
cout<<pq.top().name<<" "<<pq.top().priority;
pq.pop();
cout<<endl;
}
return 0;
}
input :
batman 2
goku 9
mario 4
Output
goku 9
mario 4
batman 2
This is what a constant expression in Java looks like:
package com.mycompany.mypackage;
public class MyLinks {
// constant expression
public static final String GUESTBOOK_URL = "/guestbook";
}
You can use it with annotations as following:
import com.mycompany.mypackage.MyLinks;
@WebServlet(urlPatterns = {MyLinks.GUESTBOOK_URL})
public class GuestbookServlet extends HttpServlet {
// ...
}
if I have understood correct the question :
<!DOCTYPE HTML>_x000D_
<HEAD>_x000D_
<TITLE>Passing values</TITLE>_x000D_
<style>_x000D_
</style>_x000D_
</HEAD>_x000D_
Give a number :<input type="number" id="num"><br>_x000D_
<button onclick="MyFunction(num.value)">Press button...</button>_x000D_
<script>_x000D_
function MyFunction(num) {_x000D_
document.write("<h1>You gave "+num+"</h1>");_x000D_
}_x000D_
</script>_x000D_
</BODY>_x000D_
</HTML>
_x000D_
This is my workflow for merging selective files.
# Make a new branch (this will be temporary)
git checkout -b newbranch
# Grab the changes
git merge --no-commit featurebranch
# Unstage those changes
git reset HEAD
(You can now see the files from the merge are unstaged)
# Now you can chose which files are to be merged.
git add -p
# Remember to "git add" any new files you wish to keep
git commit
The problem got resolved when I edited the file /etc/bashrc
with same contents as in /etc/profiles
and in /etc/profiles.d/limits.sh
and did a re-login.
This question has not enough information to answer. A general solution (depending on your GUI framework): add a mouse event handler that will catch clicks and mouse movements. This will give you your (x, y) coordinates. Next use these coordinates to crop your image.
In MySQL use the '^'
to identify you want to check the first char of the string then define the array [] of letters you want to check for.
Try This
SELECT * FROM artists WHERE name REGEXP '^[abc]'
This problem happens because IIS does not find the actual location of woff2 file mime types. Set URL of font-face properly, also keep font-family as glyphicons-halflings-regular in your CSS file as shown below.
@font-face {
font-family: 'glyphicons-halflings-regular';
src: url('../../../fonts/glyphicons-halflings-regular.woff2') format('woff2');}
list.set(5,"newString");
It's quite clearly from their docs:
If you used componentWillReceiveProps for re-computing some data only when a prop changes, use a memoization helper instead.
Use: https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization
Whatever is specified in the command
in docker-compose.yml should get appended to the entrypoint
defined in the Dockerfile, provided entrypoint
is defined in exec form in the Dockerfile.
If the EntryPoint is defined in shell form, then any CMD arguments will be ignored.
SELECT *
FROM table
WHERE id = (SELECT MAX(id) FROM TABLE)
In case you want to sort dates with descending order the minus sign doesn't work with Dates.
out <- DF[rev(order(as.Date(DF$end))),]
However you can have the same effect with a general purpose function: rev(). Therefore, you mix rev and order like:
#init data
DF <- data.frame(ID=c('ID3', 'ID2','ID1'), end=c('4/1/09 12:00', '6/1/10 14:20', '1/1/11 11:10')
#change order
out <- DF[rev(order(as.Date(DF$end))),]
Hope it helped.
&
is used to separate commands. Therefore you can use ^
to escape the &
.
Well, first, you need to actually define a function before you can run it (and it doesn't need to be called main
). For instance:
class Example(object):
def run(self):
print "Hello, world!"
if __name__ == '__main__':
Example().run()
You don't need to use a class, though - if all you want to do is run some code, just put it inside a function and call the function, or just put it in the if
block:
def main():
print "Hello, world!"
if __name__ == '__main__':
main()
or
if __name__ == '__main__':
print "Hello, world!"
var persons = new List<Person>
{
new Person {ID = 1, Name = "jhon", Salary = 2500},
new Person {ID = 2, Name = "Sena", Salary = 1500},
new Person {ID = 3, Name = "Max", Salary = 5500},
new Person {ID = 4, Name = "Gen", Salary = 3500}
};
var acertainperson = persons.Where(p => p.Name == "jhon").First();
Console.WriteLine("{0}: {1} points",
acertainperson.Name, acertainperson.Salary);
jhon: 2500 points
var doingprettywell = persons.Where(p => p.Salary > 2000);
foreach (var person in doingprettywell)
{
Console.WriteLine("{0}: {1} points",
person.Name, person.Salary);
}
jhon: 2500 points
Max: 5500 points
Gen: 3500 points
var astupidcalc = from p in persons
where p.ID > 2
select new
{
Name = p.Name,
Bobos = p.Salary*p.ID,
Bobotype = "bobos"
};
foreach (var person in astupidcalc)
{
Console.WriteLine("{0}: {1} {2}",
person.Name, person.Bobos, person.Bobotype);
}
Max: 16500 bobos
Gen: 14000 bobos
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);
See Here for more details.
Or
DateTime dt = DateTime.Now;
Console.WriteLine( dt.ToString( "MMMM" ) );
Or if you want to get the culture-specific abbreviated name.
GetAbbreviatedMonthName(1);
Why don't do with native js?
var s="<span class='text-muted' style='font-size:.75em; position:absolute; bottom:3px; left:30px'>From <strong>Dan's Tools</strong></span>"
var e=document.createElement('div')
var r=document.createRange();
r.selectNodeContents(e)
var f=r.createContextualFragment(s);
e.appendChild(f);
e = e.firstElementChild;
Copy your source folder to somedir
:
cp -r srcdir
somedir
Remove all unneeded files:
find somedir -name '.svn' -exec rm -rf {} \+
launch scp from somedir
what does this error mean? Object reference not set to an instance of an object.
exactly what it says, you are trying to use a null object as if it was a properly referenced object.
npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli@latest
Then in your Local project package:
rm -rf node_modules dist
npm install --save-dev @angular/cli@latest
npm i
ng update @angular/cli
ng update @angular/core
npm install --save-dev @angular-devkit/build-angular
Was getting below error Error: Unexpected end of JSON input Unexpected end of JSON input Above steps helped from this post Can't update angular to version 6
>
itself is very wonderful arrow! Just prepend a div with it and style it.
div{_x000D_
font-size:50px;_x000D_
}_x000D_
div::before{_x000D_
content:">";_x000D_
font: 50px 'Consolas';_x000D_
font-weight:900;_x000D_
}
_x000D_
<div class="arrowed">Hatz!</div>
_x000D_
The loading of a .json
file from harddisk is an asynchronous operation and thus it needs to specify a callback function to execute after the file is loaded.
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
//usage:
readTextFile("/Users/Documents/workspace/test.json", function(text){
var data = JSON.parse(text);
console.log(data);
});
This function works also for loading a .html
or .txt
files, by overriding the mime type parameter to "text/html"
, "text/plain"
etc.
This is very good: http://simononsoftware.com/virtualenv-tutorial-part-2/
And this is a slightly more practical one: https://web.archive.org/web/20160404222648/https://iamzed.com/2009/05/07/a-primer-on-virtualenv/
Try using this code for v3:
gMap = new google.maps.Map(document.getElementById('map'));
gMap.setZoom(13); // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
This will work:
The problem may happen when you're trying to read a list with a single element as a JsonArray rather than a JsonNode or vice versa.
Since you can't know for sure if the returned list contains a single element (so the json looks like this {...}) or multiple elements (and the json looks like this [{...},{...}]) - you'll have to check in runtime the type of the element.
It should look like this:
(Note: in this code sample I'm using com.fasterxml.jackson)
String jsonStr = response.readEntity(String.class);
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(jsonStr);
// Start by checking if this is a list -> the order is important here:
if (rootNode instanceof ArrayNode) {
// Read the json as a list:
myObjClass[] objects = mapper.readValue(rootNode.toString(), myObjClass[].class);
...
} else if (rootNode instanceof JsonNode) {
// Read the json as a single object:
myObjClass object = mapper.readValue(rootNode.toString(), myObjClass.class);
...
} else {
...
}
parse_cols
is deprecated, use usecols
instead
that is:
df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols = "A,C:AA")
You don't want to list all 1000 object in your bucket at a time. A more robust solution will be to fetch a max of 10 objects at a time. You can do this with the withMaxKeys method.
The following code creates an S3 client, fetches 10 or less objects at a time and filters based on a prefix and generates a pre-signed url for the fetched object:
import com.amazonaws.HttpMethod;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;
import java.net.URL;
import java.util.Date;
/**
* @author shabab
* @since 21 Sep, 2020
*/
public class AwsMain {
static final String ACCESS_KEY = "";
static final String SECRET = "";
static final Regions BUCKET_REGION = Regions.DEFAULT_REGION;
static final String BUCKET_NAME = "";
public static void main(String[] args) {
BasicAWSCredentials awsCreds = new BasicAWSCredentials(ACCESS_KEY, SECRET);
try {
final AmazonS3 s3Client = AmazonS3ClientBuilder
.standard()
.withRegion(BUCKET_REGION)
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.build();
ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(BUCKET_NAME).withMaxKeys(10);
ListObjectsV2Result result;
do {
result = s3Client.listObjectsV2(req);
result.getObjectSummaries()
.stream()
.filter(s3ObjectSummary -> {
return s3ObjectSummary.getKey().contains("Market-subscriptions/")
&& !s3ObjectSummary.getKey().equals("Market-subscriptions/");
})
.forEach(s3ObjectSummary -> {
GeneratePresignedUrlRequest generatePresignedUrlRequest =
new GeneratePresignedUrlRequest(BUCKET_NAME, s3ObjectSummary.getKey())
.withMethod(HttpMethod.GET)
.withExpiration(getExpirationDate());
URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
System.out.println(s3ObjectSummary.getKey() + " Pre-Signed URL: " + url.toString());
});
String token = result.getNextContinuationToken();
req.setContinuationToken(token);
} while (result.isTruncated());
} catch (SdkClientException e) {
e.printStackTrace();
}
}
private static Date getExpirationDate() {
Date expiration = new java.util.Date();
long expTimeMillis = expiration.getTime();
expTimeMillis += 1000 * 60 * 60;
expiration.setTime(expTimeMillis);
return expiration;
}
}
Basically the same solution as provided by Rutger Kassies, but using a more pythonic syntax:
fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)
data = np.arange(250, 260)
for ax, d in zip(axs.ravel(), data):
ax.contourf(np.random.rand(10,10), 5, cmap=plt.cm.Oranges)
ax.set_title(str(d))
Try CTR + M it will work like before.
I had the same problem but also wanted to get the content of the file (after the YAML front-matter).
This is the best solution I have found:
if (md = contents.match(/^(?<metadata>---\s*\n.*?\n?)^(---\s*$\n?)/m))
self.contents = md.post_match
self.metadata = YAML.load(md[:metadata])
end
Source and discussion: https://practicingruby.com/articles/tricks-for-working-with-text-and-files
Updating this (9 years after it was asked) as the answer I was looking for wasn't mentioned:
Firefox also has presets for throttling connection speeds. Find them in the Network Monitor tab of the developer tools. Default is 'No throttling'.
Slowest is GPRS (Download speed: 50 Kbps, Upload speed: 20 Kbps, Minimum latency (ms): 500), ranging through 'good' and 'regular' 2G, 3G and 4G to DSL and WiFi (Download speed: 30Mbps, Upload speed: 15Mbps, Minimum latency (ms): 2).
More in the Dev Tools docs.
Java VM contains a single class object per class. Each class may have some shared variables called static variables. If the critical section of the code plays with these variables in a concurrent environment, then we need to make that particular section as synchronized. When there is more than one static synchronized method only one of them will be executed at a time without preemption. That's what lock on class object does.
401 means "Unauthorized", so there must be something with your credentials.
I think that java URL
does not support the syntax you are showing. You could use an Authenticator instead.
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(login, password.toCharArray());
}
});
and then simply invoking the regular url, without the credentials.
The other option is to provide the credentials in a Header:
String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encoded);
PS: It is not recommended to use that Base64Encoder but this is only to show a quick solution. If you want to keep that solution, look for a library that does. There are plenty.
When you do self.button = Button(...).grid(...)
, what gets assigned to self.button
is the result of the grid()
command, not a reference to the Button
object created.
You need to assign your self.button
variable before packing/griding it.
It should look something like this:
self.button = Button(self,text="Click Me",command=self.color_change,bg="blue")
self.button.grid(row = 2, column = 2, sticky = W)
Why don't you use:
<li><a href="#">bla</a></li>
a {
opacity: 0.0;
font-size: 1px;
}
li {
background-image: url('test.jpg');
}
If you haven't any span or div element, it works perfectly for links.