To reduce cyclomatic complexity use a map:
Map<String,Callable<Object>> map = new HashMap < > ( ) ;
map . put ( "apple" , new Callable<Object> () { public Object call ( method1 ( ) ; return null ; } ) ;
...
map . get ( x ) . call ( ) ;
or polymorphism
If you want to delete lines 5 through 10 and 12:
sed -e '5,10d;12d' file
This will print the results to the screen. If you want to save the results to the same file:
sed -i.bak -e '5,10d;12d' file
This will back the file up to file.bak
, and delete the given lines.
Note: Line numbers start at 1. The first line of the file is 1, not 0.
TinyXML, and also Boost.PropertyTree. The latter does not fulfill all official requirements, but is very simple.
I think floats may work best for you here, if you dont want the element to occupy the whole line, float it left should work.
.feature_wrapper span {
float: left;
clear: left;
display:inline
}
EDIT: now browsers have better support you can make use of the do inline-block.
.feature_wrapper span {
display:inline-block;
*display:inline; *zoom:1;
}
Depending on the text-align this will appear as through its inline while also acting like a block element.
You should be able to use the /quiet
or /qn
options with msiexec
to perform a silent install.
MSI packages export public properties, which you can set with the PROPERTY=value
syntax on the end of the msiexec
parameters.
For example, this command installs a package with no UI and no reboot, with a log and two properties:
msiexec /i c:\path\to\package.msi /quiet /qn /norestart /log c:\path\to\install.log PROPERTY1=value1 PROPERTY2=value2
You can read the options for msiexec
by just running it with no options from Start -> Run.
package pack2;
import java.util.Scanner;
public class group {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner data= new Scanner(System.in);
int value[]= new int[5];
int temp=0,i=0,j=0;
System.out.println("Enter 5 element of array");
for(i=0;i<5;i++)
value[i]=data.nextInt();
for(i=0;i<5;i++)
{
for(j=i;j<5;j++)
{
if(value[i]>value[j])
{
temp=value[i];
value[i]=value[j];
value[j]=temp;
}
}
}
System.out.println("Increasing Order:");
for(i=0;i<5;i++)
System.out.println(""+value[i]);
}
$filename= time()."pdf";
//$filelocation = "C://xampp/htdocs/Nilesh/Projects/mkGroup/admin/PDF";
$filelocation = "/pdf uplaod path/";
$fileNL = $filelocation."/".$filename;
$pdf->Output($fileNL,'F');
$pdf->Output($filename, 'S');
You'll need to use javascript/css to fake it.
Try here for an example: http://www.dynamicdrive.com/forums/archive/index.php/t-26322.html
Not sure if I fully understood your problem, but if it's just about creating export scripts, you should forward engineer to SQL script - Ctrl + Shift + G or File -> Export -> first option.
I had trouble using the answers above. The date ranges were missing single days due to timezone shift caused by the local day light saving time (DST). I implemented a version using UTC dates that fixes that problem:
function dateRange(startDate, endDate, steps = 1) {
const dateArray = [];
let currentDate = new Date(startDate);
while (currentDate <= new Date(endDate)) {
dateArray.push(new Date(currentDate));
// Use UTC date to prevent problems with time zones and DST
currentDate.setUTCDate(currentDate.getUTCDate() + steps);
}
return dateArray;
}
const dates = dateRange('2020-09-27', '2020-10-28');
console.log(dates);
_x000D_
Note: Whether a certain timezone or DST is applied, depends entirely on your locale. Overriding this is generally not a good idea. Using UTC dates mitigates most of the time related problems.
Bonus: You can set the time interval for which you want to create timestamps with the optional steps
parameter. If you want weekly timetamps set steps
to 7
.
Documentation says (here):
Rows are wrappers for columns. Each column has horizontal padding (called a gutter) for controlling the space between them. This padding is then counteracted on the rows with negative margins. This way, all the content in your columns is visually aligned down the left side.
So the right answer is: set col
s' padding-left/right equal to minus your row
's margin-left/right. That simple.
#my-row {
margin-left: -80px;
margin-right: -80px;
}
#my-col {
padding-left: 80px;
padding-right: 80px;
}
I tried it. 3600 frame in 32 seconds. your method is really slow. You should try this.
ffmpeg -i file.mpg -s 240x135 -vf fps=1 %d.jpg
Make sure they're really tabs! In bash, you can insert a tab using C-v TAB
$ echo "LOAD_SETTLED LOAD_INIT 2011-01-13 03:50:01" | awk -F$'\t' '{print $1}'
LOAD_SETTLED
If you're trying to use this on Cygwin, then you need to follow the instructions in this answer. (It's a problem how Cygwin treats Windows symlinks.)
Just use:
param.AddWithValue("@Date_Of_Birth",DOB);
That will take care of all your problems.
You need to access a geocoding service (i.e. from Google), there is no simple formula to transfer addresses to geo coordinates.
For fields where NULL
is acceptable, you could use var_export($var, true)
to output the string
, integer
, or NULL
literal. Note that you would not surround the output with quotes because they will be automatically added or omitted.
For example:
mysql_query("insert into table2 (f1, f2) values ('{$row['string_field']}', ".var_export($row['null_field'], true).")");
DateTime values should be inserted as if they are strings surrounded by single quotes:
'20100301'
SQL Server allows for many accepted date formats and it should be the case that most development libraries provide a series of classes or functions to insert datetime values properly. However, if you are doing it manually, it is important to distinguish the date format using DateFormat
and to use generalized format:
Set DateFormat MDY --indicates the general format is Month Day Year
Insert Table( DateTImeCol )
Values( '2011-03-12' )
By setting the dateformat, SQL Server now assumes that my format is YYYY-MM-DD
instead of YYYY-DD-MM
.
SQL Server also recognizes a generic format that is always interpreted the same way: YYYYMMDD
e.g. 20110312
.
If you are asking how to insert the current date and time using T-SQL, then I would recommend using the keyword CURRENT_TIMESTAMP
. For example:
Insert Table( DateTimeCol )
Values( CURRENT_TIMESTAMP )
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew install yarn
brew install node
brew install watchman
brew tap AdoptOpenJDK/openjdk
brew cask install adoptopenjdk8
npm install -g react-native-cli
I know this was answered already, but I just ran into the same issue trying to specify the schema to use for the liquibase command line.
Update As of JDBC v9.4 you can specify the url with the new currentSchema parameter like so:
jdbc:postgresql://localhost:5432/mydatabase?currentSchema=myschema
Appears based on an earlier patch:
Which proposed url's like so:
jdbc:postgresql://localhost:5432/mydatabase?searchpath=myschema
Simple and to the POINT:
jQuery - Upon Clicking a button or div or a label element. Check off all checkboxes on the page. Keep in mind you'll have to adjust :checkbox to make it more specific.
jQuery("#My-Button").click(function() {
jQuery(':checkbox').each(function() {
if(this.checked == true) {
this.checked = false;
} else {
this.checked = true;
}
});
});
With Dulwich tip you should be able to do:
from dulwich.repo import Repo
Repo("/path/to/source").clone("/path/to/target")
This is still very basic - it copies across the objects and the refs, but it doesn't yet create the contents of the working tree if you create a non-bare repository.
In my case, I configured an external Maven installation, and I made sure to be using a JDK instead of a JRE (in the eclipse configuration, and in the Server Environment). You can run a Maven Build of the project from eclipse to check everything is working ok.
After that, I updated the maven projects, cleaned and built the projects, cleaned the server, and redeployed the artifacts.
Parsing is to read the value of one object to convert it to another type. For example you may have a string with a value of "10". Internally that string contains the Unicode characters '1' and '0' not the actual number 10. The method Integer.parseInt takes that string value and returns a real number.
String tenString = "10"
//This won't work since you can't add an integer and a string
Integer result = 20 + tenString;
//This will set result to 30
Integer result = 20 + Integer.parseInt(tenString);
tried all the above, end up doing this
<div style="width:100%; background-color:red; text-align:center;">
<div style="width:900px; margin:0 auto; background-color:blue;">
hello
</div>
</div>
Based on the accepted response by tiago, here is a small generic function that exports a numpy array to an image having the same resolution as the array:
import matplotlib.pyplot as plt
import numpy as np
def export_figure_matplotlib(arr, f_name, dpi=200, resize_fact=1, plt_show=False):
"""
Export array as figure in original resolution
:param arr: array of image to save in original resolution
:param f_name: name of file where to save figure
:param resize_fact: resize facter wrt shape of arr, in (0, np.infty)
:param dpi: dpi of your screen
:param plt_show: show plot or not
"""
fig = plt.figure(frameon=False)
fig.set_size_inches(arr.shape[1]/dpi, arr.shape[0]/dpi)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
ax.imshow(arr)
plt.savefig(f_name, dpi=(dpi * resize_fact))
if plt_show:
plt.show()
else:
plt.close()
As said in the previous reply by tiago, the screen DPI needs to be found first, which can be done here for instance: http://dpi.lv
I've added an additional argument resize_fact
in the function which which you can export the image to 50% (0.5) of the original resolution, for instance.
When writing code you generally don't want to repeat yourself. If you have an class that can be constructed with various numbers of parameters a common solution to avoid repeating yourself is to simply call another constructor with defaults in the missing arguments. There is only one annoying restriction to this - it must be the first line of the declared constructor. Example:
MyClass()
{
this(default1, default2);
}
MyClass(arg1, arg2)
{
validate arguments, etc...
note that your validation logic is only written once now
}
As for the super()
constructor, again unlike super.method()
access it must be the first line of your constructor. After that it is very much like the this()
constructors, DRY (Don't Repeat Yourself), if the class you extend has a constructor that does some of what you want then use it and then continue with constructing your object, example:
YourClass extends MyClass
{
YourClass(arg1, arg2, arg3)
{
super(arg1, arg2) // calls MyClass(arg1, arg2)
validate and process arg3...
}
}
Additional information:
Even though you don't see it, the default no argument constructor always calls super()
first. Example:
MyClass()
{
}
is equivalent to
MyClass()
{
super();
}
I see that many have mentioned using the this
and super
keywords on methods and variables - all good. Just remember that constructors have unique restrictions on their usage, most notable is that they must be the very first instruction of the declared constructor and you can only use one.
You can simply add show.legend=FALSE
to geom to suppress the corresponding legend
As of Node.js 14.3.0 the top-level await is supported.
Required flag: --experimental-top-level-await
.
Further details: https://v8.dev/features/top-level-await
For Python 3.x you can convert your text to raw bytes through:
bytes("my data", "encoding")
For example:
bytes("attack at dawn", "utf-8")
The object returned will work with outfile.write
.
This is best it will do the Job done. It will re-size your Map. No need to inspect element anymore to re-size your Map. What it does it will automatically trigger re-size event .
google.maps.event.addListener(map, "idle", function()
{
google.maps.event.trigger(map, 'resize');
});
map_array[Next].setZoom( map.getZoom() - 1 );
map_array[Next].setZoom( map.getZoom() + 1 );
$("#element").validate().valid()
After installing and configuring Hadoop, you can quickly run the command netstat -tulpn
to find the ports open. In the new version of Hadoop 3.1.3 the ports are as follows:-
localhost:8042 Hadoop, localhost:9870 HDFS, localhost:8088 YARN
You'll have to use the ChannelFactory class.
Here's an example:
var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("http://localhost/myservice");
using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint))
{
IMyService client = null;
try
{
client = myChannelFactory.CreateChannel();
client.MyServiceOperation();
((ICommunicationObject)client).Close();
myChannelFactory.Close();
}
catch
{
(client as ICommunicationObject)?.Abort();
}
}
Related resources:
In the command prompt, type the command below and press Enter.
bcdedit /enum
Under the Windows Boot Loader sections, make note of the identifier value.
To start in safe mode from command prompt :
bcdedit /set {identifier} safeboot minimal
Then enter the command line to reboot your computer.
As detailed above, the generic List<> is the best way of doing it.
If you're stuck in .NET 1.*, then you will have to use the ArrayList class instead. This does not have compile-time type checking and you also have to add casting - messy.
Successive versions have also implemented various variations - including thread safe variants.
This is how Microsoft explains it:
.NET Framework is the "full" or "traditional" flavor of .NET that's distributed with Windows. Use this when you are building a desktop Windows or UWP app, or working with older ASP.NET 4.6+.
.NET Core is cross-platform .NET that runs on Windows, Mac, and Linux. Use this when you want to build console or web apps that can run on any platform, including inside Docker containers. This does not include UWP/desktop apps currently.
Xamarin is used for building mobile apps that can run on iOS, Android, or Windows Phone devices.
Xamarin usually runs on top of Mono, which is a version of .NET that was built for cross-platform support before Microsoft decided to officially go cross-platform with .NET Core. Like Xamarin, the Unity platform also runs on top of Mono.
A common point of confusion is where ASP.NET Core fits in. ASP.NET Core can run on top of either .NET Framework (Windows) or .NET Core (cross-platform), as detailed in this answer: Difference between ASP.NET Core (.NET Core) and ASP.NET Core (.NET Framework)
<input type="text" value="Your value">
Use the value
attribute for the pre filled in values.
I often confuse the two. Better to remember through their output:
$ touch someFile.txt
$ echo ">" > someFile.txt
$ cat someFile.txt
>
$ echo ">" > someFile.txt
$ cat someFile.txt
>
$ echo ">" > someFile.txt
$ cat someFile.txt
>
$ echo ">" >> someFile.txt
$ cat someFile.txt
>>
Actually you have a code compiled targeting a higher JDK (JDK 1.8 in your case) but at runtime you are supplying a lower JRE(JRE 7 or below).
you can fix this problem by adding target parameter while compilation
e.g. if your runtime target is 1.7, you should use 1.7 or below
javac -target 1.7 *.java
if you are using eclipse, you can sent this parameter at Window -> Preferences -> Java -> Compiler -> set "Compiler compliance level" = choose your runtime jre version or lower.
Try this:
@echo off
copy "C:\Remoting.config-Training" "C:\Remoting.config"
start C:\ThirdParty.exe
exit
Since Java 11, there is a new method String.lines
:
/**
* Returns a stream of lines extracted from this string,
* separated by line terminators.
* ...
*/
public Stream<String> lines() { ... }
Usage:
"line1\nline2\nlines3"
.lines()
.forEach(System.out::println);
Let's assume that You have a List<int> intList = new List<int>{1,2,3}
if You want to get a max value You could do
int maxValue = intList.Max();
I had similar issue. In my case on disabled elements was applied that aspNetDisabled class and all disabled controls had wrong colors. So, I used jquery to remove this class on every element/control I wont and everything works and looks great now.
This is my code for removing aspNetDisabled class:
$(document).ready(function () {
$("span").removeClass("aspNetDisabled");
$("select").removeClass("aspNetDisabled");
$("input").removeClass("aspNetDisabled");
});
Laravel Framework 5.6.26
return more than one array then we use compact('array1', 'array2', 'array3', ...)
to return view.
viewblade
is the frontend (view) blade.
return view('viewblade', compact('view1','view2','view3','view4'));
In the spirit of arrow sexiness, you could create a micro clamp/constrain/gate/&c. function using rest parameters
var clamp = (...v) => v.sort((a,b) => a-b)[1];
Then just pass in three values
clamp(100,-3,someVar);
That is, again, if by sexy, you mean 'short'
E.X You can use Singleton for global information that needs to be injected.
In my case, I was keeping the Logged user detail(username, permissions etc.) in Global Static Class. And when I tried to implement the Unit Test, there was no way I could inject dependency into Controller classes. Thus I have changed my Static Class to Singleton pattern.
public class SysManager
{
private static readonly SysManager_instance = new SysManager();
static SysManager() {}
private SysManager(){}
public static SysManager Instance
{
get {return _instance;}
}
}
http://csharpindepth.com/Articles/General/Singleton.aspx#cctor
Bitmasks are used when you want to encode multiple layers of information in a single number.
So (assuming unix file permissions) if you want to store 3 levels of access restriction (read, write, execute) you could check for each level by checking the corresponding bit.
rwx
---
110
110 in base 2 translates to 6 in base 10.
So you can easily check if someone is allowed to e.g. read the file by and'ing the permission field with the wanted permission.
Pseudocode:
PERM_READ = 4
PERM_WRITE = 2
PERM_EXEC = 1
user_permissions = 6
if (user_permissions & PERM_READ == TRUE) then
// this will be reached, as 6 & 4 is true
fi
You need a working understanding of binary representation of numbers and logical operators to understand bit fields.
You'll want to include action="javascript:void(0);"
to your form to prevent page reloads and maintain HTML standard.
I have the same problem. but when i add direction: rtl;
in tabs and accordion combo but it crashes my structure.
The way to do it is add div with direction: rtl;
as parent element, and for child div set direction: ltr;
.
I use this first https://api.jquery.com/wrap/
$( ".your selector of child element" ).wrap( "<div class='scroll'></div>" );
then just simply work with css :)
In children div add to css
.your_class {
direction: ltr;
}
And to parent div added by jQuery with class .scroll
.scroll {
unicode-bidi:bidi-override;
direction: rtl;
overflow: scroll;
overflow-x: hidden!important;
}
Works prefect for me
sudo docker info | grep -e "Root Dir"
I use Eclipse Java EE edition
Create a "Dynamic Web Project"
Install a local server in the server view, for the version of Tomcat I'm using. Then debug, and run on that server for testing.
When I deploy I export the project to a war file.
If you want absolute urls, you have the third parameter.
$product_url = $this->generateUrl('product_detail',
array(
'slug' => 'slug'
),
UrlGeneratorInterface::ABSOLUTE_URL
);
Remember to include UrlGeneratorInterface.
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
With Xcode 9 - Simulator, you can pick & drag any corner of simulator to resize it and set according to your requirement.
Look at this snapshot.
Note: With Xcode 9.1+, Simulator scale options are changed.
Keyboard short-keys:
According to Xcode 9.1+
Physical Size ? 1 command + 1
Pixel Accurate ? 2 command + 2
According to Xcode 9
50% Scale ? 1 command + 1
100% Scale ? 2 command + 2
200% Scale ? 3 command + 3
Simulator scale options from Xcode Menu:
Xcode 9.1+:
Menubar ? Window ? "Here, options available change simulator scale" (Physical Size & Pixel Accurate)
Pixel Accurate: Resizes your simulator to actual (Physical) device's pixels, if your mac system display screen size (pixel) supports that much high resolution, else this option will remain disabled.
Tip: rotate simulator ( ? + ? or ? + ? ), if Pixel Accurate is disabled. It may be enabled (if it fits to screen) in landscape.
Xcode 9.0
Menubar ? Window ? Scale ? "Here, options available change simulator scale"
Tip: How do you get screen shot with 100% (a scale with actual device size) that can be uploaded on AppStore?
Disable 'Optimize Rendering for Window scale' from Debug
menu, before you take a screen shot (See here: How to take screenshots in the iOS simulator)
There is an option
Menubar ? Debug ? Disable "Optimize Rendering for Window scale"
Here is Apple's document: Resize a simulator window
int i= Array.IndexOf(temp1, temp1.Where(x=>x.Contains("abc")).FirstOrDefault());
If you want case-insensitive comparison, use lower
or upper
:
if name.lower() == "jesse":
To get right-click to paste to work:
QuickEdit Mode
I think doing this way is much simpler:
button.setBackgroundColor(Color.BLACK);
And you need to import android.graphics.Color;
not: import android.R.color;
Or you can just write the 4-byte hex code (not 3-byte) 0xFF000000
where the first byte is setting the alpha.
First of all, public static
non-final
fields are evil. Spring does not allow injecting to such fields for a reason.
Your workaround is valid, you don't even need getter/setter, private
field is enough. On the other hand try this:
@Value("${my.name}")
public void setPrivateName(String privateName) {
Sample.name = privateName;
}
(works with @Autowired
/@Resource
). But to give you some constructive advice: Create a second class with private
field and getter instead of public static
field.
Go to the xampp shell command line and run
mysql -h localhost -u username databasename < dump.sql
Since mobile doesn't give hover feedback, I want, as a user, to see instant feedback when a link is tapped. I noticed that -webkit-tap-highlight-color
is the fastest to respond (subjective).
Add the following to your body and your links will have a tap effect.
body {
-webkit-tap-highlight-color: #ccc;
}
If you're running an Apache server on your localhost (don't do this on a production server), you can also post the results to a script instead of writing it to console.
So instead of console.log
, you can write:
JSONP('http://localhost/save.php', {fn: 'filename.txt', data: json});
Then save.php
can do this
<?php
$fn = $_REQUEST['fn'];
$data = $_REQUEST['data'];
file_put_contents("path/$fn", $data);
As an exploration of this topic, I have a presentation titled "Securing TodoMVC Using the Web Cryptography API" (video, code).
It uses the Web Cryptography API to store the todo list encrypted in localStorage by password protecting the application and using a password derived key for encryption. If you forget or lose the password, there is no recovery. (Disclaimer - it was a POC and not intended for production use.)
As the other answers state, this is still susceptible to XSS or malware installed on the client computer. However, any sensitive data would also be in memory when the data is stored on the server and the application is in use. I suggest that offline support may be the compelling use case.
In the end, encrypting localStorage probably only protects the data from attackers that have read only access to the system or its backups. It adds a small amount of defense in depth for OWASP Top 10 item A6-Sensitive Data Exposure, and allows you to answer "Is any of this data stored in clear text long term?" correctly.
jQuery.load() is probably the easiest way to load data asynchronously using a selector, but you can also use any of the jquery ajax methods (get, post, getJSON, ajax, etc.)
Note that load allows you to use a selector to specify what piece of the loaded script you want to load, as in
$("#mydiv").load(location.href + " #mydiv");
Note that this technically does load the whole page and jquery removes everything but what you have selected, but that's all done internally.
Short answer: 60-80%
Long answer: I think it totally depends on the nature of your project. I typically start a project by unit testing every practical piece. By the first "release" of the project you should have a pretty good base percentage based on the type of programming you are doing. At that point you can start "enforcing" a minimum code coverage.
Here's what u can also try....
run your application....while it is still running launch your command prompt
while your application is running type netstat -n on the command prompt. You should see a list of TCP/IP connections. Check if your list is not very long. Ideally you should have less than 5 connections in the list. Check the status of the connections.
If you have too many connections with a TIME_WAIT status it means the connection has been closed and is waiting for the OS to release the resources. If you are running on Windows, the default ephemeral port rang is between 1024 and 5000 and the default time it takes Windows to release the resource from TIME_WAIT status is 4 minutes. So if your application used more then 3976 connections in less then 4 minutes, you will get the exception you got.
Suggestions to fix it:
If you continue to receive the same error message (which is highly unlikely) you can then try the following: (Please don't do it if you are not familiar with the Windows registry)
Modify the settings so they read:
MaxUserPort = dword:00004e20 (10,000 decimal) TcpTimedWaitDelay = dword:0000001e (30 decimal)
This will increase the number of ports to 10,000 and reduce the time to release freed tcp/ip connections.
Only use suggestion 2 if 1 fails.
Thank you.
lvalue
means "left value" -- it should be assignable. You cannot change the value of text
since it is an array, not a pointer.
Either declare it as char pointer (in this case it's better to declare it as const char*
):
const char *text;
if(number == 2)
text = "awesome";
else
text = "you fail";
Or use strcpy:
char text[60];
if(number == 2)
strcpy(text, "awesome");
else
strcpy(text, "you fail");
If you are running cmake
to generate SomeLib
yourself (say as part of a superbuild), consider using the User Package Registry. This requires no hard-coded paths and is cross-platform. On Windows (including mingw64) it works via the registry. If you examine how the list of installation prefixes is constructed by the CONFIG
mode of the find_packages() command, you'll see that the User Package Registry is one of elements.
Brief how-to
Associate the targets of SomeLib
that you need outside of that external project by adding them to an export set in the CMakeLists.txt
files where they are created:
add_library(thingInSomeLib ...)
install(TARGETS thingInSomeLib Export SomeLib-export DESTINATION lib)
Create a XXXConfig.cmake
file for SomeLib
in its ${CMAKE_CURRENT_BUILD_DIR}
and store this location in the User Package Registry by adding two calls to export() to the CMakeLists.txt
associated with SomeLib
:
export(EXPORT SomeLib-export NAMESPACE SomeLib:: FILE SomeLibConfig.cmake) # Create SomeLibConfig.cmake
export(PACKAGE SomeLib) # Store location of SomeLibConfig.cmake
Issue your find_package(SomeLib REQUIRED)
commmand in the CMakeLists.txt
file of the project that depends on SomeLib
without the "non-cross-platform hard coded paths" tinkering with the CMAKE_MODULE_PATH
.
When it might be the right approach
This approach is probably best suited for situations where you'll never use your software downstream of the build directory (e.g., you're cross-compiling and never install anything on your machine, or you're building the software just to run tests in the build directory), since it creates a link to a .cmake file in your "build" output, which may be temporary.
But if you're never actually installing SomeLib
in your workflow, calling EXPORT(PACKAGE <name>)
allows you to avoid the hard-coded path. And, of course, if you are installing SomeLib
, you probably know your platform, CMAKE_MODULE_PATH
, etc, so @user2288008's excellent answer will have you covered.
You may need to change the permissions as an administrator. Open up terminal on your Mac and then open the directory that markers.xml is located in. Then type:
sudo chmod 777 markers.xml
You may be prompted for a password. Also, it could be the directories that don't allow full access. I'm not familiar with WordPress, so you may have to change the permission of each directory moving upward to the mysite directory.
jQuery UI
has a :data()
selector which can also be used. It has been around since Version 1.7.0 it seems.
You can use it like this:
Get all elements with a data-company
attribute
var companyElements = $("ul:data(group) li:data(company)");
Get all elements where data-company
equals Microsoft
var microsoft = $("ul:data(group) li:data(company)")
.filter(function () {
return $(this).data("company") == "Microsoft";
});
Get all elements where data-company
does not equal Microsoft
var notMicrosoft = $("ul:data(group) li:data(company)")
.filter(function () {
return $(this).data("company") != "Microsoft";
});
etc...
One caveat of the new :data()
selector is that you must set the data
value by code for it to be selected. This means that for the above to work, defining the data
in HTML is not enough. You must first do this:
$("li").first().data("company", "Microsoft");
This is fine for single page applications where you are likely to use $(...).data("datakey", "value")
in this or similar ways.
What worked for me was to create a viewmodel that contained the date property as a string. Assigning the DateTime property from the domain model and calling the .ToString() on the date property while assigning the value to the viewmodel.
A JSON result from an MVC action method will return the date in a format compatible with the view.
public class TransactionsViewModel
{
public string DateInitiated { get; set; }
public string DateCompleted { get; set; }
}
public class Transaction{
public DateTime? DateInitiated {get; set;}
public DateTime? DateCompleted {get; set;}
}
public JsonResult GetTransactions(){
var transactions = _transactionsRepository.All;
var model = new List<TransactionsViewModel>();
foreach (var transaction in transactions)
{
var item = new TransactionsViewModel
{
...............
DateInitiated = transaction.DateInitiated.ToString(),
DateCompleted = transaction.DateCompleted.ToString(),
};
model.Add(item);
}
return Json(model, JsonRequestBehavior.AllowGet);
}
Try this:
if (getResult.Equals(new KeyValuePair<T,U>()))
or this:
if (getResult.Equals(default(KeyValuePair<T,U>)))
~/.bashrc
is already a path to .bashrc
.
If you do echo ~
you'll see that it's a path to your home directory.
Homebrew directory is /usr/local/bin
. Homebrew is installed inside it and everything installed by homebrew will be installed there.
For example, if you do brew install python
Homebrew will put Python binary in /usr/local/bin
.
Finally, to add Homebrew directory to your path you can run echo "export PATH=/usr/local/lib:$PATH" >> ~/.bashrc
. It will create .bashrc
file if it doesn't exist and then append the needed line to the end.
You can check the result by running tail ~/.bashrc
.
You can persist values using HTML5 storage, Flash Storage, or Gears. The dojo storage library provides a nice wrapper for this.
The file will be stored in a temporary location, so use tmp_name instead of name:
if (move_uploaded_file($_FILES['image']['tmp_name'], __DIR__.'/../../uploads/'. $_FILES["image"]['name'])) {
echo "Uploaded";
} else {
echo "File not uploaded";
}
A way better solution is to just use the excelent compatibility script from Anthony Ferrara:
https://github.com/ircmaxell/password_compat
Please, and also, when checking the password, always add a way (preferibly async, so it doesn't impact the check process for timming attacks) to update the hash if needed.
There is a thorough instruction on GitLab Docs:
https://docs.gitlab.com/ee/user/project/import/github.html
Ensure that any GitHub users who you want to map to GitLab users have either:
From the top navigation bar, click + and select New project.
But Please read the GitLab Docs page for details and hooks!
(it's not much)
you can use index to access list elements
List<string> list1 = new List<string>();
list1[0] //for getting the first element of the list
You are probably missing the viewport meta tag in the html head:
<meta name="viewport" content="width=device-width, initial-scale=1">
Without it the device assumes and sets the viewport to full size.
More info here.
This code worked for me
public static void main(String[] args) {
try {
java.net.URL myUr = new java.net.URL("http://path");
System.out.println("Instantiated new URL: " + connection_url);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
}
Instantiated new URL: http://path
You use ROWNUM.
ie.
SELECT user FROM Dual WHERE ROWNUM = 1
http://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns009.htm
I'll offer an oddball alternative. Sometimes it's easier to use different encoding, especially if you're dealing with a variety of systems that don't all handle the details of URL encoding the same way. This isn't the most mainstream approach but can come in handy in certain situations.
Rather than URL-encoding the data, you can base64-encode it. The benefit of this is the encoded data is very generic, consisting only of alpha characters and sometimes trailing =
's. Example:
JSON array-of-strings:
["option", "Fred's dog", "Bill & Trudy", "param=3"]
That data, URL-encoded as the data
param:
"data=%5B%27option%27%2C+%22Fred%27s+dog%22%2C+%27Bill+%26+Trudy%27%2C+%27param%3D3%27%5D"
Same, base64-encoded:
"data=WyJvcHRpb24iLCAiRnJlZCdzIGRvZyIsICJCaWxsICYgVHJ1ZHkiLCAicGFyYW09MyJd"
The base64 approach can be a bit shorter, but more importantly it's simpler. I often have problems moving URL-encoded data between cURL, web browsers and other clients, usually due to quotes, embedded %
signs and so on. Base64 is very neutral because it doesn't use special characters.
Perhaps this is specific to .net core, I found DisplayName would not work but Display(Name=...) does. This may save someone else the troubleshooting involved :)
//using statements
using System;
using System.ComponentModel.DataAnnotations; //needed for Display annotation
using System.ComponentModel; //needed for DisplayName annotation
public class Whatever
{
//Property
[Display(Name ="Release Date")]
public DateTime ReleaseDate { get; set; }
}
//cshtml file
@Html.DisplayNameFor(model => model.ReleaseDate)
Remove the class 'Carousal slide' on page load & add it dynamically when image gets loaded using jquery.This fixed for me
If you are using the free software R, you can open the matlab files in Rstudio. Very easy!
To create all intermediate-level destination directories you could use os.makedirs()
before copying:
import os
import shutil
srcfile = 'a/long/long/path/to/file.py'
dstroot = '/home/myhome/new_folder'
assert not os.path.isabs(srcfile)
dstdir = os.path.join(dstroot, os.path.dirname(srcfile))
os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)
Thanks Ravi and other users .... Nevertheless I have got the solution
SELECT @phoneNumber=
CASE
WHEN ISNULL(rdg2.nPhoneNumber ,'0') in ('0','-',NULL)
THEN ISNULL(rdg2.nMobileNumber, '0')
WHEN ISNULL(rdg2.nMobileNumber, '0') in ('0','-',NULL)
THEN '0'
ELSE ISNULL(rdg2.nPhoneNumber ,'0')
END
FROM tblReservation_Details_Guest rdg2
WHERE nReservationID=@nReservationID
Just need to put '0' instead of 0
Working with Eclipse can be difficult at times, probably when debugging and designing layouts Eclipse sometimes get stuck and we have to restart Eclipse from time to time. Also you get problems with emulators.
Android studio was released very recently and this IDE is not yet heavily used by developers. Therefore, it may contain certain bugs.
This describes the difference between android android studio and eclipse project structure: Android Studio Project Structure (v.s. Eclipse Project Structure)
This teaches you how to use the android studio: http://www.infinum.co/the-capsized-eight/articles/android-studio-vs-eclipse-1-0
Object does not have forEach
, it belongs to Array
prototype. If you want to iterate through each key-value pair in the object and take the values. You can do this:
Object.keys(a).forEach(function (key){
console.log(a[key]);
});
Usage note: For an object v = {"cat":"large", "dog": "small", "bird": "tiny"};
, Object.keys(v)
gives you an array of the keys so you get ["cat","dog","bird"]
This is another way to specify the range of the bit-vector.
x +: N, The start position of the vector is given by x and you count up from x by N.
There is also
x -: N, in this case the start position is x and you count down from x by N.
N is a constant and x is an expression that can contain iterators.
It has a couple of benefits -
It makes the code more readable.
You can specify an iterator when referencing bit-slices without getting a "cannot have a non-constant value" error.
First of all, %d is for a int
So %1.16lld
makes no sense, because %d is an integer
That typedef you do, is also unnecessary, use the type straight ahead, makes a much more readable code.
What you want to use is the type double
, for calculating pi
and then using %f
or %1.16f
.
var d = new Date();
var n = d.getFullYear();
Yes, n will give you the 4 digit year, but you can always use substring or something similar to split up the year, thus giving you only two digits:
var final = n.toString().substring(2);
This will give you the last two digits of the year (2013 will become 13, etc...)
If there's a better way, hopefully someone posts it! This is the only way I can think of. Let us know if it works!
Using map (halfdanrump's answer) is best for me, though haven't timed it...
But if you go for a dictionary, and if you have a big_dict:
so e.g.:
big_dict = {'a':1,'b':2,'c':3,................................................}
req = ['a','c','w']
{k:big_dict.get(k,None) for k in req )
# or
{k:big_dict[k] for k in req if k in big_dict)
Note that in the converse case, that the req is big, but my_dict is small, you should loop through my_dict instead.
In general, we are doing an intersection and the complexity of the problem is O(min(len(dict)),min(len(req))). Python's own implementation of intersection considers the size of the two sets, so it seems optimal. Also, being in c and part of the core library, is probably faster than most not optimized python statements. Therefore, a solution that I would consider is:
dict = {'a':1,'b':2,'c':3,................................................}
req = ['a','c','w',...................]
{k:dic[k] for k in set(req).intersection(dict.keys())}
It moves the critical operation inside python's c code and will work for all cases.
Just ran into this problem. I don't know if it's the same thing that hit your code, but for me the root cause was because I forgot to put name=
on the last argument of the url
(or path
in Django 2.0+) function call.
For instance, the following functions throw the error from the question:
url(r'^foo/(?P<bar>[A-Za-z]+)/$', views.FooBar.as_view(), 'foo')
path('foo/{slug:bar}/', views.FooBar, 'foo')
But these actually work:
url(r'^foo/(?P<bar>[A-Za-z]+)/$', views.FooBar.as_view(), name='foo')
path('foo/{slug:bar}/', views.FooBar, name='foo')
The reason why the traceback is unhelpful is because internally, Django wants to parse the given positional argument as the keyword argument kwargs
, and since a string is an iterable, an atypical code path begins to unfold. Always use name=
on your urls!
Swift Method, and supply a demo.
func topMostController() -> UIViewController {
var topController: UIViewController = UIApplication.sharedApplication().keyWindow!.rootViewController!
while (topController.presentedViewController != nil) {
topController = topController.presentedViewController!
}
return topController
}
func demo() {
let vc = ViewController()
let nav = UINavigationController.init(rootViewController: vc)
topMostController().present(nav, animated: true, completion: nil)
}
Both commands are correct
php_value post_max_size 30M
php_value upload_max_filesize 30M
BUT to use the .htaccess
you have to enable rewrite_module
in Apache config file. In httpd.conf
find this line:
# LoadModule rewrite_module modules/mod_rewrite.so
and remove the #
.
I had the same problem, this is my solution:
var functionsToCall = new Array();_x000D_
_x000D_
function f1() {_x000D_
$.ajax({_x000D_
type:"POST",_x000D_
url: "/some/url",_x000D_
success: function(data) {_x000D_
doSomethingWith(data);_x000D_
//When done, call the next function.._x000D_
callAFunction("parameter");_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
function f2() {_x000D_
/*...*/_x000D_
callAFunction("parameter2");_x000D_
}_x000D_
function f3() {_x000D_
/*...*/_x000D_
callAFunction("parameter3");_x000D_
}_x000D_
function f4() {_x000D_
/*...*/_x000D_
callAFunction("parameter4");_x000D_
}_x000D_
function f5() {_x000D_
/*...*/_x000D_
callAFunction("parameter5");_x000D_
}_x000D_
function f6() {_x000D_
/*...*/_x000D_
callAFunction("parameter6");_x000D_
}_x000D_
function f7() {_x000D_
/*...*/_x000D_
callAFunction("parameter7");_x000D_
}_x000D_
function f8() {_x000D_
/*...*/_x000D_
callAFunction("parameter8");_x000D_
}_x000D_
function f9() {_x000D_
/*...*/_x000D_
callAFunction("parameter9");_x000D_
}_x000D_
_x000D_
function callAllFunctionsSy(params) {_x000D_
functionsToCall.push(f1);_x000D_
functionsToCall.push(f2);_x000D_
functionsToCall.push(f3);_x000D_
functionsToCall.push(f4);_x000D_
functionsToCall.push(f5);_x000D_
functionsToCall.push(f6);_x000D_
functionsToCall.push(f7);_x000D_
functionsToCall.push(f8);_x000D_
functionsToCall.push(f9);_x000D_
functionsToCall.reverse();_x000D_
callAFunction(params);_x000D_
}_x000D_
_x000D_
function callAFunction(params) {_x000D_
if (functionsToCall.length > 0) {_x000D_
var f=functionsToCall.pop();_x000D_
f(params);_x000D_
}_x000D_
}
_x000D_
What Identity is your Application Pool for the Web application running as, to troubleshoot, try creating a new App Pool with say Network Service as its identity and make your web application use that new App Pool you created and see if the error persists.
If you want to set the timeout to 20 minutes, use something like this:
<configuration>
<system.web>
<sessionState timeout="20"></sessionState>
</system.web>
</configuration>
Here's another way to do this:
- name: my command
command: echo stuff
when: "'groupname' not in group_names"
group_names
is a magic variable as documented here: https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#accessing-information-about-other-hosts-with-magic-variables :
group_names is a list (array) of all the groups the current host is in.
I'm having the same problem to solve, because I need to install JDK8 to run Android SDK Manager (because it seems that don't work well with JDK9). However, I tell you how I solve all problems on a Mac (Sierra).
First, you need brew with cask and jenv.
brew tap caskroom/versions
brew install jenv
brew cask install java8
(or java7
or java
if you want to install the latest version, jdk9)jenv versions
to list all versions installed on your machine and then activate the one you want with jenv global [JDK_NAME_OF_LIST]
You could find other useful informations here on this Github Gist brew-java-and-jenv.md, on this blog Install multiple JDK on a Mac and on Jenv Website
Try adding a semi colon to the end of your structure:
struct sotrudnik {
string name;
string speciality;
string razread;
int zarplata;
} //Semi colon here
One liner in ES6 just because it's clean.
const isEven = (num) => num % 2 == 0;
Write this in each "new activity" after you initialized your new intent->
Intent i = new Intent(this, yourClass.class);
startActivity(i);
finish();
Unlike div
, p
1 which are Block Level elements which can take up margin
on all sides,span
2 cannot as it's an Inline element which takes up margins horizontally only.
From the specification:
Margin properties specify the width of the margin area of a box. The 'margin' shorthand property sets the margin for all four sides while the other margin properties only set their respective side. These properties apply to all elements, but vertical margins will not have any effect on non-replaced inline elements.
Demo 1 (Vertical margin
not applied as span
is an inline
element)
Solution? Make your span
element, display: inline-block;
or display: block;
.
Would suggest you to use display: inline-block;
as it will be inline
as well as block
. Making it block
only will result in your element to render on another line, as block
level elements take 100%
of horizontal space on the page, unless they are made inline-block
or they are floated
to left
or right
.
1. Block Level Elements - MDN Source
2. Inline Elements - MDN Resource
In SQL Server, functions and stored procedure are two different types of entities.
Function: In SQL Server database, the functions are used to perform some actions and the action returns a result immediately. Functions are two types:
System defined
User defined
Stored Procedures: In SQL Server, the stored procedures are stored in server and it can be return zero, single and multiple values. Stored Procedures are two types:
This looks like a behavior difference in the handling of \s
between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).
Note:
GNU grep 2.5.4
echo "foo bar" | grep "\s"
(doesn't match)
whereas
GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar
Probably less trouble (as \s
is not documented):
Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar
My advice is to avoid using \s
... use [ \t]*
or [[:space:]]
or something like it instead.
When you extend FragmentActivity
or Activity
and not ListActivity
, you'll want to take a look at:
I would suggest you to either use <table>
or CSS.
CSS is preferred for being more flexible. An example would be:
<!-- of course, you should move the inline CSS style to your stylesheet -->
<!-- main container, width = 70% of page, centered -->
<div id="contentBox" style="margin:0px auto; width:70%">
<!-- columns divs, float left, no margin so there is no space between column, width=1/3 -->
<div id="column1" style="float:left; margin:0; width:33%;">
CONTENT
</div>
<div id="column2" style="float:left; margin:0;width:33%;">
CONTENT
</div>
<div id="column3" style="float:left; margin:0;width:33%">
CONTENT
</div>
</div>
jsFiddle: http://jsfiddle.net/ndhqM/
Using float:left would make 3 columns stick to each other, coming in from left inside the centered div "content box".
This is my LDAP Java login test application supporting LDAP:// and LDAPS:// self-signed test certificate. Code is taken from few SO posts, simplified implementation and removed legacy sun.java.* imports.
Usage
I have run this in Windows7 and Linux machines against WinAD directory service. Application prints username and member groups.
$ java -cp classes test.LoginLDAP url=ldap://1.2.3.4:389 [email protected] password=mypwd
$ java -cp classes test.LoginLDAP url=ldaps://1.2.3.4:636 [email protected] password=mypwd
Test application supports temporary self-signed test certificates for ldaps:// protocol, this DummySSLFactory accepts any server cert so man-in-the-middle is possible. Real life installation should import server certificate to a local JKS keystore file and not using dummy factory.
Application uses enduser's username+password for initial context and ldap queries, it works for WinAD but don't know if can be used for all ldap server implementations. You could create context with internal username+pwd then run queries to see if given enduser is found.
LoginLDAP.java
package test;
import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;
public class LoginLDAP {
public static void main(String[] args) throws Exception {
Map<String,String> params = createParams(args);
String url = params.get("url"); // ldap://1.2.3.4:389 or ldaps://1.2.3.4:636
String principalName = params.get("username"); // [email protected]
String domainName = params.get("domain"); // mydomain.com or empty
if (domainName==null || "".equals(domainName)) {
int delim = principalName.indexOf('@');
domainName = principalName.substring(delim+1);
}
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, url);
props.put(Context.SECURITY_PRINCIPAL, principalName);
props.put(Context.SECURITY_CREDENTIALS, params.get("password")); // secretpwd
if (url.toUpperCase().startsWith("LDAPS://")) {
props.put(Context.SECURITY_PROTOCOL, "ssl");
props.put(Context.SECURITY_AUTHENTICATION, "simple");
props.put("java.naming.ldap.factory.socket", "test.DummySSLSocketFactory");
}
InitialDirContext context = new InitialDirContext(props);
try {
SearchControls ctrls = new SearchControls();
ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> results = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", ctrls);
if(!results.hasMore())
throw new AuthenticationException("Principal name not found");
SearchResult result = results.next();
System.out.println("distinguisedName: " + result.getNameInNamespace() ); // CN=Firstname Lastname,OU=Mycity,DC=mydomain,DC=com
Attribute memberOf = result.getAttributes().get("memberOf");
if(memberOf!=null) {
for(int idx=0; idx<memberOf.size(); idx++) {
System.out.println("memberOf: " + memberOf.get(idx).toString() ); // CN=Mygroup,CN=Users,DC=mydomain,DC=com
//Attribute att = context.getAttributes(memberOf.get(idx).toString(), new String[]{"CN"}).get("CN");
//System.out.println( att.get().toString() ); // CN part of groupname
}
}
} finally {
try { context.close(); } catch(Exception ex) { }
}
}
/**
* Create "DC=sub,DC=mydomain,DC=com" string
* @param domainName sub.mydomain.com
* @return
*/
private static String toDC(String domainName) {
StringBuilder buf = new StringBuilder();
for (String token : domainName.split("\\.")) {
if(token.length()==0) continue;
if(buf.length()>0) buf.append(",");
buf.append("DC=").append(token);
}
return buf.toString();
}
private static Map<String,String> createParams(String[] args) {
Map<String,String> params = new HashMap<String,String>();
for(String str : args) {
int delim = str.indexOf('=');
if (delim>0) params.put(str.substring(0, delim).trim(), str.substring(delim+1).trim());
else if (delim==0) params.put("", str.substring(1).trim());
else params.put(str, null);
}
return params;
}
}
And SSL helper class.
package test;
import java.io.*;
import java.net.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.*;
import javax.net.ssl.*;
public class DummySSLSocketFactory extends SSLSocketFactory {
private SSLSocketFactory socketFactory;
public DummySSLSocketFactory() {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{ new DummyTrustManager()}, new SecureRandom());
socketFactory = ctx.getSocketFactory();
} catch ( Exception ex ){ throw new IllegalArgumentException(ex); }
}
public static SocketFactory getDefault() { return new DummySSLSocketFactory(); }
@Override public String[] getDefaultCipherSuites() { return socketFactory.getDefaultCipherSuites(); }
@Override public String[] getSupportedCipherSuites() { return socketFactory.getSupportedCipherSuites(); }
@Override public Socket createSocket(Socket socket, String string, int i, boolean bln) throws IOException {
return socketFactory.createSocket(socket, string, i, bln);
}
@Override public Socket createSocket(String string, int i) throws IOException, UnknownHostException {
return socketFactory.createSocket(string, i);
}
@Override public Socket createSocket(String string, int i, InetAddress ia, int i1) throws IOException, UnknownHostException {
return socketFactory.createSocket(string, i, ia, i1);
}
@Override public Socket createSocket(InetAddress ia, int i) throws IOException {
return socketFactory.createSocket(ia, i);
}
@Override public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException {
return socketFactory.createSocket(ia, i, ia1, i1);
}
}
class DummyTrustManager implements X509TrustManager {
@Override public void checkClientTrusted(X509Certificate[] xcs, String str) {
// do nothing
}
@Override public void checkServerTrusted(X509Certificate[] xcs, String str) {
/*System.out.println("checkServerTrusted for authType: " + str); // RSA
for(int idx=0; idx<xcs.length; idx++) {
X509Certificate cert = xcs[idx];
System.out.println("X500Principal: " + cert.getSubjectX500Principal().getName());
}*/
}
@Override public X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
}
So, eventually I did that thing that all developers hate doing. I went and checked the server log files and found a report of a syntax error in line n.
tail -n 20 /var/log/apache2/error.log
I used StoredProcedureEFCore nuget package by https://github.com/verdie-g/StoredProcedureEFCore,EnterpriseLibrary.Data.NetCore,EFCor.SqlServer,EFCore.Tools
I tried DbFirst approach with {Repository pattern}.. i think so
startup.cs
ConfigureServices(IServiceCollection services){
services.AddDbContext<AppDbContext>(opt => opt
.UseSqlServer(Configuration.GetConnectionString("SampleConnectionString")));
services.AddScoped<ISomeDAL, SomeDAL>();
}
public class AppDbContext : DbContext{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{}
}
ISomeDAl Interface has {GetPropertiesResponse GetAllPropertiesByCity(int CityId);}
public class SomeDAL : ISomeDAL
{
private readonly AppDbContext context;
public SomeDAL(AppDbContext context)
{
this.context = context;
}
public GetPropertiesResponse GetAllPropertiesByCity(int CityId)
{
//Create Required Objects for response
//wont support ref Objects through params
context.LoadStoredProc(SQL_STATEMENT)
.AddParam("CityID", CityId).Exec( r =>
{
while (r.Read())
{
ORMapping<GenericRespStatus> orm = new ORMapping<GenericRespStatus>();
orm.AssignObject(r, _Status);
}
if (r.NextResult())
{
while (r.Read())
{
Property = new Property();
ORMapping<Property> orm = new ORMapping<Property>();
orm.AssignObject(r, Property);
_propertyDetailsResult.Add(Property);
}
}
});
return new GetPropertiesResponse{Status=_Status,PropertyDetails=_propertyDetailsResult};
}
}
public class GetPropertiesResponse
{
public GenericRespStatus Status;
public List<Property> PropertyDetails;
public GetPropertiesResponse()
{
PropertyDetails = new List<Property>();
}
}
public class GenericRespStatus
{
public int ResCode { get; set; }
public string ResMsg { get; set; }
}
internal class ORMapping<T>
{
public void AssignObject(IDataReader record, T myClass)
{
PropertyInfo[] propertyInfos = typeof(T).GetProperties();
for (int i = 0; i < record.FieldCount; i++)
{
if (propertyInfos.Any(obj => obj.Name == record.GetName(i))) //&& record.GetValue(i) != DBNull.Value
{
propertyInfos.Single(obj => obj.Name == record.GetName(i)).SetValue(myClass, Convert.ChangeType(record.GetValue(i), record.GetFieldType(i)));
}
}
}
}
use wget
module of python instead. Here is a snippet
import wget
wget.download(url)
I had same issue. What I did, removed anaconda directory from the install location and re-install after that it worked as I anticipated
Change as per below
@font-face {
font-family: "Futura";
src: url("../fonts/Futura_Medium_BT.eot"); /* IE */
src: local("Futura"), url( "../fonts/Futura_Medium_BT.ttf" ) format("truetype"); /* non-IE */
}
body nav {
font-family: "Futura";
font-size:1.2em;
height: 40px;
}
Both styles, with a touch of tweaking, would work.
The first method uses a Javascript Constructor, which like most things has pros and cons.
// By convention, constructors start with an upper case letter
function MakePerson(name,age) {
// The magic variable 'this' is set by the Javascript engine and points to a newly created object that is ours.
this.name = name;
this.age = age;
this.occupation = "Hobo";
}
var jeremy = new MakePerson("Jeremy", 800);
On the other hand, your other method is called the 'Revealing Closure Pattern' if I recall correctly.
function makePerson(name2, age2) {
var name = name2;
var age = age2;
return {
name: name,
age: age
};
}
Example:
How to transfer putty configuration and session configuration from one user account to another e.g. when created a new account and want to use the putty sessions/configurations from the old account
Process:
- Export registry key from old account into a file
- Import registry key from file into new account
Export reg key: (from OLD account)
Import reg key: (into NEW account)
Login into NEW account e.g. tom
Open normal 'command prompt' (NOT admin !)
Type 'regedit'
Select 'Import' from the menu
Select the registry file to import e.g. 'puttyconfig.reg'
Done
Note:
Do not use an 'admin command prompt' as settings are located under '[HKEY_CURRENT_USER...] 'and regedit would run as admin and show that section for the admin-user rather then for the user to transfer from and/or to.
Use the constructor: new List<object>(myArray)
Detail blog to fix this issue is : http://goo.gl/JXWqfJ
You can solve this problem by following two ways:
A) Start your WAMP befor you login to skype. So that WAMP will take over the the port and there will be no conflict with the port number. And you are able to use Skype as well as WAMP.
But this is not the permanent solution for your problem. Whenever you want to start WAMP you need to signout Skype first and than only you are able to start WAMP. Which is really i don’t like.
B) Second option is to change the port of Skype itself, so that it will not conflict with WAMP. Following screen/steps will help you to solve this problem:
1) SignIn to Skype.
2) Got to the Tools -> options
3) Select the “Advanced” -> Connection
4) Unchecked “Use port 80 and 443 as alternatives for incoming connections” checkbox and click save.
5) Now Signout and SignIn again to skype. (this change will take affect only you relogin to skype)
Now every time you start WAMP will not conflict with skype.
Use this to get the page scroll position.
var screenTop = $(document).scrollTop();
$('#content').css('top', screenTop);
I know its already answered, still i am just trying to make it simple. So angular.copy(data) you can use in case where you want to modify/change your received object by keeping its original values unmodified/unchanged.
For example: suppose i have made api call and got my originalObj, now i want to change the values of api originalObj for some case but i want the original values too so what i can do is, i can make a copy of my api originalObj in duplicateObj and modify duplicateObj this way my originalObj values will not change. In simple words duplicateObj modification will not reflect in originalObj unlike how js obj behave.
$scope.originalObj={
fname:'sudarshan',
country:'India'
}
$scope.duplicateObj=angular.copy($scope.originalObj);
console.log('----------originalObj--------------');
console.log($scope.originalObj);
console.log('-----------duplicateObj---------------');
console.log($scope.duplicateObj);
$scope.duplicateObj.fname='SUD';
$scope.duplicateObj.country='USA';
console.log('---------After update-------')
console.log('----------originalObj--------------');
console.log($scope.originalObj);
console.log('-----------duplicateObj---------------');
console.log($scope.duplicateObj);
Result is like....
----------originalObj--------------
manageProfileController.js:1183 {fname: "sudarshan", country: "India"}
manageProfileController.js:1184 -----------duplicateObj---------------
manageProfileController.js:1185 {fname: "sudarshan", country: "India"}
manageProfileController.js:1189 ---------After update-------
manageProfileController.js:1190 ----------originalObj--------------
manageProfileController.js:1191 {fname: "sudarshan", country: "India"}
manageProfileController.js:1192 -----------duplicateObj---------------
manageProfileController.js:1193 {fname: "SUD", country: "USA"}
Change It like this, It worked for me. Hope It helps. firs I did
$cfg['Servers'][$i]['verbose'] = 'mysql wampserver';
//$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'changed';
/* Server parameters */
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
/* Select mysql if your server does not have mysqli */
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;
Then I Changed Like this...
$cfg['Servers'][$i]['verbose'] = 'mysql wampserver';
//$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'root';
/* Server parameters */
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
/* Select mysql if your server does not have mysqli */
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;
There might be just a typo anywhere inside a file imported by the config. For example, I made a typo deep inside my config file:
loccation /sense/movies/ {
mp4;
}
(loccation instead of location), and this causes the error:
nginx: [emerg] "server" directive is not allowed here in /etc/nginx/sites-enabled/xxx.xx:1
See main difference between ATTR | PROP | IS below:
Source: http://api.jquery.com/attr/
$( "input" )_x000D_
.change(function() {_x000D_
var $input = $( this );_x000D_
$( "p" ).html( ".attr( 'checked' ): <b>" + $input.attr( "checked" ) + "</b><br>" +_x000D_
".prop( 'checked' ): <b>" + $input.prop( "checked" ) + "</b><br>" +_x000D_
".is( ':checked' ): <b>" + $input.is( ":checked" ) + "</b>" );_x000D_
})_x000D_
.change();
_x000D_
p {_x000D_
margin: 20px 0 0;_x000D_
}_x000D_
b {_x000D_
color: blue;_x000D_
}
_x000D_
<meta charset="utf-8">_x000D_
<title>attr demo</title>_x000D_
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<input id="check1" type="checkbox" checked="checked">_x000D_
<label for="check1">Check me</label>_x000D_
<p></p>_x000D_
_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
sp_change_users_login
is deprecated.
Much easier is:
ALTER USER usr1 WITH LOGIN = login1;
Try this.
SELECT
CASE
WHEN FRUIT = 'A' THEN 'APPLE'
WHEN FRUIT = 'B' THEN 'BANANA'
ELSE 'UNKNOWN FRUIT'
END AS FRUIT
FROM FRUIT_TABLE;
Just use a logging library, like log4net, and have it log to a file appender.
The move
instruction copies a value from one register to another. The li
instruction loads a specific numeric value into that register.
For the specific case of zero, you can use either the constant zero or the zero register to get that:
move $s0, $zero
li $s0, 0
There's no register that generates a value other than zero, though, so you'd have to use li
if you wanted some other number, like:
li $s0, 12345678
Use this css, as you already have the markup for it:
.img-container {
position: absolute;
top: 50%;
left: 50%;
}
.img-container > img {
margin-top:-50%;
margin-left:-50%;
}
Here is a working JsBin: http://jsbin.com/ihilUnI/1/edit
This solution only works for square images (because a percentage margin-top value depends on the width of the container, not the height). For random-size images, you can do the following:
.img-container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* add browser-prefixes */
}
Working JsBin solution: http://jsbin.com/ihilUnI/2/edit
This works for me:
import Cookies from 'universal-cookie';
const cookies = new Cookies();
function headers(set_cookie=false) {
let headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
};
if (set_cookie) {
headers['Authorization'] = "Bearer " + cookies.get('remember_user_token');
}
return headers;
}
Then build your call:
export function fetchTests(user_id) {
return function (dispatch) {
let data = {
method: 'POST',
credentials: 'same-origin',
mode: 'same-origin',
body: JSON.stringify({
user_id: user_id
}),
headers: headers(true)
};
return fetch('/api/v1/tests/listing/', data)
.then(response => response.json())
.then(json => dispatch(receiveTests(json)));
};
}
sudo apt-get install mysql-client-core-5.5
You need to make TestGetMethod async
too and attach await in front of GetIdList();
will unwrap the task to List<int>
, So if your helper function is returning Task make sure you have await as you are calling the function async
too.
public Task<List<int>> TestGetMethod()
{
return GetIdList();
}
async Task<List<int>> GetIdList()
{
using (HttpClient proxy = new HttpClient())
{
string response = await proxy.GetStringAsync("www.test.com");
List<int> idList = JsonConvert.DeserializeObject<List<int>>();
return idList;
}
}
Another option
public async void TestGetMethod(List<int> results)
{
results = await GetIdList(); // await will unwrap the List<int>
}
This doesn't have anything to do with app.js
at all. Instead, this warning is logged when you include the Angular JS library more than once.
I've managed to reproduce the error in this JSBin. Note the two script tags (two different versions):
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
Relevant Angular code at GitHub.
DateTimeFormatter
has in-built formats that can directly be used to parse a character sequence. It is case Sensitive, Nov will work however nov and
NOV wont work:
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
try {
LocalDate datetime = LocalDate.parse(oldDate, pattern);
System.out.println(datetime);
} catch (DateTimeParseException e) {
// DateTimeParseException - Text '2019-nov-12' could not be parsed at index 5
// Exception handling message/mechanism/logging as per company standard
}
DateTimeFormatterBuilder
provides custom way to create a formatter. It is Case Insensitive, Nov , nov and NOV will be treated as same.
DateTimeFormatter f = new DateTimeFormatterBuilder().parseCaseInsensitive()
.append(DateTimeFormatter.ofPattern("yyyy-MMM-dd")).toFormatter();
try {
LocalDate datetime = LocalDate.parse(oldDate, f);
System.out.println(datetime); // 2019-11-12
} catch (DateTimeParseException e) {
// Exception handling message/mechanism/logging as per company standard
}
Below is a class which will accomplish the very basics of what you want to do when reading data from a MySQL database into a JTable
in Java.
import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableFromMySqlDatabase extends JFrame
{
public TableFromMySqlDatabase()
{
ArrayList columnNames = new ArrayList();
ArrayList data = new ArrayList();
// Connect to an MySQL Database, run query, get result set
String url = "jdbc:mysql://localhost:3306/yourdb";
String userid = "root";
String password = "sesame";
String sql = "SELECT * FROM animals";
// Java SE 7 has try-with-resources
// This will ensure that the sql objects are closed when the program
// is finished with them
try (Connection connection = DriverManager.getConnection( url, userid, password );
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql ))
{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.add( md.getColumnName(i) );
}
// Get row data
while (rs.next())
{
ArrayList row = new ArrayList(columns);
for (int i = 1; i <= columns; i++)
{
row.add( rs.getObject(i) );
}
data.add( row );
}
}
catch (SQLException e)
{
System.out.println( e.getMessage() );
}
// Create Vectors and copy over elements from ArrayLists to them
// Vector is deprecated but I am using them in this example to keep
// things simple - the best practice would be to create a custom defined
// class which inherits from the AbstractTableModel class
Vector columnNamesVector = new Vector();
Vector dataVector = new Vector();
for (int i = 0; i < data.size(); i++)
{
ArrayList subArray = (ArrayList)data.get(i);
Vector subVector = new Vector();
for (int j = 0; j < subArray.size(); j++)
{
subVector.add(subArray.get(j));
}
dataVector.add(subVector);
}
for (int i = 0; i < columnNames.size(); i++ )
columnNamesVector.add(columnNames.get(i));
// Create table with database data
JTable table = new JTable(dataVector, columnNamesVector)
{
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
};
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
}
public static void main(String[] args)
{
TableFromMySqlDatabase frame = new TableFromMySqlDatabase();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
In the NetBeans IDE which you are using - you will need to add the MySQL JDBC Driver in Project Properties as I display here:
Otherwise the code will throw an SQLException
stating that the driver cannot be found.
Now in my example, yourdb
is the name of the database and animals
is the name of the table that I am performing a query against.
Here is what will be output:
Parting note:
You stated that you were a novice and needed some help understanding some of the basic classes and concepts of Java. I will list a few here, but remember you can always browse the docs on Oracle's site.
Use single quote with single char as:
char ch = 'a';
here 'a'
is a char constant and is equal to the ASCII
value of char a.
Use double quote with strings as:
char str[] = "foo";
here "foo"
is a string literal.
Its okay to use "a"
but its not okay to use 'foo'
I cam up with a recursive solution:
def sumDigits(num):
# print "evaluating:", num
if num < 10:
return num
# solution 1
# res = num/10
# rem = num%10
# print "res:", res, "rem:", rem
# return sumDigits(res+rem)
# solution 2
arr = [int(i) for i in str(num)]
return sumDigits(sum(arr))
# print(sumDigits(1))
# print(sumDigits(49))
print(sumDigits(439230))
# print(sumDigits(439237))
Date long getTime()
returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
represented by this Date object.
//test if date1 is before date2
if(date1.getTime() < date2.getTime()) {
....
}
from @Adam Rosenfield's answer, the formatting string of fscanf
would be changed like below:
"%4095[^\r\n]%n%*[\n\r]"
it will work in osx, linux, windows line endings.
I'm using RHEL 7.4 with NGINX 1.13.8 and if I do the same with sudo, it works Ok:
sudo systemctl status nginx.service
Just make sure whoever wants to use nginx.service
has execute permissions to it.
I had the same issue. And the files that I needed to be committed were never declared in the .gitignore
file as well.
In my case adding the files forcefully using the -f
flag elevated to staging and fixed the issue.
git add -f <path to file>
combo1.DisplayMember = "Text";
combo1.ValueMember = "Value";
combo1.Items.Add(new { Text = "someText"), Value = "someValue") });
dynamic item = combo1.Items[combo1.SelectedIndex];
var itemValue = item.Value;
var itemText = item.Text;
Unfortunatly "combo1.SelectedValue" does not work, i did not want to bind my combobox with any source, so i came up with this solution. Maybe it will help someone.
I had the same problem in VS2008. In my case it was solved via solution-rebuild.
The code is correct so I'm guessing that you are using an older JDK. The javadoc for that method says it has been there since 1.6. At the command line type:
java -version
I'm guessing that you are not running 1.6
First of all, this what is written in documentation. I think it is one of your class fields, not the main one - and how you want deserialiser to construct it back w/o parameterless construction ?
I think there is a workaround to make constructor private.
struct a{
int x;
struct son{
a* _parent;
void test(){
_parent->x=1; //success
}
}_son;
}_a;
int main(){
_a._son._parent=&_a;
_a._son.test();
}
Reference example.
The need for C++ delegate implementations are a long lasting embarassment to the C++ community. Every C++ programmer would love to have them, so they eventually use them despite the facts that:
std::function()
uses heap operations (and is out of reach for serious embedded programming).
All other implementations make concessions towards either portability or standard conformity to larger or lesser degrees (please verify by inspecting the various delegate implementations here and on codeproject). I have yet to see an implementation which does not use wild reinterpret_casts, Nested class "prototypes" which hopefully produce function pointers of the same size as the one passed in by the user, compiler tricks like first forward declare, then typedef then declare again, this time inheriting from another class or similar shady techniques. While it is a great accomplishment for the implementers who built that, it is still a sad testimoney on how C++ evolves.
Only rarely is it pointed out, that now over 3 C++ standard revisions, delegates were not properly addressed. (Or the lack of language features which allow for straightforward delegate implementations.)
With the way C++11 lambda functions are defined by the standard (each lambda has anonymous, different type), the situation has only improved in some use cases. But for the use case of using delegates in (DLL) library APIs, lambdas alone are still not usable. The common technique here, is to first pack the lambda into a std::function and then pass it across the API.
Return a relative filepath to path either from the current directory or from an optional start point.
>>> from os.path import relpath
>>> relpath('/usr/var/log/', '/usr/var')
'log'
>>> relpath('/usr/var/log/', '/usr/var/sad/')
'../log'
So, if relative path starts with '..'
- it means that the second path is not descendant of the first path.
In Python3 you can use PurePath.relative_to
:
Python 3.5.1 (default, Jan 22 2016, 08:54:32)
>>> from pathlib import Path
>>> Path('/usr/var/log').relative_to('/usr/var/log/')
PosixPath('.')
>>> Path('/usr/var/log').relative_to('/usr/var/')
PosixPath('log')
>>> Path('/usr/var/log').relative_to('/etc/')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/pathlib.py", line 851, in relative_to
.format(str(self), str(formatted)))
ValueError: '/usr/var/log' does not start with '/etc'
All you have to do is copy the cv2.pyd file from the x86 folder (C:\opencv\build\python\2.7\x86\ for example) to C:\Python27\Lib\site-packages\ , not from the x64 folder.
Hope that help you.
Add a listener to the underlying Document, which is automatically created for you.
// Listen for changes in the text
textField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
if (Integer.parseInt(textField.getText())<=0){
JOptionPane.showMessageDialog(null,
"Error: Please enter number bigger than 0", "Error Message",
JOptionPane.ERROR_MESSAGE);
}
}
});
None of the answers work for all output types the same way and others focus on figures plottet within the code chunk and not external images.
The include_graphics()
function provides an easy solution. The only argument is the name of the file (with the relative path if it's in a subfolder). By setting echo
to FALSE
and fig.align=center
you get the wished result.
```{r, echo=FALSE, fig.align='center'}
include_graphics("image.jpg")
```
Full disclosure, I'm the author of this package
Google's material-design-icons project is on low maintenance and out of date for a while. There's a gap between the version in https://material.io/icons/ and the version in material-design-icons.
I've created material-design-icons-iconfont to address these major issues:
npm install
- all irrelevant svg/xml/... files has been removedGoogle Fonts
CDN npm
npm install material-design-icons-iconfont --save
It depends on how you pack your web application (webpack
/gulp
/bower
/...), you'll need to import the .css
/.scss
file (and might change the relative fonts path)
Import Using SCSS
Import in one of your sass files
$material-design-icons-font-path: '~material-design-icons-iconfont/dist/fonts/';
@import '~material-design-icons-iconfont/src/material-design-icons';
Later on, reference your desired icon <i class="material-icons">
+ icon-id + </i>
<i class="material-icons">contact_support</i>
It comes with a light demo page to assist searching and copy-pasting fonts
ifconfig | grep 'inet ' | grep -v '127.0.0.1' | awk '{print $2}'
For file names:
var cleanFileName = string.Join("", fileName.Split(Path.GetInvalidFileNameChars()));
For full paths:
var cleanPath = string.Join("", path.Split(Path.GetInvalidPathChars()));
Note that if you intend to use this as a security feature, a more robust approach would be to expand all paths and then verify that the user supplied path is indeed a child of a directory the user should have access to.
Profile pictures are scaled down to 125x125 on the facebook sever when they're uploaded, so as far as I know you can't get pictures bigger than that. How big is the picture you're getting?
I had this problem today testing a method that converted an object that contained a Map
to a JSON string. I assume Eclipse and the Maven surefire plugin were using different JREs which had different implementations of HashMap
ordering or something, which caused the tests run through Eclipse to pass and the tests run through surefire to fail (assertEquals
failed). The easiest solution was to use an implementation of Map that had reliable ordering.
if (value == "") {
// it is empty
}
[[NSDate date] timeIntervalSince1970];
It returns the number of seconds since epoch as a double. I'm almost sure you can access the milliseconds from the fractional part.
Try this in input field:
[readonly]="true"
Hope, this will work.
In pycharm I wrote the code for accessing the IP Camera like:
import cv2
cap=VideoCapture("rtsp://user_name:password@IP_address:port_number")
ret, frame=cap.read()
You will need to replace user_name
, password
, IP
and port
with suitable values
The previous posts about forming POST
requests are largely correct (add the parameters to the body, not the URL). But if there is any chance of the input data containing any reserved characters (e.g. spaces, ampersand, plus sign), then you will want to handle these reserved characters. Namely, you should percent-escape the input.
//create body of the request
NSString *userid = ...
NSString *encodedUserid = [self percentEscapeString:userid];
NSString *postString = [NSString stringWithFormat:@"userid=%@", encodedUserid];
NSData *postBody = [postString dataUsingEncoding:NSUTF8StringEncoding];
//initialize a request from url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:postBody];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//initialize a connection from request, any way you want to, e.g.
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Where the precentEscapeString
method is defined as follows:
- (NSString *)percentEscapeString:(NSString *)string
{
NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)string,
(CFStringRef)@" ",
(CFStringRef)@":/?@!$&'()*+,;=",
kCFStringEncodingUTF8));
return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"];
}
Note, there was a promising NSString
method, stringByAddingPercentEscapesUsingEncoding
(now deprecated), that does something very similar, but resist the temptation to use that. It handles some characters (e.g. the space character), but not some of the others (e.g. the +
or &
characters).
The contemporary equivalent is stringByAddingPercentEncodingWithAllowedCharacters
, but, again, don't be tempted to use URLQueryAllowedCharacterSet
, as that also allows +
and &
pass unescaped. Those two characters are permitted within the broader "query", but if those characters appear within a value within a query, they must escaped. Technically, you can either use URLQueryAllowedCharacterSet
to build a mutable character set and remove a few of the characters that they've included in there, or build your own character set from scratch.
For example, if you look at Alamofire's parameter encoding, they take URLQueryAllowedCharacterSet
and then remove generalDelimitersToEncode
(which includes the characters #
, [
, ]
, and @
, but because of a historical bug in some old web servers, neither ?
nor /
) and subDelimitersToEncode
(i.e. !
, $
, &
, '
, (
, )
, *
, +
, ,
, ;
, and =
). This is correct implementation (though you could debate the removal of ?
and /
), though pretty convoluted. Perhaps CFURLCreateStringByAddingPercentEscapes
is more direct/efficient.
I had the exact same problem with my instance. My problem was that I forgot to allow port 80 access to the server. Maybe that's your issue as well?
Check with your WHM and make sure that port is open for the IP address of your site,
When you call a Linq statement like this:
// x = new List<string>();
var count = x.Count(s => s.StartsWith("x"));
You are actually using an extension method in the System.Linq namespace, so what the compiler translates this into is:
var count = Enumerable.Count(x, s => s.StartsWith("x"));
So the error you are getting above is because the first parameter, source
(which would be x
in the sample above) is null.
You can include the branch to track when setting up remotes, to keep things working as you might expect:
git remote add --track master origin [email protected]:group/project.git # git
git remote add --track master origin [email protected]:group/project.git # git w/IP
git remote add --track master origin http://github.com/group/project.git # http
git remote add --track master origin http://172.16.1.100/group/project.git # http w/IP
git remote add --track master origin /Volumes/Git/group/project/ # local
git remote add --track master origin G:/group/project/ # local, Win
This keeps you from having to manually edit your git config or specify branch tracking manually.
I just wondered, why col-xs-6
did not work for me but then I found the answer in the Bootstrap 4 documentation. The class prefix for extra small devices is now col-
while in the previous versions it was col-xs
.
https://getbootstrap.com/docs/4.1/layout/grid/#grid-options
Bootstrap 4 dropped all col-xs-*
classes, so use col-*
instead. For example col-xs-6
replaced by col-6
.
From the standard
7.5.2 Element identifiers: the id and class attributes
Attribute definitions
id = name [CS]
This attribute assigns a name to an element. This name must be unique in a document.class = cdata-list [CS]
This attribute assigns a class name or set of class names to an element. Any number of elements may be assigned the same class name or names. Multiple class names must be separated by white space characters.
Yes, just put a space between them.
<article class="column wrapper">
Of course, there are many things you can do with CSS inheritance. Here is an article for further reading.
When you go to the MySQL download page, choose the platform "Microsoft Windows". Then download the "Windows (x86, xx-bit), ZIP Archive" (be sure to select the one with size over 140M.
The binaries will be in the "bin" folder.
I understand that this is not just the client binaries, but at least you don't have to install and setup the entire server.
The REST API for Dropbox, Twitter, Google Web Services and Facebook all uses underscores.
I came across this error today when I wanted to add a new column like this
df_temp['REMARK_TYPE'] = df.REMARK.apply(lambda v: 1 if str(v)!='nan' else 0)
I wanted to process the REMARK
column of df_temp
to return 1 or 0. However I typed wrong variable with df
. And it returned error like this:
----> 1 df_temp['REMARK_TYPE'] = df.REMARK.apply(lambda v: 1 if str(v)!='nan' else 0)
/usr/lib64/python2.7/site-packages/pandas/core/frame.pyc in __setitem__(self, key, value)
2417 else:
2418 # set column
-> 2419 self._set_item(key, value)
2420
2421 def _setitem_slice(self, key, value):
/usr/lib64/python2.7/site-packages/pandas/core/frame.pyc in _set_item(self, key, value)
2483
2484 self._ensure_valid_index(value)
-> 2485 value = self._sanitize_column(key, value)
2486 NDFrame._set_item(self, key, value)
2487
/usr/lib64/python2.7/site-packages/pandas/core/frame.pyc in _sanitize_column(self, key, value, broadcast)
2633
2634 if isinstance(value, Series):
-> 2635 value = reindexer(value)
2636
2637 elif isinstance(value, DataFrame):
/usr/lib64/python2.7/site-packages/pandas/core/frame.pyc in reindexer(value)
2625 # duplicate axis
2626 if not value.index.is_unique:
-> 2627 raise e
2628
2629 # other
ValueError: cannot reindex from a duplicate axis
As you can see it, the right code should be
df_temp['REMARK_TYPE'] = df_temp.REMARK.apply(lambda v: 1 if str(v)!='nan' else 0)
Because df
and df_temp
have a different number of rows. So it returned ValueError: cannot reindex from a duplicate axis
.
Hope you can understand it and my answer can help other people to debug their code.
BufferedReader
can't wrap an InputStream
directly. It wraps another Reader
. In this case you'd want to do something like:
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
Try this query:
SELECT id, COUNT( payer_email ) `tot`
FROM paypal_ipn_orders
GROUP BY id
HAVING `tot` >1
Does it help?
To link to a form you need:
Form2 form2 = new Form2();
form2.show();
this.hide();
then hide the previous form
this prototype:
int execlp(const char *file, const char *arg, ...);
Says that execlp ìs a variable argument function. It takes 2 const char *
. The rest of the arguments, if any, are the additional arguments to hand over to program we want to run - also char *
- all these are C strings (and the last argument must be a NULL pointer)
So, the file
argument is the path name of an executable file to be executed. arg
is the string we want to appear as argv[0]
in the executable. By convention, argv[0]
is just the file name of the executable, normally it's set to the same as file
.
The ...
are now the additional arguments to give to the executable.
Say you run this from a commandline/shell:
$ ls
That'd be execlp("ls", "ls", (char *)NULL);
Or if you run
$ ls -l /
That'd be execlp("ls", "ls", "-l", "/", (char *)NULL);
So on to execlp("/bin/sh", ..., "ls -l /bin/??", ...);
Here you are going to the shell, /bin/sh , and you're giving the shell a command to execute. That command is "ls -l /bin/??". You can run that manually from a commandline/shell:
$ ls -l /bin/??
Now, how do you run a shell and tell it to execute a command ? You open up the documentation/man page for your shell and read it.
What you want to run is:
$ /bin/sh -c "ls -l /bin/??"
This becomes
execlp("/bin/sh","/bin/sh", "-c", "ls -l /bin/??", (char *)NULL);
Side note:
The /bin/??
is doing pattern matching, this pattern matching is done by the shell, and it expands to all files under /bin/ with 2 characters. If you simply did
execlp("ls","ls", "-l", "/bin/??", (char *)NULL);
Probably nothing would happen (unless there's a file actually named /bin/??
) as there's no shell that interprets and expands /bin/??
I'm not sure whether it's a good idea to use integers at all. Some numbers might contain special characters (# as part of the extension for example) which you should be able to handle too. So I would suggest using varchars instead.
func sum(array : [Int]) -> Int{
var sum = 0
array.forEach { (item) in
sum = item + sum
}
return sum
}
func susetNumbers(array :[Int], target : Int, subsetArray: [Int],result : inout [[Int]]) -> [[Int]]{
let s = sum(array: subsetArray)
if(s == target){
print("sum\(subsetArray) = \(target)")
result.append(subsetArray)
}
for i in 0..<array.count{
let n = array[i]
let remaning = Array(array[(i+1)..<array.count])
susetNumbers(array: remaning, target: target, subsetArray: subsetArray + [n], result: &result)
}
return result
}
var resultArray = [[Int]]()
let newA = susetNumbers(array: [1,2,3,4,5], target: 5, subsetArray: [],result:&resultArray)
print(resultArray)
Try This
SELECT Title from #Movies
SELECT CASE WHEN Title = '' THEN 'No Title' ELSE Title END AS Titile from #Movies
OR
SELECT [Id], [CategoryId], ISNULL(nullif(Title,''),'No data') as Title, [Director], [DateReleased] FROM #Movies
The order in which you use middleware in Express matters: middleware declared earlier will get called first, and if it can handle a request, any middleware declared later will not get called.
If express.static
is handling the request, you need to move your middleware up:
// need cookieParser middleware before we can do anything with cookies
app.use(express.cookieParser());
// set a cookie
app.use(function (req, res, next) {
// check if client sent cookie
var cookie = req.cookies.cookieName;
if (cookie === undefined) {
// no: set a new cookie
var randomNumber=Math.random().toString();
randomNumber=randomNumber.substring(2,randomNumber.length);
res.cookie('cookieName',randomNumber, { maxAge: 900000, httpOnly: true });
console.log('cookie created successfully');
} else {
// yes, cookie was already present
console.log('cookie exists', cookie);
}
next(); // <-- important!
});
// let static middleware do its job
app.use(express.static(__dirname + '/public'));
Also, middleware needs to either end a request (by sending back a response), or pass the request to the next middleware. In this case, I've done the latter by calling next()
when the cookie has been set.
Update
As of now the cookie parser is a seperate npm package, so instead of using
app.use(express.cookieParser());
you need to install it separately using npm i cookie-parser
and then use it as:
const cookieParser = require('cookie-parser');
app.use(cookieParser());
Make sure you Double-Check that the version you refer to in the child-pom is the same as that in the parent-pom. For me, I'd bumped version in the parent and had it as 3.1.0.0-RELEASE, but in the child-pom, I was still referring to the previous version via relativePath, and had it defined as 2.0.0.0-SNAPSHOT. It did not make any difference if I included just the parent directory, or had the "pom.xml" appended to the directory:
<parent>
<artifactId>eric-project-parent</artifactId>
<groupId>com.eric.common</groupId>
<!-- Should be 3.1.0.0-RELEASE -->
<version>2.0.0.0-SNAPSHOT</version>
<relativePath>
../../EricParentAsset/projects/eric-project-parent</relativePath>
</parent>
The following will print the line matching TERMINATE
till the end of the file:
sed -n -e '/TERMINATE/,$p'
Explained: -n
disables default behavior of sed
of printing each line after executing its script on it, -e
indicated a script to sed
, /TERMINATE/,$
is an address (line) range selection meaning the first line matching the TERMINATE
regular expression (like grep) to the end of the file ($
), and p
is the print command which prints the current line.
This will print from the line that follows the line matching TERMINATE
till the end of the file:
(from AFTER the matching line to EOF, NOT including the matching line)
sed -e '1,/TERMINATE/d'
Explained: 1,/TERMINATE/
is an address (line) range selection meaning the first line for the input to the 1st line matching the TERMINATE
regular expression, and d
is the delete command which delete the current line and skip to the next line. As sed
default behavior is to print the lines, it will print the lines after TERMINATE
to the end of input.
Edit:
If you want the lines before TERMINATE
:
sed -e '/TERMINATE/,$d'
And if you want both lines before and after TERMINATE
in 2 different files in a single pass:
sed -e '1,/TERMINATE/w before
/TERMINATE/,$w after' file
The before and after files will contain the line with terminate, so to process each you need to use:
head -n -1 before
tail -n +2 after
Edit2:
IF you do not want to hard-code the filenames in the sed script, you can:
before=before.txt
after=after.txt
sed -e "1,/TERMINATE/w $before
/TERMINATE/,\$w $after" file
But then you have to escape the $
meaning the last line so the shell will not try to expand the $w
variable (note that we now use double quotes around the script instead of single quotes).
I forgot to tell that the new line is important after the filenames in the script so that sed knows that the filenames end.
Edit: 2016-0530
Sébastien Clément asked: "How would you replace the hardcoded TERMINATE
by a variable?"
You would make a variable for the matching text and then do it the same way as the previous example:
matchtext=TERMINATE
before=before.txt
after=after.txt
sed -e "1,/$matchtext/w $before
/$matchtext/,\$w $after" file
to use a variable for the matching text with the previous examples:
## Print the line containing the matching text, till the end of the file:
## (from the matching line to EOF, including the matching line)
matchtext=TERMINATE
sed -n -e "/$matchtext/,\$p"
## Print from the line that follows the line containing the
## matching text, till the end of the file:
## (from AFTER the matching line to EOF, NOT including the matching line)
matchtext=TERMINATE
sed -e "1,/$matchtext/d"
## Print all the lines before the line containing the matching text:
## (from line-1 to BEFORE the matching line, NOT including the matching line)
matchtext=TERMINATE
sed -e "/$matchtext/,\$d"
The important points about replacing text with variables in these cases are:
$variablename
) enclosed in single quotes
['
] won't "expand" but variables inside double quotes
["
] will. So, you have to change all the single quotes
to double quotes
if they contain text you want to replace with a variable. sed
ranges also contain a $
and are immediately followed by a letter like: $p
, $d
, $w
. They will also look like variables to be expanded, so you have to escape those $
characters with a backslash [\
] like: \$p
, \$d
, \$w
.I think you're looking for;
string[] skus = myLines.Select(x => x.Sku).ToArray();
However, if you're going to iterate over the sku's in subsequent code I recommend not using the ToArray()
bit as it forces the queries execution prematurely and makes the applications performance worse. Instead you can just do;
var skus = myLines.Select(x => x.Sku); // produce IEnumerable<string>
foreach (string sku in skus) // forces execution of the query
I tried pasting Endoro's command (Thanks Endoro) directly into the command prompt to add a prefix to files but encountered an error. Solution was to reduce %% to %, so:
for /f "delims=" %i in ('dir /b /a-d *.*') do ren "%~i" "Service.Enviro.%~ni%~xi"
I also recommend the SSH SFTP Updater Support plugin. Just solved all my problems too...especially in regards to getting plugins to delete through the admin. Just install it in the usual way, and the next time you're prompted by WordPress for FTP details, there'll be extra fields for you to copy/paste your private SSH key or upload your PEM file.
Only problem I have is in getting it to remember the key (tried both methods). Don't like the idea of having to find and enter it every time I need to delete a plugin. But at least it's a solid fix for now.
check, if this works for you.
File -> Settings -> (type appe in search box) and select Appearance -> Select Intellij from dropdown option of Theme on the right (under UI Options).
Hope this helps someone.
Hadley's tidyr
just got this amazing function drop_na
library(tidyr)
DF %>% drop_na(y)
x y z
1 1 0 NA
2 2 10 33
Try adding 2 spaces (or a backslash \
) after the first line:
[Name of link](url)
My line of text\
Visually:
[Name of link](url)<space><space>
My line of text\
Output:
<p><a href="url">Name of link</a><br>
My line of text<br></p>
Explaining if any one want to send some parameters while calling stored procedure as below,
using (SqlConnection con = new SqlConnection(connetionString))
{
using (var command = new SqlCommand(storedProcName, con))
{
foreach (var item in sqlParams)
{
item.Direction = ParameterDirection.Input;
item.DbType = DbType.String;
command.Parameters.Add(item);
}
command.CommandType = CommandType.StoredProcedure;
using (var adapter = new SqlDataAdapter(command))
{
adapter.Fill(dt);
}
}
}
I understand that the answer was useful however for some reason it does not work for me however I have moved the situation with the following code and it is perfect
<?php
$codigoarticulo = $_POST['codigoarticulo'];
$nombrearticulo = $_POST['nombrearticulo'];
$seccion = $_POST['seccion'];
$precio = $_POST['precio'];
$fecha = $_POST['fecha'];
$importado = $_POST['importado'];
$paisdeorigen = $_POST['paisdeorigen'];
try {
$server = 'mysql: host=localhost; dbname=usuarios';
$user = 'root';
$pass = '';
$base = new PDO($server, $user, $pass);
$base->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$base->query("SET character_set_results = 'utf8',
character_set_client = 'utf8',
character_set_connection = 'utf8',
character_set_database = 'utf8',
character_set_server = 'utf8'");
$base->exec("SET character_set_results = 'utf8',
character_set_client = 'utf8',
character_set_connection = 'utf8',
character_set_database = 'utf8',
character_set_server = 'utf8'");
$sql = "
INSERT INTO productos
(CÓDIGOARTÍCULO, NOMBREARTÍCULO, SECCIÓN, PRECIO, FECHA, IMPORTADO, PAÍSDEORIGEN)
VALUES
(:c_art, :n_art, :sec, :pre, :fecha_art, :import, :p_orig)";
// SE ejecuta la consulta ben prepare
$result = $base->prepare($sql);
// se pasan por parametros aqui
$result->bindParam(':c_art', $codigoarticulo);
$result->bindParam(':n_art', $nombrearticulo);
$result->bindParam(':sec', $seccion);
$result->bindParam(':pre', $precio);
$result->bindParam(':fecha_art', $fecha);
$result->bindParam(':import', $importado);
$result->bindParam(':p_orig', $paisdeorigen);
$result->execute();
echo 'Articulo agregado';
} catch (Exception $e) {
echo 'Error';
echo $e->getMessage();
} finally {
}
?>
Here is a simple mail sending code with attachment
try
{
SmtpClient mailServer = new SmtpClient("smtp.gmail.com", 587);
mailServer.EnableSsl = true;
mailServer.Credentials = new System.Net.NetworkCredential("[email protected]", "mypassword");
string from = "[email protected]";
string to = "[email protected]";
MailMessage msg = new MailMessage(from, to);
msg.Subject = "Enter the subject here";
msg.Body = "The message goes here.";
msg.Attachments.Add(new Attachment("D:\\myfile.txt"));
mailServer.Send(msg);
}
catch (Exception ex)
{
Console.WriteLine("Unable to send email. Error : " + ex);
}
Read more Sending emails with attachment in C#
Do not use arrow function to create functional components.
Do as one of the examples below:
function MyComponent(props) {
const [states, setStates] = React.useState({ value: '' });
return (
<input
type="text"
value={states.value}
onChange={(event) => setStates({ value: event.target.value })}
/>
);
}
Or
//IMPORTANT: Repeat the function name
const MyComponent = function MyComponent(props) {
const [states, setStates] = React.useState({ value: '' });
return (
<input
type="text"
value={states.value}
onChange={(event) => setStates({ value: event.target.value })}
/>
);
};
If you have problems with "ref"
(probably in loops), the solution is to use forwardRef()
:
// IMPORTANT: Repeat the function name
// Add the "ref" argument to the function, in case you need to use it.
const MyComponent = React.forwardRef( function MyComponent(props, ref) {
const [states, setStates] = React.useState({ value: '' });
return (
<input
type="text"
value={states.value}
onChange={(event) => setStates({ value: event.target.value })}
/>
);
});
If you're looking to turn the items in a list into a big long string, do this: String.Join("", myList)
. Some older versions of the framework don't allow you to pass an IEnumerable as the second parameter, so you may need to convert your list to an array by calling .ToArray().
With recent browser support of "Clear-Site-Data" headers, you can clear different types of data: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data
header('Clear-Site-Data: "cache", "cookies", "storage", "executionContexts"');
There are a lot of good reasons in other answers but all seem to forget that
for_each
allows you to use reverse or pretty much any custom iterator when for loop always starts with begin()
iterator.
Example with reverse iterator:
std::list<int> l {1,2,3};
std::for_each(l.rbegin(), l.rend(), [](auto o){std::cout<<o;});
Example with some custom tree iterator:
SomeCustomTree<int> a{1,2,3,4,5,6,7};
auto node = a.find(4);
std::for_each(node.breadthFirstBegin(), node.breadthFirstEnd(), [](auto o){std::cout<<o;});
function isPrevDate() {
alert("startDate is " + Startdate);
if(Startdate.length != 0 && Startdate !='') {
var start_date = Startdate.split('-');
alert("Input date: "+ start_date);
start_date=start_date[1]+"/"+start_date[2]+"/"+start_date[0];
alert("start date arrray format " + start_date);
var a = new Date(start_date);
//alert("The date is a" +a);
var today = new Date();
var day = today.getDate();
var mon = today.getMonth()+1;
var year = today.getFullYear();
today = (mon+"/"+day+"/"+year);
//alert(today);
var today = new Date(today);
alert("Today: "+today.getTime());
alert("a : "+a.getTime());
if(today.getTime() > a.getTime() )
{
alert("Please select Start date in range");
return false;
} else {
return true;
}
}
}
> S = matrix(c(1,2,3,4,5,2,1,2,3,4,3,2,1,2,3,4,3,2,1,2,5,4,3,2,1),ncol = 5,byrow = TRUE);S
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 2 1 2 3 4
[3,] 3 2 1 2 3
[4,] 4 3 2 1 2
[5,] 5 4 3 2 1
> S<-S[,-2]
> S
[,1] [,2] [,3] [,4]
[1,] 1 3 4 5
[2,] 2 2 3 4
[3,] 3 1 2 3
[4,] 4 2 1 2
[5,] 5 3 2 1
Just use the command S <- S[,-2]
to remove the second column. Similarly to delete a row, for example, to delete the second row use S <- S[-2,]
.
You can also drag a tap gesture recogniser to the image view in Storyboard
. Then create an action by ctrl + drag
to the code.
In Bootstrap 4, if you want to do something like this:
Mobile | Desktop
-----------------------------
A | A
C | B C
B | D
D |
You need to reverse the order of B then C then apply order-{breakpoint}-first
to B. And apply two different settings, one that will make them share the same cols and other that will make them take the full width of the 12 cols:
Smaller screens: 12 cols to B and 12 cols to C
Larger screens: 12 cols between the sum of them (B + C = 12)
Like this
<div class='row no-gutters'>
<div class='col-12'>
A
</div>
<div class='col-12'>
<div class='row no-gutters'>
<div class='col-12 col-md-6'>
C
</div>
<div class='col-12 col-md-6 order-md-first'>
B
</div>
</div>
</div>
<div class='col-12'>
D
</div>
</div>
Using LINQ:
arr = (arr ?? Enumerable.Empty<string>()).Concat(new[] { newitem }).ToArray();
I like using this as it is a one-liner and very convenient to embed in a switch statement, a simple if-statement, or pass as argument.
EDIT:
Some people don't like new[] { newitem }
because it creates a small, one-item, temporary array. Here is a version using Enumerable.Repeat
that does not require creating any object (at least not on the surface -- .NET iterators probably create a bunch of state machine objects under the table).
arr = (arr ?? Enumerable.Empty<string>()).Concat(Enumerable.Repeat(newitem,1)).ToArray();
And if you are sure that the array is never null
to start with, you can simplify it to:
arr.Concat(Enumerable.Repeat(newitem,1)).ToArray();
Notice that if you want to add items to a an ordered collection, List
is probably the data structure you want, not an array to start with.
The font-min-size
and font-max-size
CSS properties were removed from the CSS Fonts Module Level 4 specification (and never implemented in browsers AFAIK). And the CSS Working Group replaced the CSS examples with font-size: clamp(...)
which doesn't have the greatest browser support yet so we'll have to wait for browsers to support it. See example in https://developer.mozilla.org/en-US/docs/Web/CSS/clamp#Examples.