This is how I achieved the same in Scala. I am not sure if it is more efficient than the valid answer, but it requires less coding
val parquetFileDF = sqlContext.read.parquet("myParquetFule.parquet")
val myRow7th = parquetFileDF.rdd.take(7).last
All Bootstrap versions:
var isShown = $('.modal').hasClass('in') || $('.modal').hasClass('show')
To just close it independent of state and version:
$('.modal button.close').click()
Bootstrap 3 and before
var isShown = $('.modal').hasClass('in')
Bootstrap 4
var isShown = $('.modal').hasClass('show')
The correct answer is: There is no such thing as kernel space and user space. The processor instruction set has special permissions to set destructive things like the root of the page table map, or access hardware device memory, etc.
Kernel code has the highest level privileges, and user code the lowest. This prevents user code from crashing the system, modifying other programs, etc.
Generally kernel code is kept under a different memory map than user code (just as user spaces are kept in different memory maps than each other). This is where the "kernel space" and "user space" terms come from. But that is not a hard and fast rule. For example, since the x86 indirectly requires its interrupt/trap handlers to be mapped at all times, part (or some OSes all) of the kernel must be mapped into user space. Again, this does not mean that such code has user privileges.
Why is the kernel/user divide necessary? Some designers disagree that it is, in fact, necessary. Microkernel architecture is based on the idea that the highest privileged sections of code should be as small as possible, with all significant operations done in user privileged code. You would need to study why this might be a good idea, it is not a simple concept (and is famous for both having advantages and drawbacks).
Here you go:
$('td[id^="' + value +'"]')
so if the value is for instance 'foo'
, then the selector will be 'td[id^="foo"]'
.
Note that the quotes are mandatory: [id^="...."]
.
Source: http://api.jquery.com/attribute-starts-with-selector/
Not for nothing, but there is another way. First, construct your LINQ query. Then, construct a query of the Enumerated result and apply whatever type of formatting works for you.
var query = from t in db.Table select new { t.DateField };
var result = from c in query.AsEnumerable() select new { c.DateField.toString("dd MMM yyy") };
I have to say, the extra step is annoying, but it works nicely.
It would make for a handy function. Also, note I'm using STUFF instead of SUBSTRING.
create function str2uniq(@s varchar(50)) returns uniqueidentifier as begin
-- just in case it came in with 0x prefix or dashes...
set @s = replace(replace(@s,'0x',''),'-','')
-- inject dashes in the right places
set @s = stuff(stuff(stuff(stuff(@s,21,0,'-'),17,0,'-'),13,0,'-'),9,0,'-')
return cast(@s as uniqueidentifier)
end
Just specify it in shared.loader
or common.loader
property of /conf/catalina.properties
.
.yaml
is apparently the official extension, because some applications fail when using .yml
. On the other hand I am not familiar with any applications which use YAML code, but fail with a .yaml
extension.
I just stumbled across this, as I was used to writing .yml
in Ansible and Docker Compose. Out of habit I used .yml
when writing Netplan files which failed silently. I finally figured out my mistake. The author of a popular Ansible Galaxy role for Netplan makes the same assumption in his code:
- name: Capturing Existing Configurations
find:
paths: /etc/netplan
patterns: "*.yml,*.yaml"
register: _netplan_configs
Yet any files with a .yml
extension get ignored by Netplan in the same way as files with a .bak
extension. As Netplan is very quiet, and gives no feedback whatsoever on success, even with netplan apply --debug
, a config such as 01-netcfg.yml
will fail silently without any meaningful feedback.
You did not say which database, but with mysql here is an easy way to get a date from a timestamp (and the varchar type conversion should happen automatically):
mysql> select date(now());
+-------------+
| date(now()) |
+-------------+
| 2008-09-16 |
+-------------+
1 row in set (0.00 sec)
You can also use info files
to list all the sections of all the binaries loaded in process binary.
The correct, fully Pythonic way to read a file is the following:
with open(...) as f:
for line in f:
# Do something with 'line'
The with
statement handles opening and closing the file, including if an exception is raised in the inner block. The for line in f
treats the file object f
as an iterable, which automatically uses buffered I/O and memory management so you don't have to worry about large files.
There should be one -- and preferably only one -- obvious way to do it.
As id is PK it MUST be unique and not null. If you do not mention any field in the fields list for insert it'll be supposed to be null or default value. Set identity (i.e. autoincrement) for this field if you do not want to set it manualy every time.
you can use framelayout to achieve this.
how to use framelayout
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:src="@drawable/ic_launcher"
android:scaleType="fitCenter"
android:layout_height="250px"
android:layout_width="250px"/>
<TextView
android:text="Frame Demo"
android:textSize="30px"
android:textStyle="bold"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:gravity="center"/>
</FrameLayout>
ref: tutorialspoint
There are 2 solutions to paginate efficiently on a DB2 table :
1 - the technique using the function row_number() and the clause OVER which has been presented on another post ("SELECT row_number() OVER ( ORDER BY ... )"). On some big tables, I noticed sometimes a degradation of performances.
2 - the technique using a scrollable cursor. The implementation depends of the language used. That technique seems more robust on big tables.
I presented the 2 techniques implemented in PHP during a seminar next year. The slide is available on this link : http://gregphplab.com/serendipity/uploads/slides/DB2_PHP_Best_practices.pdf
Sorry but this document is only in french.
Sys.sleep() will not work if the CPU usage is very high; as in other critical high priority processes are running (in parallel).
This code worked for me. Here I am printing 1 to 1000 at a 2.5 second interval.
for (i in 1:1000)
{
print(i)
date_time<-Sys.time()
while((as.numeric(Sys.time()) - as.numeric(date_time))<2.5){} #dummy while loop
}
I use innerHTML together a ref to span:
import React, { useRef, useEffect, useState } from 'react';
export default function Sample() {
const spanRef = useRef<HTMLSpanElement>(null);
const [someHTML,] = useState("some <b>bold</b>");
useEffect(() => {
if (spanRef.current) {
spanRef.current.innerHTML = someHTML;
}
}, [spanRef.current, someHTML]);
return <div>
my custom text follows<br />
<span ref={spanRef} />
</div>
}
Forget float, margin and html 3/5. The mail is very obsolete. You need do all with table. One line = one table. You need margin or padding ? Do another column.
Example : i need one line with 1 One Picture of 40*40 2 One margin of 10 px 3 One text of 400px
I start my line :
<table style=" background-repeat:no-repeat; width:450px;margin:0;" cellpadding="0" cellspacing="0" border="0">
<tr style="height:40px; width:450px; margin:0;">
<td style="height:40px; width:40px; margin:0;">
<img src="" style="width=40px;height40;margin:0;display:block"
</td>
<td style="height:40px; width:10px; margin:0;">
</td>
<td style="height:40px; width:400px; margin:0;">
<p style=" margin:0;"> my text </p>
</td>
</tr>
</table>
This is the Known limitation in MySQLWorkbench (you can't edit table w/o PK):
Method 1: (method not working in somecases)
right-click on a table within the Object Browser and choose the Edit Table Data option from there.
Method 2:
I would rather suggest you to add Primary Key Instead:
ALTER TABLE `your_table_name` ADD PRIMARY KEY (`column_name`);
and you might want to remove the existing rows first:
Truncate table your_table_name
Yes, they do completely different things. pass
simply does nothing, while continue
goes on with the next loop iteration. In your example, the difference would become apparent if you added another statement after the if
: After executing pass
, this further statement would be executed. After continue
, it wouldn't.
>>> a = [0, 1, 2]
>>> for element in a:
... if not element:
... pass
... print element
...
0
1
2
>>> for element in a:
... if not element:
... continue
... print element
...
1
2
I know this is an older post but it may be useful for those who are looking to show a .NET server side image using jQuery.
You have to use a slightly different logic.
So, $("#<%=myServerimg.ClientID%>").show() will not work if you hid the image using myServerimg.visible = false.
Instead, use the following on server side:
myServerimg.Style.Add("display", "none")
I needed this instead of using padding because I used inline-block containers to display a series of individual events in a workflow timeline. The last event in the timeline needed no arrow after it.
Ended up with something like:
.transaction-tile:after {
content: "\f105";
}
.transaction-tile:last-child:after {
content: "\00a0";
}
Used fontawesome for the gt (chevron) character. For whatever reason "content: none;" was producing alignment issues on the last tile.
$('.toggle img').data('block', 'something').attr('src', 'something.jpg');
How about like this:
char* cmd = "./foo 1 2 3";
system(cmd);
Swift 4, Swift 5
let viewController = UIApplication.shared.keyWindow?.rootViewController
if viewController is MyViewController {
}
You can use the 'attributes' method:
@car.attributes = {:model => 'Sierra', :years => '1990', :looks => 'Sexy'}
Source: http://api.rubyonrails.org/classes/ActiveRecord/Base.html
attributes=(new_attributes, guard_protected_attributes = true) Allows you to set all the attributes at once by passing in a hash with keys matching the attribute names (which again matches the column names).
If guard_protected_attributes is true (the default), then sensitive attributes can be protected from this form of mass-assignment by using the attr_protected macro. Or you can alternatively specify which attributes can be accessed with the attr_accessible macro. Then all the attributes not included in that won’t be allowed to be mass-assigned.
class User < ActiveRecord::Base
attr_protected :is_admin
end
user = User.new
user.attributes = { :username => 'Phusion', :is_admin => true }
user.username # => "Phusion"
user.is_admin? # => false
user.send(:attributes=, { :username => 'Phusion', :is_admin => true }, false)
user.is_admin? # => true
BUILD_NUMBER
is the current build number. You can use it in the command you execute for the job, or just use it in the script your job executes.
See the Jenkins documentation for the full list of available environment variables. The list is also available from within your Jenkins instance at http://hostname/jenkins/env-vars.html.
You can use following query which worked for me-
For updating-
UPDATE table SET colName= REPLACE(LTRIM(RTRIM(REPLACE(colName, '"', ''))), '', '"') WHERE...
For selecting-
SELECT REPLACE(LTRIM(RTRIM(REPLACE(colName, '"', ''))), '', '"') FROM TableName
String prefTag = "someTag";
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext);
prefs.edit().remove(prefTag).commit();
This will delete the saved shared preferences with the name "someTag".
The vue-router
uses hash-mode
, in simple words it is something that you would normally expect from an achor tag like this.
<a href="#some_section">link<a>
To make the hash disappear
const routes = [
{
path: '/',
name: 'Home',
component: Home,
},
] // Routes Array
const router = new VueRouter({
mode: 'history', // Add this line
routes
})
Warning
: If you do not have a properly configured server or you are using a client-side SPA user may get a 404 Error
if they try to access https://website.com/posts/3
directly from their browser.
Vue Router Docs
I've found that this can happen due to a number of various reasons.
In my case when I scroll to the end of the SQL import "Report", under the "Post-execute (Success)" heading it will tell me how many rows were copied and it's usually the next row in sheet which has the issue. Also you can tell which column by the import messages (in your case it was "Copy of F2") so you can generally find out which was the offending cell in Excel.
I've seen this happen for very silly reasons such as the date format in Excel being different than previous rows. For example cell A2 being "05/02/2017" while A3 being "5/2/2017" or even "05-02-2017". It seems the import wants things to be perfectly consistent.
It even happens if the Excel formats are different so if B2 is "512" but an Excel "Number" format and B3 is "512" but an Excel "Text" format then the Cell will cause an error.
I've also had situations where I literally had to delete all the "empty" rows below my data rows in the Excel sheet. Sometimes they appear empty but Excel considers them having "blank" data or something like that so the import tries to import them as well. This usually happens if you've had previous data in your Excel sheet which you've cleared but haven't properly deleted the rows.
And then there's the obvious reasons of trying to import text value into an integer column or insert a NULL into a NOT NULL column as mentioned by the others.
Spotlight.js is a great library for iterating over the window object and other host objects looking for certain things.
// find all "length" properties
spotlight.byName('length');
// or find all "map" properties on jQuery
spotlight.byName('map', { 'object': jQuery, 'path': '$' });
// or all properties with `RegExp` values
spotlight.byKind('RegExp');
// or all properties containing "oo" in their name
spotlight.custom(function(value, key) { return key.indexOf('oo') > -1; });
You'll like it for this.
This was made better in python3 and documented in the stdlib documentation
The urllib.request.Request
class gained a method=...
parameter in python3.
Some sample usage:
req = urllib.request.Request('https://example.com/', data=b'DATA!', method='PUT')
urllib.request.urlopen(req)
Ok if anyone else is having this problem this may be your answer:
If you are trying to hide absolute positioned elements make sure the container of those absolute positioned elements is relatively positioned.
You could do this if firstname and surname are separated by space:
SELECT SUBSTRING(FirstAndSurnameCol, 0, CHARINDEX(' ', FirstAndSurnameCol)) Firstname,
SUBSTRING(FirstAndSurnameCol, CHARINDEX(' ', FirstAndSurnameCol)+1, LEN(FirstAndSurnameCol)) Surname FROM ...
Use the DATEPART function to extract the month from the date.
So you would do something like this:
SELECT DATEPART(month, Closing_Date) AS Closing_Month, COUNT(Status) AS TotalCount
FROM t
GROUP BY DATEPART(month, Closing_Date)
You should construct your string as URI object and Authority property returns what you need.
The only reason to have a return in a void function would be to exit early due to some conditional statement:
void foo(int y)
{
if(y == 0) return;
// do stuff with y
}
As unwind said: when the code ends, it ends. No need for an explicit return at the end.
parse_cols
is deprecated, use usecols
instead
that is:
df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols = "A,C:AA")
For Leaflet, I'm using
map.setView(markersLayer.getBounds().getCenter());
I agree with:
hashCode()
implementation could result to multiple collisions, which means that in the worst case every object goes to the same bucket, thus O(N) if each bucket is backed by a List
.HashMap
dynamically replaces the Nodes (linked list) used in each bucket with TreeNodes (red-black tree when a list gets bigger than 8 elements) resulting to a worst performance of O(logN).But, this is not the full truth if we want to be 100% precise. The implementation of hashCode()
and the type of key Object
(immutable/cached or being a Collection) might also affect real time complexity in strict terms.
Let's assume the following three cases:
HashMap<Integer, V>
HashMap<String, V>
HashMap<List<E>, V>
Do they have the same complexity? Well, the amortised complexity of the 1st one is, as expected, O(1). But, for the rest, we also need to compute hashCode()
of the lookup element, which means we might have to traverse arrays and lists in our algorithm.
Lets assume that the size of all of the above arrays/lists is k.
Then, HashMap<String, V>
and HashMap<List<E>, V>
will have O(k) amortised complexity and similarly, O(k + logN) worst case in Java8.
*Note that using a String
key is a more complex case, because it is immutable and Java caches the result of hashCode()
in a private variable hash
, so it's only computed once.
/** Cache the hash code for the string */
private int hash; // Default to 0
But, the above is also having its own worst case, because Java's String.hashCode()
implementation is checking if hash == 0
before computing hashCode
. But hey, there are non-empty Strings that output a hashcode
of zero, such as "f5a5a608", see here, in which case memoization might not be helpful.
jQuery is just a set of helpers/libraries written in Javascript. You can still use all Javascript features, so you can call whatever functions, also from inside jQuery callbacks. So both possibilities should be okay.
You need to use the alias
directive for location /static
:
server {
index index.html;
server_name test.example.com;
root /web/test.example.com/www;
location /static/ {
alias /web/test.example.com/static/;
}
}
The nginx wiki explains the difference between root and alias better than I can:
Note that it may look similar to the root directive at first sight, but the document root doesn't change, just the file system path used for the request. The location part of the request is dropped in the request Nginx issues.
Note that root
and alias
handle trailing slashes differently.
<div class="preload">
<img src="http://i.imgur.com/KUJoe.gif">
</div>
<div class="content">
I would like to display a loading bar before the entire page is loaded.
</div>
$(function() {
$(".preload").fadeOut(2000, function() {
$(".content").fadeIn(1000);
});
});?
.content {display:none;}
.preload {
width:100px;
height: 100px;
position: fixed;
top: 50%;
left: 50%;
}
?
There is a builtin mixin: transparentize($color, $amount);
background-color: transparentize(#F05353, .3);
The amount should be between 0 to 1;
Official Sass Documentation (Module: Sass::Script::Functions)
This tool creates the folders with the images in them automatically for you. All you have to do is supply your image then drag the generated folders to your res folder. http://romannurik.github.io/AndroidAssetStudio/
All the best.
Not much documentation on PowerShell loops.
Documentation on loops in PowerShell is plentiful, and you might want to check out the following help topics: about_For
, about_ForEach
, about_Do
, about_While
.
foreach($line in Get-Content .\file.txt) {
if($line -match $regex){
# Work here
}
}
Another idiomatic PowerShell solution to your problem is to pipe the lines of the text file to the ForEach-Object
cmdlet:
Get-Content .\file.txt | ForEach-Object {
if($_ -match $regex){
# Work here
}
}
Instead of regex matching inside the loop, you could pipe the lines through Where-Object
to filter just those you're interested in:
Get-Content .\file.txt | Where-Object {$_ -match $regex} | ForEach-Object {
# Work here
}
I think you are looking for this: RowHeaderMouseDoubleClick event
private void DgwModificar_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) {
...
}
to get the row index:
int indice = e.RowIndex
I have resolved it by deleting android-support-v4.jar
from my Project. Because appcompat_v7
already have a copy of it.
If you have already import appcompat_v7 but still the problem doesn't solve. then try it.
Use Enum.Parse()
.
var content = (ContentEnum)Enum.Parse(typeof(ContentEnum), fileContentMessage);
Many 3rd party libraries have their versions of Pair, but Java has never had such a class. The closest is the inner interface java.util.Map.Entry, which exposes an immutable key property and a possibly mutable value property.
vertical-align
applies to the elements being aligned, not their parent element. To vertically align the div's children, do this instead:
div > * {
vertical-align:middle; // Align children to middle of line
}
See: http://jsfiddle.net/dfmx123/TFPx8/1186/
NOTE: vertical-align
is relative to the current text line, not the full height of the parent div
. If you wanted the parent div
to be taller and still have the elements vertically centered, set the div
's line-height
property instead of its height
. Follow jsfiddle link above for an example.
The exception is thrown if
InvocationTargetException - if the underlying method throws an exception.
So if the method, that has been invoked with reflection API, throws an exception (runtime exception for example), the reflection API will wrap the exception into an InvocationTargetException
.
Mun's answer didn't work for me so I made some changes to that answer to get it to work. Hope this helps someone. Using SQL Server 2012:
SELECT [VehicleID]
, [Name]
, STUFF((SELECT DISTINCT ',' + CONVERT(VARCHAR,City)
FROM [Location]
WHERE (VehicleID = Vehicle.VehicleID)
FOR XML PATH ('')), 1, 2, '') AS Locations
FROM [Vehicle]
I suppose you want to get the content generated by PHP, if so use:
$Vdata = file_get_contents('http://YOUR_HOST/YOUR/FILE.php');
Otherwise if you want to get the source code of the PHP file, it's the same as a .txt file:
$Vdata = file_get_contents('path/to/YOUR/FILE.php');
The best solution for me is:
// Add key/value
var dict = new Dictionary<string, string>();
dict.Add("Content-Type", "application/x-www-form-urlencoded");
// Execute post method
using (var response = httpClient.PostAsync(path, new FormUrlEncodedContent(dict))){}
tail -f /var/log/syslog | grep process_name
where process_name
is the name of the process we are interested in
Create a div, which contains both divs (full and someid) and set the height of that div to the following:
height: 100vh;
The height of the containing divs (full and someid) should be set to "auto". That's all.
Can someone please tell me how to create a static library from a .cpp and a .hpp file? Do I need to create the .o and the the .a?
Yes.
Create the .o (as per normal):
g++ -c header.cpp
Create the archive:
ar rvs header.a header.o
Test:
g++ test.cpp header.a -o executable_name
Note that it seems a bit pointless to make an archive with just one module in it. You could just as easily have written:
g++ test.cpp header.cpp -o executable_name
Still, I'll give you the benefit of the doubt that your actual use case is a bit more complex, with more modules.
Hope this helps!
I had this code in a fragment and it was crashing if I try to come back to this fragment
if (mRootView == null) {
mRootView = inflater.inflate(R.layout.fragment_main, container, false);
}
after gathering the answers on this thread, I realised that mRootView's parent still have mRootView as child. So, this was my fix.
if (mRootView == null) {
mRootView = inflater.inflate(R.layout.fragment_main, container, false);
} else {
((ViewGroup) mRootView.getParent()).removeView(mRootView);
}
hope this helps
Here's a way to do it without turning it into a string first (based on some rudimentary benchmarking, this is about twice as fast as stringifying n
first):
>>> n = 43365644
>>> [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10))-1, -1, -1)]
[4, 3, 3, 6, 5, 6, 4, 4]
Updating this after many years in response to comments of this not working for powers of 10:
[(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][bool(math.log(n,10)%1):]
The issue is that with powers of 10 (and ONLY with these), an extra step is required. ---So we use the remainder in the log_10 to determine whether to remove the leading 0
--- We can't exactly use this because floating-point math errors cause this to fail for some powers of 10. So I've decided to cross the unholy river into sin and call upon regex.
In [32]: n = 43
In [33]: [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][not(re.match('10*', str(n))):]
Out[33]: [4, 3]
In [34]: n = 1000
In [35]: [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][not(re.match('10*', str(n))):]
Out[35]: [1, 0, 0, 0]
Due to updates and changes overtime, version compatibility start causing issues with configuration.
Your webpack.config.js should be like this you can also configure how ever you dim fit.
var path = require('path');
var webpack = require("webpack");
module.exports = {
entry: './src/js/app.js',
devtool: 'source-map',
mode: 'development',
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: ["babel-loader"]
},{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}]
},
output: {
path: path.resolve(__dirname, './src/vendor'),
filename: 'bundle.min.js'
}
};
Another Thing to notice it's the change of args, you should read babel documentation https://babeljs.io/docs/en/presets
.babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
NB: you have to make sure you have the above @babel/preset-env & @babel/preset-react installed in your package.json dependencies
If you are using VB as code behind, you have to use bracket "()" instead of square bracket "[]".
Example for VB:
<script type="text/javascript">
var accesslevel = '<%= Session("accesslevel").ToString().ToLower() %>';
</script>
Click event Bubbles, now what is meant by bubbling, a good point to starts is here.
you can use event.stopPropagation()
, if you don't want that event should propagate further.
Also a good link to refer on MDN
Without knowing your full application it is hard to say what the best way to approach the problem is, but a common technique is to use a header which starts with a fixed length field, which denotes the length of the rest of your message.
Assume that your header consist only of a 4 byte integer which denotes the length of the rest of your message. Then simply do the following.
// This assumes buffer is at least x bytes long,
// and that the socket is blocking.
void ReadXBytes(int socket, unsigned int x, void* buffer)
{
int bytesRead = 0;
int result;
while (bytesRead < x)
{
result = read(socket, buffer + bytesRead, x - bytesRead);
if (result < 1 )
{
// Throw your error.
}
bytesRead += result;
}
}
Then later in the code
unsigned int length = 0;
char* buffer = 0;
// we assume that sizeof(length) will return 4 here.
ReadXBytes(socketFileDescriptor, sizeof(length), (void*)(&length));
buffer = new char[length];
ReadXBytes(socketFileDescriptor, length, (void*)buffer);
// Then process the data as needed.
delete [] buffer;
This makes a few assumptions:
Since it is common to want to explicitly know the size of the integer you are sending across the network define them in a header file and use them explicitly such as:
// These typedefs will vary across different platforms
// such as linux, win32, OS/X etc, but the idea
// is that a Int8 is always 8 bits, and a UInt32 is always
// 32 bits regardless of the platform you are on.
// These vary from compiler to compiler, so you have to
// look them up in the compiler documentation.
typedef char Int8;
typedef short int Int16;
typedef int Int32;
typedef unsigned char UInt8;
typedef unsigned short int UInt16;
typedef unsigned int UInt32;
This would change the above to:
UInt32 length = 0;
char* buffer = 0;
ReadXBytes(socketFileDescriptor, sizeof(length), (void*)(&length));
buffer = new char[length];
ReadXBytes(socketFileDescriptor, length, (void*)buffer);
// process
delete [] buffer;
I hope this helps.
use below simple code, no need to use any library
String list = "your_json_string";
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<YourClassObject>>() {}.getType();
ArrayList<YourClassObject> users = new Gson().fromJson(list , listType);
It might be considered a bit 'hacky' but depending the size and contents of the slice, you can join the slice together and do a string search.
For example you have a slice containing single word values (e.g. "yes", "no", "maybe"). These results are appended to a slice. If you want to check if this slice contains any "maybe" results, you may use
exSlice := ["yes", "no", "yes", "maybe"]
if strings.Contains(strings.Join(exSlice, ","), "maybe") {
fmt.Println("We have a maybe!")
}
How suitable this is really depends on the size of the slice and length of its members. There may be performance or suitability issues for large slices or long values, but for smaller slices of finite size and simple values it is a valid one-liner to achieve the desired result.
String labelText ="<html>Name :"+name+"<br>Surname :"+surname+"<br>Gender :"+gender+"</html>";
JLabel label=new JLabel(labelText);
label.setVisible(true);
label.setBounds(10, 10,300, 100);
dialog.add(label);
It should wait until get request completed. After that I'll return get request body from where function is called.
function foo() {
var jqXHR = $.ajax({
url: url,
type: 'GET',
async: false,
});
return JSON.parse(jqXHR.responseText);
}
Does GitHub have this social feature?
If the commit email is kept private, GitHub now (July 2020) proposes:
Users and organizations can now add Twitter usernames to their GitHub profiles
You can now add your Twitter username to your GitHub profile directly from your profile page, via profile settings, and also the REST API.
We've also added the latest changes:
- Organization admins can now add Twitter usernames to their profile via organization profile settings and the REST API.
- All users are now able to see Twitter usernames on user and organization profiles, as well as via the REST and GraphQL APIs.
- When sponsorable maintainers and organizations add Twitter usernames to their profiles, we'll encourage new sponsors to include that Twitter username when they share their sponsorships on Twitter.
That could be a workaround to leave a message to a GitHub user.
I'm unable to reproduce your problem but have you tried converting it to an integer first?
image_name_data['id'] = image_name_data['id'].astype(int).astype('str')
Then, regarding your more general question you could use map
(as in this answer). In your case:
image_name_data['id'] = image_name_data['id'].map('{:.0f}'.format)
This happened to me suddenly because my app's distribution profile had expired. Xcode began using the wildcard profile instead, which did not have the push notification entitlement enabled. I didn't receive any warning. The fix was easy; I just had to generate another distribution profile for my app in the Apple Developer Member Center, download it, and double-click to install in Xcode.
Nothing as useful as this: Common Data Structure Operations:
I used a deque... seems to work for me. This example has a vector, but you could skip that aspect and simply add them to deque.
#include <deque>
template <typename T>
double mov_avg(vector<T> vec, int len){
deque<T> dq = {};
for(auto i = 0;i < vec.size();i++){
if(i < len){
dq.push_back(vec[i]);
}
else {
dq.pop_front();
dq.push_back(vec[i]);
}
}
double cs = 0;
for(auto i : dq){
cs += i;
}
return cs / len;
}
//Skip the vector portion, track the input number (or size of deque), and the value.
double len = 10;
double val; //Accept as input
double instance; //Increment each time input accepted.
deque<double> dq;
if(instance < len){
dq.push_back(val);
}
else {
dq.pop_front();
dq.push_back(val);
}
}
double cs = 0;
for(auto i : dq){
cs += i;
}
double rolling_avg = cs / len;
//To simplify further -- add values to this, then simply average the deque.
int MAX_DQ = 3;
void add_to_dq(deque<double> &dq, double value){
if(dq.size() < MAX_DQ){
dq.push_back(value);
}else {
dq.pop_front();
dq.push_back(value);
}
}
Another sort of hack I use occasionally is using mod to overwrite values in a vector.
vector<int> test_mod = {0,0,0,0,0};
int write = 0;
int LEN = 5;
int instance = 0; //Filler for N -- of Nth Number added.
int value = 0; //Filler for new number.
write = instance % LEN;
test_mod[write] = value;
//Will write to 0, 1, 2, 3, 4, 0, 1, 2, 3, ...
//Then average it for MA.
//To test it...
int write_idx = 0;
int len = 5;
int new_value;
for(auto i=0;i<100;i++){
cin >> new_value;
write_idx = i % len;
test_mod[write_idx] = new_value;
This last (hack) has no buckets, buffers, loops, nothing. Simply a vector that's overwritten. And it's 100% accurate (for avg / values in vector). Proper order is rarely maintained, as it starts rewriting backwards (at 0), so 5th index would be at 0 in example {5,1,2,3,4}, etc.
Convert the Special characters to apostrophe,
Data <- gsub("[^0-9A-Za-z///' ]","'" , Data ,ignore.case = TRUE)
Below code it to remove extra ''' apostrophe
Data <- gsub("''","" , Data ,ignore.case = TRUE)
Use gsub(..)
function for replacing the special character with apostrophe
how about doing it the way hooktube does it? they don't actually use the video URL for the html5 element, but the google video redirector url that calls upon that video. check out here's how they present some despacito random video...
<video id="player-obj" controls="" src="https://redirector.googlevideo.com/videoplayback?ratebypass=yes&mt=1510077993----SKIPPED----amp;utmg=ytap1,,hd720"><source>Your browser does not support HTML5 video.</video>
the code is for the following video page https://hooktube.com/watch?v=72UO0v5ESUo
youtube to mp3 on the other hand has turned into extremely monetized monster that returns now download.html on half of video download requests... annoying...
the 2 links in this answer are to my personal experiences with both resources. how hooktube is nice and fresh and actually helps avoid censorship and geo restrictions.. check it out, it's pretty cool. and youtubeinmp4 is a popup monster now known as ConvertInMp4...
If you want to do this kind of testing, you’ll love the UI Automation support in iOS 4. You can write JavaScript to simulate button presses, etc. fairly easily, though the documentation (especially the getting-started part) is a bit sparse.
Use:
s.erase(std::remove_if(s.begin(), s.end(), my_predicate), s.end());
bool my_predicate(char c)
{
return !(isalpha(c) || c=='_' || c==' '); // depending on you definition of special characters
}
And you'll get a clean string s
.
erase()
will strip it of all the special characters and is highly customisable with the my_predicate()
function.
.communicate()
writes input (there is no input in this case so it just closes subprocess' stdin to indicate to the subprocess that there is no more input), reads all output, and waits for the subprocess to exit.
The exception EOFError is raised in the child process by raw_input()
(it expected data but got EOF (no data)).
p.stdout.read()
hangs forever because it tries to read all output from the child at the same time as the child waits for input (raw_input()
) that causes a deadlock.
To avoid the deadlock you need to read/write asynchronously (e.g., by using threads or select) or to know exactly when and how much to read/write, for example:
from subprocess import PIPE, Popen
p = Popen(["python", "-u", "1st.py"], stdin=PIPE, stdout=PIPE, bufsize=1)
print p.stdout.readline(), # read the first line
for i in range(10): # repeat several times to show that it works
print >>p.stdin, i # write input
p.stdin.flush() # not necessary in this case
print p.stdout.readline(), # read output
print p.communicate("n\n")[0], # signal the child to exit,
# read the rest of the output,
# wait for the child to exit
Note: it is a very fragile code if read/write are not in sync; it deadlocks.
Beware of block-buffering issue (here it is solved by using "-u" flag that turns off buffering for stdin, stdout in the child).
Anyone who is here in 2021, can use @SteeveDroz answer; but unfortunately, that is only for 1 character. So I put it into a for loop to loop through and change each character of the string.
function binary_encode($str){
$bin = "";
for($i = 0, $j = strlen($str); $i < $j; $i++) $bin .= decbin(ord($str[$i])) . " ";
$bin = substr($bin, 0, strlen($bin) - 1);
return $bin;
}
function binary_decode($bin){
$char = explode(' ', $bin);
$nstr = '';
foreach($char as $ch) $nstr .= chr(bindec($ch));
return $nstr;
}
Usage:
$bin = binary_encode("String Here");
$str = binary_decode("1010011 1110100 1110010 1101001 1101110 1100111 100000 1001000 1100101 1110010 1100101");
http://sandbox.onlinephpfunctions.com/code/2553fc9e26c5148fddbb3486091d119aa59ae464
IEquatable<T>
can be a much easier way to do this with modern frameworks.
You get a nice simple bool Equals(T other)
function and there's no messing around with casting or creating a separate class.
public class Person : IEquatable<Person>
{
public Person(string name, string hometown)
{
this.Name = name;
this.Hometown = hometown;
}
public string Name { get; set; }
public string Hometown { get; set; }
// can't get much simpler than this!
public bool Equals(Person other)
{
return this.Name == other.Name && this.Hometown == other.Hometown;
}
public override int GetHashCode()
{
return Name.GetHashCode(); // see other links for hashcode guidance
}
}
Note you DO have to implement GetHashCode
if using this in a dictionary or with something like Distinct
.
PS. I don't think any custom Equals methods work with entity framework directly on the database side (I think you know this because you do AsEnumerable) but this is a much simpler method to do a simple Equals for the general case.
If things don't seem to be working (such as duplicate key errors when doing ToDictionary) put a breakpoint inside Equals to make sure it's being hit and make sure you have GetHashCode
defined (with override keyword).
Here's probably a quick approach,
With two icons shown above, you shall have a RadioGroup
something like this
RadioGroup
's orientation to horizontalRadioButton
's Properties, try giving the icon for Button
under CompoundButton
,Since the question on how to convert from ISO-8859-1 to UTF-8 is closed because of this one I'm going to post my solution here.
The problem is when you try to GET anything by using XMLHttpRequest, if the XMLHttpRequest.responseType is "text" or empty, the XMLHttpRequest.response is transformed to a DOMString and that's were things break up. After, it's almost impossible to reliably work with that string.
Now, if the content from the server is ISO-8859-1 you'll have to force the response to be of type "Blob" and later convert this to DOMSTring. For example:
var ajax = new XMLHttpRequest();
ajax.open('GET', url, true);
ajax.responseType = 'blob';
ajax.onreadystatechange = function(){
...
if(ajax.responseType === 'blob'){
// Convert the blob to a string
var reader = new window.FileReader();
reader.addEventListener('loadend', function() {
// For ISO-8859-1 there's no further conversion required
Promise.resolve(reader.result);
});
reader.readAsBinaryString(ajax.response);
}
}
Seems like the magic is happening on readAsBinaryString so maybe someone can shed some light on why this works.
Using the title attribute:
<div id="sub1 sub2 sub3" title="some text on mouse over">some text</div>
Hello sought a solution to make an Ajax form work with Google Tag Manager (GTM), the return false prevented the completion and submit the activation of the event in real time on google analytics solution was to change the return false by e.preventDefault (); that worked correctly follows the code:
$("#Contact-Form").submit(function(e) {
e.preventDefault();
...
});
In IntellJ 2017.2,
Ctrl+[ and Ctrl+] navigate between previous locations in the current file.
Ctrl+Alt+← and Ctrl+Alt+→ navigate between previous locations in all files.
You should use double instead of float for precise calculations, and float instead of double when using less accurate calculations. Float contains only decimal numbers, but double contains an IEEE754 double-precision floating point number, making it easier to contain and computate numbers more accurately. Hope this helps.
Have you tried just
dictionary["cat"] = 5;
:)
Update
dictionary["cat"] = 5+2;
dictionary["cat"] = dictionary["cat"]+2;
dictionary["cat"] += 2;
Beware of non-existing keys :)
Actually, you can, even though accepted answer saying that you can't.
There is a _JAVA_OPTIONS
environment variable, more about it here
If you want to add multiple files in a given folder you can split them using {,}
. This is awesome for not repeating long paths, e.g.
git add long/path/{file1,file2,...,filen}
Beware not to put spaces between the ,
.
psql
's inline help:
\h ALTER TABLE
Also documented in the postgres docs (an excellent resource, plus easy to read, too).
ALTER TABLE tablename ADD CONSTRAINT constraintname UNIQUE (columns);
If you want your script to return values, just do return [1,2,3]
from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:
(again, this would have to be run by a separate Python script and be imported in order to even do any good):
import ...
def main():
# calculate stuff
return [1,2,3]
(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)
import sys
# calculate and stuff
sys.exit(100)
And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.
(os._exit(100)
also works, and is a bit more forceful)
If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.
import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)
Are you running your script in a controlled scheduling environment then exit codes are the best way to go.
There's also the option to simply write information to a file, and store the result there.
# calculate
with open('finish.txt', 'wb') as fh:
fh.write(str(5)+'\n')
And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.
If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.
If you have a checkbox in your html something like:
<input id="conducted" type = "checkbox" name="party" value="0">
and you want to add an EventListener to this checkbox using javascript, in your associated js file, you can do as follows:
checkbox = document.getElementById('conducted');
checkbox.addEventListener('change', e => {
if(e.target.checked){
//do something
}
});
I was having similar problems loading 3D models from S3 into a javascript 3D viewer (3D HOP), but strangely enough only with certain file types (.nxs).
What fixed it for me was changing AllowedHeader
from the default Authorization
to *
in the CORS config:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
In android-studio version 2. just go
Right Click on Project
-->Open Module Option
-->Click Your Module
--> click sign done
then press ok
button.
I left something like this as a comment, but I feel it probably needs more visibility as none of the answers mention this method:
The method I now prefer for initializing a std::string
with non-printing characters in general (and embedded null characters in particular) is to use the C++11 feature of initializer lists.
std::string const str({'\0', '6', '\a', 'H', '\t'});
I am not required to perform error-prone manual counting of the number of characters that I am using, so that if later on I want to insert a '\013' in the middle somewhere, I can and all of my code will still work. It also completely sidesteps any issues of using the wrong escape sequence by accident.
The only downside is all of those extra '
and ,
characters.
The 'pidof' command will not display pids of shell/perl/python scripts. So to find the process id’s of my Perl script I had to use the -x option i.e. 'pidof -x perlscriptname'
Looking at:
No public installers with the RunInstallerAttribute.Yes attribute could be found in the C:\Users\myusername\Documents\Visual Studio 2010\Projects\TestService\TestSe rvice\obj\x86\Debug\TestService.exe assembly.
It looks like you may not have an installer class in your code. This is a class that inherits from Installer
that will tell installutil
how to install your executable as a service.
P.s. I have my own little self-installing/debuggable Windows Service template here which you can copy code from or use: Debuggable, Self-Installing Windows Service
For immutable data types:
l = [0] * 100
# [0, 0, 0, 0, 0, ...]
l = ['foo'] * 100
# ['foo', 'foo', 'foo', 'foo', ...]
For values that are stored by reference and you may wish to modify later (like sub-lists, or dicts):
l = [{} for x in range(100)]
(The reason why the first method is only a good idea for constant values, like ints or strings, is because only a shallow copy is does when using the <list>*<number>
syntax, and thus if you did something like [{}]*100
, you'd end up with 100 references to the same dictionary - so changing one of them would change them all. Since ints and strings are immutable, this isn't a problem for them.)
If you want to add to an existing list, you can use the extend()
method of that list (in conjunction with the generation of a list of things to add via the above techniques):
a = [1,2,3]
b = [4,5,6]
a.extend(b)
# a is now [1,2,3,4,5,6]
Patch builtins.open
and use mock_open
, which is part of the mock
framework. patch
used as a context manager returns the object used to replace the patched one:
from unittest.mock import patch, mock_open
with patch("builtins.open", mock_open(read_data="data")) as mock_file:
assert open("path/to/open").read() == "data"
mock_file.assert_called_with("path/to/open")
If you want to use patch
as a decorator, using mock_open()
's result as the new=
argument to patch
can be a little bit weird. Instead, use patch
's new_callable=
argument and remember that every extra argument that patch
doesn't use will be passed to the new_callable
function, as described in the patch
documentation:
patch()
takes arbitrary keyword arguments. These will be passed to theMock
(or new_callable) on construction.
@patch("builtins.open", new_callable=mock_open, read_data="data")
def test_patch(mock_file):
assert open("path/to/open").read() == "data"
mock_file.assert_called_with("path/to/open")
Remember that in this case patch
will pass the mocked object as an argument to your test function.
You need to patch __builtin__.open
instead of builtins.open
and mock
is not part of unittest
, you need to pip install
and import it separately:
from mock import patch, mock_open
with patch("__builtin__.open", mock_open(read_data="data")) as mock_file:
assert open("path/to/open").read() == "data"
mock_file.assert_called_with("path/to/open")
You may put an inner div in the container that is enough wide to hold all the floated divs.
#container {_x000D_
background-color: red;_x000D_
overflow: hidden;_x000D_
width: 200px;_x000D_
}_x000D_
_x000D_
#inner {_x000D_
overflow: hidden;_x000D_
width: 2000px;_x000D_
}_x000D_
_x000D_
.child {_x000D_
float: left;_x000D_
background-color: blue;_x000D_
width: 50px;_x000D_
height: 50px;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="inner">_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
</div>_x000D_
</div>
_x000D_
You can use this code:
private void OnClickNavigate(object sender, RoutedEventArgs e)
{
NavigatedWindow navigatesWindow = new NavigatedWindow();
navigatesWindow.ShowDialog();
}
All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)
Based on this related answer, you are looking at a list that looks like: A-Z
, a-z
, 0-9
, -
, .
, _
, ~
, :
, /
, ?
, #
, [
, ]
, @
, !
, $
, &
, '
, (
, )
, *
, +
, ,
, ;
, %
, and =
. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. %
can only be used in conjunction with url encoding as in %20
), the RFC has all of these specifics.
you need to call $.uniform.update()
if you update element using javascript as mentioned in the documentation.
Yes, generally the best way to store a file in a database is to save the byte array in a BLOB column. You will probably want a couple of columns to additionally store the file's metadata such as name, extension, and so on.
It is not always a good idea to store files in the database - for instance, the database size will grow fast if you store files in it. But that all depends on your usage scenario.
One additional element that I realized is that typically .ssh folder is created in your root folder in Mac OS X /Users/. If you try to use ssh -vT [email protected] from another folder it will give you an error even if you had added the correct key.
You need to add the key again (ssh-add 'correct path to id_rsa') from the current folder to authenticate successfully (assuming that you have already uploaded the key to your profile in Git)
You could use a CountDownLatch
from the java.util.concurrent
package. It is very useful when waiting for one or more threads to complete before continuing execution in the awaiting thread.
For example, waiting for three tasks to complete:
CountDownLatch latch = new CountDownLatch(3);
...
latch.await(); // Wait for countdown
The other thread(s) then each call latch.countDown()
when complete with the their tasks. Once the countdown is complete, three in this example, the execution will continue.
Add a jQuery function,
(function($){
$.fn.regex = function(pattern, fn, fn_a){
var fn = fn || $.fn.text;
return this.filter(function() {
return pattern.test(fn.apply($(this), fn_a));
});
};
})(jQuery);
Then,
$('span').regex(/Sent/)
will select all span elements with text matches /Sent/.
$('span').regex(/tooltip.year/, $.fn.attr, ['class'])
will select all span elements with their classes match /tooltip.year/.
Use the @Url.Action method. This will work and determines the correct route regardless of what IIS server you deploy to.
Example- window.location.href="@Url.Action("Action", "Controller")";
so in the case of the Index action on the Home controller - window.location.href="@Url.Action("Index", "Home")";
git pull --rebase origin master
You could loop through DataGridView
using Rows
property, like:
foreach (DataGridViewRow row in datagridviews.Rows)
{
currQty += row.Cells["qty"].Value;
//More code here
}
The newer verion of PowerShell handles this and the MS Documentation has a great example of copying a file with different credentials here
$Session = New-PSSession -ComputerName "Server02" -Credential "Contoso\User01"
Copy-Item "D:\Folder002\" -Destination "C:\Folder002_Copy\" -ToSession $Session
PyExecJS is able to use each of PyV8, Node, JavaScriptCore, SpiderMonkey, JScript.
>>> import execjs
>>> execjs.eval("'red yellow blue'.split(' ')")
['red', 'yellow', 'blue']
>>> execjs.get().name
'Node.js (V8)'
"currently yes but i think it might cause problems at peak moments" I can confirm, that I had a problem where I got timeouts because of peak requests. After I set the max pool size, the application ran without any problems. IIS 7.5 / ASP.Net
Some extra information about .NET Core (after reading erdomke's post about setting a private field to supply the content-type on a request that doesn't have content)...
After debugging my code, I can't see the private field to set via reflection - so I thought I'd try to recreate the problem.
I have tried the following code using .Net 4.6:
HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Get, @"myUrl");
httpRequest.Content = new StringContent(string.Empty, Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
Task<HttpResponseMessage> response = client.SendAsync(httpRequest); //I know I should have used async/await here!
var result = response.Result;
And, as expected, I get an aggregate exception with the content "Cannot send a content-body with this verb-type."
However, if i do the same thing with .NET Core (1.1) - I don't get an exception. My request was quite happily answered by my server application, and the content-type was picked up.
I was pleasantly surprised about that, and I hope it helps someone!
You can use computeIfPresent
method and supply it a mapping function, which will be called to compute a new value based on existing one.
For example,
Map<String, Integer> words = new HashMap<>();
words.put("hello", 3);
words.put("world", 4);
words.computeIfPresent("hello", (k, v) -> v + 1);
System.out.println(words.get("hello"));
Alternatevely, you could use merge
method, where 1 is the default value and function increments existing value by 1:
words.merge("hello", 1, Integer::sum);
In addition, there is a bunch of other useful methods, such as putIfAbsent
, getOrDefault
, forEach
, etc.
Install Pillow (or PIL), e.g.:
$ pip install pillow
Now you can
from PIL import Image
with Image.open('path/to/file.jpg') as img:
img.show()
Other common alternatives include running xdg-open
or starting the browser with the image path:
import webbrowser
webbrowser.open('path/to/file.jpg')
If you really want to show the image inline in the console and not as a new window, you may do that but only in a Linux console using fbi
see ask Ubuntu or else use ASCII-art like CACA.
no that cannot work(not with real data):
String sql = "INSERT INTO course " +
"VALUES (course_code, course_desc, course_chair)";
stmt.executeUpdate(sql);
change it to:
String sql = "INSERT INTO course (course_code, course_desc, course_chair)" +
"VALUES (?, ?, ?)";
Create a PreparedStatment with that sql and insert the values with index:
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "Test2");
preparedStatement.setString(3, "Test3");
preparedStatement.executeUpdate();
Building on jävi's answer, this can be done without IDs or additional button attributes like this:
http://jsfiddle.net/isherwood/E5Ly5/
<button class="popper" data-toggle="popover">Pop me</button>
<div class="popper-content hide">My first popover content goes here.</div>
<button class="popper" data-toggle="popover">Pop me</button>
<div class="popper-content hide">My second popover content goes here.</div>
<button class="popper" data-toggle="popover">Pop me</button>
<div class="popper-content hide">My third popover content goes here.</div>
$('.popper').popover({
container: 'body',
html: true,
content: function () {
return $(this).next('.popper-content').html();
}
});
I have set OnGroupExpandListener and override onGroupExpand() as:
and use setSelectionFromTop() method which Sets the selected item and positions the selection y pixels from the top edge of the ListView. (If in touch mode, the item will not be selected but it will still be positioned appropriately.) (android docs)
yourlist.setOnGroupExpandListener (new ExpandableListView.OnGroupExpandListener()
{
@Override
public void onGroupExpand(int groupPosition) {
expList.setSelectionFromTop(groupPosition, 0);
//your other code
}
});
Personally I would remove the returns and keep the breaks. I would use the switch statement to assign a value to a variable. Then return that variable after the switch statement.
Though this is an arguable point I've always felt that good design and encapsulation means one way in and one way out. It is much easier to guarantee the logic and you don't accidentally miss cleanup code based on the cyclomatic complexity of your function.
One exception: Returning early is okay if a bad parameter is detected at the beginning of a function--before any resources are acquired.
in the video source change the type to "video/quicktime"
<video width="400" controls Autoplay=autoplay>
<source src="D:/mov1.mov" type="video/quicktime">
</video>
As mentioned by others, this is used for front end cache busting. To implement this, I have personally find grunt-cache-bust npm package useful.
uint32_t
is standard, uint32
is not. That is, if you include <inttypes.h>
or <stdint.h>
, you will get a definition of uint32_t
. uint32
is a typedef in some local code base, but you should not expect it to exist unless you define it yourself. And defining it yourself is a bad idea.
You can do like this,this is the quickest process
Var result = MsgList.Except(MsgList.Where(o => SentList.Select(s => s.MsgID).ToList().Contains(o.MsgID))).ToList();
This will give you expected output.
CSS Attribute selectors will allow you to check attributes for a string. (in this case - a class-name)
https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
(looks like it's actually at 'recommendation' status for 2.1 and 3)
Here's an outline of how I *think it works:
[ ]
: is the container for complex selectors if you will... class
: 'class' is the attribute you are looking at in this case.*
: modifier(if any): in this case - "wildcard" indicates you're looking for ANY match.test-
: the value (assuming there is one) of the attribute - that contains the string "test-" (which could be anything)So, for example:
[class*='test-'] {
color: red;
}
You could be more specific if you have good reason, with the element too
ul[class*='test-'] > li { ... }
I've tried to find edge cases, but I see no need to use a combination of ^
and *
- as * gets everything...
example: http://codepen.io/sheriffderek/pen/MaaBwp
http://caniuse.com/#feat=css-sel2
Everything above IE6 will happily obey. : )
note that:
[class] { ... }
Will select anything with a class...
public static string ToLeadZeros(this int strNum, int num)
{
var str = strNum.ToString();
return str.PadLeft(str.Length + num, '0');
}
// var i = 1;
// string num = i.ToLeadZeros(5);
Just for the record:
Ruby on Rails 4 application in OS X with PostgresApp (in this case 0.17.1 version needed - kind of an old project):
gem install pg -v '0.17.1' -- --with-pg-config=/Applications/Postgres.app/Contents/Versions/9.3/bin/pg_config
The expression in this answer does that for one jack
and one james
in any order.
Here, we'd explore other scenarios.
jack
and One james
Just in case, two jack
or two james
would not be allowed, only one jack
and one james
would be valid, we can likely design an expression similar to:
^(?!.*\bjack\b.*\bjack\b)(?!.*\bjames\b.*\bjames\b)(?=.*\bjames\b)(?=.*\bjack\b).*$
Here, we would exclude those instances using these statements:
(?!.*\bjack\b.*\bjack\b)
and,
(?!.*\bjames\b.*\bjames\b)
We can also simplify that to:
^(?!.*\bjack\b.*\bjack\b|.*\bjames\b.*\bjames\b)(?=.*\bjames\b|.*\bjack\b).*$
If you wish to simplify/update/explore the expression, it's been explained on the top right panel of regex101.com. You can watch the matching steps or modify them in this debugger link, if you'd be interested. The debugger demonstrates that how a RegEx engine might step by step consume some sample input strings and would perform the matching process.
jex.im visualizes regular expressions:
const regex = /^(?!.*\bjack\b.*\bjack\b|.*\bjames\b.*\bjames\b)(?=.*\bjames\b|.*\bjack\b).*$/gm;
const str = `hi jack here is james
hi james here is jack
hi james jack here is jack james
hi jack james here is james jack
hi jack jack here is jack james
hi james james here is james jack
hi jack jack jack here is james
`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
_x000D_
jack
and One james
in a specific orderThe expression can be also designed for first a james
then a jack
, similar to the following one:
^(?!.*\bjack\b.*\bjack\b|.*\bjames\b.*\bjames\b)(?=.*\bjames\b.*\bjack\b).*$
and vice versa:
^(?!.*\bjack\b.*\bjack\b|.*\bjames\b.*\bjames\b)(?=.*\bjack\b.*\bjames\b).*$
Batch files have really very limited logic powers so the best you can hope to come up with is a good workaround that indirectly achieves what you want. That's not to say that you should feel they are inferior to a real language - they still demand the same attention to detail and manual debugging as a real application. It's just that you'll need to work a lot harder to make them do what you want in a robust manner.
For the OP's question it sounds like you require two specific files to exist. Just use a tally:
IF EXIST somefile.txt (
set /a file1_status=1
)
IF EXIST someotehrfile.txt (
set /a file2_status=1
)
set /a file_status_result=file1_status + file2_status
if %file_status_result% equ 2 (
goto somefileexists
)
goto exit
:somefileexists
IF EXIST someotherfile.txt SET var=...
:exit
My example uses 3 variables, but you could just add 1 to file_result_status if the file exists. But if you want more granular control later in your batch file you can record the result for each file as I have done so you don't have to keep checking if a file exists later on.
If you are using Ubuntu, just go to android directory of your react-native project and create a file called local.properties
and add android sdk path to it as follow:
sdk.dir = /home/[YOUR_USERNAME]/Android/Sdk
Use the zzz
format specifier to get the timezone offset as hours and minutes. You also want to use the HH
format specifier to get the hours in 24 hour format.
DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz")
Result:
2011-08-09T23:49:58+02:00
Some culture settings uses periods instead of colons for time, so you might want to use literal colons instead of time separators:
DateTime.Now.ToString("yyyy-MM-ddTHH':'mm':'sszzz")
In Xcode 10 the OS_ACTIVITY_MODE
variable with disable
(or default
) value also turns off the NSLog
no matter what.
So if you want to get rid of the console noise but not of your own logs, you could try the good old printf("")
instead of the NSLog since it is not affected by the OS_ACTIVITY_MODE
= disable
.
But better check out the new os_log
API here.
You can also do this using DOM Level 2 CSS interfaces (MDN):
var sheet = window.document.styleSheets[0];
sheet.insertRule('strong { color: red; }', sheet.cssRules.length);
...on all but (naturally) IE8 and prior, which uses its own marginally-different wording:
sheet.addRule('strong', 'color: red;', -1);
There is a theoretical advantage in this compared to the createElement-set-innerHTML method, in that you don't have to worry about putting special HTML characters in the innerHTML, but in practice style elements are CDATA in legacy HTML, and ‘<’ and ‘&’ are rarely used in stylesheets anyway.
You do need a stylesheet in place before you can started appending to it like this. That can be any existing active stylesheet: external, embedded or empty, it doesn't matter. If there isn't one, the only standard way to create it at the moment is with createElement.
typeperf
gives me issues when it randomly doesn't work on some computers (Error: No valid counters.
) or if the account has insufficient rights. Otherwise, here is a way to extract just the value from its output. It still needs rounding though:
@for /f "delims=, tokens=2" %p in ('typeperf "\Processor(_Total)\% Processor Time" -sc 3 ^| find ":"') do @echo %~p%
Powershell has two cmdlets to get the percent utilization for all CPUs: Get-Counter
(preferred) or Get-WmiObject
:
Powershell "Get-Counter '\Processor(*)\% Processor Time' | Select -Expand Countersamples | Select InstanceName, CookedValue"
Or,
Powershell "Get-WmiObject Win32_PerfFormattedData_PerfOS_Processor | Select Name, PercentProcessorTime"
To get the overall CPU load with formatted output exactly like the question:
Powershell "[string][int](Get-Counter '\Processor(*)\% Processor Time').Countersamples[0].CookedValue + '%'"
Or,
Powershell "gwmi Win32_PerfFormattedData_PerfOS_Processor | Select -First 1 | %{'{0}%' -f $_.PercentProcessorTime}"
The secret is simple: Ctrl+Shift+F
Nope. No way to do that natively. You're going to have to subclass UIImageView, and add an imageFileName property (which you set when you set the image).
you can use 'email' or 'emailx' command.
(1) $ vim /etc/mail.rc # or # vim /etc/nail.rc
set from = [email protected] #
set smtp = smtp.exmail.gmail.com #gmail's smtp server
set smtp-auth-user = [email protected] #sender's email address
set smtp-auth-password = xxxxxxx #get from gmail, not your email account passwd
set smtp-auth=login
(2) $ echo "Pls remember to remove unused ons topics!" | mail -s "waste topics" -a a.txt [email protected] #send to group user '[email protected]'
Had this problem and solved typing this : C:\Program Files (x86)\Java\jdk1.7.0_51\bin\javadoc.exe
Also worth to mention, that when partial function passed another function where we want to "hard code" some parameters, that should be rightmost parameter
def func(a,b):
return a*b
prt = partial(func, b=7)
print(prt(4))
#return 28
but if we do the same, but changing a parameter instead
def func(a,b):
return a*b
prt = partial(func, a=7)
print(prt(4))
it will throw error, "TypeError: func() got multiple values for argument 'a'"
jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div
(or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.
Unlike centralized version control systems, Git clones the entire repository, so you don't only get the current remote files, but the whole history. You local repository will include all this.
There might have been tags to mark a particular version at the time. If not, you can create them yourself locally. A good way to do this is to use git log
or perhaps more visually with tools like gitk
(perhaps gitk --all
to see all the branches and tags). If you can spot the commits hashes that were used at the time, you can tag them using git tag <hash>
and then check those out in new working copies (for example git checkout -b new_branch_name tag_name
or directly with the hash instead of the tag name).
You can easily import your model and run this:
from models import User
# User is the name of table that has a column name
users = User.query.all()
for user in users:
print user.name
as stated in the node docs The process.argv property returns an array containing the command line arguments passed when the Node.js process was launched.
For example, assuming the following script for process-args.js:
// print process.argv
process.argv.forEach((val, index) => {
console.log(`${index}: ${val}`);
});
Launching the Node.js process as:
$ node process-args.js one two=three four
Would generate the output:
0: /usr/local/bin/node
1: /Users/mjr/work/node/process-args.js
2: one
3: two=three
4: four
you can find custom list adapter class with filterable using text change in edit text...
create custom list adapter class with implementation of Filterable:
private class CustomListAdapter extends BaseAdapter implements Filterable{
private LayoutInflater inflater;
private ViewHolder holder;
private ItemFilter mFilter = new ItemFilter();
public CustomListAdapter(List<YourCustomData> newlist) {
filteredData = newlist;
}
@Override
public int getCount() {
return filteredData.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
holder = new ViewHolder();
if(inflater==null)
inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertView == null){
convertView = inflater.inflate(R.layout.row_listview_item, null);
holder.mTextView = (TextView)convertView.findViewById(R.id.row_listview_member_tv);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.mTextView.setText(""+filteredData.get(position).getYourdata());
return convertView;
}
@Override
public Filter getFilter() {
return mFilter;
}
}
class ViewHolder{
TextView mTextView;
}
private class ItemFilter extends Filter {
@SuppressLint("DefaultLocale")
@Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<YourCustomData> list = YourObject.getYourDataList();
int count = list.size();
final ArrayList<YourCustomData> nlist = new ArrayList<YourCustomData>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = ""+list.get(i).getYourText();
if (filterableString.toLowerCase().contains(filterString)) {
YourCustomData mYourCustomData = list.get(i);
nlist.add(mYourCustomData);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<YourCustomData>) results.values;
mCustomListAdapter.notifyDataSetChanged();
}
}
mEditTextSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(mCustomListAdapter!=null)
mCustomListAdapter.getFilter().filter(s.toString());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
ThreadLocalRandom
equivalent of class java.util.Random
for multithreaded environment. Generating a random number is carried out locally in each of the threads. So we have a better performance by reducing the conflicts.
int rand = ThreadLocalRandom.current().nextInt(x,y);
x
,y
- intervals e.g. (1,10)
Here is another alternative that I insert at top of the Python files in tests
folder:
# Path hack.
import sys, os
sys.path.insert(0, os.path.abspath('..'))
There's this library GeoCoordinate for these platforms:
Installation is done via NuGet:
PM> Install-Package GeoCoordinate
Usage
GeoCoordinate pin1 = new GeoCoordinate(lat, lng);
GeoCoordinate pin2 = new GeoCoordinate(lat, lng);
double distanceBetween = pin1.GetDistanceTo(pin2);
The distance between the two coordinates, in meters.
In my case I had all these worked except for the correct character recognition.
But you need to consider these few things:
ocr.Init(@"c:\tessdata", "eng", true);
hope that this helps
function validate()
{
var a=documents.forms["yourformname"]["yourpasswordfieldname"].value;
var b=documents.forms["yourformname"]["yourconfirmpasswordfieldname"].value;
if(!(a==b))
{
alert("both passwords are not matching");
return false;
}
return true;
}
I Think This will be helpful
+ (NSString *)toBase64String:(NSString *)string {
NSData *data = [string dataUsingEncoding: NSUnicodeStringEncoding];
NSString *ret = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
return ret;
}
+ (NSString *)fromBase64String:(NSString *)string {
NSData *aData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSData *aDataDecoded = [[NSData alloc]initWithBase64EncodedString:string options:0];
NSString *decryptedStr = [[NSString alloc]initWithData:aDataDecoded encoding:NSUTF8StringEncoding];
return [decryptedStr autorelease];
}
The value of the certificate comes mostly from the trust of the internet users in the issuer of the certificate. To that end, Verisign is tough to beat. A certificate says to the client that you are who you say you are, and the issuer has verified that to be true.
You can get a free SSL certificate signed, for example, by StartSSL. This is an improvement on self-signed certificates, because your end-users would stop getting warning pop-ups informing them of a suspicious certificate on your end. However, the browser bar is not going to turn green when communicating with your site over https, so this solution is not ideal.
The cheapest SSL certificate that turns the bar green will cost you a few hundred dollars, and you would need to go through a process of proving the identity of your company to the issuer of the certificate by submitting relevant documents.
WinXp:
I have created a .bat
file
node c:\path\to\file\my_program.js
That just run my_program.bat
from Explorer or in cmd window
Here is a quick bash script in case it's useful to anyone. I just want to be able to set an environment variable so that I can pushd
to the code.
#!/bin/bash
module=${1:?"I need a module name"}
python << EOI
import $module
import os
print os.path.dirname($module.__file__)
EOI
Shell example:
[root@sri-4625-0004 ~]# export LXML=$(get_python_path.sh lxml)
[root@sri-4625-0004 ~]# echo $LXML
/usr/lib64/python2.7/site-packages/lxml
[root@sri-4625-0004 ~]#
We don't need to plt.ioff()
or plt.show()
(if we use %matplotlib inline
). You can test above code without plt.ioff()
. plt.close()
has the essential role. Try this one:
%matplotlib inline
import pylab as plt
# It doesn't matter you add line below. You can even replace it by 'plt.ion()', but you will see no changes.
## plt.ioff()
# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('test0.png')
plt.close(fig)
# Create a new figure, plot into it, then don't close it so it does get displayed
fig2 = plt.figure()
plt.plot([1,3,2])
plt.savefig('test1.png')
If you run this code in iPython, it will display a second plot, and if you add plt.close(fig2)
to the end of it, you will see nothing.
In conclusion, if you close figure by plt.close(fig)
, it won't be displayed.
Kotlin solution, based on what others wrote here:
fun isTableExists(database: SQLiteDatabase, tableName: String): Boolean {
database.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '$tableName'", null)?.use {
return it.count > 0
} ?: return false
}
use this JavaScript code:
<script>
setTimeout(function(){
window.location.href = 'form2.html';
}, 5000);
</script>
I've found that the best way to debug is to use the microsoft tool called DTCPing
I've had my fare deal of problems in our old company network, and I've got a few tips:
In my experience, if the DTCPing is able to setup a DTC connection initiated from the client and initiated from the server, your transactions are not the problem any more.
Another solution to get rid of content jump on fixed modal, when removing body scroll is to normalize page width:
body {width: 100vw; overflow-x: hidden;}
Then you can play with fixed position or overflow:hidden for body when the modal is open. But it will hide horizontal scrollbars - usually they're not needed on responsive website.
It's not generally correct that you can "remove an item from a database" with both methods. To be precise it is like so:
ObjectContext.DeleteObject(entity)
marks the entity as Deleted
in the context. (It's EntityState
is Deleted
after that.) If you call SaveChanges
afterwards EF sends a SQL DELETE
statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
EntityCollection.Remove(childEntity)
marks the relationship between parent and childEntity
as Deleted
. If the childEntity
itself is deleted from the database and what exactly happens when you call SaveChanges
depends on the kind of relationship between the two:
If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows NULL
values, this foreign will be set to null and if you call SaveChanges
this NULL
value for the childEntity
will be written to the database (i.e. the relationship between the two is removed). This happens with a SQL UPDATE
statement. No DELETE
statement occurs.
If the relationship is required (the FK doesn't allow NULL
values) and the relationship is not identifying (which means that the foreign key is not part of the child's (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (with DeleteObject
then). If you don't do any of these a referential constraint is violated and EF will throw an exception when you call SaveChanges
- the infamous "The relationship could not be changed because one or more of the foreign-key properties is non-nullable" exception or similar.
If the relationship is identifying (it's necessarily required then because any part of the primary key cannot be NULL
) EF will mark the childEntity
as Deleted
as well. If you call SaveChanges
a SQL DELETE
statement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
I am actually a bit confused about the Remarks section on the MSDN page you have linked because it says: "If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion.". This seems unprecise or even wrong to me because all three cases above have a "referential integrity constraint" but only in the last case the child is in fact deleted. (Unless they mean with "dependent object" an object that participates in an identifying relationship which would be an unusual terminology though.)
I prefer to use:
if(!StringUtils.isBlank(myString)) { // checks if myString is whitespace, empty, or null
// do something
}
You should always write command after a Tab and not white space.
This applies to gcc
line (line #4) in your case. You need to insert tab before gcc
.
Also replace \rm -fr ll
with rm -fr ll
. Insert tabs before this command too.
You can use jQuery each function as it is explained below:
Define your data:
var jsonStr = '[{"name":"Lenovo Thinkpad 41A4298,"website":"google"},{"name":"Lenovo Thinkpad 41A2222,"website":"google"},{"name":"Lenovo Thinkpad 41Awww33,"website":"yahoo"},{"name":"Lenovo Thinkpad 41A424448,"website":"google"},{"name":"Lenovo Thinkpad 41A429rr8,"website":"ebay"},{"name":"Lenovo Thinkpad 41A429ff8,"website":"ebay"},{"name":"Lenovo Thinkpad 41A429ss8,"website":"rediff"},{"name":"Lenovo Thinkpad 41A429sg8,"website":"yahoo"}]';
Parse JSON string to JSON object:
var json = JSON.parse(jsonStr);
Iterate and filter:
$.each(JSON.parse(json), function (idx, obj) {
if (obj.website == 'yahoo') {
// do whatever you want
}
});
Rebasing can be a real headache. You have to resolve the merge conflicts and continue rebasing. For example you can use the merge tool (which differs depending on your settings)
git mergetool
Then add your changes and go on
git rebase --continue
Good luck
In the other hand, using REST API of other servers are very popular in PHP. Suppose you are looking for a way to redirect some HTTP requests into the other server (for example getting an xml file). Here is a PHP package to help you:
https://github.com/romanpitak/PHP-REST-Client
So, getting the xml file:
$client = new Client('http://example.com');
$request = $client->newRequest('/filename.xml');
$response = $request->getResponse();
echo $response->getParsedResponse();
I too got this same error on my image handler that I wrote. I got it like 30 times a day on site with heavy traffic, managed to reproduce it also. You get this when a user cancels the request (closes the page or his internet connection is interrupted for example), in my case in the following row:
myContext.Response.OutputStream.Write(buffer, 0, bytesRead);
I can’t think of any way to prevent it but maybe you can properly handle this. Ex:
try
{
…
myContext.Response.OutputStream.Write(buffer, 0, bytesRead);
…
}catch (HttpException ex)
{
if (ex.Message.StartsWith("The remote host closed the connection."))
;//do nothing
else
//handle other errors
}
catch (Exception e)
{
//handle other errors
}
finally
{//close streams etc..
}
l = [83, 84, 65, 67, 75]
s = "".join([chr(c) for c in l])
print s
Another option would be file_get_contents()
:
// $xml_str = your xml
// $url = target url
$post_data = array('xml' => $xml_str);
$stream_options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
'content' => http_build_query($post_data)));
$context = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);
A panel expands to a span (or a div), with it's content within it. A placeholder is just that, a placeholder that's replaced by whatever you put in it.
I was having the same problem and could not figure out what I was doing wrong. Turns out, the auto-complete for Android Studio was changing the text to either all caps or all lower case (depending on whether I typed in upper case or lower cast words before the auto-complete). The OS was not registering the name due to this issue and I would get the error regarding a missing permission. As stated above, ensure your permissions are labeled correctly:
Correct:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Incorrect:
<uses-permission android:name="ANDROID.PERMISSION.ACCESS_FINE_LOCATION" />
Incorrect:
<uses-permission android:name="android.permission.access_fine_location" />
Though this may seem trivial, its easy to overlook.
If there is some setting to make permissions non-case-sensitive, please add a comment with the instructions. Thank you!
By default android will set Holo to the Dark theme. There is no theme called Holo.Dark, there's only Holo.Light, that's why you are getting the resource not found error.
So just set it to:
<style name="AppTheme" parent="android:Theme.Holo" />
Simply call getUrl() on URLConnection instance after calling getInputStream():
URLConnection con = new URL( url ).openConnection();
System.out.println( "orignal url: " + con.getURL() );
con.connect();
System.out.println( "connected url: " + con.getURL() );
InputStream is = con.getInputStream();
System.out.println( "redirected url: " + con.getURL() );
is.close();
If you need to know whether the redirection happened before actually getting it's contents, here is the sample code:
HttpURLConnection con = (HttpURLConnection)(new URL( url ).openConnection());
con.setInstanceFollowRedirects( false );
con.connect();
int responseCode = con.getResponseCode();
System.out.println( responseCode );
String location = con.getHeaderField( "Location" );
System.out.println( location );
I create a new key, I had to search the csproj for the old one and refactor it.
It sounds like your printMousePos
function should:
Currently, it does this:
See the problem? Your variables are never getting set, because as soon as you add your function to the "mousemove" event you print them.
It seems like you probably don't need that mousemove event at all; I would try something like this:
function printMousePos(e) {
var cursorX = e.pageX;
var cursorY = e.pageY;
document.getElementById('test').innerHTML = "x: " + cursorX + ", y: " + cursorY;
}
You can use the excellent jquery-Json plugin:
http://code.google.com/p/jquery-json/
Makes it easy to convert to and from Json objects.
Method 1 : Using jQuery Ajax Get call (partial page update).
Suitable for when you need to retrieve jSon data from database.
Controller's Action Method
[HttpGet]
public ActionResult Foo(string id)
{
var person = Something.GetPersonByID(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
Jquery GET
function getPerson(id) {
$.ajax({
url: '@Url.Action("Foo", "SomeController")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: { id: id },
success: function(person) {
$('#FirstName').val(person.FirstName);
$('#LastName').val(person.LastName);
}
});
}
Person class
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Method 2 : Using jQuery Ajax Post call (partial page update).
Suitable for when you need to do partial page post data into database.
Post method is also same like above just replace [HttpPost]
on Action method and type as post
for jquery method.
For more information check Posting JSON Data to MVC Controllers Here
Method 3 : As a Form post scenario (full page update).
Suitable for when you need to save or update data into database.
View
@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{
@Html.TextBoxFor(model => m.Text)
<input type="submit" value="Save" />
}
Action Method
[HttpPost]
public ActionResult SaveData(FormCollection form)
{
// Get movie to update
return View();
}
Method 4 : As a Form Get scenario (full page update).
Suitable for when you need to Get data from database
Get method also same like above just replace [HttpGet]
on Action method and FormMethod.Get
for View's form method.
I hope this will help to you.
Richard Möhn's comparison is not fair.
As Andrea Di Biagio's comment, the in-place method np.maximum(x, 0, x)
will modify x at the first loop.
So here is my benchmark:
import numpy as np
def baseline():
x = np.random.random((5000, 5000)) - 0.5
return x
def relu_mul():
x = np.random.random((5000, 5000)) - 0.5
out = x * (x > 0)
return out
def relu_max():
x = np.random.random((5000, 5000)) - 0.5
out = np.maximum(x, 0)
return out
def relu_max_inplace():
x = np.random.random((5000, 5000)) - 0.5
np.maximum(x, 0, x)
return x
Timing it:
print("baseline:")
%timeit -n10 baseline()
print("multiplication method:")
%timeit -n10 relu_mul()
print("max method:")
%timeit -n10 relu_max()
print("max inplace method:")
%timeit -n10 relu_max_inplace()
Get the results:
baseline:
10 loops, best of 3: 425 ms per loop
multiplication method:
10 loops, best of 3: 596 ms per loop
max method:
10 loops, best of 3: 682 ms per loop
max inplace method:
10 loops, best of 3: 602 ms per loop
In-place maximum method is only a bit faster than the maximum method, and it may because it omits the variable assignment for 'out'. And it's still slower than the multiplication method.
And since you're implementing the ReLU func. You may have to save the 'x' for backprop through relu. E.g.:
def relu_backward(dout, cache):
x = cache
dx = np.where(x > 0, dout, 0)
return dx
So i recommend you to use multiplication method.
You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.
I will try to explain you what this error is about.
Starting from MySQL 5.7.5, option ONLY_FULL_GROUP_BY
is enabled by default.
Thus, according to standart SQL92 and earlier:
does not permit queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on (uniquely determined by) GROUP BY columns
So, for example:
SELECT * FROM `users` GROUP BY `name`;
You will get error message after executing query above.
#1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'testsite.user.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
Why?
Because MySQL dont exactly understand, what certain values from grouped records to retrieve, and this is the point.
I.E. lets say you have this records in your users
table:
And you will execute invalid query showen above.
And you will get error shown above, because, there is 3 records with name John
, and it is nice, but, all of them have different email
field values.
So, MySQL simply don't understand which of them to return in resulting grouped record.
You can fix this issue, by simply changing your query like this:
SELECT `name` FROM `users` GROUP BY `name`
Also, you may want to add more fields to SELECT section, but you cant do that, if they are not aggregated, but there is crutch you could use (but highly not reccomended):
SELECT ANY_VALUE(`id`), ANY_VALUE(`email`), `name` FROM `users` GROUP BY `name`
Now, you may ask, why using ANY_VALUE
is highly not recommended?
Because MySQL don't exactly know what value of grouped records to retrieve, and by using this function, you asking it to fetch any of them (in this case, email of first record with name = John was fetched).
Exactly I cant come up with any ideas on why you would want this behaviour to exist.
Please, if you dont understand me, read more about how grouping in MySQL works, it is very simple.
And by the end, here is one more simple, yet valid query.
If you want to query total users count according to available ages, you may want to write down this query
SELECT `age`, COUNT(`age`) FROM `users` GROUP BY `age`;
Which is fully valid, according to MySQL rules.
And so on.
It is important to understand what exactly the problem is and only then write down the solution.
I believe what you're looking to do is "Resize/Resample" your images. Here is a good site that gives instructions and provides a utility class(That I also happen to use):
http://www.codeproject.com/KB/GDI-plus/imgresizoutperfgdiplus.aspx
Okay, so first of all check if you are in the correct directory where your python script is located.
On the net, they say to run the command :
python3 your_file_name.py
But it doesn't work.
What worked for me however was:
python -u my_file_name.py
If one is on a Linux distro (e.g. CentOS, Debian) then perhaps the most accessible way to find out about core files and related conditions is in the man page. Just run the following command from a terminal:
man 5 core
The GNU site suggests this nice awk script, which prints both the words and their frequency.
Possible changes:
sort -nr
(and reverse word
and freq[word]
) to see the result in descending order.freq[3]++
- replace 3 with the column number.Here goes:
# wordfreq.awk --- print list of word frequencies
{
$0 = tolower($0) # remove case distinctions
# remove punctuation
gsub(/[^[:alnum:]_[:blank:]]/, "", $0)
for (i = 1; i <= NF; i++)
freq[$i]++
}
END {
for (word in freq)
printf "%s\t%d\n", word, freq[word]
}
If you're using an old version of typescript < 2.1 then you can use similar to the following which is basically casting of any to typed object:
const typedProduct = <Product>{
code: <string>product.sku
};
NOTE: Using this method is only good for data models as it will remove all the methods in the object. It's basically casting any object to a typed object
I found this question as the top result while Googling how to find the owner of a table in Oracle, so I thought that I would contribute a table specific answer for others' convenience.
To find the owner of a specific table in an Oracle DB, use the following query:
select owner from ALL_TABLES where TABLE_NAME ='<MY-TABLE-NAME>';
@Html.TextBoxFor(model => model.IssueDate, new { @class = "form-control", name = "inv_issue_date", id = "inv_issue_date", title = "Select Invoice Issue Date", placeholder = "dd/mm/yyyy", style = "text-align:center;" })
Please be carefull with the usage of autoSizeColumn()
. It can be used without problems on small files but please take care that the method is called only once (at the end) for each column and not called inside a loop which would make no sense.
Please avoid using autoSizeColumn()
on large Excel files. The method generates a performance problem.
We used it on a 110k rows/11 columns file. The method took ~6m to autosize all columns.
For more details have a look at: How to speed up autosizing columns in apache POI?
Although answer is provided I found simpler solution:
Date:
01/20/2017
By doing replace
CurrentDate = replace(date, "/", "-")
It will output:
01-20-2017
{key: value for (key, value) in iterable}
Note: this is for Python 3.x (and 2.7 upwards). Formerly in Python 2.6 and earlier, the dict
built-in could receive an iterable of key/value pairs, so you can pass it a list comprehension or generator expression. For example:
dict((key, func(key)) for key in keys)
In simple cases you don't need a comprehension at all...
dict
built-in directly:1) consumed from any iterable yielding pairs of keys/vals
dict(pairs)
2) "zip'ped" from two separate iterables of keys/vals
dict(zip(list_of_keys, list_of_values))
you can use File to return a file like View, Content etc
public ActionResult PrintDocInfo(string Attachment)
{
string test = Attachment;
if (test != string.Empty || test != "" || test != null)
{
string filename = Attachment.Split('\\').Last();
string filepath = Attachment;
byte[] filedata = System.IO.File.ReadAllBytes(Attachment);
string contentType = MimeMapping.GetMimeMapping(Attachment);
System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
{
FileName = filename,
Inline = true,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(filedata, contentType);
}
else { return Content("<h3> Patient Clinical Document Not Uploaded</h3>"); }
}
Is the name of your service class really IService (on the Service namespace)? What you probably had originally was a mismatch in the name of the service class in the name
attribute of the <service>
element.
use a FileWriter instead.
FileWriter(File file, boolean append)
the second argument in the constructor tells the FileWriter to append any given input to the file rather than overwriting it.
here is some code for your example:
File log = new File("log.txt")
try{
if(!log.exists()){
System.out.println("We had to make a new file.");
log.createNewFile();
}
FileWriter fileWriter = new FileWriter(log, true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("******* " + timeStamp.toString() +"******* " + "\n");
bufferedWriter.close();
System.out.println("Done");
} catch(IOException e) {
System.out.println("COULD NOT LOG!!");
}
If you want to format a date like JavaScript's (new Date()).toISOString()
for some reason, this is how you can do it in PHP:
$now = microtime(true);
gmdate('Y-m-d\TH:i:s', $now).sprintf('.%03dZ',round(($now-floor($now))*1000));
Sample output:
2016-04-27T18:25:56.696Z
Just to prove that subtracting off the whole number doesn't reduce the accuracy of the decimal portion:
>>> number_format(123.01234567890123456789,25)
=> "123.0123456789012408307826263"
>>> number_format(123.01234567890123456789-123,25)
=> "0.0123456789012408307826263"
PHP did round the decimal places, but it rounded them the same way in both cases.
Hi, you can do something like that. This function deletes all spaces.
string delSpaces(string &str)
{
str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
return str;
}
I made another function, that deletes all unnecessary spaces.
string delUnnecessary(string &str)
{
int size = str.length();
for(int j = 0; j<=size; j++)
{
for(int i = 0; i <=j; i++)
{
if(str[i] == ' ' && str[i+1] == ' ')
{
str.erase(str.begin() + i);
}
else if(str[0]== ' ')
{
str.erase(str.begin());
}
else if(str[i] == '\0' && str[i-1]== ' ')
{
str.erase(str.end() - 1);
}
}
}
return str;
}
Just login into http://localhost/phpmyadmin/
with username:root
password:
with blank password. And then choose users account.And then choose add user account.
If your Python SDK is properly configured and you are still facing the problem that builtins are not recognized, try this:
File -> Invalidate Caches/Restart
For anyone who needs to set up the title through the Toolbar some time after setting the SupportActionBar, read this.
The internal implementation of the support library just checks if the Toolbar has a title (not null) at the moment the SupportActionBar is set up. If there is, then this title will be used instead of the window title. You can then set a dummy title while you load the real title.
mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
mActionBarToolbar.setTitle("");
setSupportActionBar(mActionBarToolbar);
later...
mActionBarToolbar.setTitle(title);
For existing project end existing repository with files:
git init
git remote add origin <.git>
git checkout -b master
git branch --set-upstream-to=origin/master master
git pull --allow-unrelated-histories
Extensions without enough permission on chrome can cause these warnings, for example for React developer tools, check if the following procedure solves your problem:
Or
Then choose "this can read and write site data". You should see 3 options in the list, pick one that is strict enough based on how much you trust the extension and also satisfies the extensions's needs.