Just generate ID and check whether it is already present or not in your list of generated IDs.
for windows, if you want global config, then run
git config --global http.sslVerify false
System.Diagnostics.Process.Start("PATH to exe", "Command Line Arguments");
You can use either foreign key on many side of OneToMany
relation (i.e. ManyToOne
relation) or use ManyToMany
(on any side) with unique constraint.
Converting from file with base64 string to png image.
4 variants which works.
var {promisify} = require('util');
var fs = require("fs");
var readFile = promisify(fs.readFile)
var writeFile = promisify(fs.writeFile)
async function run () {
// variant 1
var d = await readFile('./1.txt', 'utf8')
await writeFile("./1.png", d, 'base64')
// variant 2
var d = await readFile('./2.txt', 'utf8')
var dd = new Buffer(d, 'base64')
await writeFile("./2.png", dd)
// variant 3
var d = await readFile('./3.txt')
await writeFile("./3.png", d.toString('utf8'), 'base64')
// variant 4
var d = await readFile('./4.txt')
var dd = new Buffer(d.toString('utf8'), 'base64')
await writeFile("./4.png", dd)
}
run();
Get-ChildItem -Recurse *.txt | Format-Table FullName
That is what I used. I feel it is more understandable as it doesn't contain any loop syntax.
I recommend the answer found here: How do I concatenate two arrays in C#?
e.g.
var z = new int[x.Length + y.Length];
x.CopyTo(z, 0);
y.CopyTo(z, x.Length);
In Entity Framework Core 2.1 we can use Query Types as Yuriy N suggested.
A more detailed article on how to use them can be found here
The most straight forward approach according to the article's examples would be:
1.We have for example the following entity Models to manage publications
public class Magazine
{
public int MagazineId { get; set; }
public string Name { get; set; }
public string Publisher { get; set; }
public List<Article> Articles { get; set; }
}
public class Article
{
public int ArticleId { get; set; }
public string Title { get; set; }
public int MagazineId { get; set; }
public DateTime PublishDate { get; set; }
public Author Author { get; set; }
public int AuthorId { get; set; }
}
public class Author
{
public int AuthorId { get; set; }
public string Name { get; set; }
public List<Article> Articles { get; set; }
}
2.We have a view called AuthorArticleCounts, defined to return the name and number of articles an author has written
SELECT
a.AuthorName,
Count(r.ArticleId) as ArticleCount
from Authors a
JOIN Articles r on r.AuthorId = a.AuthorId
GROUP BY a.AuthorName
3.We go and create a model to be used for the View
public class AuthorArticleCount
{
public string AuthorName { get; private set; }
public int ArticleCount { get; private set; }
}
4.We create after that a DbQuery property in my DbContext to consume the view results inside the Model
public DbQuery<AuthorArticleCount> AuthorArticleCounts{get;set;}
4.1. You might need to override OnModelCreating() and set up the View especially if you have different view name than your Class.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Query<AuthorArticleCount>().ToView("AuthorArticleCount");
}
5.Finally we can easily get the results of the View like this.
var results=_context.AuthorArticleCounts.ToList();
UPDATE According to ssougnez's comment
It's worth noting that DbQuery won't be/is not supported anymore in EF Core 3.0. See here
Ok so the key for me was to use the .FlattenHierarchy BindingFlag. I don't really know why I just added it on a hunch and it started working. So the final solution that allows me to get Public Instance or Static Properties is:
obj.GetType.GetProperty(propName, Reflection.BindingFlags.Public _
Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance Or _
Reflection.BindingFlags.FlattenHierarchy)
The offending lines are the following:
MaxConnections=90
InitialConnections=80
You can increase the values to allow more connections.
The #include
directive literally means "copy all the data in that file to this spot." So when you include the header file, it's textually within the code file, and everything in it will be there, give or take the effect of other directives or macro replacements, when the code file (now called the compilation unit or translation unit) is handed off from the preprocessor module to the compiler module.
Which means the declaration and definition of your static member function were really in the same file all along...
The accepted answer is good. Just to make it easier to understand.
Example component:
export default function MyComponent(props) {
const [updateView, setUpdateView] = useState(0);
return (
<>
<span style={{ display: "none" }}>{updateView}</span>
</>
);
}
To force re-rendering call the code below:
setUpdateView((updateView) => ++updateView);
The best way to find the position of item in the list is by using Collections interface,
Eg,
List<Integer> sampleList = Arrays.asList(10,45,56,35,6,7);
Collections.binarySearch(sampleList, 56);
Output : 2
Don't know if anyone is still looking here, but you can do this by going to Window menu > Preferences, then open the General list, choose keys. Scroll down the list of keys until you see "Shift Left". Click that. Below that you'll see some boxes, one of which lets you bind a key. It won't accept Shift-Tab, so I bound it to Shift-`. Apply-and-close and you're all set.
Safety first (with Kotlin):
// Default to null
EnumName.values().getOrNull(ordinal)
// Default to a value
EnumName.values().getOrElse(ordinal) { EnumName.MyValue }
There are a number of properties on the StringComparer
static class that return comparers for any type of case-sensitivity you might want:
For instance, you can call
StringComparer.CurrentCultureIgnoreCase.Equals(string1, string2)
or
StringComparer.CurrentCultureIgnoreCase.Compare(string1, string2)
It's a bit cleaner than the string.Equals
or string.Compare
overloads that take a StringComparison
argument.
Using the class:
import android.provider.MediaStore.Video.Thumbnails;
We can get two preview thumbnail sizes from the video:
Thumbnails.MICRO_KIND
for 96 x 96Thumbnails.MINI_KIND
for 512 x 384 pxThis is a code example:
String filePath = "/sdcard/DCIM/Camera/my_video.mp4"; //change the location of your file!
ImageView imageview_mini = (ImageView)findViewById(R.id.thumbnail_mini);
ImageView imageview_micro = (ImageView)findViewById(R.id.thumbnail_micro);
Bitmap bmThumbnail;
//MICRO_KIND, size: 96 x 96 thumbnail
bmThumbnail = ThumbnailUtils.createVideoThumbnail(filePath, Thumbnails.MICRO_KIND);
imageview_micro.setImageBitmap(bmThumbnail);
// MINI_KIND, size: 512 x 384 thumbnail
bmThumbnail = ThumbnailUtils.createVideoThumbnail(filePath, Thumbnails.MINI_KIND);
imageview_mini.setImageBitmap(bmThumbnail);
Tried the given example, but over VPN and with 400k+ keys it was too slow for me. Also it did not give me the key objects.
I wrote a small Python called tool redis-mass-get to combine KEYS
and MGET
requests against Redis:
# installation:
pip install redis-mass-get
# pipeline example CSV:
redis-mass-get -f csv -och redis://my.redis.url product:* | less
# write to json-file example with progress indicator:
redis-mass-get -d results.json -jd redis://my.redis.url product:*
It supports JSON, CSV and TXT output to file or stdout
for usage in pipes. More info can be found at: Reading multiple key/values from Redis.
I have had the same error on python3 and this help me:
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};'
'SERVER=YourServerName;'
'DATABASE=YourDatabaseName;UID=USER_NAME;PWD=PASS_WORD;')
remember python is case-sensitive so you have to mention DRIVER,SERVER,... in upper case. and you can visit this link for more information:
Weird, just had simmilar issue, went here http://www.microsoft.com/en-us/download/confirmation.aspx?id=30679 downloaded and installed vcredist_x86 (i'm using 32bit apache) and it works like a charm.
You're taking name
in document.getElementById()
Your cb
should be txt206451
(ID Attribute) not name
attribute.
Or
You can have it by document.getElementsByName()
var cb = document.getElementsByName('field206451')[0]; // First one
OR
var cb = document.getElementById('txt206451');
And for setting values into hidden use document.getElementsByName()
like following
var cb = document.getElementById('txt206451');
var label = document.getElementsByName('label206451')[0]; // Get the first one of index
console.log(label);
cb.addEventListener('change', function (evt) { // use change here. not neccessarily
if (this.checked) {
label.value = 'Thanks'
} else {
label.value = '0'
}
}, false);
Add session_start(); before !Doctype Declaration
<?php session_start(); ?>
<!doctype html>
<html>
<body>
<?php
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800))
{
session_destroy();
session_unset();
}
?>
</body>
</html>
You can't search LONGs directly. LONGs can't appear in the WHERE clause. They can appear in the SELECT list though so you can use that to narrow down the number of rows you'd have to examine.
Oracle has recommended converting LONGs to CLOBs for at least the past 2 releases. There are fewer restrictions on CLOBs.
The result is correct based on the SQL statement. Left join returns all values from the right table, and only matching values from the left table.
ID and NAME columns are from the right side table, so are returned.
Score is from the left table, and 30 is returned, as this value relates to Name "Flow". The other Names are NULL as they do not relate to Name "Flow".
The below would return the result you were expecting:
SELECT a.*, b.Score
FROM @Table1 a
LEFT JOIN @Table2 b
ON a.ID = b.T1_ID
WHERE 1=1
AND a.Name = 'Flow'
The SQL applies a filter on the right hand table.
Open your terminal and check to see if you have Xcode installed already with this:
xcode-select -p
in return, if you get this:
/Library/Developer/CommandLineTools
That means you have that Xcode is installed.
Another way you can check would you if you have "HomeBrew" installed you can use the following command to see if you have Xcode and the version:
brew config
And finally, if you don't have the Xcode follow this link to download the Xcode from the Appstore. Xcode from the App Store.
Good Luck.
No one has mentioned this yet, and this may not be a common problem, but I had a similar problem with Xcode 5: Make sure you have a default keychain selected in the Mac's Keychain Access. I trying out a fresh install of Mountain Lion and deleted one keychain, which happened to be the default. After setting another keychain as the default (right-click on the keychain and select Make Keychain "Keychain_name" default"), Xcode was able to set up the valid signing identities.
you must check these few things:
I had the same problem, and it solved after I changed username to ubuntu. In AWS documentation was mentioned to user ec2-user but somehow does not work for me.
When I tried your code, it worked.
The only reason that your event is not working, may be that your DOM was not ready and your button with id "event-btn" was not yet ready. And your javascript got executed and tried to bind the event with that element.
Before using the DOM element for binding, that element should be ready. There are many options to do that.
Option1: You can move your event binding code within document ready event. Like:
document.addEventListener('DOMContentLoaded', (event) => {
//your code to bind the event
});
Option2: You can use timeout event, so that binding is delayed for few seconds. like:
setTimeout(function(){
//your code to bind the event
}, 500);
Option3: move your javascript include to the bottom of your page.
I hope this helps you.
I would suggest Travis for Open source project. It's just simple to configure and use.
Simple steps to setup:
.travis.yml
file in root of your project. Add Travis as service in your repository settings page.Now every time you commit into your repository Travis will build your project. You can follow simple steps to get started with Travis CI.
You don't even need to define a constructor
struct foo {
bool a = true;
bool b = true;
bool c;
} bar;
To clarify: these are called brace-or-equal-initializers (because you may also use brace initialization instead of equal sign). This is not only for aggregates: you can use this in normal class definitions. This was added in C++11.
When starting the JVM, two parameters can be adjusted to suit your memory needs :
-Xms<size>
specifies the initial Java heap size and
-Xmx<size>
the maximum Java heap size.
mkdir [-switch] foldername
-p
is a switch which is optional, it will create subfolder and parent folder as well even parent folder doesn't exist.
From the man page:
-p, --parents no error if existing, make parent directories as needed
Example:
mkdir -p storage/framework/{sessions,views,cache}
This will create subfolder sessions,views,cache inside framework folder irrespective of 'framework' was available earlier or not.
Usage:
sftp("file:/C:/home/file.txt", "ssh://user:pass@host/home");
sftp("ssh://user:pass@host/home/file.txt", "file:/C:/home");
i = Your_int_value
Write bytes value like this for example:
the_file.write(i.to_bytes(2,"little"))
Depend of you int value size and the bit order your prefer
I did it in one project of mine. I used MDB to store the data about bills and used Excel to render them, giving the user the possibility to adapt it.
In this case the best solution is:
Not to use any ADO/DAO in Excel. I implemented everything as public functions in MDB modules and called them directly from Excel. You can return even complex data objects, like arrays of strings etc by calling MDB functions with necessary arguments. This is similar to client/server architecture of modern web applications: you web application just does the rendering and user interaction, database and middle tier is then on the server side.
Use Excel forms for user interaction and for data visualisation.
I usually have a very last sheet with some names regions for settings: the path to MDB files, some settings (current user, password if needed etc.) -- so you can easily adapt your Excel implementation to different location of you "back-end" data.
Here is a function which helps you check if the mouse is inside an element or not. The only thing you should do is to call the function where you can have a live mouse-associated EventObject. something like this:
$("body").mousemove(function(event){
element_mouse_is_inside($("#mycontainer", event, true, {});
});
You can see the source code here in github or at the bottom of the post:
https://github.com/mostafatalebi/ElementsLocator/blob/master/elements_locator.jquery.js
function element_mouse_is_inside (elementToBeChecked, mouseEvent, with_margin, offset_object)
{
if(!with_margin)
{
with_margin = false;
}
if(typeof offset_object !== 'object')
{
offset_object = {};
}
var elm_offset = elementToBeChecked.offset();
var element_width = elementToBeChecked.width();
element_width += parseInt(elementToBeChecked.css("padding-left").replace("px", ""));
element_width += parseInt(elementToBeChecked.css("padding-right").replace("px", ""));
var element_height = elementToBeChecked.height();
element_height += parseInt(elementToBeChecked.css("padding-top").replace("px", ""));
element_height += parseInt(elementToBeChecked.css("padding-bottom").replace("px", ""));
if( with_margin)
{
element_width += parseInt(elementToBeChecked.css("margin-left").replace("px", ""));
element_width += parseInt(elementToBeChecked.css("margin-right").replace("px", ""));
element_height += parseInt(elementToBeChecked.css("margin-top").replace("px", ""));
element_height += parseInt(elementToBeChecked.css("margin-bottom").replace("px", ""));
}
elm_offset.rightBorder = elm_offset.left+element_width;
elm_offset.bottomBorder = elm_offset.top+element_height;
if(offset_object.hasOwnProperty("top"))
{
elm_offset.top += parseInt(offset_object.top);
}
if(offset_object.hasOwnProperty("left"))
{
elm_offset.left += parseInt(offset_object.left);
}
if(offset_object.hasOwnProperty("bottom"))
{
elm_offset.bottomBorder += parseInt(offset_object.bottom);
}
if(offset_object.hasOwnProperty("right"))
{
elm_offset.rightBorder += parseInt(offset_object.right);
}
var mouseX = mouseEvent.pageX;
var mouseY = mouseEvent.pageY;
if( (mouseX > elm_offset.left && mouseX < elm_offset.rightBorder)
&& (mouseY > elm_offset.top && mouseY < elm_offset.bottomBorder) )
{
return true;
}
else
{
return false;
}
}
Let's say you have a cell with a subview, and you want the cell's height to be high enough to encompass the subview + padding.
1) Set the subview's bottom constraint equal to the cell.contentView minus the padding you want. Do not set constraints on the cell or cell.contentView itself.
2) Set either the tableView's rowHeight
property or tableView:heightForRowAtIndexPath:
to UITableViewAutomaticDimension
.
3) Set either the tableView's estimatedRowHeight
property or tableView:estimatedHeightForRowAtIndexPath:
to a best guess of the height.
That's it.
It sounds as if the only problem here is that the default editor that is launched is vi
or vim
, with which you're not familiar. (As quick tip, to exit that editor without saving changes, hit Esc a few times and then type :, q, ! and Enter.)
There are several ways to set up your default editor, and you haven't indicated which operating system you're using, so it's difficult to recommend one in particular. I'd suggest using:
git config --global core.editor "name-of-your-editor"
... which sets a global git preference for a particular editor. Alternatively you can set the $EDITOR
environment variable.
The simplest thing you can do is cherry picking a range. It does the same as the rebase --onto
but is easier for the eyes :)
git cherry-pick quickfix1..quickfix2
For support to all API levels you can use it like this:
ViewPropertyAnimator.animate(view).translationYBy(-yourY).translationXBy(-yourX).setDuration(0);
Static storage duration means that the variable resides in the same place in memory through the lifetime of the program.
Linkage is orthogonal to this.
I think this is the most important distinction you can make. Understand this and the rest, as well as remembering it, should come easy (not addressing @Tony directly, but whoever might read this in the future).
The keyword static
can be used to denote internal linkage and static storage, but in essence these are different.
What does it mean with local variable? Is that a function local variable?
Yes. Regardless of when the variable is initialized (on first call to the function and when execution path reaches the declaration point), it will reside in the same place in memory for the life of the program. In this case, static
gives it static storage.
Now what about the case with static and file scope? Are all global variables considered to have static storage duration by default?
Yes, all globals have by definition static storage duration (now that we cleared up what that means). But namespace scoped variables aren't declared with static
, because that would give them internal linkage, so a variable per translation unit.
How does static relate to the linkage of a variable?
It gives namespace-scoped variables internal linkage. It gives members and local variables static storage duration.
Let's expand on all this:
//
static int x; //internal linkage
//non-static storage - each translation unit will have its own copy of x
//NOT A TRUE GLOBAL!
int y; //static storage duration (can be used with extern)
//actual global
//external linkage
struct X
{
static int x; //static storage duration - shared between class instances
};
void foo()
{
static int x; //static storage duration - shared between calls
}
This whole static keyword is downright confusing
Definitely, unless you're familiar with it. :) Trying to avoid adding new keywords to the language, the committee re-used this one, IMO, to this effect - confusion. It's used to signify different things (might I say, probably opposing things).
You can use reset_index
to turn the index back into a column:
monthly_mean.reset_index().plot(x='index', y='A')
Runas doesn't magically run commands as an administrator, it runs them as whatever account you provide credentials for. If it's not an administrator account, runas doesn't care.
I've just had the same problem on a CentOS 7 box.
Seems I'd hit selinux. Putting selinux into permissive mode (setenforce permissive
) has worked round the problem for now. I'll try and get back with a proper fix.
Complementing Matt Frear's answer - This would be an ASP NET Core alternative for reading the file directly from Stream, without saving&reading it from disk:
public ActionResult OnPostUpload(List<IFormFile> files)
{
try
{
var file = files.FirstOrDefault();
var inputstream = file.OpenReadStream();
XSSFWorkbook workbook = new XSSFWorkbook(stream);
var FIRST_ROW_NUMBER = {{firstRowWithValue}};
ISheet sheet = workbook.GetSheetAt(0);
// Example: var firstCellRow = (int)sheet.GetRow(0).GetCell(0).NumericCellValue;
for (int rowIdx = 2; rowIdx <= sheet.LastRowNum; rowIdx++)
{
IRow currentRow = sheet.GetRow(rowIdx);
if (currentRow == null || currentRow.Cells == null || currentRow.Cells.Count() < FIRST_ROW_NUMBER) break;
var df = new DataFormatter();
for (int cellNumber = {{firstCellWithValue}}; cellNumber < {{lastCellWithValue}}; cellNumber++)
{
//business logic & saving data to DB
}
}
}
catch(Exception ex)
{
throw new FileFormatException($"Error on file processing - {ex.Message}");
}
}
For Python 3.4+:
import csv
from pathlib import Path
base_path = Path(__file__).parent
file_path = (base_path / "../data/test.csv").resolve()
with open(file_path) as f:
test = [line for line in csv.reader(f)]
For this case you can use ptp eclipse https://eclipse.org/ptp/ for source browsing and building.
You can use this pluging to debug your application
http://marketplace.eclipse.org/content/direct-remote-c-debugging
an alternative way is to use ui-sref-active
A directive working alongside ui-sref to add classes to an element when the related ui-sref directive's state is active, and removing them when it is inactive. The primary use-case is to simplify the special appearance of navigation menus relying on ui-sref, by having the "active" state's menu button appear different, distinguishing it from the inactive menu items.
Usage:
ui-sref-active='class1 class2 class3' - classes "class1", "class2", and "class3" are each added to the directive element when the related ui-sref's state is active, and removed when it is inactive.
Example:
Given the following template,
<ul>
<li ui-sref-active="active" class="item">
<a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
</li>
<!-- ... -->
</ul>
when the app state is "app.user", and contains the state parameter "user" with value "bilbobaggins", the resulting HTML will appear as
<ul>
<li ui-sref-active="active" class="item active">
<a ui-sref="app.user({user: 'bilbobaggins'})" href="/users/bilbobaggins">@bilbobaggins</a>
</li>
<!-- ... -->
</ul>
The class name is interpolated once during the directives link time (any further changes to the interpolated value are ignored). Multiple classes may be specified in a space-separated format.
Use ui-sref-opts directive to pass options to $state.go(). Example:
<a ui-sref="home" ui-sref-opts="{reload: true}">Home</a>
You can do it quite easily with (introduced in PostgreSQL 8.2) VALUES (), ().
Syntax will be like this:
select c.*
from comments c
join (
values
(1,1),
(3,2),
(2,3),
(4,4)
) as x (id, ordering) on c.id = x.id
order by x.ordering
EOF indicates "end of file". A newline (which is what happens when you press enter) isn't the end of a file, it's the end of a line, so a newline doesn't terminate this loop.
The code isn't wrong[*], it just doesn't do what you seem to expect. It reads to the end of the input, but you seem to want to read only to the end of a line.
The value of EOF is -1 because it has to be different from any return value from getchar
that is an actual character. So getchar
returns any character value as an unsigned char, converted to int, which will therefore be non-negative.
If you're typing at the terminal and you want to provoke an end-of-file, use CTRL-D (unix-style systems) or CTRL-Z (Windows). Then after all the input has been read, getchar()
will return EOF
, and hence getchar() != EOF
will be false, and the loop will terminate.
[*] well, it has undefined behavior if the input is more than LONG_MAX characters due to integer overflow, but we can probably forgive that in a simple example.
Short answer: You can't.
Long answer: You can use the INFORMATION_SCHEMA to get the table definitions and use this to generate the necessary UPDATE statements dynamically. For example you could start with this:
SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'your_schema'
I'd try to avoid doing this though if at all possible.
MySql decimal types are a little bit more complicated than just left-of and right-of the decimal point.
The first argument is precision, which is the number of total digits. The second argument is scale which is the maximum number of digits to the right of the decimal point.
Thus, (4,2)
can be anything from -99.99
to 99.99
.
As for why you're getting 99.99
instead of the desired 3.80
, the value you're inserting must be interpreted as larger than 99.99
, so the max value is used. Maybe you could post the code that you are using to insert or update the table.
Edit
Corrected a misunderstanding of the usage of scale and precision, per http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html.
My favourite UI tutorials all come from zetcode.com:
These are tutorials I'd consider to be "starting tutorials". The example tutorial gets you up and going, but doesn't show you anything too advanced or give much explanation. Still, often, I find the big problem is "how do I start?" and these have always proved useful to me.
If you dont want to use $.browser
, take a look at case 1, otherwise maybe case 2 and 3 can help you just to get informed because it is not recommended to use $.browser
(the user agent can be spoofed using this). An alternative can be using jQuery.support
that will detect feature support and not agent info.
But...
If you insist on getting browser type (just Chrome or Safari) but not using $.browser
, case 1 is what you looking for...
Case 1: (No jQuery and no $.browser, just javascript)
Live Demo: http://jsfiddle.net/oscarj24/DJ349/
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
var isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);
if (isChrome) alert("You are using Chrome!");
if (isSafari) alert("You are using Safari!");
These cases I used in times before and worked well but they are not recommended...
Case 2: (Using jQuery and $.browser, this one is tricky)
Live Demo: http://jsfiddle.net/oscarj24/gNENk/
$(document).ready(function(){
/* Get browser */
$.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
/* Detect Chrome */
if($.browser.chrome){
/* Do something for Chrome at this point */
/* Finally, if it is Chrome then jQuery thinks it's
Safari so we have to tell it isn't */
$.browser.safari = false;
}
/* Detect Safari */
if($.browser.safari){
/* Do something for Safari */
}
});
Case 3: (Using jQuery and $.browser, "elegant" solution)
Live Demo: http://jsfiddle.net/oscarj24/uJuEU/
$.browser.chrome = $.browser.webkit && !!window.chrome;
$.browser.safari = $.browser.webkit && !window.chrome;
if ($.browser.chrome) alert("You are using Chrome!");
if ($.browser.safari) alert("You are using Safari!");
You have to add to the source property an object with a property called "uri" where you can specify the path of your image as you can see in the following example:
<Image style={styles.image} source={{uri: "http://www.mysyte.com/myimage.jpg"}} />
remember then to set the width and height via the style property:
var styles = StyleSheet.create({
image:{
width: 360,
height: 40,
}
});
I had this problem with Eclipse neon and JDK 1.8. After changing to JDK 1.7 the problem was solved.
There is an attribute called android:weightSum.
You can set android:weightSum="2" in the parent linear_layout and android:weight="1" in the inner linear_layout.
Remember to set the inner linear_layout to fill_parent so weight attribute can work as expected.
Btw, I don't think its necesary to add a second view, altough I haven't tried. :)
<LinearLayout
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:weightSum="2">
<LinearLayout
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_weight="1">
</LinearLayout>
</LinearLayout>
Maybe this would help:
String[] some_array = getResources().getStringArray(R.array.your_string_array)
So you get the array-list as a String[] and then choose any i, some_array[i].
Configure static ip for your laptop and raspberry pi. On the rapberryPI configure it as following.
pi@rpi>sudo nano /etc/network/interfaces
Then configure following as required to connect to your laptop.
iface eth0 inet static
address 192.168.1.81
netmask 255.255.255.0
broadcast 192.168.1.255
One Short Answere is:
Cloning the objects before adding them. For example, instead of newList.addAll(oldList);
for(Person p : oldList) {
newList.add(p.clone());
}
Assuming clone
is correctly overriden inPerson
.
I meet this same question. The port 443 wasn't open in Centos.
Check the 443 port with the following command:
sudo lsof -i tcp:443
In the first line of /etc/httpd/conf.d/ssl.conf add this two lines:
LoadModule ssl_module modules/mod_ssl.so
Listen 443
I know this is pretty long after your post, but wanted to post for others who might be experiencing this issue and stumble across this post as I did.
It seems there's something about jquery's $.each
that changes the nature of the elements in the array.
I wanted to do the following:
$.getJSON('/ajax/get_messages.php', function(data) {
/* data:
[{"title":"Failure","details":"Unsuccessful. Please try again.","type":"error"},
{"title":"Information Message","details":"A basic informational message - Please be aware","type":"info"}]
*/
console.log ("Data0Title: " + data[0].title);
// prints "Data0Title: Failure"
console.log ("Data0Type: " + data[0].type);
// prints "Data0Type: error"
console.log ("Data0Details: " + data[0].details);
// prints "Data0Details: Unsuccessful. Please try again"
/* Loop through data array and print messages to console */
});
To accomplish the loop, I first tried using a jquery $.each
to loop through the data array. However, as the OP notes, this doesn't work right:
$.each(data, function(nextMsg) {
console.log (nextMsg.title + " (" + nextMsg.type + "): " + nextMsg.details);
// prints
// "undefined (undefined): undefined
// "undefined (undefined): undefined
});
This didn't exactly make sense since I am able to access the data[0]
elements when using a numeric key on the data array. So since using a numerical index worked, I tried (successfully) replacing the $.each
block with a for loop:
var i=0;
for (i=0;i<data.length;i++){
console.log (data[i].title + " (" + data[i].type + "): " + data[i].details);
// prints
// "Failure (error): Unsuccessful. Please try again"
// "Information Message (info): A basic informational message - Please be aware"
}
So I don't know the underlying problem, a basic, old fashioned javascript for loop seems to be a functional alternative to jquery's $.each
Simple Way from Scratch.
Download Anaconda from https://repo.anaconda.com/archive/Anaconda3-5.2.0-Windows-x86_64.exe
Install Anaconda by double clicking it.
Open anaconda prompt by searching anaconda in windows search and type the following command while being connected to internet.
A. conda create -n tensorflow_env python=3.6
B. conda activate tensorflow_env
C. conda install -c conda-forge tensorflow
Step C will take time. After install type python
in conda prompt and type
import tensorflow as tf
If no error is found your installation is successful.
The best way is going to documentation.
.append()
vs .after()
append()
: Insert content, specified by the parameter, to the end of each element in the set of matched elements.after()
: Insert content, specified by the parameter, after each element in the set of matched elements. .prepend()
vs .before()
prepend()
: Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.before()
: Insert content, specified by the parameter, before each element in the set of matched elements.So, append and prepend refers to child of the object whereas after and before refers to sibling of the the object.
I think another option is to open workspace in RStudio and then change list to grid at the top right of the environment(image below). Then tick the objects you want to clear and finally click on clear.
Open the sql file in your text editor;
1. Search: utf8mb4_unicode_ci Replace: utf8_general_ci (Replace All)
2. Search: utf8mb4_unicode_520_ci Replace: utf8_general_ci (Replace All)
3. Search: utf8mb4 Replace: utf8 (Replace All)
Save and upload!
To convert the string to an actual dict, you can do df['Pollutant Levels'].map(eval)
. Afterwards, the solution below can be used to convert the dict to different columns.
Using a small example, you can use .apply(pd.Series)
:
In [2]: df = pd.DataFrame({'a':[1,2,3], 'b':[{'c':1}, {'d':3}, {'c':5, 'd':6}]})
In [3]: df
Out[3]:
a b
0 1 {u'c': 1}
1 2 {u'd': 3}
2 3 {u'c': 5, u'd': 6}
In [4]: df['b'].apply(pd.Series)
Out[4]:
c d
0 1.0 NaN
1 NaN 3.0
2 5.0 6.0
To combine it with the rest of the dataframe, you can concat
the other columns with the above result:
In [7]: pd.concat([df.drop(['b'], axis=1), df['b'].apply(pd.Series)], axis=1)
Out[7]:
a c d
0 1 1.0 NaN
1 2 NaN 3.0
2 3 5.0 6.0
Using your code, this also works if I leave out the iloc
part:
In [15]: pd.concat([df.drop('b', axis=1), pd.DataFrame(df['b'].tolist())], axis=1)
Out[15]:
a c d
0 1 1.0 NaN
1 2 NaN 3.0
2 3 5.0 6.0
Detached HEAD
means that what's currently checked out is not a local branch.
Some scenarios that will result in a Detached HEAD
state:
If you checkout a remote branch, say origin/master
. This is a read-only branch. Thus, when creating a commit from origin/master
it will be free-floating, i.e. not connected to any branch.
If you checkout a specific tag or commit. When doing a new commit from here, it will again be free-floating, i.e. not connected to any branch. Note that when a branch is checked out, new commits always gets automatically placed at the tip.
When you want to go back and checkout a specific commit or tag to start working from there, you could create a new branch originating from that commit and switch to it by git checkout -b new_branch_name
. This will prevent the Detached HEAD
state as you now have a branch checked out and not a commit.
You had a mistake on the statement below. Use . not ,
echo '<img src="', $dir, '/', $file, '" alt="', $file, $
to
echo '<img src="'. $dir. '/'. $file. '" alt="'. $file. $
and
echo 'Directory \'', $dir, '\' not found!';
to
echo 'Directory \''. $dir. '\' not found!';
While this is sort of a follow up to the previous answer, it adds a little (hopefully).
Mainly what I want to clarify is that usually we think of drawing things like draw a rectangle at 10, 3
.
So if we think about that like this: move origin to 10, 3
, then draw rectangle at 0, 0
.
Then all we have to do is add a rotate in between.
Another big point is the alignment of the text. It's easiest to draw the text at 0, 0, so using the correct alignment can allow us to do that without measuring the text width.
We should still move the text by an amount to get it centered vertically, and unfortunately canvas does not have great line height support, so that's a guess and check thing ( correct me if there is something better ).
I've created 3 examples that provide a point and a text with 3 alignments, to show what the actual point on the screen is where the font will go.
var font, lineHeight, x, y;
x = 100;
y = 100;
font = 20;
lineHeight = 15; // this is guess and check as far as I know
this.context.font = font + 'px Arial';
// Right Aligned
this.context.save();
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);
this.context.textAlign = 'right';
this.context.fillText('right', 0, lineHeight / 2);
this.context.restore();
this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);
// Center
this.context.fillStyle = 'black';
x = 150;
y = 100;
this.context.save();
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);
this.context.textAlign = 'center';
this.context.fillText('center', 0, lineHeight / 2);
this.context.restore();
this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);
// Left
this.context.fillStyle = 'black';
x = 200;
y = 100;
this.context.save();
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);
this.context.textAlign = 'left';
this.context.fillText('left', 0, lineHeight / 2);
this.context.restore();
this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);
The line this.context.fillText('right', 0, lineHeight / 2);
is basically 0, 0
, except we move slightly for the text to be centered near the point
In .NET4.5
, MVC 5
Javascript:
object in JS:
mechanism that does post.
$('.button-green-large').click(function() {
$.ajax({
url: 'Quote',
type: "POST",
dataType: "json",
data: JSON.stringify(document.selectedProduct),
contentType: 'application/json; charset=utf-8',
});
});
C#
Objects:
public class WillsQuoteViewModel
{
public string Product { get; set; }
public List<ClaimedFee> ClaimedFees { get; set; }
}
public partial class ClaimedFee //Generated by EF6
{
public long Id { get; set; }
public long JourneyId { get; set; }
public string Title { get; set; }
public decimal Net { get; set; }
public decimal Vat { get; set; }
public string Type { get; set; }
public virtual Journey Journey { get; set; }
}
Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Quote(WillsQuoteViewModel data)
{
....
}
Object received:
Hope this saves you some time.
int value;
if (int.TryParse("your string", out value))
{
Console.WriteLine(value);
}
Solved: The problem lies here:
I set POST
via both _CUSTOMREQUEST
and _POST
and the _CUSTOMREQUEST
persisted as POST
while _POST
switched to _HTTPGET
. The Server assumed the header from _CUSTOMREQUEST
to be the right one and came back with a 411.
curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'POST');
<div id="placeholder" style="position:absolute; top:0; right:0; bottom:0; left:0;"></div>
You need to look at the return value of the call to showConfirmDialog
. I.E.:
int dialogResult = JOptionPane.showConfirmDialog (null, "Would You Like to Save your Previous Note First?","Warning",dialogButton);
if(dialogResult == JOptionPane.YES_OPTION){
// Saving code here
}
You were testing against dialogButton
, which you were using to set the buttons that should be displayed by the dialog, and this variable was never updated - so dialogButton
would never have been anything other than JOptionPane.YES_NO_OPTION
.
Per the Javadoc for showConfirmDialog
:
Returns: an integer indicating the option selected by the user
To count number of tables just do this:
USE your_db_name; -- set database
SHOW TABLES; -- tables lists
SELECT FOUND_ROWS(); -- number of tables
Sometimes easy things will do the work.
First install the JDK1.8 set to Path Open Eclipse and Oper Eclipse Market Place option. Search for jdk 1.8 for kepler Install the required plugin. Restart the eclipse. Change compiler level to 1.8 from preferences. If still there is an error then click on the file and change the compiler setting explicitly to Jdk 1.8
https://trac.ffmpeg.org/wiki/Encode/MP3
VBR Encoding:
ffmpeg -vn -ar 44100 -ac 2 -q:a 1 -codec:a libmp3lame output.mp3
This could help if you wish to get directory contents as an array, ignoring hidden files and directories.
function dir_tree($dir_path)
{
$rdi = new \RecursiveDirectoryIterator($dir_path);
$rii = new \RecursiveIteratorIterator($rdi);
$tree = [];
foreach ($rii as $splFileInfo) {
$file_name = $splFileInfo->getFilename();
// Skip hidden files and directories.
if ($file_name[0] === '.') {
continue;
}
$path = $splFileInfo->isDir() ? array($file_name => array()) : array($file_name);
for ($depth = $rii->getDepth() - 1; $depth >= 0; $depth--) {
$path = array($rii->getSubIterator($depth)->current()->getFilename() => $path);
}
$tree = array_merge_recursive($tree, $path);
}
return $tree;
}
The result would be something like;
dir_tree(__DIR__.'/public');
[
'css' => [
'style.css',
'style.min.css',
],
'js' => [
'script.js',
'script.min.js',
],
'favicon.ico',
]
DATE TIME BASED INPUT
var dt1 = new Date("2019-1-8 11:19:16");
var dt2 = new Date("2019-1-8 11:24:16");
var diff =(dt2.getTime() - dt1.getTime()) ;
var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);
var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);
var response = {
status : 200,
Hour : hours,
Mins : mins
}
OUTPUT
{
"status": 200,
"Hour": 0,
"Mins": 5
}
If you want to convert CSV to Excel without Excel being installed, you can use the great .NET library EPPlus (under LGPL license) to create and modify Excel Sheets and also convert CSV to Excel really fast!
$HOME\Documents\WindowsPowerShell\Modules\EPPlus
)[Reflection.Assembly]::UnsafeLoadFrom($DLLPath) | Out-Null
# Create temporary CSV and Excel file names
$FileNameCSV = "$HOME\Downloads\test.csv"
$FileNameExcel = "$HOME\Downloads\test.xlsx"
# Create CSV File (with first line containing type information and empty last line)
Get-Process | Export-Csv -Delimiter ';' -Encoding UTF8 -Path $FileNameCSV
# Load EPPlus
$DLLPath = "$HOME\Documents\WindowsPowerShell\Modules\EPPlus\EPPlus.dll"
[Reflection.Assembly]::LoadFile($DLLPath) | Out-Null
# Set CSV Format
$Format = New-object -TypeName OfficeOpenXml.ExcelTextFormat
$Format.Delimiter = ";"
# use Text Qualifier if your CSV entries are quoted, e.g. "Cell1","Cell2"
$Format.TextQualifier = '"'
$Format.Encoding = [System.Text.Encoding]::UTF8
$Format.SkipLinesBeginning = '1'
$Format.SkipLinesEnd = '1'
# Set Preferred Table Style
$TableStyle = [OfficeOpenXml.Table.TableStyles]::Medium1
# Create Excel File
$ExcelPackage = New-Object OfficeOpenXml.ExcelPackage
$Worksheet = $ExcelPackage.Workbook.Worksheets.Add("FromCSV")
# Load CSV File with first row as heads using a table style
$null=$Worksheet.Cells.LoadFromText((Get-Item $FileNameCSV),$Format,$TableStyle,$true)
# Load CSV File without table style
#$null=$Worksheet.Cells.LoadFromText($file,$format)
# Fit Column Size to Size of Content
$Worksheet.Cells[$Worksheet.Dimension.Address].AutoFitColumns()
# Save Excel File
$ExcelPackage.SaveAs($FileNameExcel)
Write-Host "CSV File $FileNameCSV converted to Excel file $FileNameExcel"
This is my benchmark results
test 4,267,740 ops/sec ±1.32% (60 runs sampled)
exec 3,649,719 ops/sec ±2.51% (60 runs sampled)
match 3,623,125 ops/sec ±1.85% (62 runs sampled)
indexOf 6,230,325 ops/sec ±0.95% (62 runs sampled)
test method is faster than the match method, but the fastest method is the indexOf
You are mixing mysqli and mysql extensions, which will not work.
You need to use
$myConnection= mysqli_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysqli_select_db($myConnection, "mrmagicadam") or die ("no database");
mysqli
has many improvements over the original mysql
extension, so it is recommended that you use mysqli
.
Must it be mutable? Use a list. Must it not be mutable? Use a tuple.
Otherwise, it's a question of choice.
For collections of heterogeneous objects (like a address broken into name, street, city, state and zip) I prefer to use a tuple. They can always be easily promoted to named tuples.
Likewise, if the collection is going to be iterated over, I prefer a list. If it's just a container to hold multiple objects as one, I prefer a tuple.
My own tests conclusively show that br
tags do not like to be targeted for css.
But if you can add style then you can probably also add a scrip tag to the header of the page?
Link to an external .js
that does something like this:
function replaceLineBreaksWithHorizontalRulesInElement( element )
{
elems = element.getElementsByTagName( 'br' );
for ( var i = 0; i < elems.length; i ++ )
{
br = elems.item( i );
hr = document.createElement( 'hr' );
br.parentNode.replaceChild( hr, br );
}
}
So in short, it's not optimal, but here is my solution.
Something I am using (jquery needed), in my script I need it for the current day, but of course you can edit it accordingly.
HTML:
<label>Date:</label><input name="date" id="dateChange" type="date"/>
<input id="SubtractDay" type="button" value="-" />
<input id="AddDay" type="button" value="+" />
JavaScript:
var counter = 0;
$("#SubtractDay").click(function() {
counter--;
var today = new Date();
today.setDate(today.getDate() + counter);
var formattedDate = new Date(today);
var d = ("0" + formattedDate.getDate()).slice(-2);
var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
var y = formattedDate.getFullYear();
$("#dateChange").val(d + "/" + m + "/" + y);
});
$("#AddDay").click(function() {
counter++;
var today = new Date();
today.setDate(today.getDate() + counter);
var formattedDate = new Date(today);
var d = ("0" + formattedDate.getDate()).slice(-2);
var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
var y = formattedDate.getFullYear();
$("#dateChange").val(d + "/" + m + "/" + y);
});
For future users. @keshavDulal answer doesn't work for latest version. And I couldn't find a proper fix for the issues that are reporting in the latest version 3.3.3
.
Anyway I finally fixed it after researching a bit. Here is the solution for winston version 3.3.3
Install winston and winston-daily-rotate-file
npm install winston
npm install winston-daily-rotate-file
Create a new file utils/logger.js
const winston = require('winston');
const winstonRotator = require('winston-daily-rotate-file');
var logger = new winston.createLogger({
transports: [
new (winston.transports.DailyRotateFile)({
name: 'access-file',
level: 'info',
filename: './logs/access.log',
json: false,
datePattern: 'yyyy-MM-DD',
prepend: true,
maxFiles: 10
}),
new (winston.transports.DailyRotateFile)({
name: 'error-file',
level: 'error',
filename: './logs/error.log',
json: false,
datePattern: 'yyyy-MM-DD',
prepend: true,
maxFiles: 10
})
]
});
module.exports = {
logger
};
Then in any file where you want to use logging import the module like
const logger = require('./utils/logger').logger;
Use logger like the following:
logger.info('Info service started');
logger.error('Service crashed');
You can also query the INFORMATION_SCHEMA.SCHEMATA view:
SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA
I believe querying the INFORMATION_SCHEMA views is recommended as they protect you from changes to the underlying sys tables. From the SQL Server 2008 R2 Help:
Information schema views provide an internal, system table-independent view of the SQL Server metadata. Information schema views enable applications to work correctly although significant changes have been made to the underlying system tables. The information schema views included in SQL Server comply with the ISO standard definition for the INFORMATION_SCHEMA.
Ironically, this is immediately preceded by this note:
Some changes have been made to the information schema views that break backward compatibility. These changes are described in the topics for the specific views.
This will produce an array of names
> jq '[ .users[] | (.first + " " + .last) ]' ~/test.json
[
"Stevie Wonder",
"Michael Jackson"
]
I solved the same problem by installing "matplotlib".
Cant update the DB row. I was facing the same error. Now working with following code:
_context.Entry(_SendGridSetting).CurrentValues.SetValues(vm);
await _context.SaveChangesAsync();
On Linux man ascii
says:
ASCII is the American Standard Code for Information Interchange. It is a 7-bit code.
Especially for parent divs with relative (unknown) height, the centering in the unknown solution works great for me. There are some really nice code examples in the article.
It was tested in Chrome, Firefox, Opera, and Internet Explorer.
/* This parent can be any width and height */_x000D_
.block {_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
/* The ghost, nudged to maintain perfect centering */_x000D_
.block:before {_x000D_
content: '';_x000D_
display: inline-block;_x000D_
height: 100%;_x000D_
vertical-align: middle;_x000D_
margin-right: -0.25em; /* Adjusts for spacing */_x000D_
}_x000D_
_x000D_
/* The element to be centered, can_x000D_
also be of any width and height */ _x000D_
.centered {_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
width: 300px;_x000D_
}
_x000D_
<div style="width: 400px; height: 200px;">_x000D_
<div class="block" style="height: 90%; width: 100%">_x000D_
<div class="centered">_x000D_
<h1>Some text</h1>_x000D_
<p>Any other text..."</p>_x000D_
</div> _x000D_
</div>_x000D_
</div>
_x000D_
use a double %%
I had the same problem but with an other cause. The solution was to deactivate Avira Browser Protection (in german Browser-Schutz). I took the solusion from m2e cannot transfer metadata from nexus, but maven command line can. It can be activated again ones maven has the needed plugin.
To add to Farid's pseudo-answer,
Consider using Passport.js over everyauth.
The answers to this question provide some insight to the differences.
There are plenty of benefits to offloading your user authentication to Google, Facebook or another website. If your application's requirements are such that you could use Passport as your sole authentication provider or alongside traditional login, it can make the experience easier for your users.
If you look at the documentation for str.split
:
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].
In other words, if you're trying to figure out what to pass to split
to get '\n\tName: Jane Smith'
to ['Name:', 'Jane', 'Smith']
, just pass nothing (or None).
This almost solves your whole problem. There are two parts left.
First, you've only got two fields, the second of which can contain spaces. So, you only want one split, not as many as possible. So:
s.split(None, 1)
Next, you've still got those pesky colons. But you don't need to split on them. At least given the data you've shown us, the colon always appears at the end of the first field, with no space before and always space after, so you can just remove it:
key, value = s.split(None, 1)
key = key[:-1]
There are a million other ways to do this, of course; this is just the one that seems closest to what you were already trying.
On Windows when you are using PowerShell you have to enclose all parameters with quotes.
So if you want to create a maven webapp archetype you would do as follows:
Prerequisites:
Howto:
Note: This is tested only on windows 10 powershell
As other answers indicate, on Windows you cannot delete a file that is open. However one other thing that can stop a file from being deleted on Windows is if it is is mmap'd to a MappedByteBuffer
(or DirectByteBuffer
) -- if so, the file cannot be deleted until the byte buffer is garbage collected. There is some relatively safe code for forcibly closing (cleaning) a DirectByteBuffer
before it is garbage collected here: https://github.com/classgraph/classgraph/blob/master/src/main/java/nonapi/io/github/classgraph/utils/FileUtils.java#L606 After cleaning the ByteBuffer
, you can delete the file. However, make sure you never use the ByteBuffer
again after cleaning it, or the JVM will crash.
The getcode() method (Added in python2.6) returns the HTTP status code that was sent with the response, or None if the URL is no HTTP URL.
>>> a=urllib.urlopen('http://www.google.com/asdfsf')
>>> a.getcode()
404
>>> a=urllib.urlopen('http://www.google.com/')
>>> a.getcode()
200
I bet the problem is being shown in this line
SqlDataReader dr3 = com2.ExecuteReader();
I suggest that you execute the first reader and do a dr.Close();
and the iterate historicos
, with another loop, performing the com2.ExecuteReader()
.
public List<string[]> get_dados_historico_verificacao_email_WEB(string email)
{
List<string[]> historicos = new List<string[]>();
conecta();
sql = "SELECT * FROM historico_verificacao_email WHERE nm_email = '" + email + "' ORDER BY dt_verificacao_email DESC, hr_verificacao_email DESC";
com = new SqlCommand(sql, conexao);
SqlDataReader dr = com.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
string[] dados_historico = new string[6];
dados_historico[0] = dr["nm_email"].ToString();
dados_historico[1] = dr["dt_verificacao_email"].ToString();
dados_historico[1] = dados_historico[1].Substring(0, 10);
//System.Windows.Forms.MessageBox.Show(dados_historico[1]);
dados_historico[2] = dr["hr_verificacao_email"].ToString();
dados_historico[3] = dr["ds_tipo_verificacao"].ToString();
dados_historico[5] = dr["cd_login_usuario"].ToString();
historicos.Add(dados_historico);
}
dr.Close();
sql = "SELECT COUNT(e.cd_historico_verificacao_email) QT FROM emails_lidos e WHERE e.cd_historico_verificacao_email = '" + dr["cd_historico_verificacao_email"].ToString() + "'";
tipo_sql = "seleção";
com2 = new SqlCommand(sql, conexao);
for(int i = 0 ; i < historicos.Count() ; i++)
{
SqlDataReader dr3 = com2.ExecuteReader();
while (dr3.Read())
{
historicos[i][4] = dr3["QT"].ToString(); //quantidade de emails lidos naquela verificação
}
dr3.Close();
}
}
return historicos;
There are many ways you can import Text file to the current sheet. Here are three (including the method that you are using above)
Cells.Copy
Using a QueryTable
Here is a simple macro that I recorded. Please amend it to suit your needs.
Sub Sample()
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Sample.txt", Destination:=Range("$A$1") _
)
.Name = "Sample"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
Open the text file in memory
Sub Sample()
Dim MyData As String, strData() As String
Open "C:\Sample.txt" For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
strData() = Split(MyData, vbCrLf)
End Sub
Once you have the data in the array you can export it to the current sheet.
Using the method that you are already using
Sub Sample()
Dim wbI As Workbook, wbO As Workbook
Dim wsI As Worksheet
Set wbI = ThisWorkbook
Set wsI = wbI.Sheets("Sheet1") '<~~ Sheet where you want to import
Set wbO = Workbooks.Open("C:\Sample.txt")
wbO.Sheets(1).Cells.Copy wsI.Cells
wbO.Close SaveChanges:=False
End Sub
FOLLOWUP
You can use the Application.GetOpenFilename
to choose the relevant file. For example...
Sub Sample()
Dim Ret
Ret = Application.GetOpenFilename("Prn Files (*.prn), *.prn")
If Ret <> False Then
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & Ret, Destination:=Range("$A$1"))
'~~> Rest of the code
End With
End If
End Sub
It looks like that this limitation can be avoided if you use the following URL pattern:
https://googledrive.com/host/file-id
For your case the download URL will look like this - https://googledrive.com/host/0ByvXJAlpPqQPYWNqY0V3MGs0Ujg
Please keep in mind that this method works only if file is shared with "Public on the web" option.
I don't think that x[[1,3]][:,[1,3]]
is hardly readable. If you want to be more clear on your intent, you can do:
a[[1,3],:][:,[1,3]]
I am not an expert in slicing but typically, if you try to slice into an array and the values are continuous, you get back a view where the stride value is changed.
e.g. In your inputs 33 and 34, although you get a 2x2 array, the stride is 4. Thus, when you index the next row, the pointer moves to the correct position in memory.
Clearly, this mechanism doesn't carry well into the case of an array of indices. Hence, numpy will have to make the copy. After all, many other matrix math function relies on size, stride and continuous memory allocation.
Yes, use the rendered
attribute.
<h:form rendered="#{some boolean condition}">
You usually tie it to the model rather than letting the model grab the component and manipulate it.
E.g.
<h:form rendered="#{bean.booleanValue}" />
<h:form rendered="#{bean.intValue gt 10}" />
<h:form rendered="#{bean.objectValue eq null}" />
<h:form rendered="#{bean.stringValue ne 'someValue'}" />
<h:form rendered="#{not empty bean.collectionValue}" />
<h:form rendered="#{not bean.booleanValue and bean.intValue ne 0}" />
<h:form rendered="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />
Note the importance of keyword based EL operators such as gt
, ge
, le
and lt
instead of >
, >=
, <=
and <
as angle brackets <
and >
are reserved characters in XML. See also this related Q&A: Error parsing XHTML: The content of elements must consist of well-formed character data or markup.
As to your specific use case, let's assume that the link is passing a parameter like below:
<a href="page.xhtml?form=1">link</a>
You can then show the form as below:
<h:form rendered="#{param.form eq '1'}">
(the #{param}
is an implicit EL object referring to a Map
representing the request parameters)
I just did some tests of the four options that I know about.
Measure-Command {$(1..1000) | Out-Null}
TotalMilliseconds : 76.211
Measure-Command {[Void]$(1..1000)}
TotalMilliseconds : 0.217
Measure-Command {$(1..1000) > $null}
TotalMilliseconds : 0.2478
Measure-Command {$null = $(1..1000)}
TotalMilliseconds : 0.2122
## Control, times vary from 0.21 to 0.24
Measure-Command {$(1..1000)}
TotalMilliseconds : 0.2141
So I would suggest that you use anything but Out-Null
due to overhead. The next important thing, to me, would be readability. I kind of like redirecting to $null
and setting equal to $null
myself. I use to prefer casting to [Void]
, but that may not be as understandable when glancing at code or for new users.
I guess I slightly prefer redirecting output to $null
.
Do-Something > $null
Edit
After stej's comment again, I decided to do some more tests with pipelines to better isolate the overhead of trashing the output.
Here are some tests with a simple 1000 object pipeline.
## Control Pipeline
Measure-Command {$(1..1000) | ?{$_ -is [int]}}
TotalMilliseconds : 119.3823
## Out-Null
Measure-Command {$(1..1000) | ?{$_ -is [int]} | Out-Null}
TotalMilliseconds : 190.2193
## Redirect to $null
Measure-Command {$(1..1000) | ?{$_ -is [int]} > $null}
TotalMilliseconds : 119.7923
In this case, Out-Null
has about a 60% overhead and > $null
has about a 0.3% overhead.
Addendum 2017-10-16: I originally overlooked another option with Out-Null
, the use of the -inputObject
parameter. Using this the overhead seems to disappear, however the syntax is different:
Out-Null -inputObject ($(1..1000) | ?{$_ -is [int]})
And now for some tests with a simple 100 object pipeline.
## Control Pipeline
Measure-Command {$(1..100) | ?{$_ -is [int]}}
TotalMilliseconds : 12.3566
## Out-Null
Measure-Command {$(1..100) | ?{$_ -is [int]} | Out-Null}
TotalMilliseconds : 19.7357
## Redirect to $null
Measure-Command {$(1..1000) | ?{$_ -is [int]} > $null}
TotalMilliseconds : 12.8527
Here again Out-Null
has about a 60% overhead. While > $null
has an overhead of about 4%. The numbers here varied a bit from test to test (I ran each about 5 times and picked the middle ground). But I think it shows a clear reason to not use Out-Null
.
This works better for me as sometimes I have troubles calling .datepicker('setDate', new Date());
as it messes if if i have the datepicker already configured with parameters.
$("#myDateText").val(moment(new Date()).format('DD/MM/YYYY'));
The java application takes too long to respond(maybe due start-up/jvm being cold) thus you get the proxy error.
Proxy Error
The proxy server received an invalid response from an upstream server.
The proxy server could not handle the request GET /lin/Campaignn.jsp.
As Albert Maclang said amending the http timeout configuration may fix the issue. I suspect the java application throws a 500+ error thus the apache gateway error too. You should look in the logs.
This is how I do it.
void SplitBufferToArray(char *buffer, char * delim, char ** Output) {
int partcount = 0;
Output[partcount++] = buffer;
char* ptr = buffer;
while (ptr != 0) { //check if the string is over
ptr = strstr(ptr, delim);
if (ptr != NULL) {
*ptr = 0;
Output[partcount++] = ptr + strlen(delim);
ptr = ptr + strlen(delim);
}
}
Output[partcount++] = NULL;
}
I think you should add style="background:white;" to make looks like it is writable
<input type="text" size="23" name="dateMonthly" id="dateMonthly" readonly="readonly" style="background:white;"/>
svn status | grep "^\?" | awk '{print $2}' | xargs svn add
Taken from somewhere on the web but I've been using it for a while and it works well.
<style type="text/css">
div {
text-align: center;
}
.img1{
width: 150px;
height: 150px;
border-radius: 50%;
}
span{
display: block;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type='password' class='secondInput mt-4 mr-1' placeholder="Password">
<span class='dif'></span>
<br>
<button>ADD</button>
</div>
<script type="text/javascript">
$('button').click(function() {
$('.dif').html("<img/>");
})
Of course. if you are running on Tensorflow or CNTk backends, your code will run on your GPU devices defaultly.But if Theano backends, you can use following
Theano flags:
"THEANO_FLAGS=device=gpu,floatX=float32 python my_keras_script.py"
Assuming you have an ArrayList
that contains characters, you could do this:
List<Character> list = new ArrayList<Character>();
list.addAll(Arrays.asList('+', '-', '*', '^'));
Simple! "origin" is just what you nicknamed your remote repository when you ran a command like this:
git remote add origin [email protected]:USERNAME/REPOSITORY-NAME.git
From then on Git knows that "origin" points to that specific repository (in this case a GitHub repository). You could have named it "github" or "repo" or whatever you wanted.
str = "\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a"
require 'cgi'
CGI.escape(str)
# => "%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%9A"
Taken from @J-Rou's comment
To call the function you have to add ()
{this.renderIcon()}
You declare the variable as extern
in a common header:
//globals.h
extern int x;
And define it in an implementation file.
//globals.cpp
int x = 1337;
You can then include the header everywhere you need access to it.
I suggest you also wrap the variable inside a namespace
.
date only work with GNU date (usually comes with Linux)
for OS X, two choices:
change command (verified)
#!/bin/sh #DATE=20090801204150 #date -jf "%Y%m%d%H%M%S" $DATE "+date \"%A,%_d %B %Y %H:%M:%S\"" date "Saturday, 1 August 2009 20:41:50"
http://www.unix.com/shell-programming-and-scripting/116310-date-conversion.html
Download the GNU Utilities from Coreutils - GNU core utilities (not verified yet) http://www.unix.com/emergency-unix-and-linux-support/199565-convert-string-date-add-1-a.html
I had the same problem as the OP except I remembered to declare the ReadOnlyVariables.
After some playing around, I discovered it was the name of my variable that was the issue. "File_Path" in SSIS somehow got converted to "FilePath". C# does not play nicely with underscores in variable names.
So to access the variable, I type
string fp = Variables.FilePath;
In the PreExecute() method of the Script Component.
Works on almost all browsers.
You can try giving padding-bottom
as a percentage.
<div style="height:0;width:20%;padding-bottom:20%;background-color:red">
<div>
Content goes here
</div>
</div>
The outer div is making a square and inner div contains the content. This solution worked for me many times.
Here's a jsfiddle
The following jQuery selects div nodes that contain text but have no children, which are the leaf nodes of the DOM tree.
$('div:contains("test"):not(:has(*))').css('background-color', 'red');
_x000D_
<div>div1_x000D_
<div>This is a test, nested in div1</div>_x000D_
<div>Nested in div1<div>_x000D_
</div>_x000D_
<div>div2 test_x000D_
<div>This is another test, nested in div2</div>_x000D_
<div>Nested in div2</div>_x000D_
</div>_x000D_
<div>_x000D_
div3_x000D_
</div>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
You could do something like this for your case - (syntax may be a bit off). Also look at this link
subQuery = (from crtu in CompanyRolesToUsers where crtu.RoleId==2 || crtu.RoleId==3 select crtu.UserId).ToArrayList();
finalQuery = from u in Users where u.LastName.Contains('fra') && subQuery.Contains(u.Id) select u;
Just something I found for Wordpress users,
As obvious as it sounds, If your div is returning some AJAX content based on say a header that would commonly link out to a new post page, some tutorials will say to return false since you're returning the post data on the same page and the return would prevent the page from moving. However if you return false, you also prevent Fancybox2 from doing it's thing as well. I spent hours trying to figure that stupid simple thing out.
So for these kind of links, just make sure that the href property is the hashed (#) div you wish to select, and in your javascript, make sure that you do not return false since you no longer will need to.
Simple I know ^_^
Identifiers (including column names) that are not double-quoted are folded to lower case in PostgreSQL. Column names that were created with double-quotes and thereby retained upper-case letters (and/or other syntax violations) have to be double-quoted for the rest of their life:
"first_Name"
Values (string literals / constants) are enclosed in single quotes:
'xyz'
So, yes, PostgreSQL column names are case-sensitive (when double-quoted):
SELECT * FROM persons WHERE "first_Name" = 'xyz';
Read the manual on identifiers here.
My standing advice is to use legal, lower-case names exclusively so double-quoting is not needed.
Suggestion: format a FRAMESET HTML page which contains, let´s say, 9 frames inside. Each frame will GET a different "instance" of your myapp.php page. There will be 9 different threads running on the Web server, in parallel.
From the documentation for strtotime()
:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
In your date string, you have 12-16-2013
. 16
isn't a valid month, and hence strtotime()
returns false
.
Since you can't use DateTime class, you could manually replace the -
with /
using str_replace()
to convert the date string into a format that strtotime()
understands:
$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16
You probably don't have access to one of the meta tables that SQL Developer 3 is querying. If I picked the right query, it runs the following SELECT statement:
select * from (
SELECT o.OBJECT_NAME, o.OBJECT_ID ,'' short_name, decode(bitand(t.property, 32), 32, 'YES', 'NO') partitioned,
decode(bitand(t.property, 64), 64, 'IOT',
decode(bitand(t.property, 512), 512, 'IOT_OVERFLOW',
decode(bitand(t.flags, 536870912), 536870912, 'IOT_MAPPING', null))) iot_type,
o.OWNER OBJECT_OWNER, o.CREATED, o.LAST_DDL_TIME, O.GENERATED, O.TEMPORARY, case when xt.obj# is null then 'N' else 'Y' end EXTERNAL
FROM SYS.Dba_OBJECTS O ,sys.tab$ t, sys.external_tab$ xt
WHERE O.OWNER = :SCHEMA
and o.object_id = t.obj#(+)
and o.object_id = xt.obj#(+)
AND O.OBJECT_TYPE = 'TABLE'
union all
SELECT OBJECT_NAME, OBJECT_ID , syn.SYNONYM_NAME short_NAME, decode(bitand(t.property, 32), 32, 'YES', 'NO') partitioned,
decode(bitand(t.property, 64), 64, 'IOT',
decode(bitand(t.property, 512), 512, 'IOT_OVERFLOW',
decode(bitand(t.flags, 536870912), 536870912, 'IOT_MAPPING', null))) iot_type,
SYN.TABLE_OWNER OBJECT_OWNER, o.CREATED, o.LAST_DDL_TIME, O.GENERATED, O.TEMPORARY, case when xt.obj# is null then 'N' else 'Y' end EXTERNAL
FROM SYS.Dba_OBJECTS O, sys.user_synonyms syn,sys.tab$ t, sys.external_tab$ xt
WHERE syn.table_owner = o.owner
and syn.TABLE_NAME = o.object_NAME
and o.object_id = t.obj#
and o.object_id = xt.obj#(+)
and o.object_type = 'TABLE'
and :INCLUDE_SYNS = 1
)
where /**/object_name not in (select object_name from recyclebin)
AND not object_name like 'BIN$%'
Try to run this statement to get a full error messages indicating which table doesn't exists (which is equivalent to "is not visible due to missing access rights"). SQL Developer will ask for values for SCHEMA
and INCLUDE_SYNS
. Set SCHEMA
to your username and INCLUDE_SYNS
to 0.
SQL Developer 1.1 probably used a simpler query that worked with your access rights.
The Eclipse Word-Wrap plugin works for any type of file for me.
I think is better to use a Label(or TextBlock) into a Label, you can't attach a mouse event directly in the border control, finally it is attached in the TextBlock, this is my recomendation:
<Label
Height="32"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Stretch"
MouseLeftButtonUp="MenuItem_MouseLeftButtonUp">
<TextBlock Padding="32 0 10 0">
Label with click event
</TextBlock>
</Label>
A company insurance policy insures an employee and any dependents, the DEPENDENT cannot exist without the EMPLOYEE; that is, a person cannot get insurance coverage as a dependent unless the person is a dependent of an employee.DEPENDENT is the weak entity in the relationship "EMPLOYEE has DEPENDENT"
What I did was creating my own Window and Style. Because I like to have control over everything and I didn't want some external libraries just to use a Window from it. I looked at already mentioned MahApps.Metro on GitHub
and also very nice Modern UI on GitHub. (.NET4.5 only)
There is one more it's Elysium but I really didn't try this one.
The style I did was really easy when I looked how it's done in these. Now I have my own Window and I can do whatever I want with xaml... for me it's the main reason why I did my own. And I made one more for you too :) I should probably say that I wouldn't be able to do it without exploring Modern UI it was great help. I tried to make it look like VS2012 Window. It looks like this.
Here is code (please note that it's targeting .NET4.5)
public class MyWindow : Window
{
public MyWindow()
{
this.CommandBindings.Add(new CommandBinding(SystemCommands.CloseWindowCommand, this.OnCloseWindow));
this.CommandBindings.Add(new CommandBinding(SystemCommands.MaximizeWindowCommand, this.OnMaximizeWindow, this.OnCanResizeWindow));
this.CommandBindings.Add(new CommandBinding(SystemCommands.MinimizeWindowCommand, this.OnMinimizeWindow, this.OnCanMinimizeWindow));
this.CommandBindings.Add(new CommandBinding(SystemCommands.RestoreWindowCommand, this.OnRestoreWindow, this.OnCanResizeWindow));
}
private void OnCanResizeWindow(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = this.ResizeMode == ResizeMode.CanResize || this.ResizeMode == ResizeMode.CanResizeWithGrip;
}
private void OnCanMinimizeWindow(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = this.ResizeMode != ResizeMode.NoResize;
}
private void OnCloseWindow(object target, ExecutedRoutedEventArgs e)
{
SystemCommands.CloseWindow(this);
}
private void OnMaximizeWindow(object target, ExecutedRoutedEventArgs e)
{
SystemCommands.MaximizeWindow(this);
}
private void OnMinimizeWindow(object target, ExecutedRoutedEventArgs e)
{
SystemCommands.MinimizeWindow(this);
}
private void OnRestoreWindow(object target, ExecutedRoutedEventArgs e)
{
SystemCommands.RestoreWindow(this);
}
}
And here resources:
<BooleanToVisibilityConverter x:Key="bool2VisibilityConverter" />
<Color x:Key="WindowBackgroundColor">#FF2D2D30</Color>
<Color x:Key="HighlightColor">#FF3F3F41</Color>
<Color x:Key="BlueColor">#FF007ACC</Color>
<Color x:Key="ForegroundColor">#FFF4F4F5</Color>
<SolidColorBrush x:Key="WindowBackgroundColorBrush" Color="{StaticResource WindowBackgroundColor}"/>
<SolidColorBrush x:Key="HighlightColorBrush" Color="{StaticResource HighlightColor}"/>
<SolidColorBrush x:Key="BlueColorBrush" Color="{StaticResource BlueColor}"/>
<SolidColorBrush x:Key="ForegroundColorBrush" Color="{StaticResource ForegroundColor}"/>
<Style x:Key="WindowButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Foreground" Value="{DynamicResource ForegroundColorBrush}" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Padding" Value="1" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid Background="{TemplateBinding Background}">
<ContentPresenter x:Name="contentPresenter"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
Margin="{TemplateBinding Padding}"
RecognizesAccessKey="True" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{StaticResource HighlightColorBrush}" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="{DynamicResource BlueColorBrush}" />
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter TargetName="contentPresenter" Property="Opacity" Value=".5" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="MyWindowStyle" TargetType="local:MyWindow">
<Setter Property="Foreground" Value="{DynamicResource ForegroundColorBrush}" />
<Setter Property="Background" Value="{DynamicResource WindowBackgroundBrush}"/>
<Setter Property="ResizeMode" Value="CanResizeWithGrip" />
<Setter Property="UseLayoutRounding" Value="True" />
<Setter Property="TextOptions.TextFormattingMode" Value="Display" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MyWindow">
<Border x:Name="WindowBorder" Margin="{Binding Source={x:Static SystemParameters.WindowNonClientFrameThickness}}" Background="{StaticResource WindowBackgroundColorBrush}">
<Grid>
<Border BorderThickness="1">
<AdornerDecorator>
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="25" />
<RowDefinition Height="*" />
<RowDefinition Height="15" />
</Grid.RowDefinitions>
<ContentPresenter Grid.Row="1" Grid.RowSpan="2" Margin="7"/>
<Rectangle x:Name="HeaderBackground" Height="25" Fill="{DynamicResource WindowBackgroundColorBrush}" VerticalAlignment="Top" Grid.Row="0"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Top" WindowChrome.IsHitTestVisibleInChrome="True" Grid.Row="0">
<Button Command="{Binding Source={x:Static SystemCommands.MinimizeWindowCommand}}" ToolTip="minimize" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="30" Height="25" RenderTransform="1,0,0,1,0,1">
<Path Data="M0,6 L8,6 Z" Width="8" Height="7" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="2" />
</Grid>
</Button.Content>
</Button>
<Grid Margin="1,0,1,0">
<Button x:Name="Restore" Command="{Binding Source={x:Static SystemCommands.RestoreWindowCommand}}" ToolTip="restore" Visibility="Collapsed" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="30" Height="25" UseLayoutRounding="True" RenderTransform="1,0,0,1,.5,.5">
<Path Data="M2,0 L8,0 L8,6 M0,3 L6,3 M0,2 L6,2 L6,8 L0,8 Z" Width="8" Height="8" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="1" />
</Grid>
</Button.Content>
</Button>
<Button x:Name="Maximize" Command="{Binding Source={x:Static SystemCommands.MaximizeWindowCommand}}" ToolTip="maximize" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="31" Height="25">
<Path Data="M0,1 L9,1 L9,8 L0,8 Z" Width="9" Height="8" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="2" />
</Grid>
</Button.Content>
</Button>
</Grid>
<Button Command="{Binding Source={x:Static SystemCommands.CloseWindowCommand}}" ToolTip="close" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="30" Height="25" RenderTransform="1,0,0,1,0,1">
<Path Data="M0,0 L8,7 M8,0 L0,7 Z" Width="8" Height="7" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="1.5" />
</Grid>
</Button.Content>
</Button>
</StackPanel>
<TextBlock x:Name="WindowTitleTextBlock" Grid.Row="0" Text="{TemplateBinding Title}" HorizontalAlignment="Left" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" Margin="8 -1 0 0" FontSize="16" Foreground="{TemplateBinding Foreground}"/>
<Grid Grid.Row="2">
<Path x:Name="ResizeGrip" Visibility="Collapsed" Width="12" Height="12" Margin="1" HorizontalAlignment="Right"
Stroke="{StaticResource BlueColorBrush}" StrokeThickness="1" Stretch="None" Data="F1 M1,10 L3,10 M5,10 L7,10 M9,10 L11,10 M2,9 L2,11 M6,9 L6,11 M10,9 L10,11 M5,6 L7,6 M9,6 L11,6 M6,5 L6,7 M10,5 L10,7 M9,2 L11,2 M10,1 L10,3" />
</Grid>
</Grid>
</AdornerDecorator>
</Border>
<Border BorderBrush="{StaticResource BlueColorBrush}" BorderThickness="1" Visibility="{Binding IsActive, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Converter={StaticResource bool2VisibilityConverter}}" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="WindowState" Value="Maximized">
<Setter TargetName="Maximize" Property="Visibility" Value="Collapsed" />
<Setter TargetName="Restore" Property="Visibility" Value="Visible" />
<Setter TargetName="LayoutRoot" Property="Margin" Value="7" />
</Trigger>
<Trigger Property="WindowState" Value="Normal">
<Setter TargetName="Maximize" Property="Visibility" Value="Visible" />
<Setter TargetName="Restore" Property="Visibility" Value="Collapsed" />
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="ResizeMode" Value="CanResizeWithGrip" />
<Condition Property="WindowState" Value="Normal" />
</MultiTrigger.Conditions>
<Setter TargetName="ResizeGrip" Property="Visibility" Value="Visible" />
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="WindowChrome.WindowChrome">
<Setter.Value>
<WindowChrome CornerRadius="0" GlassFrameThickness="1" UseAeroCaptionButtons="False" />
</Setter.Value>
</Setter>
</Style>
I wrote simple code for it without any third-party library. This code is only for a horizontal splitter (vertical is the same).
function onload()
{
dragElement( document.getElementById("separator"), "H" );
}
// This function is used for dragging and moving
function dragElement( element, direction, handler )
{
// Two variables for tracking positions of the cursor
const drag = { x : 0, y : 0 };
const delta = { x : 0, y : 0 };
/* If present, the handler is where you move the DIV from
otherwise, move the DIV from anywhere inside the DIV */
handler ? ( handler.onmousedown = dragMouseDown ): ( element.onmousedown = dragMouseDown );
// A function that will be called whenever the down event of the mouse is raised
function dragMouseDown( e )
{
drag.x = e.clientX;
drag.y = e.clientY;
document.onmousemove = onMouseMove;
document.onmouseup = () => { document.onmousemove = document.onmouseup = null; }
}
// A function that will be called whenever the up event of the mouse is raised
function onMouseMove( e )
{
const currentX = e.clientX;
const currentY = e.clientY;
delta.x = currentX - drag.x;
delta.y = currentY - drag.y;
const offsetLeft = element.offsetLeft;
const offsetTop = element.offsetTop;
const first = document.getElementById("first");
const second = document.getElementById("second");
let firstWidth = first.offsetWidth;
let secondWidth = second.offsetWidth;
if (direction === "H" ) // Horizontal
{
element.style.left = offsetLeft + delta.x + "px";
firstWidth += delta.x;
secondWidth -= delta.x;
}
drag.x = currentX;
drag.y = currentY;
first.style.width = firstWidth + "px";
second.style.width = secondWidth + "px";
}
}
_x000D_
.splitter {
width: 500px;
height: 100px;
display: flex;
}
#separator {
cursor: col-resize;
background: url(https://raw.githubusercontent.com/RickStrahl/jquery-resizable/master/assets/vsizegrip.png) center center no-repeat #535353;
width: 10px;
height: 100px;
min-width: 10px;
}
#first {
background-color: green;
width: 100px;
height: 100px;
min-width: 10px;
}
#second {
background-color: red;
width: 390px;
height: 100px;
min-width: 10px;
}
_x000D_
<html>
<head>
<link rel="stylesheet" href="T10-Splitter.css">
<script src="T10-Splitter.js"></script>
</head>
<body onload="onload()">
<div class="splitter">
<div id="first"></div>
<div id="separator"></div>
<div id="second"></div>
</div>
</body>
</html>
_x000D_
Another conversion that uses remainders and supports different languages:
function numberToWords(number) {
var result = [];
var fraction = number.toFixed(2).split('.');
var integer_part = parseInt(fraction[0]);
// var fractional_part = parseInt(fraction[1]); -- not handled here
var previousNumber = null;
for (var i = 0; i < fraction[0].length; i++) {
var reminder = Math.floor(integer_part % 10);
integer_part /= 10;
var name = getNumberName(reminder, i, fraction[0].length, previousNumber);
previousNumber = reminder;
if (name)
result.push(name);
}
result.reverse();
return result.join(' ');
}
The getNumberName
function is language-dependent and handles numbers up to 9999 (but it is easy to extend it to handle larger numbers):
function getNumberName(number, power, places, previousNumber) {
var result = "";
if (power == 1) {
result = handleTeensAndTys(number, previousNumber);
} else if (power == 0 && places != 1 || number == 0) {
// skip number that was handled in teens and zero
} else {
result = locale.numberNames[number.toString()] + locale.powerNames[power.toString()];
}
return result;
}
handleTeensAndTys
handles multiples of ten:
function handleTeensAndTys(number, previousNumber) {
var result = "";
if (number == 1) { // teens
if (previousNumber in locale.specialTeenNames) {
result = locale.specialTeenNames[previousNumber];
} else if (previousNumber in locale.specialTyNames) {
result = locale.specialTyNames[previousNumber] + locale.teenSuffix;
} else {
result = locale.numberNames[previousNumber] + locale.teenSuffix;
}
} else if (number == 0) { // previousNumber was not handled in teens
result = locale.numberNames[previousNumber.toString()];
} else { // other tys
if (number in locale.specialTyNames) {
result = locale.specialTyNames[number];
} else {
result = locale.numberNames[number];
}
result += locale.powerNames[1];
if (previousNumber != 0) {
result += " " + locale.numberNames[previousNumber.toString()];
}
}
return result;
}
Finally, locale examples:
var locale = { // English
numberNames: {1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine" },
powerNames: {0: "", 1: "ty", 2: " hundred", 3: " thousand" },
specialTeenNames: {0: "ten", 1: "eleven", 2: "twelve" },
specialTyNames: {2: "twen", 3: "thir", 5: "fif" },
teenSuffix: "teen"
};
var locale = { // Estonian
numberNames: {1: "üks", 2: "kaks", 3: "kolm", 4: "neli", 5: "viis", 6: "kuus", 7: "seitse", 8: "kaheksa", 9: "üheksa"},
powerNames: {0: "", 1: "kümmend", 2: "sada", 3: " tuhat" },
specialTeenNames: {0: "kümme"},
specialTyNames: {},
teenSuffix: "teist"
};
Here's a JSFiddle with tests: https://jsfiddle.net/rcrxna7v/15/
I think tir38's answer is the cleanest solution. Have in mind that if you are using android.app.AlerDialog and holo themes your style should look like this
<style name="WrapEverythingDialog" parent=[holo theme ex. android:Theme.Holo.Dialog]>
<item name="windowMinWidthMajor">0dp</item>
<item name="windowMinWidthMinor">0dp</item>
</style>
And if using support.v7.app.AlertDialog or androidx.appcompat.app.AlertDialog with AppCompat theme your style should look like this
<style name="WrapEverythingDialog" parent=[Appcompat theme ex. Theme.AppCompat.Light.Dialog.Alert]>
<item name="android:windowMinWidthMajor">0dp</item>
<item name="android:windowMinWidthMinor">0dp</item>
</style>
For old g++ compiler, you can do this
template <class T, size_t N>
char (&helper(T (&)[N]))[N];
#define arraysize(array) (sizeof(helper(array)))
int main() {
int a[10];
std::cout << arraysize(a) << std::endl;
return 0;
}
This works as you wish:
<html>
<head>
<style type="text/css">
ul
{
overflow-x:hidden;
white-space:nowrap;
height: 1em;
width: 100%;
}
li
{
display:inline;
}
</style>
</head>
<body>
<ul>
<li>abcdefghijklmonpqrstuvwxyz</li>
<li>abcdefghijklmonpqrstuvwxyz</li>
<li>abcdefghijklmonpqrstuvwxyz</li>
<li>abcdefghijklmonpqrstuvwxyz</li>
<li>abcdefghijklmonpqrstuvwxyz</li>
<li>abcdefghijklmonpqrstuvwxyz</li>
<li>abcdefghijklmonpqrstuvwxyz</li>
</ul>
</body>
</html>
The reader acts like a generator. On a file with some fake data:
>>> import sys, csv
>>> data = csv.reader(open('data.csv'),delimiter=';')
>>> data
<_csv.reader object at 0x1004a11a0>
>>> data.next()
['a', ' b', ' c']
>>> data.next()
['x', ' y', ' z']
>>> data.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Using operator.itemgetter as Ignacio suggests:
>>> data = csv.reader(open('data.csv'),delimiter=';')
>>> import operator
>>> sortedlist = sorted(data, key=operator.itemgetter(2), reverse=True)
>>> sortedlist
[['x', ' y', ' z'], ['a', ' b', ' c']]
You can update your python version to 3.8 in conda using the command
conda install -c anaconda python=3.8
as per https://anaconda.org/anaconda/python. Though not all packages support 3.8 yet, running
conda update --all
may resolve some dependency failures. You can also create a new environment called py38 using this command
conda create -n py38 python=3.8
Edit - note that the conda install
option will potentially take a while to solve the environment, and if you try to abort this midway through you will lose your Python installation (usually this means it will resort to non-conda pre-installed system Python installation).
The following worked for me.
var temp = ctx.Set<DbTable>()
.GroupBy(g => new { g.id })
.ToDictionary(d => d.Key.id);
This will get what you want in plain JS.
var el = document.getElementById('*spaM4');
text = (el.innerText || el.textContent);
When you want to have cross component interaction, then you need to know what are @Input , @Output , EventEmitter and Subjects.
If the relation between components is parent- child or vice versa we use @input & @output with event emitter..
@output emits an event and you need to emit using event emitter.
If it's not parent child relationship.. then you have to use subjects or through a common service.
The simplest way would be to inject the following object where you need to initiate the shutdown
ShutdownManager.java
import org.springframework.context.ApplicationContext;
import org.springframework.boot.SpringApplication;
@Component
class ShutdownManager {
@Autowired
private ApplicationContext appContext;
/*
* Invoke with `0` to indicate no error or different code to indicate
* abnormal exit. es: shutdownManager.initiateShutdown(0);
**/
public void initiateShutdown(int returnCode){
SpringApplication.exit(appContext, () -> returnCode);
}
}
you can create a arraylist, and use Collection.addAll()
to convert the string array to your arraylist
If you also get the key, you can delete that item like this:
foreach ($display_related_tags as $key => $tag_name) {
if($tag_name == $found_tag['name']) {
unset($display_related_tags[$key]);
}
}
Object.defineProperty(Results, "Active", {value : 'true',
writable : true,
enumerable : true,
configurable : true});
You could use javascript. The other answers to date seem to also target Safari.
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
alert("You'll only see this in Chrome");
$('#someID').css('background-position', '10px 20px');
}
<form id="uploadForm" class="disp-inline" role="form" action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file">
</form>
<button onclick="checkSize();"></button>
<script>
function checkSize(){
var size = $('#uploadForm')["0"].firstChild.files["0"].size;
console.log(size);
}
</script>
I found this to be the easiest if you don't plan on submitted the form through standard ajax / html5 methods, but of course it works with anything.
NOTES:
var size = $('#uploadForm')["0"]["0"].files["0"].size;
This used to work, but it doesn't in chrome anymore, i just tested the code above and it worked in both ff and chrome (lastest). The second ["0"] is now firstChild.
Try adding in log4j.xml
<!-- enable query logging -->
<category name="org.springframework.jdbc.core.JdbcTemplate">
<priority value="DEBUG" />
</category>
<!-- enable query logging for SQL statement parameter value -->
<category name="org.springframework.jdbc.core.StatementCreatorUtils">
<priority value="TRACE" />
</category>
your logs looks like:
DEBUG JdbcTemplate:682 - Executing prepared SQL query
DEBUG JdbcTemplate:616 - Executing prepared SQL statement [your sql query]
TRACE StatementCreatorUtils:228 - Setting SQL statement parameter value: column index 1, parameter value [param], value class [java.lang.String], SQL type unknown
It is a generic type parameter, see Generics documentation.
T
is not a reserved keyword. T
, or any given name, means a type parameter. Check the following method (just as a simple example).
T GetDefault<T>()
{
return default(T);
}
Note that the return type is T
. With this method you can get the default value of any type by calling the method as:
GetDefault<int>(); // 0
GetDefault<string>(); // null
GetDefault<DateTime>(); // 01/01/0001 00:00:00
GetDefault<TimeSpan>(); // 00:00:00
.NET uses generics in collections, ... example:
List<int> integerList = new List<int>();
This way you will have a list that only accepts integers, because the class is instancited with the type T
, in this case int
, and the method that add elements is written as:
public class List<T> : ...
{
public void Add(T item);
}
Some more information about generics.
You can limit the scope of the type T
.
The following example only allows you to invoke the method with types that are classes:
void Foo<T>(T item) where T: class
{
}
The following example only allows you to invoke the method with types that are Circle
or inherit from it.
void Foo<T>(T item) where T: Circle
{
}
And there is new()
that says you can create an instance of T
if it has a parameterless constructor. In the following example T
will be treated as Circle
, you get intellisense...
void Foo<T>(T item) where T: Circle, new()
{
T newCircle = new T();
}
As T
is a type parameter, you can get the object Type
from it. With the Type
you can use reflection...
void Foo<T>(T item) where T: class
{
Type type = typeof(T);
}
As a more complex example, check the signature of ToDictionary
or any other Linq method.
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);
There isn't a T
, however there is TKey
and TSource
. It is recommended that you always name type parameters with the prefix T
as shown above.
You could name TSomethingFoo
if you want to.
You can try progress bar instead of seek bar
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_marginBottom="35dp"
/>
You can use jquery.chosen or bootstrap-select to add style to your buttons.Both work great. Caveat for Using Chosen or bootstrap-select: they both hide the original select and add in their own div with its own ID. If you are using jquery.validate along with this, for instance, it wont find the original select to do its validation on because it has been renamed.
A beautiful gem in this closed question:
The "oneliner way", altering neither of the input dicts, is
basket = dict(basket_one, **basket_two)
Learn what **basket_two
(the **
) means here.
In case of conflict, the items from basket_two
will override the ones from basket_one
. As one-liners go, this is pretty readable and transparent, and I have no compunction against using it any time a dict that's a mix of two others comes in handy (any reader who has trouble understanding it will in fact be very well served by the way this prompts him or her towards learning about dict
and the **
form;-). So, for example, uses like:
x = mungesomedict(dict(adict, **anotherdict))
are reasonably frequent occurrences in my code.
Originally submitted by Alex Martelli
Note: In Python 3, this will only work if every key in basket_two is a string
.
# modules to easily set characters and iterate over them
import itertools, string
# character limit so you don't run out of ram
maxChar = int(input('Character limit for password: '))
# file to save output to, so you can look over the output without using so much ram
output_file = open('insert filepath here', 'a+')
# this is the part that actually iterates over the valid characters, and stops at the
# character limit.
x = list(map(''.join, itertools.permutations(string.ascii_lowercase, maxChar)))
# writes the output of the above line to a file
output_file.write(str(x))
# saves the output to the file and closes it to preserve ram
output_file.close()
I piped the output to a file to save ram, and used the input function so you can set the character limit to something like "hiiworld". Below is the same script but with a more fluid character set using letters, numbers, symbols, and spaces.
import itertools, string
maxChar = int(input('Character limit for password: '))
output_file = open('insert filepath here', 'a+')
x = list(map(''.join, itertools.permutations(string.printable, maxChar)))
x.write(str(x))
x.close()
You need to use regular expressions to identify the unwanted characters. For the most easily readable code, you want the str_replace_all
from the stringr
package, though gsub
from base R works just as well.
The exact regular expression depends upon what you are trying to do. You could just remove those specific characters that you gave in the question, but it's much easier to remove all punctuation characters.
x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=" #or whatever
str_replace_all(x, "[[:punct:]]", " ")
(The base R equivalent is gsub("[[:punct:]]", " ", x)
.)
An alternative is to swap out all non-alphanumeric characters.
str_replace_all(x, "[^[:alnum:]]", " ")
Note that the definition of what constitutes a letter or a number or a punctuatution mark varies slightly depending upon your locale, so you may need to experiment a little to get exactly what you want.
If you have Pillow
installed with scipy
and it is still giving you error then check your scipy
version because it has been removed from scipy since 1.3.0rc1
.
rather install scipy 1.1.0
by :
pip install scipy==1.1.0
check https://github.com/scipy/scipy/issues/6212
The method imread
in scipy.misc
requires the forked package of PIL
named Pillow
. If you are having problem installing the right version of PIL try using imread
in other packages:
from matplotlib.pyplot import imread
im = imread(image.png)
To read jpg
images without PIL
use:
import cv2 as cv
im = cv.imread(image.jpg)
You can try
from scipy.misc.pilutil import imread
instead of from scipy.misc import imread
Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.
The answer is only valid if you have not changed the "Sketchbook Location" field in Preferences. So, first, you need to open the Arduino IDE and go to the menu
"File -> Preferences"
In the dialog, look at the field "Sketchbook Location" and open the corresponding folder. The "libraries" folder in inside.
Depends on the database server. MySQL
doesn't care, its basically the same thing.
Oracle
, DB2
, and other enterprise level database solutions make a distinction. Usually a schema is a collection of tables and a Database is a collection of schemas.
You should create a custom exception that prototypically inherits from Error. For example:
function InvalidArgumentException(message) {
this.message = message;
// Use V8's native method if available, otherwise fallback
if ("captureStackTrace" in Error)
Error.captureStackTrace(this, InvalidArgumentException);
else
this.stack = (new Error()).stack;
}
InvalidArgumentException.prototype = Object.create(Error.prototype);
InvalidArgumentException.prototype.name = "InvalidArgumentException";
InvalidArgumentException.prototype.constructor = InvalidArgumentException;
This is basically a simplified version of what disfated posted above with the enhancement that stack traces work on Firefox and other browsers. It satisfies the same tests that he posted:
Usage:
throw new InvalidArgumentException();
var err = new InvalidArgumentException("Not yet...");
And it will behave is expected:
err instanceof InvalidArgumentException // -> true
err instanceof Error // -> true
InvalidArgumentException.prototype.isPrototypeOf(err) // -> true
Error.prototype.isPrototypeOf(err) // -> true
err.constructor.name // -> InvalidArgumentException
err.name // -> InvalidArgumentException
err.message // -> Not yet...
err.toString() // -> InvalidArgumentException: Not yet...
err.stack // -> works fine!
127.0.0.1
is normally the IP address assigned to the "loopback" or local-only interface. This is a "fake" network adapter that can only communicate within the same host. It's often used when you want a network-capable application to only serve clients on the same host. A process that is listening on 127.0.0.1
for connections will only receive local connections on that socket.
"localhost" is normally the hostname for the 127.0.0.1
IP address. It's usually set in /etc/hosts
(or the Windows equivalent named "hosts" somewhere under %WINDIR%
). You can use it just like any other hostname - try "ping localhost" to see how it resolves to 127.0.0.1
.
0.0.0.0
has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0
that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1
from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0
will accept connections on that interface too.
That hopefully answers the IP side of your question. I'm not familiar with Jekyll or Vagrant, but I'm guessing that your port forwarding 8080 => 4000
is somehow bound to a particular network adapter, so it isn't in the path when you connect locally to 127.0.0.1
Slightly more compact:
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)
Note:
sort
has been deprecated, replaced by sort_index
for this scenarioinplace
as it is usually harder to read and prevents chaining. See explanation in answer here:
Pandas: peculiar performance drop for inplace rename after dropnaFor C#:
driver.Manage().Window.Maximize();
For Java:
driver.manage().window().maximize();
For a .NET Core 2.0 console app, I did the following:
{ "myKey1" : "my test value 1", "myKey2" : "my test value 2", "foo" : "bar" }
Configure to copy the file to the output directory whenever the project is built (in VS -> Solution Explorer -> right-click file -> select 'Properties' -> Advanced -> Copy to Output Directory -> select 'Copy Always')
Install the following nuget package in my project:
Add the following to Program.cs (or wherever Main()
is located):
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
// rest of code...
}
Then read the values using either of the following ways:
string myKey1 = configuration["myKey1"];
Console.WriteLine(myKey1);
string foo = configuration.GetSection("foo").Value;
Console.WriteLine(foo);
The Integer.toString(size)
call converts into the char representation of your integer, i.e. the char '5'
. The ASCII representation of that character is the value 65.
You need to parse the string back to an integer value first, e.g. by using Integer.parseInt
, to get back the original int value.
As a bottom line, for a signed/unsigned conversion, it is best to leave String
out of the picture and use bit manipulation as @JB suggests.
You can download language pack and use "Install or Uninstall display languages" wizard. To do this:
Win+R
, paste lpksetup
and press Enter
Install display languages
buttonBrowse
and pick the *.cab file of the MUI language you downloadedFrom Sql Server 2008 you have "date" format.
So you can use
SELECT * FROM LOGS WHERE CONVERT(date,[CHECK_IN]) BETWEEN '2013-10-18' AND '2013-10-18'
https://docs.microsoft.com/en-us/sql/t-sql/data-types/date-transact-sql
A simple, easy, hands-on, way to get you out of hot water, especially if you're not so comfortable with git:
View the log of your file
git log myFile.js
commit 1023057173029091u23f01w276931f7f42595f84f Author: kmiklas Date: Tue Aug 7 09:29:34 2018 -0400
JIRA-12345 - Refactor with new architecture.
Note hash of file:
1023057173029091u23f01w276931f7f42595f84f
Show the file using the hash. Make sure it's what you want:
git show 1023057173029091u23f01w276931f7f42595f84f:./myFile.js
Redirect file to a local copy
git show 1023057173029091u23f01w276931f7f42595f84f:./myFile.js > myFile.07aug2018.js
Back up your current file.
cp myFile.js myFile.bak.js
Open both files in your favorite text editor.
vim myFile.js
vim myFile.07aug2018.js
Copy n' paste code from myFile.07aug2018.js to myFile.js, and save.
Commit and push myFile.js
Again view the log, and confirm that your file is properly in place.
Tell your clients to pull the latest, happily watch it work with the old version in place.
Not the sexiest, or most git-centric solution, and definitely a "manual" reset/reversion, but it works. It requires minimal knowledge of git, and doesn't disturb the commit history.
I don't think this is allowed by most browsers for security reasons, in a pure JavaScript context as the question asks.
After trying the other suggestions to no avail I discovered that this issue was related to styling for me. I don't know a lot about the why but I found that my SVGs were not visible because they were not holding their place in the DOM.
In essence, the containers around my SVGs were at width: 0 and overflow: hidden.
I fixed this by setting a width on the containers but it is possible that there is a more direct solution to that particular issue.
with()
is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.
Example:
User > hasMany > Post
$users = User::with('posts')->get();
foreach($users as $user){
$users->posts; // posts is already loaded and no additional DB query is run
}
has()
is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation')
that means you only want to get the models that have at least one related model in this relation.
Example:
User > hasMany > Post
$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection
whereHas()
works basically the same as has()
but allows you to specify additional filters for the related model to check.
Example:
User > hasMany > Post
$users = User::whereHas('posts', function($q){
$q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned
Expanding on @Kiran's answer, which I agree is more succinct and Pythonic, this adds codecs to support the reading and writing of UTF-8:
import codecs
from tempfile import mkstemp
from shutil import move
from os import remove
def replace(source_file_path, pattern, substring):
fh, target_file_path = mkstemp()
with codecs.open(target_file_path, 'w', 'utf-8') as target_file:
with codecs.open(source_file_path, 'r', 'utf-8') as source_file:
for line in source_file:
target_file.write(line.replace(pattern, substring))
remove(source_file_path)
move(target_file_path, source_file_path)
One way for me to understand wildcards is to think that the wildcard isn't specifying the type of the possible objects that given generic reference can "have", but the type of other generic references that it is is compatible with (this may sound confusing...) As such, the first answer is very misleading in it's wording.
In other words, List<? extends Serializable>
means you can assign that reference to other Lists where the type is some unknown type which is or a subclass of Serializable. DO NOT think of it in terms of A SINGLE LIST being able to hold subclasses of Serializable (because that is incorrect semantics and leads to a misunderstanding of Generics).
The example below is an adaptation and simplification of a longer post from We ? Swift. This is what it will look like:
It can be just the usual Single View Application.
Replace the ViewController.swift code with the following:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// Data model: These strings will be the data for the table view cells
let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
// cell reuse id (cells that scroll out of view can be reused)
let cellReuseIdentifier = "cell"
// don't forget to hook this up from the storyboard
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Register the table view cell class and its reuse id
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
// (optional) include this line if you want to remove the extra empty cell divider lines
// self.tableView.tableFooterView = UIView()
// This view controller itself will provide the delegate methods and row data for the table view.
tableView.delegate = self
tableView.dataSource = self
}
// number of rows in table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.animals.count
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// create a new cell if needed or reuse an old one
let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
// set the text from the data model
cell.textLabel?.text = self.animals[indexPath.row]
return cell
}
// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You tapped cell number \(indexPath.row).")
}
}
Read the in-code comments to see what is happening. The highlights are
UITableViewDelegate
and UITableViewDataSource
protocols.numberOfRowsInSection
method determines how many rows there will be in the table view.cellForRowAtIndexPath
method sets up each row.didSelectRowAtIndexPath
method is called every time a row is tapped.Drag a UITableView
onto your View Controller. Use auto layout to pin the four sides.
Control drag from the Table View in IB to the tableView
outlet in the code.
That's all. You should be able run your app now.
This answer was tested with Xcode 9 and Swift 4
Row Deletion
You only have to add a single method to the basic project above if you want to enable users to delete rows. See this basic example to learn how.
Row Spacing
If you would like to have spacing between your rows, see this supplemental example.
Custom cells
The default layout for the table view cells may not be what you need. Check out this example to help get you started making your own custom cells.
Dynamic Cell Height
Sometimes you don't want every cell to be the same height. Starting with iOS 8 it is easy to automatically set the height depending on the cell content. See this example for everything you need to get you started.
In JavaScript (via jQuery):
$(function() {_x000D_
$("body").click(function(e) {_x000D_
if (e.target.id == "myDiv" || $(e.target).parents("#myDiv").length) {_x000D_
alert("Inside div");_x000D_
} else {_x000D_
alert("Outside div");_x000D_
}_x000D_
});_x000D_
})
_x000D_
#myDiv {_x000D_
background: #ff0000;_x000D_
width: 25vw;_x000D_
height: 25vh;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="myDiv"></div>
_x000D_
Canvas would be a great way to do this, as @pst said above. Check out this answer for a good example:
Some code that would serve you specifically as well:
var imgd = context.getImageData(x, y, width, height);
var pix = imgd.data;
for (var i = 0, n = pix.length; i < n; i += 4) {
console.log pix[i+3]
}
This will go row by row, so you'd need to convert that into an x,y and either convert the for loop to a direct check or run a conditional inside.
Reading your question again, it looks like you want to be able to get the point that the person clicks on. This can be done pretty easily with jquery's click event. Just run the above code inside a click handler as such:
$('el').click(function(e){
console.log(e.clientX, e.clientY)
}
Those should grab your x and y values.
I had this issue although data length was shorter than the field length. It turned out that the problem was having another log table (for audit trail), filled by a trigger on the main table, where the column size also had to be changed.
I wonder, why nobody yet mentioned this possibility:
::listen(port)
with string (intentionally or not), which wouldn't be a valid port number representation, it then can be internally converted to port number -1
, ant then engine will try to connect to that -1
port, which then yields the same EADDRINUSE
error, which in turn might be slightly confusing and turn you in the wrong direction for error fix search (hi, me xD).So, debug your code and check what exactly you pass to functions, before starting to check for the processes, that are using your port.
Since this question is gaining lots of views and this was the accepted answer, I felt the need to add the following disclaimer:
This answer was specific to the OP's question (Which had the width set in the examples). While it works, it requires you to have a width on each of the elements, the image and the paragraph. Unless that is your requirement, I recommend using Joe Conlin's solution which is posted as another answer on this question.
The span
element is an inline element, you can't change its width in CSS.
You can add the following CSS to your span so you will be able to change its width.
display: block;
Another way, which usually makes more sense, is to use a <p>
element as a parent for your <span>
.
<li id="CN2787">
<img class="fav_star" src="images/fav.png">
<p>
<span>Text, text and more text</span>
</p>
</li>
Since <p>
is a block
element, you can set its width using CSS, without having to change anything.
But in both cases, since you have a block element now, you will need to float the image so that your text doesn't all go below your image.
li p{width: 100px; margin-left: 20px}
.fav_star {width: 20px;float:left}
P.S. Instead of float:left
on the image, you can also put float:right
on li p
but in that case, you will also need text-align:left
to realign the text correctly.
P.S.S. If you went ahead with the first solution of not adding a <p>
element, your CSS should look like so:
li span{width: 100px; margin-left: 20px;display:block}
.fav_star {width: 20px;float:left}
This function returns an array regardless of the size of the range.
Ranges will return an array unless the range is only 1 cell and then it returns a single value instead. This function will turn the single value into an array (1 based, the same as the array's returned by ranges)
This answer improves on previous answers as it will return an array from a range no matter what the size. It is also more efficient that other answers as it will return the array generated by the range if possible. Works with single dimension and multi-dimensional arrays
The function works by trying to find the upper bounds of the array. If that fails then it must be a single value so we'll create an array and assign the value to it.
Public Function RangeToArray(inputRange As Range) As Variant()
Dim size As Integer
Dim inputValue As Variant, outputArray() As Variant
' inputValue will either be an variant array for ranges with more than 1 cell
' or a single variant value for range will only 1 cell
inputValue = inputRange
On Error Resume Next
size = UBound(inputValue)
If Err.Number = 0 Then
RangeToArray = inputValue
Else
On Error GoTo 0
ReDim outputArray(1 To 1, 1 to 1)
outputArray(1,1) = inputValue
RangeToArray = outputArray
End If
On Error GoTo 0
End Function
enum for error code/message definition is still a nice solution though it has a i18n concerns. Actually we may have two situations: the code/message is displayed to the end user or to the system integrator. For the later case, I18N is not necessary. I think the web services is most likely the later case.
If you're on Cygwin this command will show you the locations:
mysql --help |grep -A1 Default|grep my
$about->first()->id
or
$stm->first()->title
and your problem is sorted out.
First, build -> clean project -> rebuild it again.
If its not working, then in your build.gradle
, set the multiDexEnabled
as true
eg:
defaultConfig {
applicationId "com.example.myapplication"
minSdkVersion 21
targetSdkVersion 27
multiDexEnabled true
versionCode 1
versionName "1.0"
testInstrumentationRunner"android.support.test.runner.AndroidJUnitRunner"
}
In my case it was the problem of building the extension, I was pointing at an extension src (with manifest and everything) but without a build.
If you run into this scenario run
npm i
then
npm build
There's a flag for that:
In [11]: df = pd.DataFrame([["foo1"], ["foo2"], ["bar"], [np.nan]], columns=['a'])
In [12]: df.a.str.contains("foo")
Out[12]:
0 True
1 True
2 False
3 NaN
Name: a, dtype: object
In [13]: df.a.str.contains("foo", na=False)
Out[13]:
0 True
1 True
2 False
3 False
Name: a, dtype: bool
See the str.replace
docs:
na : default NaN, fill value for missing values.
So you can do the following:
In [21]: df.loc[df.a.str.contains("foo", na=False)]
Out[21]:
a
0 foo1
1 foo2
I am working on a MVC5/Web API project and needed to be able to get authorization for the Web Api methods. When my index view is first loaded I make a call to the 'token' Web API method which I believe is created automatically.
The client side code (CoffeeScript) to get the token is:
getAuthenticationToken = (username, password) ->
dataToSend = "username=" + username + "&password=" + password
dataToSend += "&grant_type=password"
$.post("/token", dataToSend).success saveAccessToken
If successful the following is called, which saves the authentication token locally:
saveAccessToken = (response) ->
window.authenticationToken = response.access_token
Then if I need to make an Ajax call to a Web API method that has the [Authorize] tag I simply add the following header to my Ajax call:
{ "Authorization": "Bearer " + window.authenticationToken }
The easiest way to use PhantomJS in python is via Selenium. The simplest installation method is
npm -g install phantomjs-prebuilt
After installation, you may use phantom as simple as:
from selenium import webdriver
driver = webdriver.PhantomJS() # or add to your PATH
driver.set_window_size(1024, 768) # optional
driver.get('https://google.com/')
driver.save_screenshot('screen.png') # save a screenshot to disk
sbtn = driver.find_element_by_css_selector('button.gbqfba')
sbtn.click()
If your system path environment variable isn't set correctly, you'll need to specify the exact path as an argument to webdriver.PhantomJS()
. Replace this:
driver = webdriver.PhantomJS() # or add to your PATH
... with the following:
driver = webdriver.PhantomJS(executable_path='/usr/local/lib/node_modules/phantomjs/lib/phantom/bin/phantomjs')
References:
It is possible that you compiled your binary with incompatible architecture settings on your build host vs. your execution host. Can you please have a look at the enabled target settings via
g++ {all-your-build-flags-here} -Q -v --help=target
on your build host? In particular, the COLLECT_GCC_OPTIONS
variable may give you valuable debug info. Then have a look at the CPU capabilities on your execution host via
cat /proc/cpuinfo | grep -m1 flags
Look out for mismatches such as -msse4.2 [enabled]
on your build host but a missing sse4_2
flag in the CPU capabilities.
If that doesn't help, please provide the output of ldd commonKT
on both build and execution host.
in a Visual Basic Macro you would use
pName = ActiveWorkbook.Path ' the path of the currently active file
wbName = ActiveWorkbook.Name ' the file name of the currently active file
shtName = ActiveSheet.Name ' the name of the currently selected worksheet
The first sheet in a workbook can be referenced by
ActiveWorkbook.Worksheets(1)
so after deleting the [Report] tab you would use
ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name
to "work on that sheet later on" you can create a range object like
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]
and continue working on MySheet(rowNum, colNum)
etc. ...
shortcut creation of a range object without defining shtName:
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]
dog.ts
import b = require('./baseTypes');
export module Living.Things {
// Error, can't find name 'Animal', ??
// Solved: can find, if properly referenced; exporting modules is useless, anyhow
export class Dog extends b.Living.Things.Animal {
public woof(): void {
return;
}
}
}
tree.ts
// Error, can't use the same name twice, ??
// Solved: cannot declare let or const variable twice in same scope either: just use a different name
import b = require('./baseTypes');
import d = require('./dog');
module Living.Things {
// Why do I have to write b.Living.Things.Plant instead of b.Plant??
class Tree extends b.Living.Things.Plant {
}
}
AFAIK the simplest solution is:
df_shuffled = df.reindex(np.random.permutation(df.index))
The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.
If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.
I think you want \b\w{1,10}\b
. The \b
matches a word boundary.
Of course, you could also replace the \b
and do ^\w{1,10}$
. This will match a word of at most 10 characters as long as its the only contents of the string. I think this is what you were doing before.
Since it's Java, you'll actually have to escape the backslashes: "\\b\\w{1,10}\\b"
. You probably knew this already, but it's gotten me before.
you can also do something more specific like that based on Anthony Artemiew's response:
<View style={globalStyles.searchSection}>
<TextInput
style={globalStyles.input}
placeholder="Rechercher"
onChangeText={(searchString) =>
{this.setState({searchString})}}
underlineColorAndroid="transparent"
/>
<Ionicons onPress={()=>console.log('Recherche en cours...')} style={globalStyles.searchIcon} name="ios-search" size={30} color="#1764A5"/>
</View>
Style:
searchSection: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
borderRadius:50,
marginLeft:35,
width:340,
height:40,
margin:25
},
searchIcon: {
padding: 10,
},
input: {
flex: 1,
paddingTop: 10,
paddingRight: 10,
paddingBottom: 10,
paddingLeft: 0,
marginLeft:10,
borderTopLeftRadius:50,
borderBottomLeftRadius:50,
backgroundColor: '#fff',
color: '#424242',
},
"The $.browser property is deprecated in jQuery 1.3, and its functionality may be moved to a team-supported plugin in a future release of jQuery."
nchar requires more space than nvarchar.
eg,
A nchar(100) will always store 100 characters even if you only enter 5, the remaining 95 chars will be padded with spaces. Storing 5 characters in a nvarchar(100) will save 5 characters.
A Session object is basically an ongoing transaction of changes to a database (update, insert, delete). These operations aren't persisted to the database until they are committed (if your program aborts for some reason in mid-session transaction, any uncommitted changes within are lost).
The session object registers transaction operations with session.add()
, but doesn't yet communicate them to the database until session.flush()
is called.
session.flush()
communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction. The changes aren't persisted permanently to disk, or visible to other transactions until the database receives a COMMIT for the current transaction (which is what session.commit()
does).
session.commit()
commits (persists) those changes to the database.
flush()
is always called as part of a call to commit()
(1).
When you use a Session object to query the database, the query will return results both from the database and from the flushed parts of the uncommitted transaction it holds. By default, Session objects autoflush
their operations, but this can be disabled.
Hopefully this example will make this clearer:
#---
s = Session()
s.add(Foo('A')) # The Foo('A') object has been added to the session.
# It has not been committed to the database yet,
# but is returned as part of a query.
print 1, s.query(Foo).all()
s.commit()
#---
s2 = Session()
s2.autoflush = False
s2.add(Foo('B'))
print 2, s2.query(Foo).all() # The Foo('B') object is *not* returned
# as part of this query because it hasn't
# been flushed yet.
s2.flush() # Now, Foo('B') is in the same state as
# Foo('A') was above.
print 3, s2.query(Foo).all()
s2.rollback() # Foo('B') has not been committed, and rolling
# back the session's transaction removes it
# from the session.
print 4, s2.query(Foo).all()
#---
Output:
1 [<Foo('A')>]
2 [<Foo('A')>]
3 [<Foo('A')>, <Foo('B')>]
4 [<Foo('A')>]
also you can use "AND" instead of "OR" if you want both attributes to be applied.
select * from tickets where (assigned_to='1') and (status='open') order by created_at desc;