"Convert CSV to SQL" helped me. Add your CSV file and you are good to go.
[k for k,v in l if v =='delicia']
here l is the list of tuples-[(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]
And instead of converting it to a dict, we are using llist comprehension.
*Key* in Key,Value in list, where value = **delicia**
You should be able to perform a select on the orders table, using a raw WHERE to find the max(id
) in a subquery, like this:
\DB::table('orders')->where('id', \DB::raw("(select max(`id`) from orders)"))->get();
If you want to use Eloquent (for example, so you can convert your response to an object) you will want to use whereRaw, because some functions such as toJSON
or toArray
will not work without using Eloquent models.
$order = Order::whereRaw('id = (select max(`id`) from orders)')->get();
That, of course, requires that you have a model that extends Eloquent.
class Order extends Eloquent {}
As mentioned in the comments, you don't need to use whereRaw
, you can do the entire query using the query builder without raw SQL.
// Using the Query Builder
\DB::table('orders')->find(\DB::table('orders')->max('id'));
// Using Eloquent
$order = Order::find(\DB::table('orders')->max('id'));
(Note that if the id
field is not unique, you will only get one row back - this is because find()
will only return the first result from the SQL server.).
I ran into this problem recently and wrote up a post about the particular case in our code that was causing this problem.
http://cappuccino.org/discuss/2010/03/01/internet-explorer-global-variables-and-stack-overflows/
The quick summary is: recursion that passes through the host global object is limited to a stack depth of 13. In other words, if the reference your function call is using (not necessarily the function itself) was defined with some form window.foo = function, then recursing through foo is limited to a depth of 13.
There are a couple of things to check:
proceedToSecond
" into the FireBug console to see if the function gets definedscript
tag: it should be <script type="text/javascript">
instead of <script type = "text/javascript">
You can do it like this:
In your main view controller:
func showModal() {
let modalViewController = ModalViewController()
modalViewController.modalPresentationStyle = .overCurrentContext
presentViewController(modalViewController, animated: true, completion: nil)
}
In your modal view controller:
class ModalViewController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = UIColor.clearColor()
view.opaque = false
}
}
If you are working with a storyboard:
Just add a Storyboard Segue with Kind
set to Present Modally
to your modal view controller and on this view controller set the following values:
As Crashalot pointed out in his comment: Make sure the segue only uses Default
for both Presentation
and Transition
. Using Current Context
for Presentation
makes the modal turn black instead of remaining transparent.
switch ($method) {
case "GET":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
break;
case "POST":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
break;
case "DELETE":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
break;
}
x = [1, 10, 100]
for i in x:
print '%02d' % i
results in:
01
10
100
Read more information about string formatting using % in the documentation.
I know it's late but taskkill /im devenv.exe /t /f
should work. the /t
kills child processes too.
With Guava 15 you can also simply use:
Set s = Sets.newConcurrentHashSet();
I had the same problem and fixed it by using the withCredentials
property.
XMLHttpRequest from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request.
axios.get('some api url', {withCredentials: true});
If you're like me, and would rather not make this security hole system or user-wide, then you can add a config option to any git repos that need this by running this command in those repos. (note only works with git version >= 2.10, released 2016-09-04)
git config core.sshCommand 'ssh -oHostKeyAlgorithms=+ssh-dss'
This only works after the repo is setup however. If you're not comfortable adding a remote manually (and just want to clone) then you can run the clone like this:
GIT_SSH_COMMAND='ssh -oHostKeyAlgorithms=+ssh-dss' git clone ssh://user@host/path-to-repository
then run the first command to make it permanent.
If you don't have the latest, and still would like to keep the hole as local as possible I recommend putting
export GIT_SSH_COMMAND='ssh -oHostKeyAlgorithms=+ssh-dss'
in a file somewhere, say git_ssh_allow_dsa_keys.sh
, and source
ing it when needed.
If you use Java 8 and if it is possible that your search returns null, you could try using the Optional class.
To find a carnet:
private final Optional<Carnet> findCarnet(Collection<Carnet> yourList, String codeIsin){
// This stream will simply return any carnet that matches the filter. It will be wrapped in a Optional object.
// If no carnets are matched, an "Optional.empty" item will be returned
return yourList.stream().filter(c -> c.getCodeIsin().equals(codeIsin)).findAny();
}
Now a usage for it:
public void yourMethod(String codeIsin){
List<Carnet> listCarnet = carnetEJB.findAll();
Optional<Carnet> carnetFound = findCarnet(listCarnet, codeIsin);
if(carnetFound.isPresent()){
// You use this ".get()" method to actually get your carnet from the Optional object
doSomething(carnetFound.get());
}
else{
doSomethingElse();
}
}
+1 to @Aric Coady's simplest solution.
And also one way to random select one of keys with max value in the dictionary:
stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000}
import random
maxV = max(stats.values())
# Choice is one of the keys with max value
choice = random.choice([key for key, value in stats.items() if value == maxV])
this is my full solution which would read any base64 image format and save it in the proper format in the database:
// Save base64 image to disk
try
{
// Decoding base-64 image
// Source: http://stackoverflow.com/questions/20267939/nodejs-write-base64-image-file
function decodeBase64Image(dataString)
{
var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
var response = {};
if (matches.length !== 3)
{
return new Error('Invalid input string');
}
response.type = matches[1];
response.data = new Buffer(matches[2], 'base64');
return response;
}
// Regular expression for image type:
// This regular image extracts the "jpeg" from "image/jpeg"
var imageTypeRegularExpression = /\/(.*?)$/;
// Generate random string
var crypto = require('crypto');
var seed = crypto.randomBytes(20);
var uniqueSHA1String = crypto
.createHash('sha1')
.update(seed)
.digest('hex');
var base64Data = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAZABkAAD/4Q3zaHR0cDovL25zLmFkb2JlLmN...';
var imageBuffer = decodeBase64Image(base64Data);
var userUploadedFeedMessagesLocation = '../img/upload/feed/';
var uniqueRandomImageName = 'image-' + uniqueSHA1String;
// This variable is actually an array which has 5 values,
// The [1] value is the real image extension
var imageTypeDetected = imageBuffer
.type
.match(imageTypeRegularExpression);
var userUploadedImagePath = userUploadedFeedMessagesLocation +
uniqueRandomImageName +
'.' +
imageTypeDetected[1];
// Save decoded binary image to disk
try
{
require('fs').writeFile(userUploadedImagePath, imageBuffer.data,
function()
{
console.log('DEBUG - feed:message: Saved to disk image attached by user:', userUploadedImagePath);
});
}
catch(error)
{
console.log('ERROR:', error);
}
}
catch(error)
{
console.log('ERROR:', error);
}
You can use 0b000001
since Visual Studio 2017 (C# 7.0)
public async Task<bool> Update(MyObject item)
{
Context.Entry(await Context.MyDbSet.FirstOrDefaultAsync(x => x.Id == item.Id)).CurrentValues.SetValues(item);
return (await Context.SaveChangesAsync()) > 0;
}
Utilize regular buttons and set the display property to inline in order to center the buttons on a single line. Setting the display property to inline-block will also put them on the same line, but they will not be centered via that display property setting.
Label
is an inline element - so, unless a width is defined, its width is exact the same which the letters span. Your div
element is a block element so its width is by default 100%.
You will have to place the text-align: right;
on the div
element in your case, or applying display: block;
to your label
Another option is to set a width for each label and then use text-align
. The display: block
method will not be necessary using this.
Although rather late, but you can manually download the required DLLs from nuget at the following link: https://www.nuget.org/packages/Microsoft.ReportViewer.Runtime.Common/12.0.2402.15
Open the file .Rar Archive, extract the dlls and copy them manually to the bin folder of your publish.
This solution worked for me. Hope that helps !!
You can do it this way (synchronously, but compact):
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:MyURL]]];
A much better approach is to use Apple's LazyTableImages to preserve interactivity.
Apparently, org.json.simple.JSONArray
implements a raw Iterator. This means that each element is considered to be an Object
. You can try to cast:
for(Object o: arr){
if ( o instanceof JSONObject ) {
parse((JSONObject)o);
}
}
This is how things were done back in Java 1.4 and earlier.
If dns_get_record()
fails, it should return FALSE
, so you can suppress the warning with @
and then check the return value.
From Python 3.10 there is a new feature of Parenthesized context managers, which permits syntax like:
with (
open("a", "w") as a,
open("b", "w") as b
):
do_something()
To simply redirect a browser using javascript:
window.location.href = "http://example.com/new_url";
To redirect AND submit a form (i.e. login details), requires no javascript:
<form action="/new_url" method="POST">
<input name="username">
<input type="password" name="password">
<button type="submit">Submit</button>
</form>
Here is my answer using the group by clause.
SELECT *
FROM feeds f
LEFT JOIN
(
SELECT artist_id, feed_id
FROM feeds_artists
GROUP BY artist_id, feed_id
) fa ON fa.feed_id = f.id
LEFT JOIN artists a ON a.artist_id = fa.artist_id
The free Google Geocoding API provides this service via a HTTP REST API. Note, the API is usage and rate limited, but you can pay for unlimited access.
Try this link to see an example of the output (this is in json, output is also available in XML)
https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true
I would approach it like this:
sizes = [100, 250] print "How much space should the random song list occupy?" print '\n'.join("{0}. {1}Mb".format(n, s) for n, s in enumerate(sizes, 1)) # present choices choice = int(raw_input("Enter choice:")) # throws error if not int size = sizes[0] # safe starting choice if choice in range(2, len(sizes) + 1): size = sizes[choice - 1] # note index offset from choice print "You want to create a random song list that is {0}Mb.".format(size)
You could also loop until you get an acceptable answer and cover yourself in case of error:
choice = 0 while choice not in range(1, len(sizes) + 1): # loop try: # guard against error choice = int(raw_input(...)) except ValueError: # couldn't make an int print "Please enter a number" choice = 0 size = sizes[choice - 1] # now definitely valid
A bit late on this one but this worked perfectly for me when trying to hide the background for IE6 & 7
.myclass{
background-image: url("images/myimg.png");
background-position: right top;
background-repeat: no-repeat;
background-size: 22px auto;
padding-left: 48px;
height: 42px;
_background-image: none;
*background-image: none;
}
I got this hack via: http://briancray.com/posts/target-ie6-and-ie7-with-only-1-extra-character-in-your-css/
#myelement
{
color: #999; /* shows in all browsers */
*color: #999; /* notice the * before the property - shows in IE7 and below */
_color: #999; /* notice the _ before the property - shows in IE6 and below */
}
Here is a code to get the child elements (In java):
String childTag = childElement.getTagName();
if(childTag.equals("html"))
{
return "/html[1]"+current;
}
WebElement parentElement = childElement.findElement(By.xpath(".."));
List<WebElement> childrenElements = parentElement.findElements(By.xpath("*"));
int count = 0;
for(int i=0;i<childrenElements.size(); i++)
{
WebElement childrenElement = childrenElements.get(i);
String childrenElementTag = childrenElement.getTagName();
if(childTag.equals(childrenElementTag))
{
count++;
}
}
You do cls.isFilled = True
. That overwrites the method called isFilled
and replaces it with the value True. That method is now gone and you can't call it anymore. So when you try to call it again you get an error, since it's not there anymore.
The solution is use a different name for the variable than you do for the method.
You can start a thread like:
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
try {
//Do you task
}catch (Exception ex){
ex.printStackTrace();}
}
});
thread.start();
To stop a Thread:
thread.join();//it will kill you thread
//if you want to know whether your thread is alive or dead you can use
System.out.println("Thread is "+thread.isAlive());
Its advisable to create a new thread rather than restarting it.
Mine froze on the Diagnostic Tools for 3 hours. I tried disabling my firewall and turning off internet among many other attempts to resolve this. In the end the following actions allowed the installer to complete and VS2015 Community edition to launch.
All seems to be working OK so far (fingers crossed!!)
jQuery Validation Plugin already implements min and max rules, we just need to create an adapter for our custom attribute:
public class MaxAttribute : ValidationAttribute, IClientValidatable
{
private readonly int maxValue;
public MaxAttribute(int maxValue)
{
this.maxValue = maxValue;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = ErrorMessageString, maxValue;
rule.ValidationType = "max";
rule.ValidationParameters.Add("max", maxValue);
yield return rule;
}
public override bool IsValid(object value)
{
return (int)value <= maxValue;
}
}
Adapter:
$.validator.unobtrusive.adapters.add(
'max',
['max'],
function (options) {
options.rules['max'] = parseInt(options.params['max'], 10);
options.messages['max'] = options.message;
});
Min attribute would be very similar.
I see the status field on the jqXhr object, here is a fiddle with it working:
http://jsfiddle.net/magicaj/55HQq/3/
$.ajax({
//...
success: function(data, textStatus, xhr) {
console.log(xhr.status);
},
complete: function(xhr, textStatus) {
console.log(xhr.status);
}
});
There is no difference - bool is simply an alias of System.Boolean.
http://msdn.microsoft.com/en-us/library/c8f5xwh7(VS.71).aspx
Personally, I loathe the preprocessor, so I'd always go with const
.
The main advantage to a #define
is that it requires no memory to store in your program, as it is really just replacing some text with a literal value. It also has the advantage that it has no type, so it can be used for any integer value without generating warnings.
Advantages of "const
"s are that they can be scoped, and they can be used in situations where a pointer to an object needs to be passed.
I don't know exactly what you are getting at with the "static
" part though. If you are declaring globally, I'd put it in an anonymous namespace instead of using static
. For example
namespace {
unsigned const seconds_per_minute = 60;
};
int main (int argc; char *argv[]) {
...
}
I always go back to this article SQL Server 2005 XQuery and XML-DML - Part 1 to know how to use the XML features in SQL Server 2005.
For basic XPath know-how, I'd recommend the W3Schools tutorial.
you can use something like this:
$(this).addClass('someClass');
$(Selector).trigger('ClassChanged')
$(otherSelector).bind('ClassChanged', data, function(){//stuff });
but otherwise, no, there's no predefined function to fire an event when a class changes.
Read more about triggers here
koala_dev answered that this will work:
html, body {
max-width: 100%;
overflow-x: hidden;
}
And MarkWPiper comments that ":-/ Caused touch / momentum scrolling to stop working on iPhone"
The solution to keep touch / momentum on iPhone is to add this line inside the css block for html,body:
height:auto!important;
The above programs might give you NullPointerException. This is an easier way to add an element to the end of linkedList.
public class LinkedList {
Node head;
public static class Node{
int data;
Node next;
Node(int item){
data = item;
next = null;
}
}
public static void main(String args[]){
LinkedList ll = new LinkedList();
ll.head = new Node(1);
Node second = new Node(2);
Node third = new Node(3);
Node fourth = new Node(4);
ll.head.next = second;
second.next = third;
third.next = fourth;
fourth.next = null;
ll.printList();
System.out.println("Add element 100 to the last");
ll.addLast(100);
ll.printList();
}
public void printList(){
Node t = head;
while(n != null){
System.out.println(t.data);
t = t.next;
}
}
public void addLast(int item){
Node new_item = new Node(item);
if(head == null){
head = new_item;
return;
}
new_item.next = null;
Node last = head;
Node temp = null;
while(last != null){
if(last != null)
temp = last;
last = last.next;
}
temp.next = new_item;
return;
}
}
Extend LinearLayout/RelativeLayout and use it straight on the XML
package com.pkg_name ;
...imports...
public class LinearLayoutOutlined extends LinearLayout {
Paint paint;
public LinearLayoutOutlined(Context context) {
super(context);
// TODO Auto-generated constructor stub
setWillNotDraw(false) ;
paint = new Paint();
}
public LinearLayoutOutlined(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
setWillNotDraw(false) ;
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
/*
Paint fillPaint = paint;
fillPaint.setARGB(255, 0, 255, 0);
fillPaint.setStyle(Paint.Style.FILL);
canvas.drawPaint(fillPaint) ;
*/
Paint strokePaint = paint;
strokePaint.setARGB(255, 255, 0, 0);
strokePaint.setStyle(Paint.Style.STROKE);
strokePaint.setStrokeWidth(2);
Rect r = canvas.getClipBounds() ;
Rect outline = new Rect( 1,1,r.right-1, r.bottom-1) ;
canvas.drawRect(outline, strokePaint) ;
}
}
<?xml version="1.0" encoding="utf-8"?>
<com.pkg_name.LinearLayoutOutlined
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width=...
android:layout_height=...
>
... your widgets here ...
</com.pkg_name.LinearLayoutOutlined>
This worked for me,
CREATE TABLE newtable LIKE oldtable;
Replicates newtable with old table
INSERT newtable SELECT * FROM oldtable
;
Copies all the row data to new table.
Thank you
I think the best approach is to use OAuth2. Google it and you will find a lot of useful posts to help you set it up.
It will make easier to develop client applications for your API from a web app or a mobile one.
Hope it helps you.
in Intellij, what resolved the issue for me was to open the Maven right side toolbar
choose "Clean" , "install" and hit the "Play" button:
Hi i got a tricky solution, which works only on new browsers:
just open a websocket to your server, when the user closes the window, the onclose event will be fired
Maybe you should better use a case
for such lists:
case "$cms" in
wordpress|meganto|typo3)
do_your_else_case
;;
*)
do_your_then_case
;;
esac
I think for long such lists this is better readable.
If you still prefer the if
you can do it with single brackets in two ways:
if [ "$cms" != wordpress -a "$cms" != meganto -a "$cms" != typo3 ]; then
or
if [ "$cms" != wordpress ] && [ "$cms" != meganto ] && [ "$cms" != typo3 ]; then
I had similar Issue where we have GenericResponse object containing list of values
ResponseEntity<ResponseDTO> responseEntity = restTemplate.exchange(
redisMatchedDriverUrl,
HttpMethod.POST,
requestEntity,
ResponseDTO.class
);
Usage of objectMapper helped in converting LinkedHashMap into respective DTO objects
ObjectMapper mapper = new ObjectMapper();
List<DriverLocationDTO> driverlocationsList = mapper.convertValue(responseDTO.getData(), new TypeReference<List<DriverLocationDTO>>() { });
Answered a question such as this before, you can take a look at the results here:
Creating form to have fields and text next to each other - what is the semantic way to do it?
So to apply the same rules to your fiddle you can use display:inline-block
to display your label and input groups side by side, like so:
CSS
input {
margin-top: 5px;
margin-bottom: 5px;
display:inline-block;
*display: inline; /* for IE7*/
zoom:1; /* for IE7*/
vertical-align:middle;
margin-left:20px
}
label {
display:inline-block;
*display: inline; /* for IE7*/
zoom:1; /* for IE7*/
float: left;
padding-top: 5px;
text-align: right;
width: 140px;
}
I believe you want bgcolor. Something like this:
document.getElementById("button").bgcolor="#ffffff";
Here are a couple of demos that might help:
DECLARE @STR VARCHAR(400)
DECLARE @specialchars VARCHAR(50) = '%[~,@,#,$,%,&,*,(,),!^?:]%'
SET @STR = '1, 45 4,3 68.00-'
WHILE PATINDEX( @specialchars, @STR ) > 0
---Remove special characters using Replace function
SET @STR = Replace(Replace(REPLACE( @STR, SUBSTRING( @STR, PATINDEX( @specialchars, @STR ), 1 ),''),'-',''), ' ','')
SELECT @STR
HttpClient
is not a class, it is an interface. You cannot use it for development in the way you mean.
What you want is a class that implements the HttpClient
interface, and that is CloseableHttpClient
.
Switch to AppCompatActivity and add a 25 dp paddingTop on the toolbar and turn on
<item name="android:windowTranslucentStatus">true</item>
Then, the will toolbar go up top the top
<a href="https://www." style="color: inherit;"target="_blank">
For CSS inline style, this worked best for me.
I do not recall my original use case for this mechanism. Nowadays, I cannot think of any valid use case.
Your client should be able to detect when the connection is lost and allow you to re-create the connection. If it important that part of program logic is executed using the same connection, then use transactions.
tl;dr; Do not use this method.
A pragmatic solution is to force MySQL to keep the connection alive:
setInterval(function () {
db.query('SELECT 1');
}, 5000);
I prefer this solution to connection pool and handling disconnect because it does not require to structure your code in a way thats aware of connection presence. Making a query every 5 seconds ensures that the connection will remain alive and PROTOCOL_CONNECTION_LOST
does not occur.
Furthermore, this method ensures that you are keeping the same connection alive, as opposed to re-connecting. This is important. Consider what would happen if your script relied on LAST_INSERT_ID()
and mysql connection have been reset without you being aware about it?
However, this only ensures that connection time out (wait_timeout
and interactive_timeout
) does not occur. It will fail, as expected, in all others scenarios. Therefore, make sure to handle other errors.
Syntax: error_log file | stderr | syslog:server=address[,parameter=value] | memory:size [debug | info | notice | warn | error | crit | alert | emerg];
Default:
error_log logs/error.log error;
Context: main, http, stream, server, location
http://nginx.org/en/docs/ngx_core_module.html#error_log
Don't use: /dev/stderr
This will break your setup if you're going to use systemd-nspawn.
Scott S's answer worked perfectly.
I was coding a web-based phone dialpad for mobile, and every time the user would press a number on the keypad (composed of td span elements in a table), the softkeyboard would pop up. I also wanted the user to not be able to tap into the input box of the number being dialed. This actually solved both problems in 1 shot. The following was used:
<input type="text" id="phone-number" onfocus="blur();" />
Having unsigned
in variable declaration is more useful for the programmers themselves - don't treat the variables as negative. As you've noticed, both -1
and 4294967295
have exact same bit representation for a 4 byte integer. It's all about how you want to treat or see them.
The statement unsigned int a = -1;
is converting -1
in two's complement and assigning the bit representation in a
. The printf()
specifier x
, d
and u
are showing how the bit representation stored in variable a
looks like in different format.
$("input").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
$("form").submit();
}
});
This can sometimes be an issue with a postgres upgrade.
In my case, it happened when upgrading from 9.3 to 9.4.
See http://www.postgresql.org/docs/9.4/static/upgrading.html
OS X/Homebrew:
Try running postgres -D /usr/local/var/postgres
-- it will give you a much more verbose output if postgres fails to start.
In my case, running rm -rf /usr/local/var/postgres && initdb /usr/local/var/postgres -E utf8
removed my old databases and then reinitialized the postgres db schema.
Thanks to https://github.com/Homebrew/homebrew/issues/35240 for that solution.
After regenerating my databases (with rake db:create
) everything worked fine again.
After many hours troubleshooting this stuff... Here are some quick highlights that helped us from the X-UA-Compatible
docs: http://msdn.microsoft.com/en-us/library/cc288325(VS.85).aspx#ctl00_contentContainer_ctl16
Using <meta http-equiv="X-UA-Compatible" content=" _______ " />
The Standard User Agent modes (the non-emulate ones) ignore <!DOCTYPE>
directives in your page and render based on the standards supported by that version of IE (e.g., IE=8
will better obey table border spacing and some pseudo selectors than IE=7
).
Whereas, the Emulate modes tell IE to follow any <!DOCTYPE>
directives in your page, rendering standards mode based the version you choose and quirks mode based on IE=5
Possible values for the content
attribute are:
content="IE=5"
content="IE=7"
content="IE=EmulateIE7"
content="IE=8"
content="IE=EmulateIE8"
content="IE=9"
content="IE=EmulateIE9"
content="IE=edge"
The accepted answer didn't actually tell how to get the location, so here is a little more detail. You pass in an int
array of length 2 and the values are replaced with the view's (x, y) coordinates (of the top, left corner).
int[] location = new int[2];
myView.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
Notes
getLocationOnScreen
with getLocationInWindow
should give the same results in most cases (see this answer). However, if you are in a smaller window like a Dialog or custom keyboard, then use you will need to choose which one better suits your needs.(0,0)
if you call this method in onCreate
because the view has not been laid out yet. You can use a ViewTreeObserver
to listen for when the layout is done and you can get the measured coordinates. (See this answer.)Another way would be to use glue
package:
glue_collapse(glue("{sdata}"))
paste(glue("{sdata}"), collapse = '')
You can use either a different HTML parser (like lxml, or Beautiful Soup) -- one that offers functions to extract just text. Or, you can run a regex on your line string that strips out the tags. See Python docs for more.
Since you can't rollback you should merge that commit into the new head you got when you pulled. If you don't want any of the work you did in it you can easily do that using this tip.
So if you've pulled and updated to their head you can do this:
hg --config ui.merge=internal:local merge
keeps all the changes in the currently checked out revision, and none of the changes in the not-checked-out revision (the one you wrote that you no longer want).
This is a great way to do it because it keeps your history accurate and complete. If 2 years from now someone finds a bug in what you pulled down you can look in your (unused but saved) implementation of the same thing and go, "oh, I did it right". :)
If you're in Rails, .blank?
should be the method you are looking for:
a = nil
b = []
c = ""
a.blank? #=> true
b.blank? #=> true
c.blank? #=> true
d = "1"
e = ["1"]
d.blank? #=> false
e.blank? #=> false
So the answer would be:
variable = id if variable.blank?
SELECT * FROM Member WHERE month(date_created) = month(NOW() - INTERVAL 1 MONTH);
In my case I was using spring+hibernate and forgot to run my MYSQL server due to which hibernate was not getting loaded and thus was throwing error
Just to add to Shahid's answer - you can account for orientation changes or different devices using this (iOS7+):
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...
//Create the background
UIView* statusBg = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.window.frame.size.width, 20)];
statusBg.backgroundColor = [UIColor colorWithWhite:1 alpha:.7];
//Add the view behind the status bar
[self.window.rootViewController.view addSubview:statusBg];
//set the constraints to auto-resize
statusBg.translatesAutoresizingMaskIntoConstraints = NO;
[statusBg.superview addConstraint:[NSLayoutConstraint constraintWithItem:statusBg attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:statusBg.superview attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]];
[statusBg.superview addConstraint:[NSLayoutConstraint constraintWithItem:statusBg attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:statusBg.superview attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.0]];
[statusBg.superview addConstraint:[NSLayoutConstraint constraintWithItem:statusBg attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:statusBg.superview attribute:NSLayoutAttributeRight multiplier:1.0 constant:0.0]];
[statusBg.superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[statusBg(==20)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(statusBg)]];
[statusBg.superview setNeedsUpdateConstraints];
...
}
For anyone having issues with passwords with special chars just omit the password and it will prompt you for it:
git push https://[email protected]/YOUR_GIT_USERNAME/yourGitFileName.git
What about using a combination of some/findIndex and indexOf?
So something like this:
var array1 = ["apple","banana","orange"];
var array2 = ["grape", "pineapple"];
var found = array1.some(function(v) { return array2.indexOf(v) != -1; });
To make it more readable you could add this functionality to the Array object itself.
Array.prototype.indexOfAny = function (array) {
return this.findIndex(function(v) { return array.indexOf(v) != -1; });
}
Array.prototype.containsAny = function (array) {
return this.indexOfAny(array) != -1;
}
Note: If you'd want to do something with a predicate you could replace the inner indexOf with another findIndex and a predicate
$("input[name='btnsubmit']").attr('disabled', true);
$('input[name="filphoto"]').change(function () {
var ext = this.value.match(/\.(.+)$/)[1];
switch (ext)
{
case 'jpg':
case 'jpeg':
case 'png':
case 'bmp':
$("input[name='btnsubmit']").attr('disabled', false);
break;
default:
alert('This is not an allowed file type.');
$("input[name='btnsubmit']").attr('disabled', true);
this.value = '';
Use simple CSS height: 100%; matches the height of the parent and using height: 100vh matches the height of the viewport.
Use vh instead of %;
{ // json object node
"formules": [ // json array formules
{ // json object
"formule": "Linear Motion", // string
"url": "qp1"
}
What you are doing
Context context = null; // context is null
try {
String jsonLocation = AssetJSONFile("formules.json", context);
So change to
try {
String jsonLocation = AssetJSONFile("formules.json", CatList.this);
To parse
I believe you get the string from the assests folder.
try
{
String jsonLocation = AssetJSONFile("formules.json", context);
JSONObject jsonobject = new JSONObject(jsonLocation);
JSONArray jarray = (JSONArray) jsonobject.getJSONArray("formules");
for(int i=0;i<jarray.length();i++)
{
JSONObject jb =(JSONObject) jarray.get(i);
String formula = jb.getString("formule");
String url = jb.getString("url");
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
I had some issues that this didn't address in getting this environment set up on OSX. It had to do with the solution that I was maintaining having additional dependencies on some of the Google APIs. It wasn't enough to just download and install the items listed in the first response.
You have to download these.
A lot of the times the implementation will exist in the same namespace as the interface. So, I came up with this:
public class InterfaceConverter : JsonConverter
{
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.ReadFrom(reader);
var typeVariable = this.GetTypeVariable(token);
if (TypeExtensions.TryParse(typeVariable, out var implimentation))
{ }
else if (!typeof(IEnumerable).IsAssignableFrom(objectType))
{
implimentation = this.GetImplimentedType(objectType);
}
else
{
var genericArgumentTypes = objectType.GetGenericArguments();
var innerType = genericArgumentTypes.FirstOrDefault();
if (innerType == null)
{
implimentation = typeof(IEnumerable);
}
else
{
Type genericType = null;
if (token.HasAny())
{
var firstItem = token[0];
var genericTypeVariable = this.GetTypeVariable(firstItem);
TypeExtensions.TryParse(genericTypeVariable, out genericType);
}
genericType = genericType ?? this.GetImplimentedType(innerType);
implimentation = typeof(IEnumerable<>);
implimentation = implimentation.MakeGenericType(genericType);
}
}
return JsonConvert.DeserializeObject(token.ToString(), implimentation);
}
public override bool CanConvert(Type objectType)
{
return !typeof(IEnumerable).IsAssignableFrom(objectType) && objectType.IsInterface || typeof(IEnumerable).IsAssignableFrom(objectType) && objectType.GetGenericArguments().Any(t => t.IsInterface);
}
protected Type GetImplimentedType(Type interfaceType)
{
if (!interfaceType.IsInterface)
{
return interfaceType;
}
var implimentationQualifiedName = interfaceType.AssemblyQualifiedName?.Replace(interfaceType.Name, interfaceType.Name.Substring(1));
return implimentationQualifiedName == null ? interfaceType : Type.GetType(implimentationQualifiedName) ?? interfaceType;
}
protected string GetTypeVariable(JToken token)
{
if (!token.HasAny())
{
return null;
}
return token.Type != JTokenType.Object ? null : token.Value<string>("$type");
}
}
Therefore, you can include this globally like so:
public static JsonSerializerSettings StandardSerializerSettings => new JsonSerializerSettings
{
Converters = new List<JsonConverter>
{
new InterfaceConverter()
}
};
Another option I would recommend is to create a separate application that is stateless that would take the large file. On your main app open a new window or iframe that will accept the file and send it through that window then hide the window or iframe once the upload has started using Javascript.
Try this:
top.document.getElementById('AppFrame').setAttribute("src",fullPath);
You don't really need to use Singleton pattern because it's considered to be an antipattern. Basically there is a lot of reasons to not to implement this pattern at all. Read this to start with: Best practice on PHP singleton classes.
If after all you still think you need to use Singleton pattern then we could write a class that will allow us to get Singleton functionality by extending our SingletonClassVendor abstract class.
This is what I came with to solve this problem.
<?php
namespace wl;
/**
* @author DevWL
* @dosc allows only one instance for each extending class.
* it acts a litle bit as registry from the SingletonClassVendor abstract class point of view
* but it provides a valid singleton behaviour for its children classes
* Be aware, the singleton pattern is consider to be an anti-pattern
* mostly because it can be hard to debug and it comes with some limitations.
* In most cases you do not need to use singleton pattern
* so take a longer moment to think about it before you use it.
*/
abstract class SingletonClassVendor
{
/**
* holds an single instance of the child class
*
* @var array of objects
*/
protected static $instance = [];
/**
* @desc provides a single slot to hold an instance interchanble between all child classes.
* @return object
*/
public static final function getInstance(){
$class = get_called_class(); // or get_class(new static());
if(!isset(self::$instance[$class]) || !self::$instance[$class] instanceof $class){
self::$instance[$class] = new static(); // create and instance of child class which extends Singleton super class
echo "new ". $class . PHP_EOL; // remove this line after testing
return self::$instance[$class]; // remove this line after testing
}
echo "old ". $class . PHP_EOL; // remove this line after testing
return static::$instance[$class];
}
/**
* Make constructor abstract to force protected implementation of the __constructor() method, so that nobody can call directly "new Class()".
*/
abstract protected function __construct();
/**
* Make clone magic method private, so nobody can clone instance.
*/
private function __clone() {}
/**
* Make sleep magic method private, so nobody can serialize instance.
*/
private function __sleep() {}
/**
* Make wakeup magic method private, so nobody can unserialize instance.
*/
private function __wakeup() {}
}
Use example:
/**
* EXAMPLE
*/
/**
* @example 1 - Database class by extending SingletonClassVendor abstract class becomes fully functional singleton
* __constructor must be set to protected becaouse:
* 1 to allow instansiation from parent class
* 2 to prevent direct instanciation of object with "new" keword.
* 3 to meet requierments of SingletonClassVendor abstract class
*/
class Database extends SingletonClassVendor
{
public $type = "SomeClass";
protected function __construct(){
echo "DDDDDDDDD". PHP_EOL; // remove this line after testing
}
}
/**
* @example 2 - Config ...
*/
class Config extends SingletonClassVendor
{
public $name = "Config";
protected function __construct(){
echo "CCCCCCCCCC" . PHP_EOL; // remove this line after testing
}
}
Just to prove that it works as expected:
/**
* TESTING
*/
$bd1 = Database::getInstance(); // new
$bd2 = Database::getInstance(); // old
$bd3 = Config::getInstance(); // new
$bd4 = Config::getInstance(); // old
$bd5 = Config::getInstance(); // old
$bd6 = Database::getInstance(); // old
$bd7 = Database::getInstance(); // old
$bd8 = Config::getInstance(); // old
echo PHP_EOL."COMPARE ALL DATABASE INSTANCES".PHP_EOL;
var_dump($bd1);
echo '$bd1 === $bd2' . ($bd1 === $bd2)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
echo '$bd2 === $bd6' . ($bd2 === $bd6)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
echo '$bd6 === $bd7' . ($bd6 === $bd7)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
echo PHP_EOL;
echo PHP_EOL."COMPARE ALL CONFIG INSTANCES". PHP_EOL;
var_dump($bd3);
echo '$bd3 === $bd4' . ($bd3 === $bd4)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
echo '$bd4 === $bd5' . ($bd4 === $bd5)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
echo '$bd5 === $bd8' . ($bd5 === $bd8)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
$crud->set_relation('id','students','{first_name} {last_name}');
$crud->display_as('student_id','Students Name');
It means that the data variable is passing None (which is type NoneType), its equivalent for nothing. So it can't be iterable as a list, as you are trying to do.
This code reads the file line by line.
public static void readFileByLine(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
You can also set a delimiter as a line separator and then perform the same.
scanner.useDelimiter(System.getProperty("line.separator"));
You have to check whether there is a next token available and then read the next token. You will also need to doublecheck the input given to the Scanner. i.e. dico.txt. By default, Scanner breaks its input based on whitespace. Please ensure that the input has the delimiters in right place
UPDATED ANSWER for your comment:
I just tried to create an input file with the content as below
a
à
abaissa
abaissable
abaissables
abaissai
abaissaient
abaissais
abaissait
tried to read it with the below code.it just worked fine.
File file = new File("/home/keerthivasan/Desktop/input.txt");
Scanner scr = null;
try {
scr = new Scanner(file);
while(scr.hasNext()){
System.out.println("line : "+scr.next());
}
} catch (FileNotFoundException ex) {
Logger.getLogger(ScannerTest.class.getName()).log(Level.SEVERE, null, ex);
}
Output:
line : a
line : à
line : abaissa
line : abaissable
line : abaissables
line : abaissai
line : abaissaient
line : abaissais
line : abaissait
so, I am sure that this should work. Since you work in Windows ennvironment, The End of Line (EOL) sequence (0x0D 0x0A, \r\n) is actually two ASCII characters, a combination of the CR and LF characters. if you set your Scanner instance to use delimiter as follows, it will pick up probably
scr = new Scanner(file);
scr.useDelimiter("\r\n");
and then do your looping to read lines. Hope this helps!
I have created a Cards Layout - 3 cards in a row using Bootstrap 4 / CSS3 (of course its responsive). The following example uses basic Bootstrap 4 classes such as container
, row
, col-x
, list-group
and list-group-item
. Thought to share here if someone is interested in this sort of a layout.
HTML
<div class="container">
<div class="row">
<div class="col-sm-12 col-md-4">
<div class="custom-column">
<div class="custom-column-header">Header</div>
<div class="custom-column-content">
<ul class="list-group">
<li class="list-group-item"><i class="fa fa-check"></i> Cras justo odio</li>
<li class="list-group-item"><i class="fa fa-check"></i> Dapibus ac facilisis in</li>
<li class="list-group-item"><i class="fa fa-check"></i> Morbi leo risus</li>
<li class="list-group-item"><i class="fa fa-check"></i> Porta ac consectetur ac</li>
<li class="list-group-item"><i class="fa fa-check"></i> Vestibulum at eros</li>
</ul>
</div>
<div class="custom-column-footer"><button class="btn btn-primary btn-lg">Click here</button></div>
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="custom-column">
<div class="custom-column-header">Header</div>
<div class="custom-column-content">
<ul class="list-group">
<li class="list-group-item"><i class="fa fa-check"></i> Cras justo odio</li>
<li class="list-group-item"><i class="fa fa-check"></i> Dapibus ac facilisis in</li>
<li class="list-group-item"><i class="fa fa-check"></i> Morbi leo risus</li>
<li class="list-group-item"><i class="fa fa-check"></i> Porta ac consectetur ac</li>
<li class="list-group-item"><i class="fa fa-check"></i> Vestibulum at eros</li>
</ul>
</div>
<div class="custom-column-footer"><button class="btn btn-primary btn-lg">Click here</button></div>
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="custom-column">
<div class="custom-column-header">Header</div>
<div class="custom-column-content">
<ul class="list-group">
<li class="list-group-item"><i class="fa fa-check"></i> Cras justo odio</li>
<li class="list-group-item"><i class="fa fa-check"></i> Dapibus ac facilisis in</li>
<li class="list-group-item"><i class="fa fa-check"></i> Morbi leo risus</li>
<li class="list-group-item"><i class="fa fa-check"></i> Porta ac consectetur ac</li>
<li class="list-group-item"><i class="fa fa-check"></i> Vestibulum at eros</li>
</ul>
</div>
<div class="custom-column-footer"><button class="btn btn-primary btn-lg">Click here</button></div>
</div>
</div>
</div>
</div>
CSS / SCSS
$primary-color: #ccc;
$col-bg-color: #eee;
$col-footer-bg-color: #eee;
$col-header-bg-color: #007bff;
$col-content-bg-color: #fff;
body {
background-color: $primary-color;
}
.custom-column {
background-color: $col-bg-color;
border: 5px solid $col-bg-color;
padding: 10px;
box-sizing: border-box;
}
.custom-column-header {
font-size: 24px;
background-color: #007bff;
color: white;
padding: 15px;
text-align: center;
}
.custom-column-content {
background-color: $col-content-bg-color;
border: 2px solid white;
padding: 20px;
}
.custom-column-footer {
background-color: $col-footer-bg-color;
padding-top: 20px;
text-align: center;
}
The backslash \
is reserved for use as an escape character in Javascript.
To use a backslash literally you need to use two backslashes
\\
public static void main(String k[])
{
System.out.println ("NUMBER OF VALUES ="+k.length);
int arrymy[]=new int[k.length];
for (int i = 0; i < k.length; i++)
{
int newGues = Integer.parseInt(k[i]);
arrymy[i] = newGues;
}
}
Since C++17 you can also use the standardized free function:
std::size(container)
which will return the amount of elements in that container.
example:
std::vector<int> vec = { 1, 2, 3, 4, 8 };
std::cout << std::size(vec) << "\n\n"; // 5
int A[] = {40,10,20};
std::cout << std::size(A) << '\n'; // 3
Though I like the tag way... if you don't want to use tags for whatever reason,
you could create a member NSArray
of premade buttons:
NSArray* buttons ;
then create those buttons before rendering the tableView and push them into the array.
Then inside of the tableView:cellForRowAtIndexPath:
function you can do:
UIButton* button = [buttons objectAtIndex:[indexPath row] ] ;
[cell.contentView addSubview:button];
Then in the buttonPressedAction:
function, you can do
- (void)buttonPressedAction:(id)sender {
UIButton* button = (UIButton*)sender ;
int row = [buttons indexOfObject:button] ;
// Do magic
}
i faced this issue where i was using SQL it is different from MYSQL the solution was puting in this format: =date('m-d-y h:m:s'); rather than =date('y-m-d h:m:s');
Create a separate ul.nav
for just that list item and float that ul
right.
One extremely important notice:
NEVER use a direct package names as in something similar to passing a string value containing the package name. Use the method getPackageName(). This will make the renaming dynamic. Do whatever to reach the method getPackageName().
In Eclipse Juno, the correct way of renaming is:
Not related to variables, your example will also be solved by MOD
:
=Mod(VLOOKUP(A1, B:B, 1, 0);10)
Yes. You can get an element by its ID by calling document.getElementById
. It will return an element node if found, and null
otherwise:
var x = document.getElementById("elementid"); // Get the element with id="elementid"
x.style.color = "green"; // Change the color of the element
If you have a String
, you can do that:
String s = "test";
try {
s.getBytes("UTF-8");
} catch(UnsupportedEncodingException uee) {
uee.printStackTrace();
}
If you have a 'broken' String
, you did something wrong, converting a String
to a String
in another encoding is defenetely not the way to go! You can convert a String
to a byte[]
and vice-versa (given an encoding). In Java String
s are AFAIK encoded with UTF-16
but that's an implementation detail.
Say you have a InputStream
, you can read in a byte[]
and then convert that to a String
using
byte[] bs = ...;
String s;
try {
s = new String(bs, encoding);
} catch(UnsupportedEncodingException uee) {
uee.printStackTrace();
}
or even better (thanks to erickson) use InputStreamReader
like that:
InputStreamReader isr;
try {
isr = new InputStreamReader(inputStream, encoding);
} catch(UnsupportedEncodingException uee) {
uee.printStackTrace();
}
This is a CSS trick, not a formal solution. I leave the code with the period black because it helps me position the element. Afterward, color your content (color:white) and (margin-top:-5px or so) to make it as though the period is not there.
div.yourdivname:after {
content: ".";
border-bottom:1px solid grey;
width:60%;
display:block;
margin:0 auto;
}
Update for ECMAScript 2017:
Math.clamp(x, lower, upper)
But note that as of today, it's a Stage 1 proposal. Until it gets widely supported, you can use a polyfill.
If the file is placed under target/classes after compiling, then it is already in a directory that is part of the build path. The directory src/main/resources is the Maven default directory for such resources, and it is automatically placed to the build path by the Eclipse Maven plugin (M2E). So, there is no need to move your properties file.
The other topic is, how to retrieve such resources. Resources in the build path are automatically in the class path of the running Java program. Considering this, you should always load such resources with a class loader. Example code:
String resourceName = "myconf.properties"; // could also be a constant
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Properties props = new Properties();
try(InputStream resourceStream = loader.getResourceAsStream(resourceName)) {
props.load(resourceStream);
}
// use props here ...
What this message from the glibc dynamic linker actually means is that the library mentioned (/lib/libpam.so.0
in your case) doesn't have the VERDEF
ELF section while the binary (authpam
in your case) has some version definitions in VERNEED
section for this library (presumably, libpam.so.0
). You can easily see it with readelf
, just look at .gnu.version_d
and .gnu.version_r
sections (or lack thereof).
So it's not a symbol version mismatch, because if the binary wanted to get some specific version via VERNEED
and the library didn't provide it in its actual VERDEF
, that would be a hard linker error and the binary wouldn't run at all (like this compared to this or that). It's that the binary wants some versions, but the library doesn't provide any information about its versions.
What does it mean in practice? Usually, exactly what is seen in this example — nothing, things just work ignoring versioning. Could things break? Of course, yes, so the other answers are correct in the fact that one should use the same libraries at runtime as the ones the binary was linked to at build time.
More information could be found in Ulrich Dreppers "ELF Symbol Versioning".
>>> values = [1, 0, 3]
>>> n_values = np.max(values) + 1
>>> np.eye(n_values)[values]
array([[ 0., 1., 0., 0.],
[ 1., 0., 0., 0.],
[ 0., 0., 0., 1.]])
C++ is faster on average (as it was initially, largely a superset of C, though there are some differences). However, for specific benchmarks, there is often another language which is faster.
https://benchmarksgame-team.pages.debian.net/benchmarksgame/
fannjuch-redux
was fastest in Scala
n-body
and fasta
were faster in Ada.
spectral-norm
was fastest in Fortran.
reverse-complement
, mandelbrot
and pidigits
were fastest in ATS.
regex-dna
was fastest in JavaScript.
chameneou-redux
was fastest is Java 7.
thread-ring
was fastest in Haskell.
The rest of the benchmarks were fastest in C or C++.
`CSS:
input#search{
background-image: url(bg.jpg);
background-repeat: no-repeat;
text-indent: 20px;
}
input#search:focus{
background-image:none;
}
HTML:
<input type="text" id="search" name="search" value="search" />`
I use the little utility which comes with PureMPI.net called execcmd.exe
. Its syntax is as follows:
execcmd \\yourremoteserver <your command here>
Doesn't get any simpler than this :)
Note that since git1.7.11 ([ANNOUNCE] Git 1.7.11.rc1 and release note, June 2012) mentions:
"
git push --recurse-submodules
" learned to optionally look into the histories of submodules bound to the superproject and push them out.
Probably done after this patch and the --on-demand
option:
recurse-submodules=<check|on-demand>::
Make sure all submodule commits used by the revisions to be pushed are available on a remote tracking branch.
- If
check
is used, it will be checked that all submodule commits that changed in the revisions to be pushed are available on a remote.
Otherwise the push will be aborted and exit with non-zero status.- If
on-demand
is used, all submodules that changed in the revisions to be pushed will be pushed.
If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status.
So you could push everything in one go with (from the parent repo) a:
git push --recurse-submodules=on-demand
This option only works for one level of nesting. Changes to the submodule inside of another submodule will not be pushed.
With git 2.7 (January 2016), a simple git push will be enough to push the parent repo... and all its submodules.
See commit d34141c, commit f5c7cd9 (03 Dec 2015), commit f5c7cd9 (03 Dec 2015), and commit b33a15b (17 Nov 2015) by Mike Crowe (mikecrowe
).
(Merged by Junio C Hamano -- gitster
-- in commit 5d35d72, 21 Dec 2015)
push
: addrecurseSubmodules
config optionThe
--recurse-submodules
command line parameter has existed for some time but it has no config file equivalent.Following the style of the corresponding parameter for
git fetch
, let's inventpush.recurseSubmodules
to provide a default for this parameter.
This also requires the addition of--recurse-submodules=no
to allow the configuration to be overridden on the command line when required.The most straightforward way to implement this appears to be to make
push
use code insubmodule-config
in a similar way tofetch
.
The git config
doc now include:
push.recurseSubmodules
:Make sure all submodule commits used by the revisions to be pushed are available on a remote-tracking branch.
- If the value is '
check
', then Git will verify that all submodule commits that changed in the revisions to be pushed are available on at least one remote of the submodule. If any commits are missing, the push will be aborted and exit with non-zero status.- If the value is '
on-demand
' then all submodules that changed in the revisions to be pushed will be pushed. If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status. -- If the value is '
no
' then default behavior of ignoring submodules when pushing is retained.You may override this configuration at time of push by specifying '
--recurse-submodules=check|on-demand|no
'.
So:
git config push.recurseSubmodules on-demand
git push
Git 2.12 (Q1 2017)
git push --dry-run --recurse-submodules=on-demand
will actually work.
See commit 0301c82, commit 1aa7365 (17 Nov 2016) by Brandon Williams (mbrandonw
).
(Merged by Junio C Hamano -- gitster
-- in commit 12cf113, 16 Dec 2016)
push run with --dry-run
doesn't actually (Git 2.11 Dec. 2016 and lower/before) perform a dry-run when push is configured to push submodules on-demand.
Instead all submodules which need to be pushed are actually pushed to their remotes while any updates for the superproject are performed as a dry-run.
This is a bug and not the intended behaviour of a dry-run.Teach
push
to respect the--dry-run
option when configured to recursively push submodules 'on-demand'.
This is done by passing the--dry-run
flag to the child process which performs a push for a submodules when performing a dry-run.
And still in Git 2.12, you now havea "--recurse-submodules=only
" option to push submodules out without pushing the top-level superproject.
See commit 225e8bf, commit 6c656c3, commit 14c01bd (19 Dec 2016) by Brandon Williams (mbrandonw
).
(Merged by Junio C Hamano -- gitster
-- in commit 792e22e, 31 Jan 2017)
flex: 1
means the following:
flex-grow : 1; ? The div will grow in same proportion as the window-size
flex-shrink : 1; ? The div will shrink in same proportion as the window-size
flex-basis : 0; ? The div does not have a starting value as such and will
take up screen as per the screen size available for
e.g:- if 3 divs are in the wrapper then each div will take 33%.
<div id="412412412" class="input-group date">
<div class="input-group-prepend">
<button class="btn btn-danger" type="button">Button Click</button>
<input type="text" class="form-control" value="">
</div>
</div>
In my situation, i use this code:
$(this).parent().closest('.date').attr('id')
Hope this help someone.
If you're working with me and you're working with Oracle, I would probably make you use varchar
in almost every circumstance. The assumption that char
uses less processing power than varchar
may be true...for now...but database engines get better over time and this sort of general rule has the making of a future "myth".
Another thing: I have never seen a performance problem because someone decided to go with varchar
. You will make much better use of your time writing good code (fewer calls to the database) and efficient SQL (how do indexes work, how does the optimizer make decisions, why is exists
faster than in
usually...).
Final thought: I have seen all sorts of problems with use of CHAR
, people looking for '' when they should be looking for ' ', or people looking for 'FOO' when they should be looking for 'FOO (bunch of spaces here)', or people not trimming the trailing blanks, or bugs with Powerbuilder adding up to 2000 blanks to the value it returns from an Oracle procedure.
Write the code using ASyncTask
for http handling.
Bitmap b;
ImageView img;
......
try
{
URL url = new URL("http://10.119.120.10:80/img.jpg");
InputStream is = new BufferedInputStream(url.openStream());
b = BitmapFactory.decodeStream(is);
} catch(Exception e){}
......
img.setImageBitmap(b);
if num in range(min, max):
"""do stuff..."""
else:
"""do other stuff..."""
I was porting one application from Visual C to gcc over Linux and I had the same problem with
malloc.c:3096: sYSMALLOc: Assertion using gcc on UBUNTU 11.
I moved the same code to a Suse distribution (on other computer ) and I don't have any problem.
I suspect that the problems are not in our programs but in the own libc.
It is recommended to use either the MySQLi or PDO extensions. It is not recommended to use the old mysql extension for new development, as it was deprecated in PHP 5.5.0 and was removed in PHP 7.
PHP offers three different APIs to connect to MySQL. Below we show the APIs provided by the mysql, mysqli, and PDO extensions. Each code snippet creates a connection to a MySQL server running on "example.com" using the username "username" and the password "password". And a query is run to greet the user.
Example #1 Comparing the three MySQL APIs
<?php
// mysqli
$mysqli = new mysqli("example.com", "username", "password", "database");
$result = $mysqli->query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $result->fetch_assoc();
echo htmlentities($row['_message']);
// PDO
$pdo = new PDO('mysql:host=example.com;dbname=database', 'username', 'password');
$statement = $pdo->query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['_message']);
// mysql
$c = mysql_connect("example.com", "username", "password");
mysql_select_db("database");
$result = mysql_query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = mysql_fetch_assoc($result);
echo htmlentities($row['_message']);
?>
I suggest you try out both MySQLi and PDO and find out what API design you prefer.
Read Choosing an API and Why shouldn't I use mysql_* functions in PHP?
Reflection.
using System.Reflection;
Vendor vendor = new Vendor();
object tag = vendor.Tag;
Type tagt = tag.GetType();
FieldInfo field = tagt.GetField("test");
string value = field.GetValue(tag);
Use the power wisely. Don't forget error checking. :)
With pure javascript:
var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i <= buttonsCount; i += 1) {
buttons[i].onclick = function(e) {
alert(this.id);
};
}?
If you can't find the password based on other answers that point to a default one, the log message wording in recent versions changed to
Using generated security password: <some UUID>
You can cast the the json as follows:
Given your class:
export class Employee{
firstname: string= '';
}
and the json:
let jsonObj = {
"firstname": "Hesham"
};
You can cast it as follows:
let e: Employee = jsonObj as Employee;
And the output of console.log(e);
is:
{ firstname: 'Hesham' }
Since MySQL 5.6.X you can do this:
ALTER TABLE `schema`.`users`
CHANGE COLUMN `created` `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ;
That way your column will be updated with the current timestamp when a new row is inserted, or updated.
If you're using MySQL Workbench, you can just put CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
in the DEFAULT value field, like so:
http://dev.mysql.com/doc/relnotes/mysql/5.6/en/news-5-6-5.html
If your intention is test the service without care about the rest call, I will suggest to not use any annotation in your unit test to simplify the test.
So, my suggestion is refactor your service to receive the resttemplate using injection constructor. This will facilitate the test. Example:
@Service
class SomeService {
@AutoWired
SomeService(TestTemplateObjects restTemplateObjects) {
this.restTemplateObjects = restTemplateObjects;
}
}
The RestTemplate as component, to be injected and mocked after:
@Component
public class RestTemplateObjects {
private final RestTemplate restTemplate;
public RestTemplateObjects () {
this.restTemplate = new RestTemplate();
// you can add extra setup the restTemplate here, like errorHandler or converters
}
public RestTemplate getRestTemplate() {
return restTemplate;
}
}
And the test:
public void test() {
when(mockedRestTemplateObject.get).thenReturn(mockRestTemplate);
//mock restTemplate.exchange
when(mockRestTemplate.exchange(...)).thenReturn(mockedResponseEntity);
SomeService someService = new SomeService(mockedRestTemplateObject);
someService.getListofObjectsA();
}
In this way, you have direct access to mock the rest template by the SomeService constructor.
Perhaps the error message is somewhat misleading, but the gist is that X_train
is a list, not a numpy array. You cannot use array indexing on it. Make it an array first:
out_images = np.array(X_train)[indices.astype(int)]
type
cmd.exe /k cd c:/
in a text file and save as cmd.bat Clicking this file does the trick. You can pin it to the start menu as well.
To start in a partitioned drive (e.g. D), use
cmd.exe /k d:
There are a couple of ways to solve this. The least hackiest and almost what you want:
$client = new SoapClient(
null,
array(
'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
'uri' => 'http://example.com/wsdl',
'trace' => 1,
'use' => SOAP_LITERAL,
)
);
$params = new \SoapVar("<Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer>", XSD_ANYXML);
$result = $client->Echo($params);
This gets you the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://example.com/wsdl">
<SOAP-ENV:Body>
<ns1:Echo>
<Acquirer>
<Id>MyId</Id>
<UserId>MyUserId</UserId>
<Password>MyPassword</Password>
</Acquirer>
</ns1:Echo>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
That is almost exactly what you want, except for the namespace on the method name. I don't know if this is a problem. If so, you can hack it even further. You could put the <Echo>
tag in the XML string by hand and have the SoapClient not set the method by adding 'style' => SOAP_DOCUMENT,
to the options array like this:
$client = new SoapClient(
null,
array(
'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
'uri' => 'http://example.com/wsdl',
'trace' => 1,
'use' => SOAP_LITERAL,
'style' => SOAP_DOCUMENT,
)
);
$params = new \SoapVar("<Echo><Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer></Echo>", XSD_ANYXML);
$result = $client->MethodNameIsIgnored($params);
This results in the following request XML:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<Echo>
<Acquirer>
<Id>MyId</Id>
<UserId>MyUserId</UserId>
<Password>MyPassword</Password>
</Acquirer>
</Echo>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Finally, if you want to play around with SoapVar and SoapParam objects, you can find a good reference in this comment in the PHP manual: http://www.php.net/manual/en/soapvar.soapvar.php#104065. If you get that to work, please let me know, I failed miserably.
I also face a situation when I needed to return a top result but also wanted to get the total rows that where matching the query. i finaly get to this solution:
public string Format(SelectQuery selectQuery)
{
string result;
if (string.IsNullOrWhiteSpace(selectQuery.WherePart))
{
result = string.Format(
@"
declare @maxResult int;
set @maxResult = {0};
WITH Total AS
(
SELECT count(*) as [Count] FROM {2}
)
SELECT top (@maxResult) Total.[Count], {1} FROM Total, {2}", m_limit.To, selectQuery.SelectPart, selectQuery.FromPart);
}
else
{
result = string.Format(
@"
declare @maxResult int;
set @maxResult = {0};
WITH Total AS
(
SELECT count(*) as [Count] FROM {2} WHERE {3}
)
SELECT top (@maxResult) Total.[Count], {1} FROM Total, {2} WHERE {3}", m_limit.To, selectQuery.SelectPart, selectQuery.FromPart, selectQuery.WherePart);
}
if (!string.IsNullOrWhiteSpace(selectQuery.OrderPart))
result = string.Format("{0} ORDER BY {1}", result, selectQuery.OrderPart);
return result;
}
I wanted something a bit slimmer for RSpec/Ruby so that the custom code only had to live in one place. Here's my solution:
/spec/support/selenium.rb
...
RSpec.configure do |config|
config.after(:suite) do
$custom_headers = nil
end
end
module RequestWithExtraHeaders
def headers
$custom_headers.each do |key, value|
self.set_header "HTTP_#{key}", value
end if $custom_headers
super
end
end
class ActionDispatch::Request
prepend RequestWithExtraHeaders
end
Then in my specs:
/specs/features/something_spec.rb
...
$custom_headers = {"Referer" => referer_string}
It would be easier to use XML in SQL Server to insert multiple rows otherwise it becomes very tedious.
View full article with code explanations here http://www.cyberminds.co.uk/blog/articles/how-to-insert-multiple-rows-in-sql-server.aspx
Copy the following code into sql server to view a sample.
declare @test nvarchar(max)
set @test = '<topic><dialog id="1" answerId="41">
<comment>comment 1</comment>
</dialog>
<dialog id="2" answerId="42" >
<comment>comment 2</comment>
</dialog>
<dialog id="3" answerId="43" >
<comment>comment 3</comment>
</dialog>
</topic>'
declare @testxml xml
set @testxml = cast(@test as xml)
declare @answerTemp Table(dialogid int, answerid int, comment varchar(1000))
insert @answerTemp
SELECT ParamValues.ID.value('@id','int') ,
ParamValues.ID.value('@answerId','int') ,
ParamValues.ID.value('(comment)[1]','VARCHAR(1000)')
FROM @testxml.nodes('topic/dialog') as ParamValues(ID)
To elaborate on Sami's answer:
From the docs:
class Payload(object):
def __init__(self, action, method, data):
self.action = action
self.method = method
self.data = data
import json
def as_payload(dct):
return Payload(dct['action'], dct['method'], dct['data'])
payload = json.loads(message, object_hook = as_payload)
My objection to the
.__dict__
solution is that while it does the job and is concise, the Payload class becomes totally generic - it doesn't document its fields.
For example, if the Payload message had an unexpected format, instead of throwing a key not found error when the Payload was created, no error would be generated until the payload was used.
var results = list.GroupBy(x => x.Category)
.Select(g => g.OrderBy(x => x.SortByProp).FirstOrDefault());
For those wondering how to do this for groups that are not necessarily sorted correctly, here's an expansion of this answer that uses method syntax to customize the sort order of each group and hence get the desired record from each.
Note: If you're using LINQ-to-Entities you will get a runtime exception if you use First() instead of FirstOrDefault() here as the former can only be used as a final query operation.
I find using tokens pretty clean. It is integrated into core in Drupal 7.
<?php print token_replace('[current-page:url]'); ?>
Quite simple, with a *
wildcard.
cp -r Folder1/* Folder2/
But according to your example recursion is not needed so the following will suffice:
cp Folder1/* Folder2/
EDIT:
Or skip the mkdir Folder2
part and just run:
cp -r Folder1 Folder2
For the carousel, I believe all images have to be exactly the same height and width.
Also, when you refer back to the scaffolding page from bootstrap, I'm pretty sure that span16 = 940px. With this in mind, I think we can assume that if you have a
<div class="row">
<div class="span4">
<!--left content div guessing around 235px in width -->
</div>
<div class="span8">
<!--right content div guessing around 470px in width -->
</div>
</div>
So yes, you have to be careful when setting the spans space within a row because if the image width is to large, it will send your div over into the next "row" and that is no fun :P
Just use the float style. Put your google map iframe in a div class, and the paragraph in another div class, then apply the following CSS styles to those div classes(don't forget to clear the blocks after float effect, to not make the blocks trouble below them):
css
.google_map{
width:55%;
margin-right:2%;
float: left;
}
.google_map iframe{
width:100%;
}
.paragraph {
width:42%;
float: left;
}
.clearfix{
clear:both
}
html
<div class="google_map">
<iframe></iframe>
</div>
<div class="paragraph">
<p></p>
</div>
<div class="clearfix"></div>
grep "subscription" | grep -v "spec"
It's very simple. Git doesn't care about what's the name of its directory. It only cares what's inside. So you can simply do:
# copy the directory into newrepo dir that exists already (else create it)
$ cp -r gitrepo1 newrepo
# remove .git from old repo to delete all history and anything git from it
$ rm -rf gitrepo1/.git
Note that the copy is quite expensive if the repository is large and with a long history. You can avoid it easily too:
# move the directory instead
$ mv gitrepo1 newrepo
# make a copy of the latest version
# Either:
$ mkdir gitrepo1; cp -r newrepo/* gitrepo1/ # doesn't copy .gitignore (and other hidden files)
# Or:
$ git clone --depth 1 newrepo gitrepo1; rm -rf gitrepo1/.git
# Or (look further here: http://stackoverflow.com/q/1209999/912144)
$ git archive --format=tar --remote=<repository URL> HEAD | tar xf -
Once you create newrepo
, the destination to put gitrepo1
could be anywhere, even inside newrepo
if you want it. It doesn't change the procedure, just the path you are writing gitrepo1
back.
Our server ran out of disk space on Sunday afternoon which led to an application suddenly failing and returning HTTP error 502. The logs were empty so it had to be something that was occurring before IIS even did anything.
A swift look at the event viewer(WIN+R > eventvwr
) exposed the issue.
It's a good idea to filter out the output of the System and Application windows to WAS since it can get pretty verbose in there.
The application depended on another one which was disabled. Therefore keep in mind an application can go down indirectly if one of it's dependent processes has gone down. We simply re-enabled the .NET application pool and our other application started running normally again.
As an answer I say No. You can only get values from jstl to javascript. But u can display the user name using javascript itself. Best ways are here. To display user name, if u have html like
<div id="uName"></div>
You can display user name as follows.
var val1 = document.getElementById('userName').value;
document.getElementById('uName').innerHTML = val1;
var userName = '<c:out value="${user}"/>';
here ${user} is the data you get as response(from backend).
var arrayLength = <c:out value="${details.size()}"/>;
function advanced(){
var values = new Array();
<c:if test="${empty details.users}">
values.push("No user found");
</c:if>
<c:if test="${!empty details.users}">
<c:forEach var="user" items="${details.users}" varStatus="stat">
values.push("${user.name}");
</c:forEach>
</:c:if>
alert("values[0] "+values[0]);
});
if you have enum like this
public enum PcapLinkType {
DLT_NULL(0)
DLT_EN10MB(1)
DLT_EN3MB(2),
DLT_AX25(3),
DLT_UNKNOWN(-1);
private final int value;
PcapLinkType(int value) {
this.value= value;
}
}
then you can use it like
PcapLinkType type = PcapLinkType.values()[1]; /*convert val to a PcapLinkType */
If you don't want to use RegEx (which seems highly unnecessary given your problem), perhaps you should try something like this:
public String modified(final String input){
final StringBuilder builder = new StringBuilder();
for(final char c : input.toCharArray())
if(Character.isLetterOrDigit(c))
builder.append(Character.isLowerCase(c) ? c : Character.toLowerCase(c));
return builder.toString();
}
It loops through the underlying char[]
in the String
and only appends the char
if it is a letter or digit (filtering out all symbols, which I am assuming is what you are trying to accomplish) and then appends the lower case version of the char
.
circle.xml (drawable)
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid
android:color="#000"/>
<size
android:width="10dp"
android:height="10dp"/>
</shape>
layout
<ImageView
android:id="@+id/circleColor"
android:layout_width="15dp"
android:layout_height="15dp"
android:textSize="12dp"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:background="@drawable/circle"/>
in activity
circleColor = (ImageView) view.findViewById(R.id.circleColor);
int color = Color.parseColor("#00FFFF");
((GradientDrawable)circleColor.getBackground()).setColor(color);
You could try adding an<hr>
and styling that. Its a minimal markup change but seems to need less css so that might do the trick.
fiddle:
mysql_update
is what you need.
I don't know why anyone would follow the more complex ways of correcting this issue, when MySql graciously built a tool that already does this...
var x : IHash = {};
x['key1'] = 'value1';
x['key2'] = 'value2';
console.log(x['key1']);
// outputs value1
console.log(x['key2']);
// outputs value2
If you would like to then iterate through your dictionary, you can use.
Object.keys(x).forEach((key) => {console.log(x[key])});
Object.keys returns all the properties of an object, so it works nicely for returning all the values from dictionary styled objects.
You also mentioned a hashmap in your question, the above definition is for a dictionary style interface. Therefore the keys will be unique, but the values will not.
You could use it like a hashset by just assigning the same value to the key and its value.
if you wanted the keys to be unique and with potentially different values, then you just have to check if the key exists on the object before adding to it.
var valueToAdd = 'one';
if(!x[valueToAdd])
x[valueToAdd] = valueToAdd;
or you could build your own class to act as a hashset of sorts.
Class HashSet{
private var keys: IHash = {};
private var values: string[] = [];
public Add(key: string){
if(!keys[key]){
values.push(key);
keys[key] = key;
}
}
public GetValues(){
// slicing the array will return it by value so users cannot accidentally
// start playing around with your array
return values.slice();
}
}
It can solve this problem by cd command, this command understand spaces without double quotes and you can call any program this way for example:
C:\Windows\system32>cd c:\Program Files\MongoDB\Server\3.2\bin
c:\Program Files\MongoDB\Server\3.2\bin>mongo now command prompt call mongo.exe
Like @amalBit's answer, register a listener to global layout and calculate the difference of dectorView's visible bottom and its proposed bottom, if the difference is bigger than some value(guessed IME's height), we think IME is up:
final EditText edit = (EditText) findViewById(R.id.edittext);
edit.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (keyboardShown(edit.getRootView())) {
Log.d("keyboard", "keyboard UP");
} else {
Log.d("keyboard", "keyboard Down");
}
}
});
private boolean keyboardShown(View rootView) {
final int softKeyboardHeight = 100;
Rect r = new Rect();
rootView.getWindowVisibleDisplayFrame(r);
DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
int heightDiff = rootView.getBottom() - r.bottom;
return heightDiff > softKeyboardHeight * dm.density;
}
the height threshold 100 is the guessed minimum height of IME.
This works for both adjustPan and adjustResize.
Use getElementById:
document.getElementById ('frmProduct').submit ()
declare @temp table
(
name varchar(255),
field varchar(255),
filename varchar(255),
filegroup varchar(255),
size varchar(255),
maxsize varchar(255),
growth varchar(255),
usage varchar(255)
);
INSERT @temp Exec sp_helpfile;
select * from @temp;
With RxJS
:
import { timer } from 'rxjs';
// ...
timer(your_delay_in_ms).subscribe(x => { your_action_code_here })
x
is 0.
If you give a second argument period
to timer
, a new number will be emitted each period
milliseconds (x = 0 then x = 1, x = 2, ...).
See the official doc for more details.
The above answers only work if AllowUserToAddRows
is set to false
. If that property is set to true
, then you will get a NullReferenceException
when the loop or Linq query tries to negotiate the new row. I've modified the two accepted answers above to handle AllowUserToAddRows = true
.
Loop answer:
String searchValue = "somestring";
int rowIndex = -1;
foreach(DataGridViewRow row in DataGridView1.Rows)
{
if (row.Cells["SystemId"].Value != null) // Need to check for null if new row is exposed
{
if(row.Cells["SystemId"].Value.ToString().Equals(searchValue))
{
rowIndex = row.Index;
break;
}
}
}
LINQ answer:
int rowIndex = -1;
bool tempAllowUserToAddRows = dgv.AllowUserToAddRows;
dgv.AllowUserToAddRows = false; // Turn off or .Value below will throw null exception
DataGridViewRow row = dgv.Rows
.Cast<DataGridViewRow>()
.Where(r => r.Cells["SystemId"].Value.ToString().Equals(searchValue))
.First();
rowIndex = row.Index;
dgv.AllowUserToAddRows = tempAllowUserToAddRows;
I found this question while trying to debug my mod_rewrite issues, and it definitely has some helpful advice. But in the end the most important thing is to make sure you have your regex syntax correct. Due to problems with my own RE syntax, installing the regexpCheck.php script was not a viable option.
But since Apache uses Perl-Compatible Regular Expressions (PCRE)s, any tool which helps writing PCREs should help. I've used RegexPlanet's tool with Java and Javascript REs in the past, and was happy to find that they support Perl as well.
Just type in your regular expression and one or more example URLs, and it will tell you if the regex matches (a "1" in the "~=" column) and if applicable, any matching groups (the numbers in the "split" column will correspond to the numbers Apache expects, e.g. $1, $2 etc.) for each URL. They claim PCRE support is "in beta", but it was just what I needed to solve my syntax problems.
http://www.regexplanet.com/advanced/perl/index.html
I'd have simply added a comment to an existing answer but my reputation isn't yet at that level. Hope this helps someone.
Please be careful not to overwrite the ";secure" cookie flag in https-sessions. This flag prevents the browser from sending the cookie over an unencrypted http connection, basically rendering the use of https for legit requests pointless.
private void rewriteCookieToHeader(HttpServletRequest request, HttpServletResponse response) {
if (response.containsHeader("SET-COOKIE")) {
String sessionid = request.getSession().getId();
String contextPath = request.getContextPath();
String secure = "";
if (request.isSecure()) {
secure = "; Secure";
}
response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid
+ "; Path=" + contextPath + "; HttpOnly" + secure);
}
}
When I write a service I put all the service logic in a dll project and create two "hosts" that call into this dll, one is a Windows service and the other is a command line application.
I use the command line application for debugging and attach the debugger to the real service only for bugs I can't reproduce in the command line application.
I you use this approach just remember that you have to test all the code while running in a real service, while the command line tool is a nice debugging aid it's a different environment and it doesn't behave exactly like a real service.
Your only option is to somehow clone the object.
See this stackoverflow question on how you can achieve this.
For simple JSON objects, the simplest way would be:
var newObject = JSON.parse(JSON.stringify(oldObject));
if you use jQuery, you can use:
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
UPDATE 2017: I should mention, since this is a popular answer, that there are now better ways to achieve this using newer versions of javascript:
In ES6 or TypeScript (2.1+):
var shallowCopy = { ...oldObject };
var shallowCopyWithExtraProp = { ...oldObject, extraProp: "abc" };
Note that if extraProp
is also a property on oldObject, its value will not be used because the extraProp : "abc"
is specified later in the expression, which essentially overrides it. Of course, oldObject will not be modified.
Here's various date and time information you can pull in vbscript running under Windows Script Host (WSH):
Now = 2/29/2016 1:02:03 PM
Date = 2/29/2016
Time = 1:02:03 PM
Timer = 78826.31 ' seconds since midnight
FormatDateTime(Now) = 2/29/2016 1:02:03 PM
FormatDateTime(Now, vbGeneralDate) = 2/29/2016 1:02:03 PM
FormatDateTime(Now, vbLongDate) = Monday, February 29, 2016
FormatDateTime(Now, vbShortDate) = 2/29/2016
FormatDateTime(Now, vbLongTime) = 1:02:03 PM
FormatDateTime(Now, vbShortTime) = 13:02
Year(Now) = 2016
Month(Now) = 2
Day(Now) = 29
Hour(Now) = 13
Minute(Now) = 2
Second(Now) = 3
Year(Date) = 2016
Month(Date) = 2
Day(Date) = 29
Hour(Time) = 13
Minute(Time) = 2
Second(Time) = 3
Function LPad (str, pad, length)
LPad = String(length - Len(str), pad) & str
End Function
LPad(Month(Date), "0", 2) = 02
LPad(Day(Date), "0", 2) = 29
LPad(Hour(Time), "0", 2) = 13
LPad(Minute(Time), "0", 2) = 02
LPad(Second(Time), "0", 2) = 03
Weekday(Now) = 2
WeekdayName(Weekday(Now), True) = Mon
WeekdayName(Weekday(Now), False) = Monday
WeekdayName(Weekday(Now)) = Monday
MonthName(Month(Now), True) = Feb
MonthName(Month(Now), False) = February
MonthName(Month(Now)) = February
Set os = GetObject("winmgmts:root\cimv2:Win32_OperatingSystem=@")
os.LocalDateTime = 20131204215346.562000-300
Left(os.LocalDateTime, 4) = 2013 ' year
Mid(os.LocalDateTime, 5, 2) = 12 ' month
Mid(os.LocalDateTime, 7, 2) = 04 ' day
Mid(os.LocalDateTime, 9, 2) = 21 ' hour
Mid(os.LocalDateTime, 11, 2) = 53 ' minute
Mid(os.LocalDateTime, 13, 2) = 46 ' second
Dim wmi : Set wmi = GetObject("winmgmts:root\cimv2")
Set timeZones = wmi.ExecQuery("SELECT Bias, Caption FROM Win32_TimeZone")
For Each tz In timeZones
tz.Bias = -300
tz.Caption = (UTC-05:00) Eastern Time (US & Canada)
Next
As of Bootstrap 4, you can use the spacing utilities.
Add for instance px-2
in the classes of the nav-item
to increase the padding.
To quote the Python 2.x documentation:
A prefix of 'b' or 'B' is ignored in Python 2; it indicates that the literal should become a bytes literal in Python 3 (e.g. when code is automatically converted with 2to3). A 'u' or 'b' prefix may be followed by an 'r' prefix.
The Python 3 documentation states:
Bytes literals are always prefixed with 'b' or 'B'; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.
Just wanted to add to an old thread to hopefully aid other people. I needed programmatically add a cert to the firefox database using a GPO, this was how I did it for Windows
1, First download and unzip the precompiled firefox NSS nss-3.13.5-nspr-4.9.1-compiled-x86.zip
2, Add the cert manually to firefox Options-->Advanced--Certificates-->Authorities-->Import
3, from the downloaded NSS package, run
certutil -L -d c:\users\[username]\appdata\roaming\mozilla\firefox\[profile].default
4, The above query will show you the certificate name and Trust Attributes e.g.
my company Ltd CT,C,C
5, Delete the certificate in step 2. Options-->Advanced--Certificates-->Authorities-->Delete
6, Create a powershell script using the information from step 4 as follows. This script will get the users profile path and add the certificate. This only works if the user has one firefox profile (need somehow to retrieve the users firefox folder profile name)
#Script adds Radius Certificate to independent Firefox certificate store since the browser does not use the Windows built in certificate store
#Get Firefox profile cert8.db file from users windows profile path
$ProfilePath = "C:\Users\" + $env:username + "\AppData\Roaming\Mozilla\Firefox\Profiles\"
$ProfilePath = $ProfilePath + (Get-ChildItem $ProfilePath | ForEach-Object { $_.Name }).ToString()
#Update firefox cert8.db file with Radius Certificate
certutil -A -n "UK my company" -t "CT,C,C" -i CertNameToAdd.crt -d $ProfilePath
7, Create GPO as a User Configuration to run the PowerShell script
Hope that helps save someone time
You can also do this to set a header for all future gets for the Session object, where x-test will be in all s.get() calls:
s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})
# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})
from: http://docs.python-requests.org/en/latest/user/advanced/#session-objects
It might help you!!
The AngularJs code-sample
var app = angular.module('app', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
// For any unmatched url, send to /index
$urlRouterProvider.otherwise("/login");
$stateProvider
.state('login', {
url: "/login",
templateUrl: "login.html",
controller: "LoginCheckController"
})
.state('SuccessPage', {
url: "/SuccessPage",
templateUrl: "SuccessPage.html",
//controller: "LoginCheckController"
});
});
app.controller('LoginCheckController', ['$scope', '$location', LoginCheckController]);
function LoginCheckController($scope, $location) {
$scope.users = [{
UserName: 'chandra',
Password: 'hello'
}, {
UserName: 'Harish',
Password: 'hi'
}, {
UserName: 'Chinthu',
Password: 'hi'
}];
$scope.LoginCheck = function() {
$location.path("SuccessPage");
};
$scope.go = function(path) {
$location.path("/SuccessPage");
};
}
In my case got a working solution through Cross-document Messaging (XDM) and Executing Chrome extension onclick instead of page load.
manifest.json
{
"name": "JQuery Light",
"version": "1",
"manifest_version": 2,
"browser_action": {
"default_icon": "icon.png"
},
"content_scripts": [
{
"matches": [
"https://*.google.com/*"
],
"js": [
"jquery-3.3.1.min.js",
"myscript.js"
]
}
],
"background": {
"scripts": [
"background.js"
]
}
}
background.js
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
});
});
myscript.js
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.message === "clicked_browser_action") {
console.log('Hello world!')
}
}
);
# This program reads columns in a csv file
import csv
ifile = open('years.csv', "r")
reader = csv.reader(ifile)
# initialization and declaration of variables
rownum = 0
year = 0
dec = 0
jan = 0
total_years = 0`
for row in reader:
if rownum == 0:
header = row #work with header row if you like
else:
colnum = 0
for col in row:
if colnum == 0:
year = float(col)
if colnum == 1:
dec = float(col)
if colnum == 2:
jan = float(col)
colnum += 1
# end of if structure
# now we can process results
if rownum != 0:
print(year, dec, jan)
total_years = total_years + year
print(total_years)
# time to go after the next row/bar
rownum += 1
ifile.close()
A bit late but nonetheless... You need to create and identify the csv file named "years.csv":
Year Dec Jan 1 50 60 2 25 50 3 30 30 4 40 20 5 10 10
Debug.Print
outputs to the "Immediate" window.
Also, you can simply type ?
and then a statement directly into the immediate window (and then press Enter) and have the output appear right below, like this:
This can be very handy to quickly output the property of an object...
? myWidget.name
...to set the property of an object...
myWidget.name = "thingy"
...or to even execute a function or line of code, while in debugging mode:
Sheet1.MyFunction()
I use Pokémon database as an example, the columns for my data base are
['Name', '#', 'Type 1', 'Type 2', 'Total', 'HP', 'Attack', 'Defense', 'Sp. Atk', 'Sp. Def', 'Speed', 'Generation', 'Legendary']
Here is the code:
import pandas as pd
df = pd.read_html('https://gist.github.com/armgilles/194bcff35001e7eb53a2a8b441e8b2c6')[0]
cols = df.columns.to_list()
cos_end= ["Name", "Total", "HP", "Defense"]
for i, j in enumerate(cos_end, start=(len(cols)-len(cos_end))):
cols.insert(i, cols.pop(cols.index(j)))
print(cols)
df = df.reindex(columns=cols)
print(df)
:set tabstop=4
:set shiftwidth=4
:set expandtab
This will insert four spaces instead of a tab character. Spaces are a bit more “stable”, meaning that text indented with spaces will show up the same in the browser and any other application.
Enter git-forward-merge:
Without needing to checkout destination,
git-forward-merge <source> <destination>
merges source into destination branch.
https://github.com/schuyler1d/git-forward-merge
Only works for automatic merges, if there are conflicts you need to use the regular merge.
You can use String.Format:
DateTime d = DateTime.Now;
string str = String.Format("{0:00}/{1:00}/{2:0000} {3:00}:{4:00}:{5:00}.{6:000}", d.Month, d.Day, d.Year, d.Hour, d.Minute, d.Second, d.Millisecond);
// I got this result: "02/23/2015 16:42:38.234"
Try this:
String urle = HOST + url + value;
Then return the values from:
urle.replace(" ", "%20").trim();
I have used this very often in neural networks. It is well known that when we start training a neural network we randomly initialise the weights. The model is trained on these weights on a particular dataset. After number of epochs you get trained set of weights.
Now suppose you want to again train from scratch or you want to pass the model to others to reproduce your results, the weights will be again initialised to a random numbers which mostly will be different from earlier ones. The obtained trained weights after same number of epochs ( keeping same data and other parameters ) as earlier one will differ. The problem is your model is no more reproducible that is every time you train your model from scratch it provides you different sets of weights. This is because the model is being initialized by different random numbers every time.
What if every time you start training from scratch the model is initialised to the same set of random initialise weights? In this case your model could become reproducible. This is achieved by numpy.random.seed(0). By mentioning seed() to a particular number, you are hanging on to same set of random numbers always.
It took me a while to find out what is going on, but here is the summary. I hope this save people a lot of time.
Apple are not playing nice with Wi-Fi Direct, not in the same way that Android is. The Multipeer Connectivity Framework that Apple provides combines both BLE and WiFi Direct together and will only work with Apple devices and not any device that is using Wi-Fi Direct.
It states the following in this documentation - "The Multipeer Connectivity framework provides support for discovering services provided by nearby iOS devices using infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks and subsequently communicating with those services by sending message-based data, streaming data, and resources (such as files)."
Additionally, Wi-Fi direct in this mode between i-Devices will need iPhone 5 and above.
There are apps that use a form of Wi-Fi Direct on the App Store, but these are using their own libraries.
try the below command, it should work
- shell: ls -1 /some/dir
register: contents
- file: path=/some/dir/{{ item }} state=absent
with_items: {{ contents.stdout_lines }}
I faced similar issue due to local vs remote referencing
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script>
<script src="lib/js/ui-grid/3.0.7/ui-grid.js"></script>
As ui-grid.js is dependent on angular.js, ui-grid requires angular.js by the time its loaded. But in the above case, ui-grid.js [locally saved reference file] is loaded before angularjs was loaded [from internet],
The problem was solved if I had both angular.js and ui-grid referenced locally and as well declaring angular.js before ui-grid
<script src="lib/js/angularjs/1.4.3/angular.js"></script>
<script src="lib/js/ui-grid/3.0.7/ui-grid.js"></script>
echo $'Create the snapshots\nSnapshot created\n'
This is a very fast and clean way of doing it. It also supports empty columns where as none of the answers above worked for empty columns.
Usage: SelectFirstBlankCell("F")
Public Sub SelectFirstBlankCell(col As String)
Dim i As Integer
For i = 1 To 10000
If Range(col & CStr(i)).Value = "" Then
Exit For
End If
Next i
Range(col & CStr(i)).Select
End Sub
Single Threaded Event Loop Model Processing Steps:
Clients Send request to Web Server.
Node JS Web Server internally maintains a Limited Thread pool to provide services to the Client Requests.
Node JS Web Server receives those requests and places them into a Queue. It is known as “Event Queue”.
Node JS Web Server internally has a Component, known as “Event Loop”. Why it got this name is that it uses indefinite loop to receive requests and process them.
Event Loop uses Single Thread only. It is main heart of Node JS Platform Processing Model.
Event Loop checks any Client Request is placed in Event Queue. If not then wait for incoming requests for indefinitely.
If yes, then pick up one Client Request from Event Queue
That Thread is responsible for taking that request, process it, perform Blocking IO operations, prepare response and send it back to the Event Loop
very nicely explained by @Rambabu Posa for more explanation go throw this Link
If your goal is to have
str = "Hello\nWorld";
and output what it contains in string literal form, you can use JSON.stringify
:
console.log(JSON.stringify(str)); // ""Hello\nWorld""
const str = "Hello\nWorld";_x000D_
const json = JSON.stringify(str);_x000D_
console.log(json); // ""Hello\nWorld""_x000D_
for (let i = 0; i < json.length; ++i) {_x000D_
console.log(`${i}: ${json.charAt(i)}`);_x000D_
}
_x000D_
.as-console-wrapper {_x000D_
max-height: 100% !important;_x000D_
}
_x000D_
console.log
adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal (yes, that's somewhat confusing).
JSON.stringify
takes what you give it (in this case, a string) and returns a string containing valid JSON for that value. So for the above, it returns an opening quote ("
), the word Hello
, a backslash (\
), the letter n
, the word World
, and the closing quote ("
). The linefeed in the string is escaped in the output as a \
and an n
because that's how you encode a linefeed in JSON. Other escape sequences are similarly encoded.
Adding dependencies didn't fix the issue at my end.
The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.
I removed the additional fields from the @Entity class and it worked.
No need to use these commands .. you can directly use the nexus web Interface in order to upload your JAR using GAV parameters.
So it is very simple.
First answer is amphibole. here is my explain: add:
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
in oncreate() method.
before:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
(not just before setContentView) if don't do this u will get forceclose. +1 this answer.
public void methodOnClick(View view){
Button.setBackgroundResource(R.drawable.nameImage);
}
i recommend use button inside LinearLayout for adjust to size of Linear.
For 400 error, check the repository "Deployment policy" usually its "Disable redeploy". Most of the time your library version is already there that is why you received a message "Could not PUT put 'https://yoururl/some.jar'. Received status code 400 from server: Repository does not allow updating assets: "your repository name"
So, you have a few options to resolve this. 1- allow redeploy 2- delete the version from your repository which you are trying to upload 3- change the version number
If you're on Cygwin this command will show you the locations:
mysql --help |grep -A1 Default|grep my
An unusual but pretty way of doing it
Without index:
each _ in Array(5)
= 'a'
Will print: aaaaa
With index:
each _, i in Array(5)
= i
Will print: 01234
Notes: In the examples above, I have assigned the val
parameter of jade's each
iteration syntax to _
because it is required, but will always return undefined
.
You should ensure the HTTP server headers are correct.
In particular, the header:
Content-Type: text/html; charset=utf-8
should be present.
The meta tag is ignored by browsers if the HTTP header is present.
Also ensure that your file is actually encoded as UTF-8 before serving it, check/try the following:
&#uuu;
.Note: If you use an unicode character for which your system can't find a glyph (no font with that character), your browser should display a question mark or some block like symbol. But if you see multiple roman characters like you do, this denotes an encoding problem.
Committing .gitignore can be very useful but you want to make sure you don't modify it too much thereafter especially if you regularly switch between branches. If you do you might get cases where files are ignored in a branch and not in the other, forcing you to go manually delete or rename files in your work directory because a checkout failed as it would overwrite a non-tracked file.
Therefore yes, do commit your .gitignore, but not before you are reasonably sure it won't change that much thereafter.
I would use @HostListener decorator within your component:
import { HostListener } from '@angular/core';
@Component({
...
})
export class AppComponent {
@HostListener('document:keypress', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
this.key = event.key;
}
}
There are also other options like:
host property within @Component
decorator
Angular recommends using @HostListener
decorator over host property https://angular.io/guide/styleguide#style-06-03
@Component({
...
host: {
'(document:keypress)': 'handleKeyboardEvent($event)'
}
})
export class AppComponent {
handleKeyboardEvent(event: KeyboardEvent) {
console.log(event);
}
}
renderer.listen
import { Component, Renderer2 } from '@angular/core';
@Component({
...
})
export class AppComponent {
globalListenFunc: Function;
constructor(private renderer: Renderer2) {}
ngOnInit() {
this.globalListenFunc = this.renderer.listen('document', 'keypress', e => {
console.log(e);
});
}
ngOnDestroy() {
// remove listener
this.globalListenFunc();
}
}
Observable.fromEvent
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import { Subscription } from 'rxjs/Subscription';
@Component({
...
})
export class AppComponent {
subscription: Subscription;
ngOnInit() {
this.subscription = Observable.fromEvent(document, 'keypress').subscribe(e => {
console.log(e);
})
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
Use \1
instead of $1
.
\number Matches the contents of the group of the same number.
http://docs.python.org/library/re.html#regular-expression-syntax
It prints 47.48000 if you use another MathContext:
BigDecimal b = new BigDecimal(d, MathContext.DECIMAL64);
Just pick the context you need.
Another Alternative for those who are probing around and/or in interactive mode:
$Error[0].Exception.LoaderExceptions
Note: [0] grabs the most recent Error from the stack
Just go with the command py
. I'm running python 3.6.2 on windows 7 and it works just fine.
I removed all the python paths from the system directory and the paths don't show up when I run the command echo %path%
in cmd. Python is still working fine.
I ran into this by accidentally pressing enter while typing python
...
EDIT: I didn't mention that I installed python to a custom folder C:\Python\
You can at least stop the query from breaking with an error and return NULL
if there is a division by zero:
SELECT a / NULLIF(b, 0) FROM t
However, I would NEVER convert this to Zero with coalesce
like it is shown in that other answer which got many upvotes. This is completely wrong in a mathematical sense, and it is even dangerous as your application will likely return wrong and misleading results.
just change them to password('yourpassword')
You don't need to use a second repository - you can do commands like git checkout
and git commit
on a bare repository, if only you supply a dummy work directory using the --work-tree
option.
Prepare a dummy directory:
$ rm -rf /tmp/empty_directory
$ mkdir /tmp/empty_directory
Create the master
branch without a parent (works even on a completely empty repo):
$ cd your-bare-repository.git
$ git checkout --work-tree=/tmp/empty_directory --orphan master
Switched to a new branch 'master' <--- abort if "master" already exists
Create a commit (it can be a message-only, without adding any files, because what you need is simply having at least one commit):
$ git commit -m "Initial commit" --allow-empty --work-tree=/tmp/empty_directory
$ git branch
* master
Clean up the directory, it is still empty.
$ rmdir /tmp/empty_directory
Tested on git 1.9.1. (Specifically for OP, the posh-git is just a PowerShell wrapper for standard git.)
The problem is with your package structure. Spring Boot Application has a specific package structure to allow spring context to scan and load various beans in its context.
In com.nice.application is where your Main Class is and in com.nice.controller, you have your controller classes.
Move your com.nice.controller package into com.nice.application so that Spring can access your beans.
Another solution, based on scroll listener. Initial conditions are the same as in Sevastyan answer
RecyclerView recyclerView;
TextView tvTitle; //sticky header view
//... onCreate, initialize, etc...
public void bindList(List<Item> items) { //All data in adapter. Item - just interface for different item types
adapter = new YourAdapter(items);
recyclerView.setAdapter(adapter);
StickyHeaderViewManager<HeaderItem> stickyHeaderViewManager = new StickyHeaderViewManager<>(
tvTitle,
recyclerView,
HeaderItem.class, //HeaderItem - subclass of Item, used to detect headers in list
data -> { // bind function for sticky header view
tvTitle.setText(data.getTitle());
});
stickyHeaderViewManager.attach(items);
}
Layout for ViewHolder and sticky header.
item_header.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tv_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
Layout for RecyclerView
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<!--it can be any view, but order important, draw over recyclerView-->
<include
layout="@layout/item_header"/>
</FrameLayout>
Class for HeaderItem.
public class HeaderItem implements Item {
private String title;
public HeaderItem(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
It's all use. The implementation of the adapter, ViewHolder and other things, is not interesting for us.
public class StickyHeaderViewManager<T> {
@Nonnull
private View headerView;
@Nonnull
private RecyclerView recyclerView;
@Nonnull
private StickyHeaderViewWrapper<T> viewWrapper;
@Nonnull
private Class<T> headerDataClass;
private List<?> items;
public StickyHeaderViewManager(@Nonnull View headerView,
@Nonnull RecyclerView recyclerView,
@Nonnull Class<T> headerDataClass,
@Nonnull StickyHeaderViewWrapper<T> viewWrapper) {
this.headerView = headerView;
this.viewWrapper = viewWrapper;
this.recyclerView = recyclerView;
this.headerDataClass = headerDataClass;
}
public void attach(@Nonnull List<?> items) {
this.items = items;
if (ViewCompat.isLaidOut(headerView)) {
bindHeader(recyclerView);
} else {
headerView.post(() -> bindHeader(recyclerView));
}
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
bindHeader(recyclerView);
}
});
}
private void bindHeader(RecyclerView recyclerView) {
if (items.isEmpty()) {
headerView.setVisibility(View.GONE);
return;
} else {
headerView.setVisibility(View.VISIBLE);
}
View topView = recyclerView.getChildAt(0);
if (topView == null) {
return;
}
int topPosition = recyclerView.getChildAdapterPosition(topView);
if (!isValidPosition(topPosition)) {
return;
}
if (topPosition == 0 && topView.getTop() == recyclerView.getTop()) {
headerView.setVisibility(View.GONE);
return;
} else {
headerView.setVisibility(View.VISIBLE);
}
T stickyItem;
Object firstItem = items.get(topPosition);
if (headerDataClass.isInstance(firstItem)) {
stickyItem = headerDataClass.cast(firstItem);
headerView.setTranslationY(0);
} else {
stickyItem = findNearestHeader(topPosition);
int secondPosition = topPosition + 1;
if (isValidPosition(secondPosition)) {
Object secondItem = items.get(secondPosition);
if (headerDataClass.isInstance(secondItem)) {
View secondView = recyclerView.getChildAt(1);
if (secondView != null) {
moveViewFor(secondView);
}
} else {
headerView.setTranslationY(0);
}
}
}
if (stickyItem != null) {
viewWrapper.bindView(stickyItem);
}
}
private void moveViewFor(View secondView) {
if (secondView.getTop() <= headerView.getBottom()) {
headerView.setTranslationY(secondView.getTop() - headerView.getHeight());
} else {
headerView.setTranslationY(0);
}
}
private T findNearestHeader(int position) {
for (int i = position; position >= 0; i--) {
Object item = items.get(i);
if (headerDataClass.isInstance(item)) {
return headerDataClass.cast(item);
}
}
return null;
}
private boolean isValidPosition(int position) {
return !(position == RecyclerView.NO_POSITION || position >= items.size());
}
}
Interface for bind header view.
public interface StickyHeaderViewWrapper<T> {
void bindView(T data);
}
You could also do something like this:
SELECT tb1.* FROM Table tb1 WHERE id = (SELECT MAX(tb2.id) FROM Table tb2);
Its useful when you want to make some joins.
this can be done by adding
elif isinstance(o, decimal.Decimal):
yield str(o)
in \Lib\json\encoder.py:JSONEncoder._iterencode
, but I was hoping for a better solution
dplyr since 0.4 implemented all those joins including outer_join
, but it was worth noting that for the first few releases prior to 0.4 it used not to offer outer_join
, and as a result there was a lot of really bad hacky workaround user code floating around for quite a while afterwards (you can still find such code in SO, Kaggle answers, github from that period. Hence this answer still serves a useful purpose.)
Join-related release highlights:
v0.1.3 (4/2014)
Workarounds per hadley's comments in that issue:
I've adapted the code from the answer of Mark Amery, particularly in order to get rid of isinstance
for the pros of duck-typing.
The encoding is done manually and ensure_ascii
is disabled. The python docs for json.dump
says that
If ensure_ascii is True (the default), all non-ASCII characters in the output are escaped with \uXXXX sequences
Disclaimer: in the doctest I used the Hungarian language. Some notable Hungarian-related character encodings are: cp852
the IBM/OEM encoding used eg. in DOS (sometimes referred as ascii, incorrectly I think, it is dependent on the codepage setting), cp1250
used eg. in Windows (sometimes referred as ansi, dependent on the locale settings), and iso-8859-2
, sometimes used on http servers. The test text Tüskéshátú kígyóbuvölo
is attributed to Koltai László (native personal name form) and is from wikipedia.
# coding: utf-8
"""
This file should be encoded correctly with utf-8.
"""
import json
def encode_items(input, encoding='utf-8'):
u"""original from: https://stackoverflow.com/a/13101776/611007
adapted by SO/u/611007 (20150623)
>>>
>>> ## run this with `python -m doctest <this file>.py` from command line
>>>
>>> txt = u"Tüskéshátú kígyóbuvölo"
>>> txt2 = u"T\\u00fcsk\\u00e9sh\\u00e1t\\u00fa k\\u00edgy\\u00f3b\\u0171v\\u00f6l\\u0151"
>>> txt3 = u"uúuutifu"
>>> txt4 = b'u\\xfauutifu'
>>> # txt4 shouldn't be 'u\\xc3\\xbauutifu', string content needs double backslash for doctest:
>>> assert u'\\u0102' not in b'u\\xfauutifu'.decode('cp1250')
>>> txt4u = txt4.decode('cp1250')
>>> assert txt4u == u'u\\xfauutifu', repr(txt4u)
>>> txt5 = b"u\\xc3\\xbauutifu"
>>> txt5u = txt5.decode('utf-8')
>>> txt6 = u"u\\u251c\\u2551uutifu"
>>> there_and_back_again = lambda t: encode_items(t, encoding='utf-8').decode('utf-8')
>>> assert txt == there_and_back_again(txt)
>>> assert txt == there_and_back_again(txt2)
>>> assert txt3 == there_and_back_again(txt3)
>>> assert txt3.encode('cp852') == there_and_back_again(txt4u).encode('cp852')
>>> assert txt3 == txt4u,(txt3,txt4u)
>>> assert txt3 == there_and_back_again(txt5)
>>> assert txt3 == there_and_back_again(txt5u)
>>> assert txt3 == there_and_back_again(txt4u)
>>> assert txt3.encode('cp1250') == encode_items(txt4, encoding='utf-8')
>>> assert txt3.encode('utf-8') == encode_items(txt5, encoding='utf-8')
>>> assert txt2.encode('utf-8') == encode_items(txt, encoding='utf-8')
>>> assert {'a':txt2.encode('utf-8')} == encode_items({'a':txt}, encoding='utf-8')
>>> assert [txt2.encode('utf-8')] == encode_items([txt], encoding='utf-8')
>>> assert [[txt2.encode('utf-8')]] == encode_items([[txt]], encoding='utf-8')
>>> assert [{'a':txt2.encode('utf-8')}] == encode_items([{'a':txt}], encoding='utf-8')
>>> assert {'b':{'a':txt2.encode('utf-8')}} == encode_items({'b':{'a':txt}}, encoding='utf-8')
"""
try:
input.iteritems
return {encode_items(k): encode_items(v) for (k,v) in input.iteritems()}
except AttributeError:
if isinstance(input, unicode):
return input.encode(encoding)
elif isinstance(input, str):
return input
try:
iter(input)
return [encode_items(e) for e in input]
except TypeError:
return input
def alt_dumps(obj, **kwargs):
"""
>>> alt_dumps({'a': u"T\\u00fcsk\\u00e9sh\\u00e1t\\u00fa k\\u00edgy\\u00f3b\\u0171v\\u00f6l\\u0151"})
'{"a": "T\\xc3\\xbcsk\\xc3\\xa9sh\\xc3\\xa1t\\xc3\\xba k\\xc3\\xadgy\\xc3\\xb3b\\xc5\\xb1v\\xc3\\xb6l\\xc5\\x91"}'
"""
if 'ensure_ascii' in kwargs:
del kwargs['ensure_ascii']
return json.dumps(encode_items(obj), ensure_ascii=False, **kwargs)
I'd also like to highlight the answer of Jarret Hardie which references the JSON spec, quoting:
A string is a collection of zero or more Unicode characters
In my use-case I had files with json. They are utf-8
encoded files. ensure_ascii
results in properly escaped but not very readable json files, that is why I've adapted Mark Amery's answer to fit my needs.
The doctest is not particularly thoughtful but I share the code in the hope that it will useful for someone.
var Test = (from row in Dataset1.Tables[0].AsEnumerable()
select row.Field<string>("attribute1_name") + row.Field<int>("attribute2_name")).Distinct();
Here you will find some working examples. This is also a good example of FileFilter used in JFileChooser.
The basics are, you need to override FileFilter class and write your custom code in its accpet method. The accept method in above example is doing filtration based on file types:
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
} else {
String path = file.getAbsolutePath().toLowerCase();
for (int i = 0, n = extensions.length; i < n; i++) {
String extension = extensions[i];
if ((path.endsWith(extension) && (path.charAt(path.length()
- extension.length() - 1)) == '.')) {
return true;
}
}
}
return false;
}
Or more simpler to use is FileNameFilter which has accept method with filename as argument, so you don't need to get it manually.
There are some classes in the Java platform libraries that do extend an instantiable class and add a value component. For example, java.sql.Timestamp extends java.util.Date and adds a nanoseconds field. The equals implementation for Timestamp does violate symmetry and can cause erratic behavior if Timestamp and Date objects are used in the same collection or are otherwise intermixed. The Timestamp class has a disclaimer cautioning programmers against mixing dates and timestamps. While you won’t get into trouble as long as you keep them separate, there’s nothing to prevent you from mixing them, and the resulting errors can be hard to debug. This behavior of the Timestamp class was a mistake and should not be emulated.
check out this link
http://blogs.sourceallies.com/2012/02/hibernate-date-vs-timestamp/
If you want to know on which platform you are on out of "Linux", "Windows", or "Darwin" (Mac), without more precision, you should use:
>>> import platform
>>> platform.system()
'Linux' # or 'Windows'/'Darwin'
The platform.system
function uses uname
internally.
@echo off
cd C:\Program Files (x86)\MySQL\MySQL Workbench 6.0 CE
for %%a in (D:\abc\*.sql) do (
echo %%a
mysql --host=ip --port=3306 --user=uid--password=ped < %%a
)
Step1: above lines copy into note pad save it as bat.
step2: In d drive abc folder in all Sql files in queries executed in sql server.
step3: Give your ip, user id and password.