printf("\nmaximum of %d and %d is = %d",a,b,c);
If you really, really want to use strlen(), then
cout << strlen(str.c_str()) << endl;
else the use of .length() is more in keeping with C++.
conio.h
is a C
header file used in old MS-DOS compilers to create text user interfaces. Compilers that targeted non-DOS operating systems, such as Linux, Win32 and OS/2, provided different implementations of these functions.
The #include <curses.h>
will give you almost all the functionalities that was provided in conio.h
nucurses need to be installed at the first place
In deb based Distros use
sudo apt-get install libncurses5-dev libncursesw5-dev
And in rpm based distros use
sudo yum install ncurses-devel ncurses
For getch()
class of functions, you can try this
At the time the compiler encounters the call to swapCase in main(), it does not know about the function swapCase, so it reports an error. You can either move the definition of swapCase above main, or declare swap case above main:
void swapCase(char* name);
Also, the 32 in swapCase causes the reader to pause and wonder. The comment helps! In this context, it would add clarity to write
if ('A' <= name[i] && name[i] <= 'Z')
name[i] += 'a' - 'A';
else if ('a' <= name[i] && name[i] <= 'z')
name[i] += 'A' - 'a';
The construction in my if-tests is a matter of personal style. Yours were just fine. The main thing is the way to modify name[i] -- using the difference in 'a' vs. 'A' makes it more obvious what is going on, and nobody has to wonder if the '32' is actually correct.
Good luck learning!
#include <termios.h>
#include <stdio.h>
static struct termios old, current;
/* Initialize new terminal i/o settings */
void initTermios(int echo)
{
tcgetattr(0, &old); /* grab old terminal i/o settings */
current = old; /* make new settings same as old settings */
current.c_lflag &= ~ICANON; /* disable buffered i/o */
if (echo) {
current.c_lflag |= ECHO; /* set echo mode */
} else {
current.c_lflag &= ~ECHO; /* set no echo mode */
}
tcsetattr(0, TCSANOW, ¤t); /* use these new terminal i/o settings now */
}
/* Restore old terminal i/o settings */
void resetTermios(void)
{
tcsetattr(0, TCSANOW, &old);
}
/* Read 1 character - echo defines echo mode */
char getch_(int echo)
{
char ch;
initTermios(echo);
ch = getchar();
resetTermios();
return ch;
}
/* Read 1 character without echo */
char getch(void)
{
return getch_(0);
}
/* Read 1 character with echo */
char getche(void)
{
return getch_(1);
}
/* Let's test it out */
int main(void) {
char c;
printf("(getche example) please type a letter: ");
c = getche();
printf("\nYou typed: %c\n", c);
printf("(getch example) please type a letter...");
c = getch();
printf("\nYou typed: %c\n", c);
return 0;
}
Output:
(getche example) please type a letter: g
You typed: g
(getch example) please type a letter...
You typed: g
From 5.2.2/2 (character display semantics) :
\b
(backspace) Moves the active position to the previous position on the current line. If the active position is at the initial position of a line, the behavior of the display device is unspecified.
\n
(new line) Moves the active position to the initial position of the next line.
\r
(carriage return) Moves the active position to the initial position of the current line.
Here, your code produces :
<new_line>ab
\b
: back one charactersi
: overrides the b
with s
(producing asi
on the second line)\r
: back at the beginning of the current lineha
: overrides the first two characters (producing hai
on the second line)In the end, the output is :
\nhai
fscanf
will treat 2 arguments, and thus return 2. Your while statement will be false, hence never displaying what has been read, plus as it has read only 1 line, if is not at EOF, resulting in what you see.
use driver.findElement(By.partialLinkText("long")).click();
Try the following
typeField == typeof(string)
typeField == typeof(DateTime)
The typeof
operator in C# will give you a Type
object for the named type. Type
instances are comparable with the ==
operator so this is a good method for comparing them.
Note: If I remember correctly, there are some cases where this breaks down when the types involved are COM interfaces which are embedded into assemblies (via NoPIA). Doesn't sound like this is the case here.
className={css(styles.mainDiv, 'subContainer')}
This solution is tried and tested in React SPFx.
Also add import statement :
import { css } from 'office-ui-fabric-react/lib/Utilities';
This will be helpful for the right bottom rounded button
HTML :
<a class="fixedButton" href>
<div class="roundedFixedBtn"><i class="fa fa-phone"></i></div>
</a>
CSS:
.fixedButton{
position: fixed;
bottom: 0px;
right: 0px;
padding: 20px;
}
.roundedFixedBtn{
height: 60px;
line-height: 80px;
width: 60px;
font-size: 2em;
font-weight: bold;
border-radius: 50%;
background-color: #4CAF50;
color: white;
text-align: center;
cursor: pointer;
}
Here is jsfiddle link http://jsfiddle.net/vpthcsx8/11/
I have checked all answers and of course I have used phpinfo() to check the exact location of php.ini. I don't see a File option in the menu bar on my mac. I changed both php.ini and php.ini.temp files in that folder. No vail.
Until I realized that I forgot to uncomment the modified always_populate_raw_post_data line.
Spring boot has many starters, some starters have an embedded web server, some don't. The following have the embedded web server:
spring-boot-starter-web
spring-boot-starter-data-jpa
spring-boot-starter-jetty
spring-boot-starter-tomcat
spring-boot-starter-jdbc
spring-boot-starter-data-rest
...
Pick the one that meets your requirements and that does not have server support.
I only need to make restful json api request in my spring application, so the starter I need is
spring-boot-starter-json
which provide RestTemplate
and jackson
for me to use.
EDIT: I just realised after reading your question again, that i did not answer your question. You want to enter multiple lines in the same plot. However, I'll leave it be, because this served me very well multiple times. I hope you find usefull someday
I found this a while back when learning python
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure()
# create figure window
gs = gridspec.GridSpec(a, b)
# Creates grid 'gs' of a rows and b columns
ax = plt.subplot(gs[x, y])
# Adds subplot 'ax' in grid 'gs' at position [x,y]
ax.set_ylabel('Foo') #Add y-axis label 'Foo' to graph 'ax' (xlabel for x-axis)
fig.add_subplot(ax) #add 'ax' to figure
you can make different sizes in one figure as well, use slices in that case:
gs = gridspec.GridSpec(3, 3)
ax1 = plt.subplot(gs[0,:]) # row 0 (top) spans all(3) columns
consult the docs for more help and examples. This little bit i typed up for myself once, and is very much based/copied from the docs as well. Hope it helps... I remember it being a pain in the #$% to get acquainted with the slice notation for the different sized plots in one figure. After that i think it's very simple :)
You can print a native linebreak using the standard os
library
import os
with open('test.txt','w') as f:
f.write(os.linesep)
fscanf
- "On success, the function returns the number of items successfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure.
In the case of an input failure before any data could be successfully read, EOF is returned."
So, instead of doing nothing with the return value like you are right now, you can check to see if it is == EOF
.
You should check for EOF when you call fscanf
, not check the array slot for EOF.
Here is a simple example, it will help you to get object key name.
var obj ={parts:{costPart:1000, salesPart: 2000}};
console.log(Object.keys(obj));
the output would be parts.
You could use PIL to create (and display) an image:
from PIL import Image
import numpy as np
w, h = 512, 512
data = np.zeros((h, w, 3), dtype=np.uint8)
data[0:256, 0:256] = [255, 0, 0] # red patch in upper left
img = Image.fromarray(data, 'RGB')
img.save('my.png')
img.show()
Hi I have a simple solution by using 2 themes
Splash screen theme (add it to the manifest):
<style name="SplashTheme" parent="@android:style/Theme.Holo.NoActionBar">
<item name="android:windowBackground">@color/red</item>
</style>
normal theme (add it in your activity by setTheme(R.style.Theme)):
<style name="Theme" parent="@style/Theme.Holo"> <item name="android:windowBackground">@color/blue</item>
</style>
To support SDK 10:
@Override
public void onCreate(Bundle savedInstanceState) {
setTheme(R.style.Theme);
super.onCreate(savedInstanceState);
...........
...........
}
you can use like this
private dynamic defaultReminder => reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
Add the following to your app build.gradle and select the specified release build variant and run
signingConfigs {
config {
keyAlias 'keyalias'
keyPassword 'keypwd'
storeFile file('<<KEYSTORE-PATH>>.keystore')
storePassword 'pwd'
}
}
buildTypes {
release {
debuggable true
signingConfig signingConfigs.config
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
getArguments() is returning null because "Its doesn't get anything"
Try this code to handle this situation
if(getArguments()!=null)
{
int myInt = getArguments().getInt(key, defaultValue);
}
To be very precise instanceof should be used where value is created via the constructor (generally custom types) for e.g.
var d = new String("abc")
whereas typeof to check values created just by assignments for e.g
var d = "abc"
EDIT Summary and reccomendations
Using a for each cell in range
construct is not in itself slow. What is slow is repeated access to Excel in the loop (be it reading or writing cell values, format etc, inserting/deleting rows etc).
What is too slow depends entierly on your needs. A Sub that takes minutes to run might be OK if only used rarely, but another that takes 10s might be too slow if run frequently.
So, some general advice:
for index = max to min step -1
)value
, you are stuck with cell referenceseg (not tested!)
Dim rngToDelete as range
for each rw in rng.rows
if need to delete rw then
if rngToDelete is nothing then
set rngToDelete = rw
else
set rngToDelete = Union(rngToDelete, rw)
end if
endif
next
rngToDelete.EntireRow.Delete
Original post
Conventional wisdom says that looping through cells is bad and looping through a variant array is good. I too have been an advocate of this for some time. Your question got me thinking, so I did some short tests with suprising (to me anyway) results:
test data set: a simple list in cells A1
.. A1000000
(thats 1,000,000 rows)
Test case 1: loop an array
Dim v As Variant
Dim n As Long
T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
v = r
For n = LBound(v, 1) To UBound(v, 1)
'i = i + 1
'i = r.Cells(n, 1).Value 'i + 1
Next
Debug.Print "Array Time = " & (GetTickCount - T1) / 1000#
Debug.Print "Array Count = " & Format(n, "#,###")
Result:
Array Time = 0.249 sec
Array Count = 1,000,001
Test Case 2: loop the range
T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
For Each c In r
Next c
Debug.Print "Range Time = " & (GetTickCount - T1) / 1000#
Debug.Print "Range Count = " & Format(r.Cells.Count, "#,###")
Result:
Range Time = 0.296 sec
Range Count = 1,000,000
So,looping an array is faster but only by 19% - much less than I expected.
Test 3: loop an array with a cell reference
T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
v = r
For n = LBound(v, 1) To UBound(v, 1)
i = r.Cells(n, 1).Value
Next
Debug.Print "Array Time = " & (GetTickCount - T1) / 1000# & " sec"
Debug.Print "Array Count = " & Format(i, "#,###")
Result:
Array Time = 5.897 sec
Array Count = 1,000,000
Test case 4: loop range with a cell reference
T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
For Each c In r
i = c.Value
Next c
Debug.Print "Range Time = " & (GetTickCount - T1) / 1000# & " sec"
Debug.Print "Range Count = " & Format(r.Cells.Count, "#,###")
Result:
Range Time = 2.356 sec
Range Count = 1,000,000
So event with a single simple cell reference, the loop is an order of magnitude slower, and whats more, the range loop is twice as fast!
So, conclusion is what matters most is what you do inside the loop, and if speed really matters, test all the options
FWIW, tested on Excel 2010 32 bit, Win7 64 bit All tests with
ScreenUpdating
off,Calulation
manual, Events
disabled. The easiest way for me to convert a date was to stringify it then slice it.
var event = new Date("Fri Apr 05 2019 16:59:00 GMT-0700 (Pacific Daylight Time)");
let date = JSON.stringify(event)
date = date.slice(1,11)
// console.log(date) = '2019-04-05'
Enabling Hyper-V in Windows Features solved the problem: Windows Features
No Tracking LINQ to Entities queries
Usage of AsNoTracking() is recommended when your query is meant for read operations. In these scenarios, you get back your entities but they are not tracked by your context.This ensures minimal memory usage and optimal performance
Pros
- Improved performance over regular LINQ queries.
- Fully materialized objects.
- Simplest to write with syntax built into the programming language.
Cons
- Not suitable for CUD operations.
- Certain technical restrictions, such as: Patterns using DefaultIfEmpty for OUTER JOIN queries result in more complex queries than simple OUTER JOIN statements in Entity SQL.
- You still can’t use LIKE with general pattern matching.
More info available here:
Try to look Create constants using a "settings" module? and Can I prevent modifying an object in Python?
Another one useful link: http://code.activestate.com/recipes/65207-constants-in-python/ tells us about the following option:
from copy import deepcopy
class const(object):
def __setattr__(self, name, value):
if self.__dict__.has_key(name):
print 'NO WAY this is a const' # put here anything you want(throw exc and etc)
return deepcopy(self.__dict__[name])
self.__dict__[name] = value
def __getattr__(self, name, value):
if self.__dict__.has_key(name):
return deepcopy(self.__dict__[name])
def __delattr__(self, item):
if self.__dict__.has_key(item):
print 'NOOOOO' # throw exception if needed
CONST = const()
CONST.Constant1 = 111
CONST.Constant1 = 12
print a.Constant1 # 111
CONST.Constant2 = 'tst'
CONST.Constant2 = 'tst1'
print a.Constant2 # 'tst'
So you could create a class like this and then import it from you contants.py module. This will allow you to be sure that value would not be changed, deleted.
No you can't overload it; a static constructor is useful for initializing any static fields associated with a type (or any other per-type operations) - useful in particular for reading required configuration data into readonly fields, etc.
It is run automatically by the runtime the first time it is needed (the exact rules there are complicated (see "beforefieldinit"), and changed subtly between CLR2 and CLR4). Unless you abuse reflection, it is guaranteed to run at most once (even if two threads arrive at the same time).
Here is the same problem.
You need to set table-layout:fixed
and a suitable width on the table element, as well as overflow:hidden
and white-space: nowrap
on the table cells.
The width of the table has to be the same (or smaller) than the fixed width cell(s).
With one fixed width column:
* {
box-sizing: border-box;
}
table {
table-layout: fixed;
border-collapse: collapse;
width: 100%;
max-width: 100px;
}
td {
background: #F00;
padding: 20px;
overflow: hidden;
white-space: nowrap;
width: 100px;
border: solid 1px #000;
}
_x000D_
<table>
<tbody>
<tr>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
</tr>
<tr>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
</tr>
</tbody>
</table>
_x000D_
With multiple fixed width columns:
* {
box-sizing: border-box;
}
table {
table-layout: fixed;
border-collapse: collapse;
width: 100%;
max-width: 200px;
}
td {
background: #F00;
padding: 20px;
overflow: hidden;
white-space: nowrap;
width: 100px;
border: solid 1px #000;
}
_x000D_
<table>
<tbody>
<tr>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
</tr>
<tr>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
</tr>
</tbody>
</table>
_x000D_
A width for the table must be set, but any extra width is simply taken by the fluid cell(s).
With multiple columns, fixed width and fluid width:
* {
box-sizing: border-box;
}
table {
table-layout: fixed;
border-collapse: collapse;
width: 100%;
}
td {
background: #F00;
padding: 20px;
border: solid 1px #000;
}
tr td:first-child {
overflow: hidden;
white-space: nowrap;
width: 100px;
}
_x000D_
<table>
<tbody>
<tr>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
</tr>
<tr>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
</tr>
</tbody>
</table>
_x000D_
I had this problem when the method required a parameter that I was not specifying
You need use Stream to send file (archive) in a response, what is more you have to use appropriate Content-type in your response header.
There is an example function that do it:
const fs = require('fs');
// Where fileName is name of the file and response is Node.js Reponse.
responseFile = (fileName, response) => {
const filePath = "/path/to/archive.rar" // or any file format
// Check if file specified by the filePath exists
fs.exists(filePath, function(exists){
if (exists) {
// Content-type is very interesting part that guarantee that
// Web browser will handle response in an appropriate manner.
response.writeHead(200, {
"Content-Type": "application/octet-stream",
"Content-Disposition": "attachment; filename=" + fileName
});
fs.createReadStream(filePath).pipe(response);
} else {
response.writeHead(400, {"Content-Type": "text/plain"});
response.end("ERROR File does not exist");
}
});
}
}
The purpose of the Content-Type field is to describe the data contained in the body fully enough that the receiving user agent can pick an appropriate agent or mechanism to present the data to the user, or otherwise deal with the data in an appropriate manner.
"application/octet-stream" is defined as "arbitrary binary data" in RFC 2046, purpose of this content-type is to be saved to disk - it is what you really need.
"filename=[name of file]" specifies name of file which will be downloaded.
For more information please see this stackoverflow topic.
I had to add a '.value' to the end of Evert's code to get it working.
Also I combined it with a browser check so that input type="number" field is changed to type="text" in Chrome since 'formnovalidate' doesn't seem to work right now.
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
document.getElementById("input_id").attributes["type"].value = "text";
If you are using Angular CLI: 7.3.3
What I did is, On my assets folder I put my fake json data then on my services I just did this.
const API_URL = './assets/data/db.json';
getAllPassengers(): Observable<PassengersInt[]> {
return this.http.get<PassengersInt[]>(API_URL);
}
if you need to include the key of the document in the response, another alternative is:
async getMarker() {
const snapshot = await firebase.firestore().collection('events').get()
const documents = [];
snapshot.forEach(doc => {
documents[doc.id] = doc.data();
});
return documents;
}
With quotes around the date:
mysql> CALL insertEvent('2012.01.01 12:12:12');
just right click on your project, hover maven then click update project.. done!!
As Pax rightly said, measure, don't guess. That what I did for DNSwitness and the results were suprising: the ideal number of threads was much higher than I thought, something like 15,000 threads to get the fastest results.
Of course, it depends on many things, that's why you must measure yourself.
Complete measures (in French only) in Combien de fils d'exécution ?.
This is a swiss-armyknife function you can use:
function table.find(t, val, recursive, metatables, keys, returnBool)
if (type(t) ~= "table") then
return nil
end
local checked = {}
local _findInTable
local _checkValue
_checkValue = function(v)
if (not checked[v]) then
if (v == val) then
return v
end
if (recursive and type(v) == "table") then
local r = _findInTable(v)
if (r ~= nil) then
return r
end
end
if (metatables) then
local r = _checkValue(getmetatable(v))
if (r ~= nil) then
return r
end
end
checked[v] = true
end
return nil
end
_findInTable = function(t)
for k,v in pairs(t) do
local r = _checkValue(t, v)
if (r ~= nil) then
return r
end
if (keys) then
r = _checkValue(t, k)
if (r ~= nil) then
return r
end
end
end
return nil
end
local r = _findInTable(t)
if (returnBool) then
return r ~= nil
end
return r
end
You can use it to check if a value exists:
local myFruit = "apple"
if (table.find({"apple", "pear", "berry"}, myFruit)) then
print(table.find({"apple", "pear", "berry"}, myFruit)) -- 1
You can use it to find the key:
local fruits = {
apple = {color="red"},
pear = {color="green"},
}
local myFruit = fruits.apple
local fruitName = table.find(fruits, myFruit)
print(fruitName) -- "apple"
I hope the recursive
parameter speaks for itself.
The metatables
parameter allows you to search metatables as well.
The keys
parameter makes the function look for keys in the list. Of course that would be useless in Lua (you can just do fruits[key]
) but together with recursive
and metatables
, it becomes handy.
The returnBool
parameter is a safe-guard for when you have tables that have false
as a key in a table (Yes that's possible: fruits = {false="apple"}
)
you can use SpinUntil which is buildin in the .net-framework. Please note: This method causes high cpu-workload.
The right syntax is like:
SELECT * FROM table1 INNER JOIN table2 ON table1.primaryKey = table2.ForeignKey
INNER JOIN table3 ON table3.primaryKey = table2.ForeignKey
Orthe last line joining table3 on table1 like:
ON table3.ForeignKey= table1.PrimaryKey
In Bootstrap 5, the class btn-block
doesn't work anymore. But instead, you can add the class w-100
to the button to make it as wide as its container.
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<div class="row"><div class=" col-5 ">
<a class="btn btn-outline-primary w-100 " href="# "><span>Button 1</span></a>
</div><div class="col-5 ">
<a class=" btn btn-primary w-100 weiss " href="# "><span>Button 2</span></a>
</div></div>
_x000D_
i geted through the same problem. I my case the table already have data and there were key in this table that was not present in the reference table. So i had to delete this rows that disrespect the constraints and everything worked.
You don't use the :
syntax - pull
always modifies the currently checked-out branch. Thus:
git pull origin my_remote_branch
while you have my_local_branch
checked out will do what you want.
Since you already have the tracking branch set, you don't even need to specify - you could just do...
git pull
while you have my_local_branch
checked out, and it will update from the tracked branch.
C# 7.1 (using vs 2017 update 3) introduces async main
You can write:
static async Task Main(string[] args)
{
await ...
}
For more details C# 7 Series, Part 2: Async Main
Update:
You may get a compilation error:
Program does not contain a static 'Main' method suitable for an entry point
This error is due to that vs2017.3 is configured by default as c#7.0 not c#7.1.
You should explicitly modify the setting of your project to set c#7.1 features.
You can set c#7.1 by two methods:
Method 1: Using the project settings window:
Method2: Modify PropertyGroup of .csproj manually
Add this property:
<LangVersion>7.1</LangVersion>
example:
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
<LangVersion>7.1</LangVersion>
</PropertyGroup>
The difference is quite simple:
OLTP (Online Transaction Processing)
OLTP is a class of information systems that facilitate and manage transaction-oriented applications. OLTP has also been used to refer to processing in which the system responds immediately to user requests. Online transaction processing applications are high throughput and insert or update-intensive in database management. Some examples of OLTP systems include order entry, retail sales, and financial transaction systems.
OLAP (Online Analytical Processing)
OLAP is part of the broader category of business intelligence, which also encompasses relational database, report writing and data mining. Typical applications of OLAP include business reporting for sales, marketing, management reporting, business process management (BPM), budgeting and forecasting, financial reporting and similar areas.
See more details OLTP and OLAP
In python: help(my_list.append)
for example, will give you the docstring of the function.
>>> my_list = []
>>> help(my_list.append)
Help on built-in function append:
append(...)
L.append(object) -- append object to end
Below settings are worked well for me,
"editor.insertSpaces": false,
"editor.formatOnSave": true, // only if you want auto fomattting on saving the file
"editor.detectIndentation": false
Above settings will reflect and applied to every files. You don't need to indent/format every file manually.
You should be able to do that with the Batch Task plugin.
An alternative can also be Post build task plugin.
The accepted answer provided a good starting point, but if you resize the frame, change the column widths, or even change the table data, the headers will get messed up in various ways. Every other example I've seen has similar issues, or imposes some serious restrictions on the table's layout.
I think I've finally got all these problems solved, though. It took a lot of CSS, but the final product is about as reliable and easy to use as a normal table.
Here's an example that has all the required features to replicate the table referenced by the OP: jsFiddle
The colors and borders would have to be changed to make it identical to the reference. Information on how to make those kinds of changes is provided in the CSS comments.
Here's the code:
/*the following html and body rule sets are required only if using a % width or height*/_x000D_
/*html {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}*/_x000D_
body {_x000D_
box-sizing: border-box;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0 20px 0 20px;_x000D_
text-align: center;_x000D_
background: white;_x000D_
}_x000D_
.scrollingtable {_x000D_
box-sizing: border-box;_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
overflow: hidden;_x000D_
width: auto; /*if you want a fixed width, set it here, else set to auto*/_x000D_
min-width: 0/*100%*/; /*if you want a % width, set it here, else set to 0*/_x000D_
height: 188px/*100%*/; /*set table height here; can be fixed value or %*/_x000D_
min-height: 0/*104px*/; /*if using % height, make this large enough to fit scrollbar arrows + caption + thead*/_x000D_
font-family: Verdana, Tahoma, sans-serif;_x000D_
font-size: 15px;_x000D_
line-height: 20px;_x000D_
padding: 20px 0 20px 0; /*need enough padding to make room for caption*/_x000D_
text-align: left;_x000D_
}_x000D_
.scrollingtable * {box-sizing: border-box;}_x000D_
.scrollingtable > div {_x000D_
position: relative;_x000D_
border-top: 1px solid black;_x000D_
height: 100%;_x000D_
padding-top: 20px; /*this determines column header height*/_x000D_
}_x000D_
.scrollingtable > div:before {_x000D_
top: 0;_x000D_
background: cornflowerblue; /*header row background color*/_x000D_
}_x000D_
.scrollingtable > div:before,_x000D_
.scrollingtable > div > div:after {_x000D_
content: "";_x000D_
position: absolute;_x000D_
z-index: -1;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
left: 0;_x000D_
}_x000D_
.scrollingtable > div > div {_x000D_
min-height: 0/*43px*/; /*if using % height, make this large enough to fit scrollbar arrows*/_x000D_
max-height: 100%;_x000D_
overflow: scroll/*auto*/; /*set to auto if using fixed or % width; else scroll*/_x000D_
overflow-x: hidden;_x000D_
border: 1px solid black; /*border around table body*/_x000D_
}_x000D_
.scrollingtable > div > div:after {background: white;} /*match page background color*/_x000D_
.scrollingtable > div > div > table {_x000D_
width: 100%;_x000D_
border-spacing: 0;_x000D_
margin-top: -20px; /*inverse of column header height*/_x000D_
/*margin-right: 17px;*/ /*uncomment if using % width*/_x000D_
}_x000D_
.scrollingtable > div > div > table > caption {_x000D_
position: absolute;_x000D_
top: -20px; /*inverse of caption height*/_x000D_
margin-top: -1px; /*inverse of border-width*/_x000D_
width: 100%;_x000D_
font-weight: bold;_x000D_
text-align: center;_x000D_
}_x000D_
.scrollingtable > div > div > table > * > tr > * {padding: 0;}_x000D_
.scrollingtable > div > div > table > thead {_x000D_
vertical-align: bottom;_x000D_
white-space: nowrap;_x000D_
text-align: center;_x000D_
}_x000D_
.scrollingtable > div > div > table > thead > tr > * > div {_x000D_
display: inline-block;_x000D_
padding: 0 6px 0 6px; /*header cell padding*/_x000D_
}_x000D_
.scrollingtable > div > div > table > thead > tr > :first-child:before {_x000D_
content: "";_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
height: 20px; /*match column header height*/_x000D_
border-left: 1px solid black; /*leftmost header border*/_x000D_
}_x000D_
.scrollingtable > div > div > table > thead > tr > * > div[label]:before,_x000D_
.scrollingtable > div > div > table > thead > tr > * > div > div:first-child,_x000D_
.scrollingtable > div > div > table > thead > tr > * + :before {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
white-space: pre-wrap;_x000D_
color: white; /*header row font color*/_x000D_
}_x000D_
.scrollingtable > div > div > table > thead > tr > * > div[label]:before,_x000D_
.scrollingtable > div > div > table > thead > tr > * > div[label]:after {content: attr(label);}_x000D_
.scrollingtable > div > div > table > thead > tr > * + :before {_x000D_
content: "";_x000D_
display: block;_x000D_
min-height: 20px; /*match column header height*/_x000D_
padding-top: 1px;_x000D_
border-left: 1px solid black; /*borders between header cells*/_x000D_
}_x000D_
.scrollingtable .scrollbarhead {float: right;}_x000D_
.scrollingtable .scrollbarhead:before {_x000D_
position: absolute;_x000D_
width: 100px;_x000D_
top: -1px; /*inverse border-width*/_x000D_
background: white; /*match page background color*/_x000D_
}_x000D_
.scrollingtable > div > div > table > tbody > tr:after {_x000D_
content: "";_x000D_
display: table-cell;_x000D_
position: relative;_x000D_
padding: 0;_x000D_
border-top: 1px solid black;_x000D_
top: -1px; /*inverse of border width*/_x000D_
}_x000D_
.scrollingtable > div > div > table > tbody {vertical-align: top;}_x000D_
.scrollingtable > div > div > table > tbody > tr {background: white;}_x000D_
.scrollingtable > div > div > table > tbody > tr > * {_x000D_
border-bottom: 1px solid black;_x000D_
padding: 0 6px 0 6px;_x000D_
height: 20px; /*match column header height*/_x000D_
}_x000D_
.scrollingtable > div > div > table > tbody:last-of-type > tr:last-child > * {border-bottom: none;}_x000D_
.scrollingtable > div > div > table > tbody > tr:nth-child(even) {background: gainsboro;} /*alternate row color*/_x000D_
.scrollingtable > div > div > table > tbody > tr > * + * {border-left: 1px solid black;} /*borders between body cells*/
_x000D_
<div class="scrollingtable">_x000D_
<div>_x000D_
<div>_x000D_
<table>_x000D_
<caption>Top Caption</caption>_x000D_
<thead>_x000D_
<tr>_x000D_
<th><div label="Column 1"></div></th>_x000D_
<th><div label="Column 2"></div></th>_x000D_
<th><div label="Column 3"></div></th>_x000D_
<th>_x000D_
<!--more versatile way of doing column label; requires 2 identical copies of label-->_x000D_
<div><div>Column 4</div><div>Column 4</div></div>_x000D_
</th>_x000D_
<th class="scrollbarhead"/> <!--ALWAYS ADD THIS EXTRA CELL AT END OF HEADER ROW-->_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>_x000D_
Faux bottom caption_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<!--[if lte IE 9]><style>.scrollingtable > div > div > table {margin-right: 17px;}</style><![endif]-->
_x000D_
Try this Macro. Anywhere you want the "true" or false to show up just replace it with PRINTBOOL(var) where var is the bool you want the text for.
#define PRINTBOOL(x) x?"true":"false"
Solution:
On this case, the solution was using the dot
,
so: rm -rf .* && git clone ssh://[email protected]/home/user/private/repos/project_hub.git .
rm -rf .* &&
may be omitted if we are absolutely sure that the directory is empty.
Credits go to: @James McLaughlin on comments below.
Mongo shell command that worked for me:
db.getCollection(<collection_name>).aggregate([{"$match": {'<key>': '<value to match>'}}, {"$group": {'_id': {'<group_by_attribute>': "$group_by_attribute"}}}])
The main advantages are syntactic:
You are unlikely to see any performance benefits with ES6 modules. You will still need an extra library to bundle the modules, even when there is full support for ES6 features in the browser.
Have you tried to use the "CSVIMPORT" function found in the file exchange? I haven't tried it myself, but it claims to handle all combinations of text and numbers.
http://www.mathworks.com/matlabcentral/fileexchange/23573-csvimport
You'll probably want to use a DECIMAL
type in your database. In your migration, do something like this:
# precision is the total number of digits
# scale is the number of digits to the right of the decimal point
add_column :items, :price, :decimal, :precision => 8, :scale => 2
In Rails, the :decimal
type is returned as BigDecimal
, which is great for price calculation.
If you insist on using integers, you will have to manually convert to and from BigDecimal
s everywhere, which will probably just become a pain.
As pointed out by mcl, to print the price, use:
number_to_currency(price, :unit => "€")
#=> €1,234.01
From Eclipsepedia on how to set a conditional breakpoint:
First, set a breakpoint at a given location. Then, use the context menu on the breakpoint in the left editor margin or in the Breakpoints view in the Debug perspective, and select the breakpoint’s properties. In the dialog box, check Enable Condition, and enter an arbitrary Java condition, such as
list.size()==0
. Now, each time the breakpoint is reached, the expression is evaluated in the context of the breakpoint execution, and the breakpoint is either ignored or honored, depending on the outcome of the expression.Conditions can also be expressed in terms of other breakpoint attributes, such as hit count.
A function I have in an install script made for exactly this
function assertInstalled() {
for var in "$@"; do
if ! which $var &> /dev/null; then
echo "Install $var!"
exit 1
fi
done
}
example call:
assertInstalled zsh vim wget python pip git cmake fc-cache
Yes, they are all the same.
We can review the interpreted machine code to confirm that that they're all doing the exact same thing.
import dis
def f1():
print "Hello World"
return None
def f2():
print "Hello World"
return
def f3():
print "Hello World"
dis.dis(f1)
4 0 LOAD_CONST 1 ('Hello World')
3 PRINT_ITEM
4 PRINT_NEWLINE
5 5 LOAD_CONST 0 (None)
8 RETURN_VALUE
dis.dis(f2)
9 0 LOAD_CONST 1 ('Hello World')
3 PRINT_ITEM
4 PRINT_NEWLINE
10 5 LOAD_CONST 0 (None)
8 RETURN_VALUE
dis.dis(f3)
14 0 LOAD_CONST 1 ('Hello World')
3 PRINT_ITEM
4 PRINT_NEWLINE
5 LOAD_CONST 0 (None)
8 RETURN_VALUE
Here is a variant of Avi Ginsburg's program which clearly illustrates the property of reinterpret_cast
mentioned by Chris Luengo, flodin, and cmdLP: that the compiler treats the pointed-to memory location as if it were an object of the new type:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class A
{
public:
int i;
};
class B : public A
{
public:
virtual void f() {}
};
int main()
{
string s;
B b;
b.i = 0;
A* as = static_cast<A*>(&b);
A* ar = reinterpret_cast<A*>(&b);
B* c = reinterpret_cast<B*>(ar);
cout << "as->i = " << hex << setfill('0') << as->i << "\n";
cout << "ar->i = " << ar->i << "\n";
cout << "b.i = " << b.i << "\n";
cout << "c->i = " << c->i << "\n";
cout << "\n";
cout << "&(as->i) = " << &(as->i) << "\n";
cout << "&(ar->i) = " << &(ar->i) << "\n";
cout << "&(b.i) = " << &(b.i) << "\n";
cout << "&(c->i) = " << &(c->i) << "\n";
cout << "\n";
cout << "&b = " << &b << "\n";
cout << "as = " << as << "\n";
cout << "ar = " << ar << "\n";
cout << "c = " << c << "\n";
cout << "Press ENTER to exit.\n";
getline(cin,s);
}
Which results in output like this:
as->i = 0
ar->i = 50ee64
b.i = 0
c->i = 0
&(as->i) = 00EFF978
&(ar->i) = 00EFF974
&(b.i) = 00EFF978
&(c->i) = 00EFF978
&b = 00EFF974
as = 00EFF978
ar = 00EFF974
c = 00EFF974
Press ENTER to exit.
It can be seen that the B object is built in memory as B-specific data first, followed by the embedded A object. The static_cast
correctly returns the address of the embedded A object, and the pointer created by static_cast
correctly gives the value of the data field. The pointer generated by reinterpret_cast
treats b
's memory location as if it were a plain A object, and so when the pointer tries to get the data field it returns some B-specific data as if it were the contents of this field.
One use of reinterpret_cast
is to convert a pointer to an unsigned integer (when pointers and unsigned integers are the same size):
int i;
unsigned int u = reinterpret_cast<unsigned int>(&i);
Trigger hardware accelerated rendering for the problematic element. I would advice to not do this on *, body or html tags for performance.
.problem{
-webkit-transform:translate3d(0,0,0);
}
Sure, the syntax is exactly the same as C - NewObj* pNew = (NewObj*)oldObj;
In this situation you may wish to consider supplying this list as a parameter to the constructor, something like:
// SelectionListViewController
-(id) initWith:(SomeListClass*)anItemList
{
self = [super init];
if ( self ) {
[self setList: anItemList];
}
return self;
}
Then use it like this:
myEditController = [[SelectionListViewController alloc] initWith: listOfItems];
The following has worked for me very well:
$("#button").attr('disabled', 'disabled');
You can also "WAITFOR" a "TIME":
RAISERROR('Im about to wait for a certain time...', 0, 1) WITH NOWAIT
WAITFOR TIME '16:43:30.000'
RAISERROR('I waited!', 0, 1) WITH NOWAIT
Try this in your styles.xml:
colorPrimary will be the toolbar color.
<resources>
<style name="AppTheme" parent="Theme.AppCompat">
<item name="colorPrimary">@color/primary</item>
<item name="colorPrimaryDark">@color/primary_pressed</item>
<item name="colorAccent">@color/accent</item>
</style>
Did you build this in Eclipse by the way?
ORA-01034 and ORA-27101 normally indicate that the database instance you're attempting to connect to is shut down and that you're not connected as a user who has permission to start it up. Log on to the server 192.168.1.53 and start up the orcl
instance, or ask your DBA to do this for you.
I would suggest starting with the most straightforward solutions first - maybe simple HTTP Basic Authentication + HTTPS is enough in your scenario.
If not (for example you cannot use https, or need more complex key management), you may have a look at HMAC-based solutions as suggested by others. A good example of such API would be Amazon S3 (http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html)
I wrote a blog post about HMAC based authentication in ASP.NET Web API. It discusses both Web API service and Web API client and the code is available on bitbucket. http://www.piotrwalat.net/hmac-authentication-in-asp-net-web-api/
Here is a post about Basic Authentication in Web API: http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-message-handlers/
Remember that if you are going to provide an API to 3rd parties, you will also most likely be responsible for delivering client libraries. Basic authentication has a significant advantage here as it is supported on most programming platforms out of the box. HMAC, on the other hand, is not that standardized and will require custom implementation. These should be relatively straightforward but still require work.
PS. There is also an option to use HTTPS + certificates. http://www.piotrwalat.net/client-certificate-authentication-in-asp-net-web-api-and-windows-store-apps/
NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setHour:10];
NSDate *date = [gregorian dateByAddingComponents:comps toDate:currentDate options:0];
[comps release];
Not tested in xcode though :)
Maybe you can use float:right;:
.one {_x000D_
padding-left: 1em;_x000D_
text-color: white;_x000D_
display:inline; _x000D_
}_x000D_
.two {_x000D_
background-color: #00ffff;_x000D_
}_x000D_
.pull-right{_x000D_
float:right;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div class="row">_x000D_
<h3 class="one">Text</h3>_x000D_
<button class="btn btn-secondary pull-right">Button</button>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
You can 'extract' the language from the current locale. You can extract the locale via the standard Java API, or by using the Android Context. For instance, the two lines below are equivalent:
String locale = context.getResources().getConfiguration().locale.getDisplayName();
String locale = java.util.Locale.getDefault().getDisplayName();
cURL-less you can use in php5
$url = 'URL';
$data = array('field1' => 'value', 'field2' => 'value');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);
$data = json_decode(...);
$firstId = $data[0]["id"];
$secondSeatNo = $data[1]["seat_no"];
Just like this :)
public class GetObjectsComparison
{
public object FirstObject, SecondObject;
public BindingFlags BindingFlagsConditions= BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
}
public struct SetObjectsComparison
{
public FieldInfo SecondObjectFieldInfo;
public dynamic FirstObjectFieldInfoValue, SecondObjectFieldInfoValue;
public bool ErrorFound;
public GetObjectsComparison GetObjectsComparison;
}
private static bool ObjectsComparison(GetObjectsComparison GetObjectsComparison)
{
GetObjectsComparison FunctionGet = GetObjectsComparison;
SetObjectsComparison FunctionSet = new SetObjectsComparison();
if (FunctionSet.ErrorFound==false)
foreach (FieldInfo FirstObjectFieldInfo in FunctionGet.FirstObject.GetType().GetFields(FunctionGet.BindingFlagsConditions))
{
FunctionSet.SecondObjectFieldInfo =
FunctionGet.SecondObject.GetType().GetField(FirstObjectFieldInfo.Name, FunctionGet.BindingFlagsConditions);
FunctionSet.FirstObjectFieldInfoValue = FirstObjectFieldInfo.GetValue(FunctionGet.FirstObject);
FunctionSet.SecondObjectFieldInfoValue = FunctionSet.SecondObjectFieldInfo.GetValue(FunctionGet.SecondObject);
if (FirstObjectFieldInfo.FieldType.IsNested)
{
FunctionSet.GetObjectsComparison =
new GetObjectsComparison()
{
FirstObject = FunctionSet.FirstObjectFieldInfoValue
,
SecondObject = FunctionSet.SecondObjectFieldInfoValue
};
if (!ObjectsComparison(FunctionSet.GetObjectsComparison))
{
FunctionSet.ErrorFound = true;
break;
}
}
else if (FunctionSet.FirstObjectFieldInfoValue != FunctionSet.SecondObjectFieldInfoValue)
{
FunctionSet.ErrorFound = true;
break;
}
}
return !FunctionSet.ErrorFound;
}
This will get you close, the add button has been removed out of the table so you might want to consider this...
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function() {
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
return false;
});
});
</script>
HTML markup looks like this
<a id="add">+</a></td>
<table id="mytable" width="300" border="1" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td>Name</td>
</tr>
<tr class="person">
<td><input type="text" name="name" id="name" /></td>
</tr>
</tbody>
</table>
EDIT To empty a value of a textbox after insert..
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
$('#mytable tbody>tr:last #name').val('');
return false;
EDIT2 Couldn't help myself, to reset all dropdown lists in the inserted TR you can do this
$("#mytable tbody>tr:last").each(function() {this.reset();});
I will leave the rest to you!
Included page:
<!-- opening and closing tags of included page -->
<ui:composition ...>
</ui:composition>
Including page:
<!--the inclusion line in the including page with the content-->
<ui:include src="yourFile.xhtml"/>
ui:composition
as shown above.ui:include
in the including xhtml file as also shown above.You must add an ObjectSerialization class to your program the following may work
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class ObjectSerializer {
public static String serialize(Serializable obj) throws IOException {
if (obj == null) return "";
try {
ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
objStream.writeObject(obj);
objStream.close();
return encodeBytes(serialObj.toByteArray());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Object deserialize(String str) throws IOException {
if (str == null || str.length() == 0) return null;
try {
ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str));
ObjectInputStream objStream = new ObjectInputStream(serialObj);
return objStream.readObject();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String encodeBytes(byte[] bytes) {
StringBuffer strBuf = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
}
return strBuf.toString();
}
public static byte[] decodeBytes(String str) {
byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < str.length(); i+=2) {
char c = str.charAt(i);
bytes[i/2] = (byte) ((c - 'a') << 4);
c = str.charAt(i+1);
bytes[i/2] += (c - 'a');
}
return bytes;
}
}
if you are using to store an array with SharedPreferences than use following:-
SharedPreferences sharedPreferences = this.getSharedPreferences(getPackageName(),MODE_PRIVATE);
To Serialize:-
sharedPreferences.putString("name",ObjectSerializer.serialize(array));
To Deserialize:-
newarray = (CAST_IT_TO_PROPER_TYPE) ObjectSerializer.deSerialize(sharedPreferences.getString(name),null);
Flask will process one request per thread at the same time. If you have 2 processes with 4 threads each, that's 8 concurrent requests.
Flask doesn't spawn or manage threads or processes. That's the responsability of the WSGI gateway (eg. gunicorn).
Agreeing with r-dub, keep it in source control, but to me, the real benefit is this:
collaboration in identical environments (disregarding the windohs and linux/mac stuff). Before Gemfile.lock, the next dude to install the project might see all kinds of confusing errors, blaming himself, but he was just that lucky guy getting the next version of super gem, breaking existing dependencies.
Worse, this happened on the servers, getting untested version unless being disciplined and install exact version. Gemfile.lock makes this explicit, and it will explicitly tell you that your versions are different.
Note: remember to group stuff, as :development and :test
Iterate through the list and check if contains your string "How" and if it does then remove. You can use following code:
// need to construct a new ArrayList otherwise remove operation will not be supported
List<String> list = new ArrayList<String>(Arrays.asList(new String[]
{"How are you?", "How you doing?","Joe", "Mike"}));
System.out.println("List Before: " + list);
for (Iterator<String> it=list.iterator(); it.hasNext();) {
if (!it.next().contains("How"))
it.remove(); // NOTE: Iterator's remove method, not ArrayList's, is used.
}
System.out.println("List After: " + list);
OUTPUT:
List Before: [How are you?, How you doing?, Joe, Mike]
List After: [How are you?, How you doing?]
This can also be done with the Image
class of the PIL library:
from PIL import Image
import numpy as np
im_frame = Image.open(path_to_file + 'file.png')
np_frame = np.array(im_frame.getdata())
Note: The .getdata()
might not be needed - np.array(im_frame)
should also work
Since favorites is an array, you just need to splice it off and save the document.
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var favorite = new Schema({
cn: String,
favorites: Array
});
module.exports = mongoose.model('Favorite', favorite);
exports.deleteFavorite = function (req, res, next) {
if (req.params.callback !== null) {
res.contentType = 'application/javascript';
}
// Changed to findOne instead of find to get a single document with the favorites.
Favorite.findOne({cn: req.params.name}, function (error, doc) {
if (error) {
res.send(null, 500);
} else if (doc) {
var records = {'records': doc};
// find the delete uid in the favorites array
var idx = doc.favorites ? doc.favorites.indexOf(req.params.deleteUid) : -1;
// is it valid?
if (idx !== -1) {
// remove it from the array.
doc.favorites.splice(idx, 1);
// save the doc
doc.save(function(error) {
if (error) {
console.log(error);
res.send(null, 500);
} else {
// send the records
res.send(records);
}
});
// stop here, otherwise 404
return;
}
}
// send 404 not found
res.send(null, 404);
});
};
Back in 2008 this wasn't important because of the lack of mobile OS'es but now quite important thing.
When you set accepted mime types, then in for example Android user is given system dialog with apps which can provide him the content of mime which file input accepts, what is great because navigating through files in file explorer on mobile devices is slow and often stressful.
One important thing is that some mobile browsers (based on Android version of Chrome 36 and Chrome Beta 37) does not support app filtering over extension(s) and multiple mime types.
sp_MSforeachdb 'select db_name(), * From ?..sysobjects where xtype in (''U'', ''P'') And name = ''ObjectName'''
Instead of 'ObjectName' insert object you are looking for. First column will display name of database where object is located at.
I have generated 100 different colors of different contrast, and you can increase values according to your need:
Example on Feedle: http://jsfiddle.net/zFbfE/29/ -
// CHANGE THE INITIAL SEED HERE
Math.seed = 23;
/**
* Math.seededRandom()
*
*/
Math.seededRandom = function(max, min) {
max = max || 1;
min = min || 0;
Math.seed = (Math.seed * 9301 + 49297) % 233280;
var rnd = Math.seed / 233280.0;
return min + rnd * (max - min);
}
var c, r = 0,
l = 100000,
t,
random = [],
seededRandom = [];
for(var i=0; i<100; i++)
{
random[i] = 0;
seededRandom[i] = 0;
}
// Do some loops withouth benchmarking
// to have a "fair" comparison
/*for (c = 0; c < l; ++c) {
r = 5+5;
}*/
// benchmark Math.random()
t = new Date().getTime();
s = '';
// benchmark Math.seededRandom()
t = new Date().getTime();
while(l--){
r = Math.seededRandom();
seededRandom[(r*100)|0] += 1;
}
var inc = 0;
for(c=0; c<seededRandom.length; c++) {
//var inc=15;
for(var i=0; i<seededRandom.length; i++)
{
if(i!==c) {
if(seededRandom[c] == seededRandom[i]) {
seededRandom[c] += inc;
inc = inc + 10;
// console.log(seededRandom[c]);
}
}
}
inc = inc > 255 ? 0 : inc;
}
var a=[], b=[], d=[], inc=0, dec=255;
for(c=0; c<seededRandom.length; c++) {
a[c] = (seededRandom[c] % 100) + inc;
b[c] = dec - Math.floor(seededRandom[c]/100);
if(b[c] < 0)
b[c] = b[c]* - 1;
if(a[c] > 255)
a[c] -= 255;
d[c] = Math.floor(b[c]/2);
inc += 5;
dec -= 5;
}
var app = angular.module("myAppp", []).controller('myCtrl',function($scope, $http) {
$scope.id = [];
for(var i=0; i<seededRandom.length; i++)
$scope.id.push(i);
// Generate random number
$scope.Icon = [];$scope.Icon2 = [], $scope.Icon3 = [];
var ran = 0, inc = 5, dec = 255;
for(var i=0;i<seededRandom.length;i++)
{
$scope.Icon.push(a[i]%100);
$scope.Icon2.push(b[i]%100);
$scope.Icon3.push(d[i]%100);
console.log(a[i] + "|" + b[i] + "|" + d[i]);
}
});
It works for me and I think it would be helpful for you also.
One best thing in this example is, it will generate 100 random colors and colors would be same on every page load.
it's file:///android_asset/... not file:///android_assets/... notice the plural of assets is wrong even if your file name is assets
you can try to get it in a lot of ways :
1.Using media="bogus"
and a <link>
at the foot
<head>
<!-- unimportant nonsense -->
<link rel="stylesheet" href="style.css" media="bogus">
</head>
<body>
<!-- other unimportant nonsense, such as content -->
<link rel="stylesheet" href="style.css">
</body>
2.Inserting DOM in the old way
<script type="text/javascript">
(function(){
var bsa = document.createElement('script');
bsa.type = 'text/javascript';
bsa.async = true;
bsa.src = 'https://s3.buysellads.com/ac/bsa.js';
(document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(bsa);
})();
</script>
3.if you can try plugins you could try loadCSS
<script>
// include loadCSS here...
function loadCSS( href, before, media ){ ... }
// load a file
loadCSS( "path/to/mystylesheet.css" );
</script>
What I did is to use a hidden field and put the timestamp on it and then compared it to the timestamp on the Server using PHP.
If it was faster than 15 seconds (depends on how big or small is your forms) that was a bot.
Hope this help
Use DateTime.Today
property. It will return date component of DateTime.Now
. It is equivalent of DateTime.Now.Date
.
You need to set the classpath to find your compiled class:
java -cp C:\Users\Matt\workspace\HelloWorld2\bin HelloWorld2
For me, created an empty bootstrap.css.map together with bootstrap.css and the error stopped.
This worked for me. Repeatedly calls a function updating the graph every time.
import matplotlib.pyplot as plt
import matplotlib.animation as anim
def plot_cont(fun, xmax):
y = []
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
def update(i):
yi = fun()
y.append(yi)
x = range(len(y))
ax.clear()
ax.plot(x, y)
print i, ': ', yi
a = anim.FuncAnimation(fig, update, frames=xmax, repeat=False)
plt.show()
"fun" is a function that returns an integer. FuncAnimation will repeatedly call "update", it will do that "xmax" times.
If you are trying to do something very similar: a is not None
, the same issue comes up. That is, Numpy complains that one must use a.any
or a.all
.
A workaround is to do:
if not (a is None):
pass
Not too pretty, but it does the job.
As of EF 5.0, you need to include the System.ComponentModel.DataAnnotations.Schema
namespace.
i got same problem and i solved
gem update --system 3.0.6
$config['cricket'] = 'bat';
in config.php file
$this->config->item('cricket')
use this in view
You should hook onto the change event of the <select>
element instead of on the individual options.
var select = document.getElementById('test'),
onChange = function(event) {
var shown = this.options[this.selectedIndex].value == 1;
document.getElementById('hidden_div').style.display = shown ? 'block' : 'none';
};
// attach event handler
if (window.addEventListener) {
select.addEventListener('change', onChange, false);
} else {
// of course, IE < 9 needs special treatment
select.attachEvent('onchange', function() {
onChange.apply(select, arguments);
});
}
This is in response to the above post by Efx:
If the URL already contains the var you want to change, then it is added yet again as a hidden field.
Here is a modification of that code as to prevent duplicating vars in the URL:
foreach ($_GET as $key => $value) {
if ($key != "my_key") {
echo("<input type='hidden' name='$key' value='$value'/>");
}
}
I had the same issue every time I tried to create a new project, but based on the console output, it was because of two versions of android-support-v4 that were different:
[2014-10-29 16:31:57 - HeadphoneSplitter] Found 2 versions of android-support-v4.jar in the dependency list,
[2014-10-29 16:31:57 - HeadphoneSplitter] but not all the versions are identical (check is based on SHA-1 only at this time).
[2014-10-29 16:31:57 - HeadphoneSplitter] All versions of the libraries must be the same at this time.
[2014-10-29 16:31:57 - HeadphoneSplitter] Versions found are:
[2014-10-29 16:31:57 - HeadphoneSplitter] Path: C:\Users\jbaurer\workspace\appcompat_v7\libs\android-support-v4.jar
[2014-10-29 16:31:57 - HeadphoneSplitter] Length: 627582
[2014-10-29 16:31:57 - HeadphoneSplitter] SHA-1: cb6883d96005bc85b3e868f204507ea5b4fa9bbf
[2014-10-29 16:31:57 - HeadphoneSplitter] Path: C:\Users\jbaurer\workspace\HeadphoneSplitter\libs\android-support-v4.jar
[2014-10-29 16:31:57 - HeadphoneSplitter] Length: 758727
[2014-10-29 16:31:57 - HeadphoneSplitter] SHA-1: efec67655f6db90757faa37201efcee2a9ec3507
[2014-10-29 16:31:57 - HeadphoneSplitter] Jar mismatch! Fix your dependencies
I don't know a lot about Eclipse. but I simply deleted the copy of the jar file from my project's libs folder so that it would use the appcompat_v7 jar file instead. This fixed my issue.
Your file .idea/workspace.xml
is not under git version control. You have either not added it yet (check git status/Untracked files) or ignored it (using .gitignore or .git/info/exclude files)
You can verify it using following git command, that lists all ignored files:
git ls-files --others -i --exclude-standard
This will vary depending on your architecture and how it treats basic data types. It will also depend on whether the system requires natural alignment.
Using the bootstrap flex box helps us to control the placement and alignment of your navigation element. for the problem above adding mr-auto is a better solution to it .
<div id="app" class="container">
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">Navbar</a>
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricingg</a>
</li>
</ul>
<ul class="navbar-nav " >
<li class="nav-item">
<a class="nav-link" href="{{ url('/login') }}">Login</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url('/register') }}">Register</a>
</li>
</ul>
</nav>
@yield('content')
</div>
other placement may include
fixed- top
fixed bottom
sticky-top
Sometimes (too often!) I have to untangle someone else's C++ code. And we all know that someone else's C++ code is a complete mess almost by definition :) So the first thing I do to decipher local data flow is put const in every variable definition until compiler starts barking. This means const-qualifying value arguments as well, because they are just fancy local variables initialized by caller.
Ah, I wish variables were const by default and mutable was required for non-const variables :)
Check out this link about multi project setups.
Some things to point out, make sure you have your settings.gradle updated to reference both the app and library modules.
settings.gradle: include ':app', ':libraries:lib1', ':libraries:lib2'
Also make sure that the app's build.gradle has the followng:
dependencies {
compile project(':libraries:lib1')
}
You should have the following structure:
MyProject/
| settings.gradle
+ app/
| build.gradle
+ libraries/
+ lib1/
| build.gradle
+ lib2/
| build.gradle
The app's build.gradle should use the com.android.application
plugin while any libraries' build.gradle should use the com.android.library
plugin.
The Android Studio IDE should update if you're able to build from the command line with this setup.
LANGUAGE INDEPENDENCY:
The Andrei Coscodan solution is language dependent, so a way to try to fix it is to reserve all the tags for each field: year, month and day on target languages. Consider Portugese and English, after the parsing do a final set as:
set Year=%yy%%aa%
set Month=%mm%
set Day=%dd%
Look for the year setting, I used both tags from English and Portuguese, it worked for me in Brazil where we have these two languages as the most common in Windows instalations. I expect this will work also for some languages with Latin origin like as French, Spanish, and so on.
Well, the full script could be:
@echo off
setlocal enabledelayedexpansion
:: Extract date fields - language dependent
for /f "tokens=1-4 delims=/-. " %%i in ('date /t') do (
set v1=%%i& set v2=%%j& set v3=%%k
if "%%i:~0,1%%" gtr "9" (set v1=%%j& set v2=%%k& set v3=%%l)
for /f "skip=1 tokens=2-4 delims=(-)" %%m in ('echo.^|date') do (
set %%m=!v1!& set %%n=!v2!& set %%o=!v3!
)
)
:: Final set for language independency (English and Portuguese - maybe works for Spanish and French)
set year=%yy%%aa%
set month=%mm%
set day=%dd%
:: Testing
echo Year:[%year%] - month:[%month%] - day:[%day%]
endlocal
pause
I hope this helps someone that deal with diferent languages.
dir /s /b /a:d>output.txt
will port it to a text file
select convert(varchar(10), fmdate, 101) from sery
101 is a style argument.
Rest of 'em can be found here.
A ResultSetClosedException
could be thrown for two reasons.
1.) You have opened another connection to the database without closing all other connections.
2.) Your ResultSet may be returning no values. So when you try to access data from the ResultSet java will throw a ResultSetClosedException
.
this refactored code will do it
let toTimestamp = strDate => Date.parse(strDate)
this works on all modern browsers except ie8-
When you create a flex container various default flex rules come into play.
Two of these default rules are flex-direction: row
and align-items: stretch
. This means that flex items will automatically align in a single row, and each item will fill the height of the container.
If you don't want flex items to stretch – i.e., like you wrote:
make its height the minimum required for holding its content
... then simply override the default with align-items: flex-start
.
#a {_x000D_
display: flex;_x000D_
align-items: flex-start; /* NEW */_x000D_
}_x000D_
#a > div {_x000D_
background-color: red;_x000D_
padding: 5px;_x000D_
margin: 2px;_x000D_
}_x000D_
#b {_x000D_
height: auto;_x000D_
}
_x000D_
<div id="a">_x000D_
<div id="b">left</div>_x000D_
<div>_x000D_
right<br>right<br>right<br>right<br>right<br>_x000D_
</div>_x000D_
</div>
_x000D_
Here's an illustration from the flexbox spec that highlights the five values for align-items
and how they position flex items within the container. As mentioned before, stretch
is the default value.
Source: W3C
One complicated way would be to first commit everything:
git add -u
git commit // creates commit with sha-1 A
Reset back to the original commit but checkout the_one_file from the new commit:
git reset --hard HEAD^
git checkout A path/to/the_one_file
Now you can stash the_one_file:
git stash
Cleanup by saving the committed content in your file system while resetting back to the original commit:
git reset --hard A
git reset --soft HEAD^
Yeah, somewhat awkward...
if you know sql, please write a query to get the code's value,for example sql query equivalent and elasticsearch query
POST /_sql/translate
{
"query": "select name,surname from users"
}
result is ,be carefull look at the includes key
{
"size" : 1000,
"_source" : {
"includes" : [
"name",
"surname"
],
"excludes" : [ ]
},
"sort" : [
{
"_doc" : {
"order" : "asc"
}
}
]
}
The method you are looking for is Series.combine. However, it seems some care has to be taken around datatypes. In your example, you would (as I did when testing the answer) naively call
df['col_3'] = df.col_1.combine(df.col_2, func=get_sublist)
However, this throws the error:
ValueError: setting an array element with a sequence.
My best guess is that it seems to expect the result to be of the same type as the series calling the method (df.col_1 here). However, the following works:
df['col_3'] = df.col_1.astype(object).combine(df.col_2, func=get_sublist)
df
ID col_1 col_2 col_3
0 1 0 1 [a, b]
1 2 2 4 [c, d, e]
2 3 3 5 [d, e, f]
If you want to print the array like you print a 2D list in Python:
#include <stdio.h>
int main()
{
int i, j;
int my_array[3][3] = {{10, 23, 42}, {1, 654, 0}, {40652, 22, 0}};
for(i = 0; i < 3; i++)
{
if (i == 0) {
printf("[");
}
printf("[");
for(j = 0; j < 3; j++)
{
printf("%d", my_array[i][j]);
if (j < 2) {
printf(", ");
}
}
printf("]");
if (i == 2) {
printf("]");
}
if (i < 2) {
printf(", ");
}
}
return 0;
}
Output will be:
[[10, 23, 42], [1, 654, 0], [40652, 22, 0]]
SELECT object_definition (OBJECT_ID(N'dbo.vEmployee'))
The best way to make the header full screen is set height to be 100vh
#header{
height: 100vh;
}
in postgres, assuming your field type is a timestamp:
select * from table where date_field > (now() - interval '24 hour');
Assign a new Image
object to your PictureBox
's Image
property. To load an Image
from a file, you may use the Image.FromFile
method. In your particular case, assuming the current directory is one under bin
, this should load the image bin/Pics/image1.jpg
, for example:
pictureBox1.Image = Image.FromFile("../Pics/image1.jpg");
Additionally, if these images are static and to be used only as resources in your application, resources would be a much better fit than files.
As for iOS 13.4 the preferredStatusBarStyle
method in UINavigationController
category will not be called, swizzling seems to be the only option without the need of using a subclass.
Example:
Category header:
@interface UINavigationController (StatusBarStyle)
+ (void)setUseLightStatusBarStyle;
@end
Implementation:
#import "UINavigationController+StatusBarStyle.h"
#import <objc/runtime.h>
@implementation UINavigationController (StatusBarStyle)
void (^swizzle)(Class, SEL, SEL) = ^(Class c, SEL orig, SEL new){
Method origMethod = class_getInstanceMethod(c, orig);
Method newMethod = class_getInstanceMethod(c, new);
if(class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))
class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
else
method_exchangeImplementations(origMethod, newMethod);
};
+ (void)setUseLightStatusBarStyle {
swizzle(self.class, @selector(preferredStatusBarStyle), @selector(_light_preferredStatusBarStyle));
}
- (UIStatusBarStyle)_light_preferredStatusBarStyle {
return UIStatusBarStyleLightContent;
}
@end
Usage in AppDelegate.h:
#import "UINavigationController+StatusBarStyle.h"
[UINavigationController setUseLightStatusBarStyle];
you are thinking too much... Take a look at this [i think this is what you wanted - if not let me know]
css
.even{background: red; color:white;}
.odd{background: darkred; color:white;}
html
<div class="container">
<ul class="list-unstyled">
<li class="col-md-6 odd">Dumby Content</li>
<li class="col-md-6 odd">Dumby Content</li>
<li class="col-md-6 even">Dumby Content</li>
<li class="col-md-6 even">Dumby Content</li>
<li class="col-md-6 odd">Dumby Content</li>
<li class="col-md-6 odd">Dumby Content</li>
</ul>
</div>
For me, Visual Studio on Mac doesn't support Node.js (editing and debugging) whereas Visual Studio Code does this very well.
check this out https://forum.jquery.com/topic/get-index-of-same-class-element-on-click then http://jsfiddle.net/me2loveit2/d6rFM/2/
var index = $('selector').index(this);
console.log(index)
I really enjoy using PyCharm. http://www.jetbrains.com/pycharm/
Not sure if this helps but for me, many times I reference a DLL (which automatically adds it to the bin folder of course). However that DLL might need additional DLLs (depending on what functions I'm using). I do NOT want to reference those in my Project because they just simply need to end up in the same folder as the DLL I am actually using.
I accomplish this in Visual Studio by "Adding an existing file". You should be able to add it anywhere except the Add_data folder. personally I just add it to the root.
Then change the properties of that file to ...
Build Action = None (having this set to something like Content actually copies the "root" version to the root, plus a copy in the Bin).
Copy to output folder = Copy if Newer (Basically puts it in the BIN folder only if it is missing, but doesn't do it after that)
When I publish.. my added DLL's only exists in the BIN folder and nowhere else in the Publish location (which is what I want).
import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
print data['fruits']
# the print displays:
# [u'apple', u'banana', u'orange']
You had everything you needed. data
will be a dict, and data['fruits']
will be a list
Every even number is divisible by two, regardless of if it's a decimal (but the decimal, if present, must also be even). So you can use the %
(modulo) operator, which divides the number on the left by the number on the right and returns the remainder...
boolean isEven(double num) { return ((num % 2) == 0); }
Beautiful Soup handles entity conversion. In Beautiful Soup 3, you'll need to specify the convertEntities
argument to the BeautifulSoup
constructor (see the 'Entity Conversion' section of the archived docs). In Beautiful Soup 4, entities get decoded automatically.
>>> from BeautifulSoup import BeautifulSoup
>>> BeautifulSoup("<p>£682m</p>",
... convertEntities=BeautifulSoup.HTML_ENTITIES)
<p>£682m</p>
>>> from bs4 import BeautifulSoup
>>> BeautifulSoup("<p>£682m</p>")
<html><body><p>£682m</p></body></html>
Just use the JSON.stringify method and pass it through as the "data" parameter for the $.ajax function, like follows:
$.ajax({
type: "POST",
url: "index.php",
dataType: "json",
data: JSON.stringify({ paramName: info }),
success: function(msg){
$('.answer').html(msg);
}
});
You just need to make sure you include the JSON2.js file in your page...
String s = "java is an object oriented programming language.";
final StringBuilder result = new StringBuilder(s.length());
String words[] = s.split("\\ "); // space found then split it
for (int i = 0; i < words.length; i++)
{
if (i > 0){
result.append(" ");
}
result.append(Character.toUpperCase(words[i].charAt(0))).append(
words[i].substring(1));
}
System.out.println(result);
Output: Java Is An Object Oriented Programming Language.
Here is another way that gives you access to the key and the value at the same time, in case you have to do some kind of transformation.
Map<String, Integer> pointsByName = new HashMap<>();
Map<String, Integer> maxPointsByName = new HashMap<>();
Map<String, Double> gradesByName = pointsByName.entrySet().stream()
.map(entry -> new AbstractMap.SimpleImmutableEntry<>(
entry.getKey(), ((double) entry.getValue() /
maxPointsByName.get(entry.getKey())) * 100d))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
If the query's column has an appropriate type then
var dateString = MyReader.GetDateTime(MyReader.GetOrdinal("column")).ToString(myDateFormat)
If the query's column is actually a string then see other answers.
As the others said, you can't. You can find good examples of HTML-php forms on the web, here's a very useful link that combines HTML with javascript for validation and php for sending the email.
Please check the full article (includes zip example) in the source: http://www.html-form-guide.com/contact-form/php-email-contact-form.html
HTML:
<form method="post" name="contact_form"
action="contact-form-handler.php">
Your Name:
<input type="text" name="name">
Email Address:
<input type="text" name="email">
Message:
<textarea name="message"></textarea>
<input type="submit" value="Submit">
</form>
JS:
<script language="JavaScript">
var frmvalidator = new Validator("contactform");
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email");
frmvalidator.addValidation("email","email",
"Please enter a valid email address");
</script>
PHP:
<?php
$errors = '';
$myemail = '[email protected]';//<-----Put Your email address here.
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$errors .= "\n Error: all fields are required";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n Error: Invalid email address";
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email_address\n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');
}
?>
Why not create a class Book with properties: Number, Title, and Price. Then store them in a single dimensional array? That way instead of calling
Book[i][j]
..to get your books title, call
Book[i].Title
Seems to me like it would be a bit more manageable and code friendly.
You probably just need to see the ASCII
and EXTENDED ASCII
character sets. As far as I know any of these are allowed in a char
/varchar
field.
If you use nchar
/nvarchar
then it's pretty much any character in any unicode set in the world.
Well your jsonString is wrong.
String jsonString = "{\"stat\":{\"sdr\": \"aa:bb:cc:dd:ee:ff\",\"rcv\": \"aa:bb:cc:dd:ee:ff\",\"time\": \"UTC in millis\",\"type\": 1,\"subt\": 1,\"argv\": [{\"1\":2},{\"2\":3}]}}";
use this jsonString
and if you use the same JSONParser
and ContainerFactory
in the example you will see that it will be encoded/decoded.
Additionally if you want to print your string after stat
here it goes:
try{
Map json = (Map)parser.parse(jsonString, containerFactory);
Iterator iter = json.entrySet().iterator();
System.out.println("==iterate result==");
Object entry = json.get("stat");
System.out.println(entry);
}
And about the json libraries, there are a lot of them. Better you check this.
And here's a way to do it with PrototypeJS:
Event.observe(window, 'load', function(event) {
// Do stuff
});
Update: there are two possible scenarios here:
You are determining if an object is a collection;
You are determining if a class is a collection.
The solutions are slightly different but the principles are the same. You also need to define what exactly constitutes a "collection". Implementing either Collection
or Map
will cover the Java Collections.
Solution 1:
public static boolean isCollection(Object ob) {
return ob instanceof Collection || ob instanceof Map;
}
Solution 2:
public static boolean isClassCollection(Class c) {
return Collection.class.isAssignableFrom(c) || Map.class.isAssignableFrom(c);
}
(1) can also be implemented in terms of (2):
public static boolean isCollection(Object ob) {
return ob != null && isClassCollection(ob.getClass());
}
I don't think the efficiency of either method will be greatly different from the other.
Although my MySQL background is limited, I don't think you have much luck doing that. However, you should be able to migrate over all of your data by restoring the db to a MSSQL server, then creating a SSIS or DTS package to send your tables and data to the MySQL server.
hope this helps
For CLI C++ (compiled with /clr) see this MSDN link.
In short, a property can be given the name "default":
ref class Class
{
public:
property System::String^ default[int i]
{
System::String^ get(int i) { return "hello world"; }
}
};
I have faced the same question recently. What I understand is, if the branch you are checking in has a file which you modified and it happens to be also modified and committed by that branch. Then git will stop you from switching to the branch to keep your change safe before you commit or stash.
The default restart policy is no
.
For the created containers use docker update
to update restart policy.
docker update --restart=always 0576df221c0b
0576df221c0b
is the container id.
You have a syntax error in your script and, as noted by xXPhenom22Xx, you must instantiate the tooltip.
<script type="text/javascript">
$(document).ready(function() {
$('.btn-danger').tooltip();
}); //END $(document).ready()
</script>
Note that I used your class "btn-danger". You can create a different class, or use an id="someidthatimakeup"
.
In order to get the popup exactly centered, it's a simple matter of applying a negative top margin of half the div height, and a negative left margin of half the div width. For this example, like so:
.div {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 50%;
}
This is the Windows version of a fork bomb.
%0
is the name of the currently executing batch file. A batch file that contains just this line:
%0|%0
Is going to recursively execute itself forever, quickly creating many processes and slowing the system down.
This is not a bug in windows, it is just a very stupid thing to do in a batch file.
There's no semantic difference; the trend in the standards is toward the use of id
rather than name
. However, there are differences that may lead one to prefer name
in some cases. The HTML 4.01 specification offers the following hints:
Use id
or name
? Authors should consider the following issues when deciding whether to use id
or name
for an anchor name:
If you DELETE the branch after merging it, just be aware that all hyperlinks, URLs, and references of your DELETED branch will be BROKEN.
You do not need to insert the current timestamp manually as MySQL
provides this facility to store it automatically. When the MySQL
table is created, simply do this:
TIMESTAMP
as your column type Default
value to CURRENT_TIMESTAMP
insert
any rows into the table without inserting any values for the time
columnYou'll see the current timestamp
is automatically inserted when you insert a row. Please see the attached picture.
If the response is in json you could do something like (python3):
import json
import requests as reqs
# Make the HTTP request.
response = reqs.get('http://demo.ckan.org/api/3/action/group_list')
# Use the json module to load CKAN's response into a dictionary.
response_dict = json.loads(response.text)
for i in response_dict:
print("key: ", i, "val: ", response_dict[i])
To see everything in the response you can use .__dict__
:
print(response.__dict__)
Looking at the code I found the following differences between jquery.js and jquery.slim.js:
In the jquery.slim.js, the following features are removed:
Create Procedure in MYsql.
delimiter //
create procedure SP_Dasboarddata(fromdate date, todate date)
begin
select count(Id) as count,date,status,sum(amount) as amount from
details
where (Emidate between fromdate and todate)
group by date ,status;
END;
//
Create class which contains stored procedure return result set values
[Table("SP_reslutclass")]
public class SP_reslutclass
{
[Key]
public int emicount { get; set; }
public DateTime Emidate { get; set; }
public int ? Emistatus { get; set; }
public int emiamount { get; set; }
}
Add Class in Dbcontext
public class ABCDbContext:DbContext
{
public ABCDbContext(DbContextOptions<ABCDbContext> options)
: base(options)
{
}
public DbSet<SP_reslutclass> SP_reslutclass { get; set; }
}
Call entity in repository
var counts = _Dbcontext.SP_reslutclass.FromSql("call SP_Dasboarddata
('2019-12-03','2019-12-31')").ToList();
If you want to get any parent by any child control you can use this code, and when you find the UserControl/Form/Panel or others you can call funnctions or set/get values:
Control myControl= this;
while (myControl.Parent != null)
{
if (myControl.Parent!=null)
{
myControl = myControl.Parent;
if (myControl.Name== "MyCustomUserControl")
{
((MyCustomUserControl)myControl).lblTitle.Text = "FOUND IT";
}
}
}
Parsing is just process of analyse the string of character and find the tokens from that string and parser is a component of interpreter and compiler.It uses lexical analysis and then syntactic analysis.It parse it and then compile this code after this whole process of compilation.
While integrating material dialog is possible, I found that the complexity for such a trivial feature is pretty high. The code gets more complex if you are trying to achieve a non-trivial features.
For that reason, I ended up using PrimeNG Dialog, which I found pretty straightforward to use:
m-dialog.component.html
:
<p-dialog header="Title">
Content
</p-dialog>
m-dialog.component.ts
:
@Component({
selector: 'm-dialog',
templateUrl: 'm-dialog.component.html',
styleUrls: ['./m-dialog.component.css']
})
export class MDialogComponent {
// dialog logic here
}
m-dialog.module.ts
:
import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { DialogModule } from "primeng/primeng";
import { FormsModule } from "@angular/forms";
@NgModule({
imports: [
CommonModule,
FormsModule,
DialogModule
],
exports: [
MDialogComponent,
],
declarations: [
MDialogComponent
]
})
export class MDialogModule {}
Simply add your dialog into your component's html:
<m-dialog [isVisible]="true"> </m-dialog>
PrimeNG PrimeFaces documentation is easy to follow and very precise.
You could also just change the @RequestParam default required status to false so that HTTP response status code 400 is not generated. This will allow you to place the Annotations in any order you feel like.
@RequestParam(required = false)String name
I'm not sure whether I understand your question correctly, but you can write your code in this way:
bool DoesEntityExist<T>(T instance, ....)
You can call the method in following fashion:
DoesEntityExist(myTypeInstance, ...)
This way you don't need to explicitly write the type, the framework will overtake the type automatically from the instance.
I want to mention here a very, VERY, interesting technique that is being used in huge projects like jQuery and Modernizr for concatenate things.
Both of this projects are entirely developed with requirejs modules (you can see that in their github repos) and then they use the requirejs optimizer as a very smart concatenator. The interesting thing is that, as you can see, nor jQuery neither Modernizr needs on requirejs to work, and this happen because they erase the requirejs syntatic ritual in order to get rid of requirejs in their code. So they end up with a standalone library that was developed with requirejs modules! Thanks to this they are able to perform cutsom builds of their libraries, among other advantages.
For all those interested in concatenation with the requirejs optimizer, check out this post
Also there is a small tool that abstracts all the boilerplate of the process: AlbanilJS
And what about using this.getClass().getProtectionDomain().getCodeSource().getLocation()
?
Better yet:
for i in xa*; do
sed -i 's/asd/dfg/g' $i
done
because nobody knows how many files are there, and it's easy to break command line limits.
Here's what happens when there are too many files:
# grep -c aaa *
-bash: /bin/grep: Argument list too long
# for i in *; do grep -c aaa $i; done
0
... (output skipped)
#
from http://greyblake.com/blog/2012/09/02/ruby-perfomance-tricks/
Using <<
aka concat
is far more efficient than +=
, as the latter creates a temporal object and overrides the first object with the new object.
require 'benchmark'
N = 1000
BASIC_LENGTH = 10
5.times do |factor|
length = BASIC_LENGTH * (10 ** factor)
puts "_" * 60 + "\nLENGTH: #{length}"
Benchmark.bm(10, '+= VS <<') do |x|
concat_report = x.report("+=") do
str1 = ""
str2 = "s" * length
N.times { str1 += str2 }
end
modify_report = x.report("<<") do
str1 = "s"
str2 = "s" * length
N.times { str1 << str2 }
end
[concat_report / modify_report]
end
end
output:
____________________________________________________________
LENGTH: 10
user system total real
+= 0.000000 0.000000 0.000000 ( 0.004671)
<< 0.000000 0.000000 0.000000 ( 0.000176)
+= VS << NaN NaN NaN ( 26.508796)
____________________________________________________________
LENGTH: 100
user system total real
+= 0.020000 0.000000 0.020000 ( 0.022995)
<< 0.000000 0.000000 0.000000 ( 0.000226)
+= VS << Inf NaN NaN (101.845829)
____________________________________________________________
LENGTH: 1000
user system total real
+= 0.270000 0.120000 0.390000 ( 0.390888)
<< 0.000000 0.000000 0.000000 ( 0.001730)
+= VS << Inf Inf NaN (225.920077)
____________________________________________________________
LENGTH: 10000
user system total real
+= 3.660000 1.570000 5.230000 ( 5.233861)
<< 0.000000 0.010000 0.010000 ( 0.015099)
+= VS << Inf 157.000000 NaN (346.629692)
____________________________________________________________
LENGTH: 100000
user system total real
+= 31.270000 16.990000 48.260000 ( 48.328511)
<< 0.050000 0.050000 0.100000 ( 0.105993)
+= VS << 625.400000 339.800000 NaN (455.961373)
Never try to set the compiler in the CMakeLists.txt
file.
See the CMake FAQ about how to use a different compiler:
https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-do-i-use-a-different-compiler
(Note that you are attempting method #3 and the FAQ says "(avoid)"...)
We recommend avoiding the "in the CMakeLists" technique because there are problems with it when a different compiler was used for a first configure, and then the CMakeLists file changes to try setting a different compiler... And because the intent of a CMakeLists file should be to work with multiple compilers, according to the preference of the developer running CMake.
The best method is to set the environment variables CC
and CXX
before calling CMake for the very first time in a build tree.
After CMake detects what compilers to use, it saves them in the CMakeCache.txt
file so that it can still generate proper build systems even if those variables disappear from the environment...
If you ever need to change compilers, you need to start with a fresh build tree.
You can access your host machine with the IP address "10.0.2.2
".
This has been designed in this way by the Android team. So your webserver can perfectly run at localhost and from your Android app you can access it via "http://10.0.2.2:<hostport>
".
If your emulator must access the internet through a proxy server, you can configure a custom HTTP proxy from the emulator's Extended controls screen. With the emulator open, click More , and then click Settings and Proxy. From here, you can define your own HTTP proxy settings.
If you want the duration format similar to youtube, given the number of seconds
int[] duration = { 0, 4, 40, 59, 60, 61, 400, 4000, 40000, 400000 };
foreach (int d in duration)
{
Console.WriteLine("{0, 6} -> {1, 10}", d, d > 59 ? TimeSpan.FromSeconds(d).ToString().TrimStart("00:".ToCharArray()) : string.Format("0:{0:00}", d));
}
Output:
0 -> 0:00
4 -> 0:04
40 -> 0:40
59 -> 0:59
60 -> 1:00
61 -> 1:01
400 -> 6:40
4000 -> 1:06:40
40000 -> 11:06:40
400000 -> 4.15:06:40
You can use the DevExpress PdfDocumentProcessor.Print(PdfPrinterSettings) Method.
public void Print(string pdfFilePath)
{
if (!File.Exists(pdfFilePath))
throw new FileNotFoundException("No such file exists!", pdfFilePath);
// Create a Pdf Document Processor instance and load a PDF into it.
PdfDocumentProcessor documentProcessor = new PdfDocumentProcessor();
documentProcessor.LoadDocument(pdfFilePath);
if (documentProcessor != null)
{
PrinterSettings settings = new PrinterSettings();
//var paperSizes = settings.PaperSizes.Cast<PaperSize>().ToList();
//PaperSize sizeCustom = paperSizes.FirstOrDefault<PaperSize>(size => size.Kind == PaperKind.Custom); // finding paper size
settings.DefaultPageSettings.PaperSize = new PaperSize("Label", 400, 600);
// Print pdf
documentProcessor.Print(settings);
}
}
The solution to the problem is:
Find the .gitconfig file
[user] name = 1wQasdTeedFrsweXcs234saS56Scxs5423 email = [email protected] [credential] helper = osxkeychain [url ""] insteadOf = git:// [url "https://"] [url "https://"] insteadOf = git://
there would be a blank url="" replace it with url="https://"
[user]
name = 1wQasdTeedFrsweXcs234saS56Scxs5423
email = [email protected]
[credential]
helper = osxkeychain
[url "https://"]
insteadOf = git://
[url "https://"]
[url "https://"]
insteadOf = git://
This will work :)
Happy Bower-ing
You can use this table date_formats for converting your date to different formats. My shortest code:
func getDayOfWeek(today: String) -> Int{
let formatter:NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let todayDate = formatter.dateFromString(today)
formatter.dateFormat = "e" // "eeee" -> Friday
let weekDay = formatter.stringFromDate(todayDate!)
return Int(weekDay)!
}
getDayOfWeek("2015-12-18") // 6
Just add margin: 0 auto;
to the inside div.
You could use lookaround instead if all you want to match is whitespace:
(?<=\s|^)\d+(?=\s|$)
Model1.belongsTo(Model2, { as: 'alias' })
Model1.findAll({include: [{model: Model2 , as: 'alias' }]},{raw: true}).success(onSuccess).error(onError);
If this error is new, and pulling from Docker Hub worked in the past, note Docker Hub now introduced rate limiting in Nov 2020
You will frequently see messages like:
Warning: No authentication provided, using CircleCI credentials for pulls from Docker Hub.
From Circle CI and other similar tools that use Docker Hub. Or:
Error response from daemon: pull access denied for cimg/mongo, repository does not exist or may require 'docker login': denied: requested access to the resource is denied
You'll need to specify the credentials used to fetch the image:
For CircleCI users:
- image: circleci/mongo:4.4.2
# Needed to pull down Mongo images from Docker hub
# Get from https://hub.docker.com/
# Set up at https://app.circleci.com/pipelines/github/org/sapp
auth:
username: $DOCKERHUB_USERNAME
password: $DOCKERHUB_PASSWORD
I've been looking at this too and trying to work out how to apply timezone and DST. Here's my code.
public long applyGMTOffsetDST(long time) {
// Works out adjustments for timezone and daylight saving time
Calendar mCalendar = new GregorianCalendar();
TimeZone mTimeZone = mCalendar.getTimeZone();
boolean dstBool = mTimeZone.getDefault().inDaylightTime( new Date() );
// add an hour if DST active
if (dstBool == true) {
time = time + secondsPerHour;
}
// add offest hours
int mGMTOffset = mTimeZone.getRawOffset();
if (mGMTOffset > 0) {
long offsetSeconds = secondsPerHour * mGMTOffset;
time = time + offsetSeconds;
}
return time;
}
This seems to work, but is there a better way to get the actual time off the device which represents a time that is meaningful and accurate to the user?
A loop inside JSX is very simple. Try this:
return this.state.data.map((item,index) => <ComponentName key={index} data={item}/>);
When dealing with mocking lists and iterating them, I always use something like:
@Spy
private List<Object> parts = new ArrayList<>();
I hope this will be helpful.. If I understood the problem
html{
background-color:green;
}
body {
position:relative;
left:200px;
background-color:red;
}
div{
position:relative;
left:100px;
width:100px;
height:100px;
background-color:blue;
}
You are writing to memory you do not own:
int board[2][50]; //make an array with 3 columns (wrong)
//(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
board[2][i] = 'O';
^
Change this line:
int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
^
To:
int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
^
When creating an array, the value used to initialize: [3]
indicates array size.
However, when accessing existing array elements, index values are zero based.
For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]
EDIT To address bad output comment and initialization comment
add an additional "\n" for formatting output:
Change:
...
for (k=0; k<50;k++) {
printf("%d",board[j][k]);
}
}
...
To:
...
for (k=0; k<50;k++) {
printf("%d",board[j][k]);
}
printf("\n");//at the end of every row, print a new line
}
...
Initialize board variable:
int board[3][50] = {0};//initialize all elements to zero
I've seen the same recommendation in Sublime Text 2.
Like it was already said, the main improvement is not evaluating the array's length at each iteration in the for loop. This a well-known optimization technique and particularly efficient in JavaScript when the array is part of the HTML document (doing a for
for the all the li
elements).
For example,
for (var i = 0; i < document.getElementsByTagName('li').length; i++)
is much slower than
for (var i = 0, len = document.getElementsByTagName('li').length; i < len; i++)
From where I'm standing, the main improvement in the form in your question is the fact that it doesn't declare an extra variable (len
in my example)
But if you ask me, the whole point is not about the i++
vs i--
optimization, but about not having to evaluate the length of the array at each iteration (you can see a benchmark test on jsperf).
try this code :
table1.GroupBy(x => x.Text).Select(x => x.FirstOrDefault());
Assuming the name of the dataframe after reading the excel sheet is df
, take an empty list (e.g. dataList
), iterate through the dataframe row by row and append to your empty list like-
dataList = [] #empty list
for index, row in df.iterrows():
mylist = [row.cluster, row.load_date, row.budget, row.actual, row.fixed_price]
dataList.append(mylist)
Or,
dataList = [] #empty list
for row in df.itertuples():
mylist = [row.cluster, row.load_date, row.budget, row.actual, row.fixed_price]
dataList.append(mylist)
No, if you print the dataList
, you will get each rows as a list in the dataList
.
Also note that redirect:
and forward:
prefixes are handled by UrlBasedViewResolver
, so you need to have at least one subclass of UrlBasedViewResolver
among your view resolvers, such as InternalResourceViewResolver
.
I like the Gnome xml parser. It's open source (MIT License, so you can use it in commercial products), fast and has DOM and SAX based interfaces.
You must manually clear the ChildItems collection and append new items into it:
thisParent.ChildItems.Clear();
thisParent.ChildItems.AddRange(modifiedParent.ChildItems);
After that you can call DeleteOrphans extension method which will handle with orphaned entities (it must be called between DetectChanges and SaveChanges methods).
public static class DbContextExtensions
{
private static readonly ConcurrentDictionary< EntityType, ReadOnlyDictionary< string, NavigationProperty>> s_navPropMappings = new ConcurrentDictionary< EntityType, ReadOnlyDictionary< string, NavigationProperty>>();
public static void DeleteOrphans( this DbContext source )
{
var context = ((IObjectContextAdapter)source).ObjectContext;
foreach (var entry in context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified))
{
var entityType = entry.EntitySet.ElementType as EntityType;
if (entityType == null)
continue;
var navPropMap = s_navPropMappings.GetOrAdd(entityType, CreateNavigationPropertyMap);
var props = entry.GetModifiedProperties().ToArray();
foreach (var prop in props)
{
NavigationProperty navProp;
if (!navPropMap.TryGetValue(prop, out navProp))
continue;
var related = entry.RelationshipManager.GetRelatedEnd(navProp.RelationshipType.FullName, navProp.ToEndMember.Name);
var enumerator = related.GetEnumerator();
if (enumerator.MoveNext() && enumerator.Current != null)
continue;
entry.Delete();
break;
}
}
}
private static ReadOnlyDictionary<string, NavigationProperty> CreateNavigationPropertyMap( EntityType type )
{
var result = type.NavigationProperties
.Where(v => v.FromEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many)
.Where(v => v.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One || (v.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.ZeroOrOne && v.FromEndMember.GetEntityType() == v.ToEndMember.GetEntityType()))
.Select(v => new { NavigationProperty = v, DependentProperties = v.GetDependentProperties().Take(2).ToArray() })
.Where(v => v.DependentProperties.Length == 1)
.ToDictionary(v => v.DependentProperties[0].Name, v => v.NavigationProperty);
return new ReadOnlyDictionary<string, NavigationProperty>(result);
}
}
Use the command where
in prompt to find the current executable in path
C:\> where tsc
C:\Users\user\AppData\Roaming\npm\tsc
C:\Users\user\AppData\Roaming\npm\tsc.cmd
I had this problem with this kind of simple form:
public partial class MyForm : Form
{
public MyForm()
{
Load += new EventHandler(Form1_Load);
}
private void Form1_Load(Object sender, EventArgs e)
{
InitializeComponent();
}
internal void UpdateLabel(string s)
{
Invoke(new Action(() => { label1.Text = s; }));
}
}
Then for n
other async threads I was using new MyForm().UpdateLabel(text)
to try and call the UI thread, but the constructor gives no handle to the UI thread instance, so other threads get other instance handles, which are either Object reference not set to an instance of an object
or Invoke or BeginInvoke cannot be called on a control until the window handle has been created
. To solve this I used a static object to hold the UI handle:
public partial class MyForm : Form
{
private static MyForm _mf;
public MyForm()
{
Load += new EventHandler(Form1_Load);
}
private void Form1_Load(Object sender, EventArgs e)
{
InitializeComponent();
_mf = this;
}
internal void UpdateLabel(string s)
{
_mf.Invoke((MethodInvoker) delegate { _mf.label1.Text = s; });
}
}
I guess it's working fine, so far...
This error happens when the resource is busy. Check if you have any referential constraints in the query. Or even the tables that you have mentioned in the query may be busy. They might be engaged with some other job which will be definitely listed in the following query results:
SELECT * FROM V$SESSION WHERE STATUS = 'ACTIVE'
Find the SID,
SELECT * FROM V$OPEN_CURSOR WHERE SID = --the id
To fix center position, I use:
open : function() {
var t = $(this).parent(), w = window;
t.offset({
top: (w.height() / 2) - (t.height() / 2),
left: (w.width() / 2) - (t.width() / 2)
});
}
You can use the xmp
element, see What was the <XMP> tag used for?. It has been in HTML since the beginning and is supported by all browsers. Specifications frown upon it, but HTML5 CR still describes it and requires browsers to support it (though it also tells authors not to use it, but it cannot really prevent you).
Everything inside xmp
is taken as such, no markup (tags or character references) is recognized there, except, for apparent reason, the end tag of the element itself, </xmp>
.
Otherwise xmp
is rendered like pre
.
When using “real XHTML”, i.e. XHTML served with an XML media type (which is rare), the special parsing rules do not apply, so xmp
is treated like pre
. But in “real XHTML”, you can use a CDATA section, which implies similar parsing rules. It has no special formatting, so you would probably want to wrap it inside a pre
element:
<pre><![CDATA[
This is a demo, tags like <p> will
appear literally.
]]></pre>
I don’t see how you could combine xmp
and CDATA section to achieve so-called polyglot markup
The easiest way is to use String.Replace
:
string myString = "THExxQUICKxxBROWNxxFOX";
mystring = mystring.Replace("xx", ", ");
Or more simply:
string myString = "THExxQUICKxxBROWNxxFOX".Replace("xx", ", ");
I had a column that did not allow nulls and I was inserting a null value.
try out like this
body {
background: #fff url("!--MIZO-PRO--!") no-repeat center 15px top 15px/100px;
}
/* 100px is the background size */
Many things changed since 2009, but I can only find answers saying you need to use NamedParametersJDBCTemplate.
For me it works if I just do a
db.query(sql, new MyRowMapper(), StringUtils.join(listeParamsForInClause, ","));
using SimpleJDBCTemplate or JDBCTemplate
Similar to the answer by @russian_spy :
<ul>
{% for choice in choices.items %}
<li>{{choice.0}} - {{choice.1}}</li>
{% endfor %}
</ul>
This might be suitable for breaking down more complex dictionaries.
Further to Stephen Weinberg's answer, I have since implemented a handy tool called iojson, which helps to populate data to an existing object easily as well as encoding the existing object to a JSON string. A iojson middleware is also provided to work with other middlewares. More examples can be found at https://github.com/junhsieh/iojson
Example:
func main() {
jsonStr := `{"Status":true,"ErrArr":[],"ObjArr":[{"Name":"My luxury car","ItemArr":[{"Name":"Bag"},{"Name":"Pen"}]}],"ObjMap":{}}`
car := NewCar()
i := iojson.NewIOJSON()
if err := i.Decode(strings.NewReader(jsonStr)); err != nil {
fmt.Printf("err: %s\n", err.Error())
}
// populating data to a live car object.
if v, err := i.GetObjFromArr(0, car); err != nil {
fmt.Printf("err: %s\n", err.Error())
} else {
fmt.Printf("car (original): %s\n", car.GetName())
fmt.Printf("car (returned): %s\n", v.(*Car).GetName())
for k, item := range car.ItemArr {
fmt.Printf("ItemArr[%d] of car (original): %s\n", k, item.GetName())
}
for k, item := range v.(*Car).ItemArr {
fmt.Printf("ItemArr[%d] of car (returned): %s\n", k, item.GetName())
}
}
}
Sample output:
car (original): My luxury car
car (returned): My luxury car
ItemArr[0] of car (original): Bag
ItemArr[1] of car (original): Pen
ItemArr[0] of car (returned): Bag
ItemArr[1] of car (returned): Pen
For others that arrive on this page from google:
DataRow also has a function .IsNull("ColumnName")
public DateTime? TestDt;
public Parse(DataRow row)
{
if (!row.IsNull("TEST_DT"))
TestDt = Convert.ToDateTime(row["TEST_DT"]);
}
Maven way
If you use Maven, you can run the following command to run all your test cases:
mvn clean test
Or you can run a particular test as below
mvn clean test -Dtest=your.package.TestClassName
mvn clean test -Dtest=your.package.TestClassName#particularMethod
If you would like to see the stack trace (if any) in the console instead of report files in the target\surefire-reports folder, set the user property surefire.useFile to false. For example:
mvn clean test -Dtest=your.package.TestClassName -Dsurefire.useFile=false
Gradle way
If you use Gradle, you can run the following command to run all your test cases:
gradle test
Or you can run a particular test as below
gradle test --tests your.package.TestClassName
gradle test --tests your.package.TestClassName.particularMethod
If you would like more information, you can consider options such as --stacktrace, or --info, or --debug.
For example, when you run Gradle with the info logging level --info, it will show you the result of each test while they are running. If there is any exception, it will show you the stack trace, pointing out what the problem is.
gradle test --info
If you would like to see the overall test results, you can open the report in the browser, for example (Open it using Google Chrome in Ubuntu):
google-chrome build/reports/tests/index.html
Ant way
Once you set up your Ant build file build.xml, you can run your JUnit test cases from the command line as below:
ant -f build.xml <Your JUnit test target name>
You can follow the link below to read more about how to configure JUnit tests in the Ant build file: https://ant.apache.org/manual/Tasks/junit.html
Normal way
If you do not use Maven, or Gradle or Ant, you can follow the following way:
First of all, you need to compile your test cases. For example (in Linux):
javac -d /absolute/path/for/compiled/classes -cp /absolute/path/to/junit-4.12.jar /absolute/path/to/TestClassName.java
Then run your test cases. For example:
java -cp /absolute/path/for/compiled/classes:/absolute/path/to/junit-4.12.jar:/absolute/path/to/hamcrest-core-1.3.jar org.junit.runner.JUnitCore your.package.TestClassName
This is a self contained project so that you can see everything in context.
Create a layout like the following with a UIView
and a UIButton
. The UIView
will be the container in which we will play our video.
If you need a sample video to practice with, you can get one from sample-videos.com. I'm using an mp4 format video in this example. Drag and drop the video file into your project. I also had to add it explicitly into the bundle resources (go to Build Phases > Copy Bundle Resources, see this answer for more).
Here is the complete code for the project.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player: AVPlayer?
@IBOutlet weak var videoViewContainer: UIView!
override func viewDidLoad() {
super.viewDidLoad()
initializeVideoPlayerWithVideo()
}
func initializeVideoPlayerWithVideo() {
// get the path string for the video from assets
let videoString:String? = Bundle.main.path(forResource: "SampleVideo_360x240_1mb", ofType: "mp4")
guard let unwrappedVideoPath = videoString else {return}
// convert the path string to a url
let videoUrl = URL(fileURLWithPath: unwrappedVideoPath)
// initialize the video player with the url
self.player = AVPlayer(url: videoUrl)
// create a video layer for the player
let layer: AVPlayerLayer = AVPlayerLayer(player: player)
// make the layer the same size as the container view
layer.frame = videoViewContainer.bounds
// make the video fill the layer as much as possible while keeping its aspect size
layer.videoGravity = AVLayerVideoGravity.resizeAspectFill
// add the layer to the container view
videoViewContainer.layer.addSublayer(layer)
}
@IBAction func playVideoButtonTapped(_ sender: UIButton) {
// play the video if the player is initialized
player?.play()
}
}
Notes
AVPlayerItem
.AVFoundation
and AVPlayer
, then you have to build all of your own controls. If you want full screen video playback, you can use AVPlayerViewController
. You will need to import AVKit
for that. It comes with a full set of controls for pause, fast forward, rewind, stop, etc. Here and here are some video tutorials.MPMoviePlayerController
that you may have seen in other answers is deprecated.The project should look like this now.
ArrayList
is what you want. LinkedList
is almost always a (performance) bug.
Why LinkedList
sucks:
ArrayList
was used.ArrayList
, it is probably going to be significantly slower anyway.LinkedList
in source because it is probably the wrong choice.I've faced the exactly same problem but I've fixed it with another approache.
Using Ubuntu 18.04, first disable systemd-resolved
service.
sudo systemctl disable systemd-resolved.service
Stop the service
sudo systemctl stop systemd-resolved.service
Then, remove the link to /run/systemd/resolve/stub-resolv.conf
in /etc/resolv.conf
sudo rm /etc/resolv.conf
Add a manually created resolv.conf
in /etc/
sudo vim /etc/resolv.conf
Add your prefered DNS server there
nameserver 208.67.222.222
I've tested this with success.
Use the command as
java -classpath ".;C:\MyLibs\a\*;D:\MyLibs\b\*" <your-class-name>
The above command will set the mentioned paths to classpath only once for executing the class named TestClass.
If you want to execute more then one classes, then you can follow this
set classpath=".;C:\MyLibs\a\*;D:\MyLibs\b\*"
After this you can execute as many classes as you want just by simply typing
java <your-class-name>
The above command will work till you close the command prompt. But after closing the command prompt, if you will reopen the command prompt and try to execute some classes, then you have to again set the classpath with the help of any of the above two mentioned methods.(First method for executing one class and second one for executing more classes)
If you want to set the classpth only once so that it could work for everytime, then do as follows
1. Right click on "My Computer" icon
2. Go to the "properties"
3. Go to the "Advanced System Settings" or "Advance Settings"
4. Go to the "Environment Variable"
5. Create a new variable at the user variable by giving the information as below
a. Variable Name- classpath
b. Variable Value- .;C:\program files\jdk 1.6.0\bin;C:\MyLibs\a\';C:\MyLibs\b\*
6.Apply this and you are done.
Remember this will work every time. You don't need to explicitly set the classpath again and again.
NOTE: If you want to add some other libs after some day, then don't forget to add a semi-colon at the end of the "variable-value" of the "Environment Variable" and then type the path of your new libs after the semi-colon. Because semi-colon separates the paths of different directories.
Hope this will help you.
You should not place an using
directive in an header file, it creates unnecessary headaches.
Also you need an include guard in your header.
EDIT: of course, after having fixed the include guard issue, you also need a complete declaration of student in the header file. As pointed out by others the forward declaration is not sufficient in your case.
In test file:
const APP_PORT = process.env.APP_PORT || 8080;
In the test script of ./package.json
:
"scripts": {
"test": "jest --setupFiles dotenv/config",
}
In ./env
:
APP_PORT=8080
phihag's answer puts each row in a single cell, while you are asking for each value to be in a separate cell. This seems to do it:
<?php
// Create a table from a csv file
echo "<html><body><table>\n\n";
$f = fopen("so-csv.csv", "r");
while (($line = fgetcsv($f)) !== false) {
$row = $line[0]; // We need to get the actual row (it is the first element in a 1-element array)
$cells = explode(";",$row);
echo "<tr>";
foreach ($cells as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
?>