If you would like to check in PHP , then you should do something like :
$query_s =mysql_query("SELECT YOURROWNAME from `YOURTABLENAME` where name = $name");
$ertom=mysql_fetch_array($query_s);
if ('' !== $ertom['YOURROWNAME']) {
//do your action
echo "It was filled";
} else {
echo "it was empty!";
}
Had this issue with ES6 and TypeORM while trying to pass .where("order.id IN (:orders)", { orders })
, where orders
was a comma separated string of numbers. When I converted to a template literal, the problem was resolved.
.where(`order.id IN (${orders})`);
Since 0.11 hive has a NVL function
nvl(T value, T default_value)
which says Returns default value if value is null else returns value
Try this, this should also get rid of those empty lines also:
SELECT prereq FROM test WHERE prereq IS NOT NULL;
As per documentation:
Your workaround would be to create a view for each of your subqueries.
Then access those views from within your view view_credit_status
What happens if you try the following?
Instead of your double REPLACE
statement, try:
REPLACE(IFNULL(ts.description, ''),'\r\n', '\n')
Also, I think it should be LINES TERMINATED BY '\r\n'
instead of just '\n'
If there is not ISNULL()
method, you can use this expression instead:
CASE WHEN fieldname IS NULL THEN 0 ELSE fieldname END
This works the same as ISNULL(fieldname, 0)
.
Views can:
And you should not design tables to match views. Your base model should concern itself with efficient storage and retrieval of the data. Views are partly a tool that mitigates the complexities that arise from an efficient, normalized model by allowing you to abstract that complexity.
Also, asking "what are the advantages of using a view over a table? " is not a great comparison. You can't go without tables, but you can do without views. They each exist for a very different reason. Tables are the concrete model and Views are an abstracted, well, View.
Use the android:drawableLeft
property on the EditText.
<EditText
...
android:drawableLeft="@drawable/my_icon" />
You can convert hex to RGB:
string ccode = "#00FFFF00";
int argb = Int32.Parse(ccode.Replace("#", ""), NumberStyles.HexNumber);
Color clr = Color.FromArgb(argb);
you have to iterate gridview Rows
for (int count = 0; count < grd.Rows.Count; count++)
{
if (((CheckBox)grd.Rows[count].FindControl("yourCheckboxID")).Checked)
{
((Label)grd.Rows[count].FindControl("labelID")).Text
}
}
System.Json works now...
Install nuget https://www.nuget.org/packages/System.Json
PM> Install-Package System.Json -Version 4.5.0
Sample:
// PM>Install-Package System.Json -Version 4.5.0
using System;
using System.Json;
namespace NetCoreTestConsoleApp
{
class Program
{
static void Main(string[] args)
{
// Note that JSON keys are case sensitive, a is not same as A.
// JSON Sample
string jsonString = "{\"a\": 1,\"b\": \"string value\",\"c\":[{\"Value\": 1}, {\"Value\": 2,\"SubObject\":[{\"SubValue\":3}]}]}";
// You can use the following line in a beautifier/JSON formatted for better view
// {"a": 1,"b": "string value","c":[{"Value": 1}, {"Value": 2,"SubObject":[{"SubValue":3}]}]}
/* Formatted jsonString for viewing purposes:
{
"a":1,
"b":"string value",
"c":[
{
"Value":1
},
{
"Value":2,
"SubObject":[
{
"SubValue":3
}
]
}
]
}
*/
// Verify your JSON if you get any errors here
JsonValue json = JsonValue.Parse(jsonString);
// int test
if (json.ContainsKey("a"))
{
int a = json["a"]; // type already set to int
Console.WriteLine("json[\"a\"]" + " = " + a);
}
// string test
if (json.ContainsKey("b"))
{
string b = json["b"]; // type already set to string
Console.WriteLine("json[\"b\"]" + " = " + b);
}
// object array test
if (json.ContainsKey("c") && json["c"].JsonType == JsonType.Array)
{
// foreach loop test
foreach (JsonValue j in json["c"])
{
Console.WriteLine("j[\"Value\"]" + " = " + j["Value"].ToString());
}
// multi level key test
Console.WriteLine("json[\"c\"][0][\"Value\"]" + " = " + json["c"][0]["Value"].ToString());
Console.WriteLine("json[\"c\"][0][\"Value\"]" + " = " + json["c"][1]["Value"].ToString());
Console.WriteLine("json[\"c\"][1][\"SubObject\"][0][\"SubValue\"]" + " = " + json["c"][1]["SubObject"][0]["SubValue"].ToString());
}
Console.WriteLine();
Console.Write("Press any key to exit.");
Console.ReadKey();
}
}
}
It should be like that:
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>unpack-dependencies</id>
<phase>generate-resources</phase>
<goals>
<goal>unpack-dependencies</goal>
</goals>
</execution>
</executions>
</plugin>
Unpacking have to be in generate-resources phase because, if in package phase, will not be included as resources. Try clean package and you'll see.
In most of the companies they required a common functionality for multiple dropdownlist for all the pages. Just call the functions or pass your (DropDownID,JsonData,KeyValue,textValue)
<script>
$(document).ready(function(){
GetData('DLState',data,'stateid','statename');
});
var data = [{"stateid" : "1","statename" : "Mumbai"},
{"stateid" : "2","statename" : "Panjab"},
{"stateid" : "3","statename" : "Pune"},
{"stateid" : "4","statename" : "Nagpur"},
{"stateid" : "5","statename" : "kanpur"}];
var Did=document.getElementById("DLState");
function GetData(Did,data,valkey,textkey){
var str= "";
for (var i = 0; i <data.length ; i++){
console.log(data);
str+= "<option value='" + data[i][valkey] + "'>" + data[i][textkey] + "</option>";
}
$("#"+Did).append(str);
}; </script>
</head>
<body>
<select id="DLState">
</select>
</body>
</html>
The setting you are looking for is allow_url_fopen
.
You have two ways of getting around it without changing php.ini, one of them is to use fsockopen()
, and the other is to use cURL.
I recommend using cURL over file_get_contents()
anyways, since it was built for this.
Every derived table (AKA sub-query) must indeed have an alias. I.e. each query in brackets must be given an alias (AS whatever
), which can the be used to refer to it in the rest of the outer query.
SELECT ID FROM (
SELECT ID, msisdn FROM (
SELECT * FROM TT2
) AS T
) AS T
In your case, of course, the entire query could be replaced with:
SELECT ID FROM TT2
It works like a charm in PhpStorm
//#region My Region 1
...
//#endregion
//#region My Region 2
...
//#endregion
This is not necessary a direct issue related to import/export. In my case, I was rendering a child element inside a parent element and the child element has jsx element / tag which is used but not imported. I imported it and I used it then it fixed the issue. So the problem was in jsx elements which are inside the child element NOT the export of child element itself.
pip freeze lists all installed packages even if not by pip/easy_install. On CentOs/Redhat a package installed through rpm is found.
You can simply use pkill -f
like this:
pkill -f 'java -jar'
EDIT: To kill a particular java process running your specific jar use this regex based pkill command:
pkill -f 'java.*lnwskInterface'
If I understand your questions correctly, all you need to do is add the .Where(m => m.r.u.UserId == 1):
var UserInRole = db.UserProfiles.
Join(db.UsersInRoles, u => u.UserId, uir => uir.UserId,
(u, uir) => new { u, uir }).
Join(db.Roles, r => r.uir.RoleId, ro => ro.RoleId, (r, ro) => new { r, ro })
.Where(m => m.r.u.UserId == 1)
.Select (m => new AddUserToRole
{
UserName = m.r.u.UserName,
RoleName = m.ro.RoleName
});
Hope that helps.
A method taking a delegate can provide multiple values to the caller. This borrows from my answer here and uses a little bit from Hadas's accepted answer.
delegate void ValuesDelegate(int upVotes, int comments);
void GetMultipleValues(ValuesDelegate callback)
{
callback(1, 2);
}
Callers provide a lambda (or a named function) and intellisense helps by copying the variable names from the delegate.
GetMultipleValues((upVotes, comments) =>
{
Console.WriteLine($"This post has {upVotes} Up Votes and {comments} Comments.");
});
You can't cast an object to a Double
if the object is not a Double.
Check out the API.
particularly note
valueOf(double d);
and
valueOf(String s);
Those methods give you a way of getting a Double
instance from a String or double primitive. (Also not the constructors; read the documentation to see how they work) The object you are trying to convert naturally has to give you something that can be transformed into a double.
Finally, keep in mind that Double
instances are immutable -- once created you can't change them.
Your library was compiled without bitcode, but the bitcode option is enabled in your project settings. Say NO
to Enable Bitcode
in your target Build Settings and the Library Build Settings to remove the warnings.
For those wondering if enabling bitcode is required:
For iOS apps, bitcode is the default, but optional. For watchOS and tvOS apps, bitcode is required. If you provide bitcode, all apps and frameworks in the app bundle (all targets in the project) need to include bitcode.
As it hasn't been proposed here, I'm adding a method using torch.device
, as this is quite handy, also when initializing tensors on the correct device
.
# setting device on GPU if available, else CPU
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Using device:', device)
print()
#Additional Info when using cuda
if device.type == 'cuda':
print(torch.cuda.get_device_name(0))
print('Memory Usage:')
print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB')
print('Cached: ', round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB')
Edit: torch.cuda.memory_cached
has been renamed to torch.cuda.memory_reserved
. So use memory_cached
for older versions.
Output:
Using device: cuda
Tesla K80
Memory Usage:
Allocated: 0.3 GB
Cached: 0.6 GB
As mentioned above, using device
it is possible to:
To move tensors to the respective device
:
torch.rand(10).to(device)
To create a tensor directly on the device
:
torch.rand(10, device=device)
Which makes switching between CPU and GPU comfortable without changing the actual code.
As there has been some questions and confusion about the cached and allocated memory I'm adding some additional information about it:
torch.cuda.max_memory_cached(device=None)
Returns the maximum GPU memory managed by the caching allocator in bytes for a
given device.
torch.cuda.memory_allocated(device=None)
Returns the current GPU memory usage by tensors in bytes for a given device.
You can either directly hand over a device
as specified further above in the post or you can leave it None and it will use the current_device()
.
Additional note: Old graphic cards with Cuda compute capability 3.0 or lower may be visible but cannot be used by Pytorch!
Thanks to hekimgil for pointing this out! - "Found GPU0 GeForce GT 750M which is of cuda capability 3.0. PyTorch no longer supports this GPU because it is too old. The minimum cuda capability that we support is 3.5."
There are the slideDown, slideUp, and slideToggle functions native to jquery 1.3+, and they work quite nicely...
https://api.jquery.com/category/effects/
You can use slideDown just like this:
$("test").slideDown("slow");
And if you want to combine effects and really go nuts I'd take a look at the animate function which allows you to specify a number of CSS properties to shape tween or morph into. Pretty fancy stuff, that.
Try:
SELECT * FROM information_schema.statistics
WHERE table_schema = [DATABASE NAME]
AND table_name = [TABLE NAME] AND column_name = [COLUMN NAME]
It will tell you if there is an index of any kind on a certain column without the need to know the name given to the index. It will also work in a stored procedure (as opposed to show index)
Same issue:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.UUID` out of START_OBJECT token
What caused it was the following:
ResponseEntity<UUID> response = restTemplate.postForEntity("/example/", null, UUID.class);
In my test I purposely set the request as null (no content POST). As previously mentioned, the cause for the OP was the same because the request didn't contain a valid JSON, so it couldn't be automatically identified as an application/json request which was the limitation on the server (consumes = "application/json"
). A valid JSON request would be. What fixed it was populating an entity with null body and json headers explicitly.
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity request = new HttpEntity<>(null, headers);
ResponseEntity<UUID> response = restTemplate.postForEntity("/example/", request, UUID.class);
Under Windows ? Preferences ? General ? Apperance you can find a dark theme.
Javascript will do the trick here.
function load() {
var file = new XMLHttpRequest();
file.open("GET", "http://remote.tld/random.txt", true);
file.onreadystatechange = function() {
if (file.readyState === 4) { // Makes sure the document is ready to parse
if (file.status === 200) { // Makes sure it's found the file
text = file.responseText;
document.getElementById("div1").innerHTML = text;
}
}
}
}
window.onLoad = load();
The questioner actually asked about int16 (etc) rather than (ugly) int16_t (etc).
There are no standard headers - nor any in Linux's /usr/include/ folder that define them without the "_t".
Avoid redundancy. If you have your jars under /libs in your app build.gradle by default you will have
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
...
}
that is enough to add all the jars you have under /libs
this is not necessary
// compile files('libs/activation.jar')
// compile files('libs/additional.jar')
// compile files('libs/mail.jar')
Method 1:\
add "C:\Program Files\cURL\bin" path into system variables Path right-click My Computer and click Properties >advanced > Environment Variables
Method 2: (if method 1 not work then)
simple open command prompt with "run as administrator"
add parameter nativeQuery = true
ex: @Query(value="Update user set user_name =:user_name,password =:password where user_id =:user_id",nativeQuery = true)
Just Checkout This :
Solution 1 :
In Subgrid Function You have to write following :
var selectid = $(this).jqGrid('getCell', row_id, 'id');
alert(selectid);
Where row_id
is the variable which you define in subgrid as parameter.
And id
is the column name which you want to get value of the cell.
Solution 2 :
If You Get Jqgrid Row Id In alert Then set your primary key id as key:true
In ColModels. So You will get value of your database id in alert. Like this :
{name:"id",index:"id",hidden:true, width:15,key:true, jsonmap:"id"},
The NameVirtualHost option would be a good option.
The accepted answer (as of 2019 JULY 29) is only still valid if you have not started using the more recent SVG-with-JS approach of FontAwesome. In which case you need to follow the instructions on their CSS Pseudo-Elements HowTo. Basically there are three things to watch out for:
You are specifying the -i
option:
-i, --include
(HTTP) Include the HTTP-header in the output. The HTTP-header includes things like server-name, date of the document, HTTP-version and more...
Simply remove that option from your command line:
response=$(curl -sb -H "Accept: application/json" "http://host:8080/some/resource")
At grub screen goto boot in recovery.
As booting hold ESC
It should take you into a gui menu. Open command and fix selinux.
Also I suggest run the clean broken packages
Assume that you have 2 branches,
"branchA" : includes commits you want to copy (from "commitA" to "commitB"
"branchB" : the branch you want the commits to be transferred from "branchA"
1)
git checkout <branchA>
2) get the IDs of "commitA" and "commitB"
3)
git checkout <branchB>
4)
git cherry-pick <commitA>^..<commitB>
5) In case you have a conflict, solve it and type
git cherry-pick --continue
to continue the cherry-pick process.
In case your table does not have th
s but only td
s (with headers included) you can try the following which is based on Nick Grealy's answer above:
const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent;_x000D_
_x000D_
const comparer = (idx, asc) => (a, b) => ((v1, v2) => _x000D_
v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)_x000D_
)(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));_x000D_
_x000D_
// do the work..._x000D_
document.querySelectorAll('tr:first-child td').forEach(td => td.addEventListener('click', (() => {_x000D_
const table = td.closest('table');_x000D_
Array.from(table.querySelectorAll('tr:nth-child(n+2)'))_x000D_
.sort(comparer(Array.from(td.parentNode.children).indexOf(td), this.asc = !this.asc))_x000D_
.forEach(tr => table.appendChild(tr) );_x000D_
})));
_x000D_
@charset "UTF-8";_x000D_
@import url('https://fonts.googleapis.com/css?family=Roboto');_x000D_
_x000D_
*{_x000D_
font-family: 'Roboto', sans-serif;_x000D_
text-transform:capitalize;_x000D_
overflow:hidden;_x000D_
margin: 0 auto;_x000D_
text-align:left;_x000D_
}_x000D_
_x000D_
table {_x000D_
color:#666;_x000D_
font-size:12px;_x000D_
background:#124;_x000D_
border:#ccc 1px solid;_x000D_
-moz-border-radius:3px;_x000D_
-webkit-border-radius:3px;_x000D_
border-radius:3px;_x000D_
border-collapse: collapse;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
table td {_x000D_
padding:10px;_x000D_
border-top: 1px solid #ffffff;_x000D_
border-bottom:1px solid #e0e0e0;_x000D_
border-left: 1px solid #e0e0e0;_x000D_
background: #fafafa;_x000D_
background: -webkit-gradient(linear, left top, left bottom, from(#fbfbfb), to(#fafafa));_x000D_
background: -moz-linear-gradient(top, #fbfbfb, #fafafa);_x000D_
width: 6.9in;_x000D_
}_x000D_
_x000D_
table tbody tr:first-child td_x000D_
{_x000D_
background: #124!important;_x000D_
color:#fff;_x000D_
}_x000D_
_x000D_
table tbody tr th_x000D_
{_x000D_
padding:10px;_x000D_
border-left: 1px solid #e0e0e0;_x000D_
background: #124!important;_x000D_
color:#fff;_x000D_
}
_x000D_
<table>_x000D_
<tr><td>Country</td><td>Date</td><td>Size</td></tr>_x000D_
<tr><td>France</td><td>2001-01-01</td><td><i>25</i></td></tr>_x000D_
<tr><td>spain</td><td>2005-05-05</td><td></td></tr>_x000D_
<tr><td>Lebanon</td><td>2002-02-02</td><td><b>-17</b></td></tr>_x000D_
<tr><td>Argentina</td><td>2005-04-04</td><td>100</td></tr>_x000D_
<tr><td>USA</td><td></td><td>-6</td></tr>_x000D_
</table>
_x000D_
I think this is very nice and short
<img src="imagenotfound.gif" alt="Image not found" onerror="this.src='imagefound.gif';" />
But, be careful. The user's browser will be stuck in an endless loop if the onerror image itself generates an error.
EDIT
To avoid endless loop, remove the onerror
from it at once.
<img src="imagenotfound.gif" alt="Image not found" onerror="this.onerror=null;this.src='imagefound.gif';" />
By calling this.onerror=null
it will remove the onerror then try to get the alternate image.
NEW I would like to add a jQuery way, if this can help anyone.
<script>
$(document).ready(function()
{
$(".backup_picture").on("error", function(){
$(this).attr('src', './images/nopicture.png');
});
});
</script>
<img class='backup_picture' src='./images/nonexistent_image_file.png' />
You simply need to add class='backup_picture' to any img tag that you want a backup picture to load if it tries to show a bad image.
I had also found this error but I have solved this problem by easy steps. If you want to solve this problem follow these steps:
Step 1: First start code block
Step 2: Go to menu bar and click on the Setting menu
Step 3: After that click on the Compiler option
Step 4: Now, a pop up window will be opened. In this window, select "GNU GCC COMPILER"
Step 5: Now go to the toolchain executables tab and select the compiler installation directory like (C:\Program Files (x86)\CodeBlocks\MinGW\bin)
Step 6: Click on the Ok.
Now you can remove this error by follow these steps. Sometimes you don't need to select bin folder. You need to select only (C:\Program Files (x86)\CodeBlocks\MinGW) this path but some system doesn't work this path. That's why you have to select path from C:/ to bin folder.
Thank you.
FOR XLSX USE
SET IN $xlsName name from XLSX with extension. Example: $xlsName = 'teste.xlsx';
$objPHPExcel = new PHPExcel();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$xlsName.'"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
FOR XLS USE
SET IN $xlsName name from XLS with extension. Example: $xlsName = 'teste.xls';
$objPHPExcel = new PHPExcel();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$xlsName.'"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
sorted(dict1, key=dict1.get)
Well, it is actually possible to do a "sort by dictionary values". Recently I had to do that in a Code Golf (Stack Overflow question Code golf: Word frequency chart). Abridged, the problem was of the kind: given a text, count how often each word is encountered and display a list of the top words, sorted by decreasing frequency.
If you construct a dictionary with the words as keys and the number of occurrences of each word as value, simplified here as:
from collections import defaultdict
d = defaultdict(int)
for w in text.split():
d[w] += 1
then you can get a list of the words, ordered by frequency of use with sorted(d, key=d.get)
- the sort iterates over the dictionary keys, using the number of word occurrences as a sort key .
for w in sorted(d, key=d.get, reverse=True):
print(w, d[w])
I am writing this detailed explanation to illustrate what people often mean by "I can easily sort a dictionary by key, but how do I sort by value" - and I think the original post was trying to address such an issue. And the solution is to do sort of list of the keys, based on the values, as shown above.
Try this:
var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));
This should return true
.
UPDATED: Added isNaN
check to handle the case commented by Julian H. Lam
This is the only thing that worked for me when I tried to run a java class from a batch file:
start "cmdWindowTitle" /B "javaw" -cp . testprojectpak.MainForm
You can customize the start
command as you want for your project, by following the proper syntax:
Syntax
START "title" [/Dpath] [options] "command" [parameters]
Key:
title : Text for the CMD window title bar (required)
path : Starting directory
command : The command, batch file or executable program to run
parameters : The parameters passed to the command
Options:
/MIN : Minimized
/MAX : Maximized
/WAIT : Start application and wait for it to terminate
/LOW : Use IDLE priority class
/NORMAL : Use NORMAL priority class
/HIGH : Use HIGH priority class
/REALTIME : Use REALTIME priority class
/B : Start application without creating a new window. In this case
^C will be ignored - leaving ^Break as the only way to
interrupt the application
/I : Ignore any changes to the current environment.
Options for 16-bit WINDOWS programs only
/SEPARATE Start in separate memory space (more robust)
/SHARED Start in shared memory space (default)
Assuming you're passing in strings rather than integers, try casting the arguments to integers:
def example(arg1, arg2, arg3):
if int(arg1) == 1 and int(arg2) == 2 and int(arg3) == 3:
print("Example Text")
(Edited to emphasize I'm not asking for clarification; I was trying to be diplomatic in my answer. )
That depends on what the target server accepts. There is no definitive standard for this. See also a.o. Wikipedia: Query string:
While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field (e.g.
field1=value1&field1=value2&field2=value3
).[4][5]
Generally, when the target server uses a strong typed programming language like Java (Servlet), then you can just send them as multiple parameters with the same name. The API usually offers a dedicated method to obtain multiple parameter values as an array.
foo=value1&foo=value2&foo=value3
String[] foo = request.getParameterValues("foo"); // [value1, value2, value3]
The request.getParameter("foo")
will also work on it, but it'll return only the first value.
String foo = request.getParameter("foo"); // value1
And, when the target server uses a weak typed language like PHP or RoR, then you need to suffix the parameter name with braces []
in order to trigger the language to return an array of values instead of a single value.
foo[]=value1&foo[]=value2&foo[]=value3
$foo = $_GET["foo"]; // [value1, value2, value3]
echo is_array($foo); // true
In case you still use foo=value1&foo=value2&foo=value3
, then it'll return only the first value.
$foo = $_GET["foo"]; // value1
echo is_array($foo); // false
Do note that when you send foo[]=value1&foo[]=value2&foo[]=value3
to a Java Servlet, then you can still obtain them, but you'd need to use the exact parameter name including the braces.
String[] foo = request.getParameterValues("foo[]"); // [value1, value2, value3]
overflow:hidden;-webkit-overflow-scrolling:touch
won't work well on iOS safari 8.1, as the fixed header will be out of visible area.
As @Yisela says, the css should be placed on .container
(the <div>
below <body>
). which seems no problem(at leas on safari iOS 8.1)
I've place the demo on my blog: http://tech.colla.me/en/show/disable_elastic_scroll_on_iOS_safari
Example:
$ svn propset svn:ignore -F .cvsignore .
property 'svn:ignore' set on '.'
I had to make a web app (ajax based) for a customer who works a lot with schools, these schools have often a bad internet connection I use this simple function to detect if there is a connection, works very well!
I use CodeIgniter and Jquery:
function checkOnline() {
setTimeout("doOnlineCheck()", 20000);
}
function doOnlineCheck() {
//if the server can be reached it returns 1, other wise it times out
var submitURL = $("#base_path").val() + "index.php/menu/online";
$.ajax({
url : submitURL,
type : "post",
dataType : "msg",
timeout : 5000,
success : function(msg) {
if(msg==1) {
$("#online").addClass("online");
$("#online").removeClass("offline");
} else {
$("#online").addClass("offline");
$("#online").removeClass("online");
}
checkOnline();
},
error : function() {
$("#online").addClass("offline");
$("#online").removeClass("online");
checkOnline();
}
});
}
In short: I don't think you can, but there seems to be a workaround:.
If you take a look into the Android Resource here:
http://developer.android.com/guide/topics/resources/string-resource.html
You see than under the array section (string array, at least), the "RESOURCE REFERENCE" (as you get from an XML) does not specify a way to address the individual items. You can even try in your XML to use "@array/yourarrayhere". I know that in design time you will get the first item. But that is of no practical use if you want to use, let's say... the second, of course.
HOWEVER, there is a trick you can do. See here:
Referencing an XML string in an XML Array (Android)
You can "cheat" (not really) the array definition by addressing independent strings INSIDE the definition of the array. For example, in your strings.xml:
<string name="earth">Earth</string>
<string name="moon">Moon</string>
<string-array name="system">
<item>@string/earth</item>
<item>@string/moon</item>
</string-array>
By using this, you can use "@string/earth" and "@string/moon" normally in your "android:text" and "android:title" XML fields, and yet you won't lose the ability to use the array definition for whatever purposes you intended in the first place.
Seems to work here on my Eclipse. Why don't you try and tell us if it works? :-)
If the element you are trying to access is inside an iframe
and you try to access it outside the context of the iframe
this will also cause it to fail.
If you want to get an element in an iframe you can find out how here.
Try this:
concat(left(datefield,10),left(timefield,8))
10 char on date field based on full date yyyy-MM-dd
.
8 char on time field based on full time hh:mm:ss
.
It depends on the format you want it. normally you can use script above and you can concat another field or string as you want it.
Because actually date and time field tread as string if you read it. But of course you will got error while update or insert it.
This should do what you want:
$("#iframe").ready(function() {
var body = $("#iframe").contents().find("body");
body.append('Test');
});
Check this JSFiddle for working demo.
Edit: You can of course do it one line style:
$("#iframe").contents().find("body").append('Test');
Below Function converts the Excel sheet (XLSX format) data to JSON. you can add promise to the function.
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/jszip.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js"></script>
<script>
var ExcelToJSON = function() {
this.parseExcel = function(file) {
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
var workbook = XLSX.read(data, {
type: 'binary'
});
workbook.SheetNames.forEach(function(sheetName) {
// Here is your object
var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
var json_object = JSON.stringify(XL_row_object);
console.log(json_object);
})
};
reader.onerror = function(ex) {
console.log(ex);
};
reader.readAsBinaryString(file);
};
};
</script>
Below post has the code for XLS format Excel to JSON javascript code?
Wouldn't unlinking it and creating the new one do the same thing in the end anyway?
I am using this, try it in playground. Define the base urls as Struct in Constants
struct Constants {
struct APIDetails {
static let APIScheme = "https"
static let APIHost = "restcountries.eu"
static let APIPath = "/rest/v1/alpha/"
}
}
private func createURLFromParameters(parameters: [String:Any], pathparam: String?) -> URL {
var components = URLComponents()
components.scheme = Constants.APIDetails.APIScheme
components.host = Constants.APIDetails.APIHost
components.path = Constants.APIDetails.APIPath
if let paramPath = pathparam {
components.path = Constants.APIDetails.APIPath + "\(paramPath)"
}
if !parameters.isEmpty {
components.queryItems = [URLQueryItem]()
for (key, value) in parameters {
let queryItem = URLQueryItem(name: key, value: "\(value)")
components.queryItems!.append(queryItem)
}
}
return components.url!
}
let url = createURLFromParameters(parameters: ["fullText" : "true"], pathparam: "IN")
//Result url= https://restcountries.eu/rest/v1/alpha/IN?fullText=true
You can avoid event bubbling by checking target of event.
For example if you have input nested to the div element where you have handler for click event, and you don't want to handle it, when input is clicked, you can just pass event.target
into your handler and check is handler should be executed based on properties of target.
For example you can check if (target.localName === "input") { return}
.
So, it's a way to "avoid" handler execution
Is it possible to have multiple version of tensorflow on the same OS?
Yes, you can use python virtual environments for this. From the docs:
A Virtual Environment is a tool to keep the dependencies required by different projects in separate places, by creating virtual Python environments for them. It solves the “Project X depends on version 1.x but, Project Y needs 4.x” dilemma, and keeps your global site-packages directory clean and manageable.
After you have install virtualenv (see the docs), you can create a virtual environment for the tutorial and install the tensorflow version you need in it:
PATH_TO_PYTHON=/usr/bin/python3.5
virtualenv -p $PATH_TO_PYTHON my_tutorial_env
source my_tutorial_env/bin/activate # this activates your new environment
pip install tensorflow==1.1
PATH_TO_PYTHON
should point to where python is installed on your system.
When you want to use the other version of tensorflow execute:
deactivate my_tutorial_env
Now you can work again with the tensorflow version that was already installed on your system.
To get the value of the selected Radio Button, Use RadioButtonName and the Form Id containing the RadioButton.
$('input[name=radioName]:checked', '#myForm').val()
OR by only
$('form input[type=radio]:checked').val();
Summernote converts your uploaded images to a base64 encoded string by default, you can process this string or as other fellows mentioned you can upload images using onImageUpload
callback. You can take a look at this gist which I modified a bit to adapt laravel csrf token
here. But that did not work for me and I had no time to find out why! Instead, I solved it via a server-side solution based on this blog post. It gets the output of the summernote and then it will upload the images and updates the final markdown HTML.
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
Route::get('/your-route-to-editor', function () {
return view('your-view');
});
Route::post('/your-route-to-processor', function (Request $request) {
$this->validate($request, [
'editordata' => 'required',
]);
$data = $request->input('editordata');
//loading the html data from the summernote editor and select the img tags from it
$dom = new \DomDocument();
$dom->loadHtml($data, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$images = $dom->getElementsByTagName('img');
foreach($images as $k => $img){
//for now src attribute contains image encrypted data in a nonsence string
$data = $img->getAttribute('src');
//getting the original file name that is in data-filename attribute of img
$file_name = $img->getAttribute('data-filename');
//extracting the original file name and extension
$arr = explode('.', $file_name);
$upload_base_directory = 'public/';
$original_file_name='time()'.$k;
$original_file_extension='png';
if (sizeof($arr) == 2) {
$original_file_name = $arr[0];
$original_file_extension = $arr[1];
}
else
{
//the file name contains extra . in itself
$original_file_name = implode("_",array_slice($arr,0,sizeof($arr)-1));
$original_file_extension = $arr[sizeof($arr)-1];
}
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$path = $upload_base_directory.$original_file_name.'.'.$original_file_extension;
//uploading the image to an actual file on the server and get the url to it to update the src attribute of images
Storage::put($path, $data);
$img->removeAttribute('src');
//you can remove the data-filename attribute here too if you want.
$img->setAttribute('src', Storage::url($path));
// data base stuff here :
//saving the attachments path in an array
}
//updating the summernote WYSIWYG markdown output.
$data = $dom->saveHTML();
// data base stuff here :
// save the post along with it attachments array
return view('your-preview-page')->with(['data'=>$data]);
});
Getting an ECONNREFUSED errno means that your kernel was refused a connection at the other end, so if it's a bug, it's either in your kernel or in the other end. What you can do is to trap the error in a very specific way and try again in a little while, since this seems to work:
# This is Python > 2.5 code
import errno, time
for attempt in range(MAXIMUM_NUMBER_OF_ATTEMPTS):
try:
# your urllib call here
except EnvironmentError as exc: # replace " as " with ", " for Python<2.6
if exc.errno == errno.ECONNREFUSED:
time.sleep(A_COUPLE_OF_SECONDS)
else:
raise # re-raise otherwise
else: # we tried, and we had no failure, so
break
else: # we never broke out of the for loop
raise RuntimeError("maximum number of unsuccessful attempts reached")
Replace the two all-caps constants with your favourite numbers.
For anyone still coming to this post, the other option is to simply omit the parentheses:
Sub SomeOtherSub(Stattyp As String)
'Daty and the other variables are defined here
CatSubProduktAreakum Stattyp, Daty + UBound(SubCategories) + 2
End Sub
The Call
keywords is only really in VBA for backwards compatibilty and isn't actually required.
If however, you decide to use the Call
keyword, then you have to change your syntax to suit.
'// With Call
Call Foo(Bar)
'// Without Call
Foo Bar
Both will do exactly the same thing.
That being said, there may be instances to watch out for where using parentheses unnecessarily will cause things to be evaluated where you didn't intend them to be (as parentheses do this in VBA) so with that in mind the better option is probably to omit the Call
keyword and the parentheses
Here is my function changing the selected option. It works for jQuery 1.3.2
function selectOption(select_id, option_val) {
$('#'+select_id+' option:selected').removeAttr('selected');
$('#'+select_id+' option[value='+option_val+']').attr('selected','selected');
}
Just incase anybody is interested in a pure css solution for this. The following code overlays a transparent div over the map, and moves the transparent div behind the map when it is clicked. The overlay prevents zooming, once clicked, and behind the map, zooming is enabled.
See my blog post Google maps toggle zoom with css for an explanation how it works, and pen codepen.io/daveybrown/pen/yVryMr for a working demo.
Disclaimer: this is mainly for learning and probably won't be the best solution for production websites.
HTML:
<div class="map-wrap small-11 medium-8 small-centered columns">
<input id="map-input" type="checkbox" />
<label class="map-overlay" for="map-input" class="label" onclick=""></label>
<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d19867.208601651986!2d-0.17101002911118332!3d51.50585742500925!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1sen!2suk!4v1482355389969"></iframe>
</div>
CSS:
.map-wrap {
position: relative;
overflow: hidden;
height: 180px;
margin-bottom: 10px;
}
#map-input {
opacity: 0;
}
.map-overlay {
display: block;
content: '';
position: absolute;
top: 0;
left: 0;
width: 100% !important;
height: 100% !important;
overflow: hidden;
z-index: 2;
}
#map-input[type=checkbox]:checked ~ iframe {
z-index: 3;
}
#map-input[type=checkbox]:checked ~ .map-overlay {
position: fixed;
top: 0;
left: 0;
width: 100% !important;
height: 100% !important;
}
iframe {
position: absolute;
top: 0;
left: 0;
width: 100% !important;
height: 100% !important;
z-index: 1;
border: none;
}
If the service is running in a background thread by extending IntentService
, you can replace IntentService
with JobIntentService
which is provided as part of Android Support Library
The advantage of using JobIntentService
is, it behaves as an IntentService
on pre-O devices and on O and higher, it dispatches it as a job
JobScheduler
can also be used for periodic/on demand jobs. But, ensure to handle backward compatibility as JobScheduler
API is available only from API 21
I was able to get this to work by using the Invoke-Expression
cmdlet.
Invoke-Expression "& `"$scriptPath`" test -r $number -b $testNumber -f $FileVersion -a $ApplicationID"
I was getting a cross domain permissions issue when trying to run the answer to this question so I went with:
function UrlExists(url) {
$('<img src="'+ url +'">').load(function() {
return true;
}).bind('error', function() {
return false;
});
}
It seems to work great, hope this helps someone!
Just took a look over the mustache docs and they support "inverted sections" in which they state
they (inverted sections) will be rendered if the key doesn't exist, is false, or is an empty list
http://mustache.github.io/mustache.5.html#Inverted-Sections
{{#value}}
value is true
{{/value}}
{{^value}}
value is false
{{/value}}
Did you setup your project to be compiled with 1.4 compliance? If so, do what krock said. Or to be more exact you need to select the J2SE-1.4 execution environment and check one of the installed JRE that you want to use in 1.4 compliance mode; most likely you'll have a 1.6 JRE installed, just check that one. Or install a 1.4 JRE if you have a setup kit, and use that one.
Otherwise go to your Eclipse preferences, Java -> Compiler and check if the compliance is set to 1.4. If it is change it back to 1.6. If it's not go to the project properties, and check if it has project specific settings. Go to Java Compiler, and uncheck that if you want to use the general eclipse preferences. Or set the project specific settings to 1.6, so that it's always 1.6 regardless of eclipse preferences.
userInfos.GroupBy(userInfo => userInfo.metric)
.OrderBy(group => group.Key)
.Select(group => Tuple.Create(group.Key, group.Count()));
The problem with your code is :
String show[]= {rs4.getString(1)};
String actuate[]={rs4.getString(2)};
This will create a new array every time your loop (an not append as you might be assuming) and hence in the end you will have only one element per array.
Here is one more way to solve this :
StringBuilder sids = new StringBuilder ();
StringBuilder lids = new StringBuilder ();
while (rs4.next()) {
sids.append(rs4.getString(1)).append(" ");
lids.append(rs4.getString(2)).append(" ");
}
String show[] = sids.toString().split(" ");
String actuate[] = lids.toString().split(" ");
These arrays will have all the required element.
If it is an application on the Market, then on app start-up, fire an Intent to open up the Market app hopefully which will cause it to check for updates.
Otherwise implementing and update checker is fairly easy. Here is my code (roughly) for it:
String response = SendNetworkUpdateAppRequest(); // Your code to do the network request
// should send the current version
// to server
if(response.equals("YES")) // Start Intent to download the app user has to manually install it by clicking on the notification
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("URL TO LATEST APK")));
Of course you should rewrite this to do the request on a background thread but you get the idea.
If you like something a little but more complex but allows your app to automatically apply the update see here.
You can do this today in Java with the Red5 media server from Flash. If you want to also decode and encode video in Java, you can use the Xuggler project.
For PHP7.0 use (php7.1-gd, php7.2-gd, php7.3-gd and php7.4-gd are also available):
sudo apt-get install php7.0-gd
and than restart your webserver.
Without VBA...
If you can use a helper column, you can use the MATCH
function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match
To simply identify duplicates, use a helper column
Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:
=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")
Drag/copy this forumla down, and it should identify the duplicates.
To highlight cells, use conditional formatting:
With some tinkering, you can use this MATCH
function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.
Something like:
=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))
For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:
=B1="Duplicate"
This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.
You can create an object of key/value pairs and jQuery will do the rest for you:
$.ajax({
...
data : { foo : 'bar', bar : 'foo' },
...
});
This way the data will be properly encoded automatically. If you do want to concoct you own string then make sure to use encodeURIComponent()
: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent
Your current code is not working because the string is not concocted properly:
'id='+ id & 'name='+ name
should be:
'id='+ encodeURIComponent(id) + '&name='+ encodeURIComponent(name)
Instead, just do a hook_form_alter
and make the button an image button and you are done!
I'm using ng-show in a directive to show and hide popups.
<div class="..." ng-show="showPopup">
None of the above worked for me, and using ng-if instead of ng-show would be an overkill. That would imply removing and adding the whole popup content into the DOM at every single click. Instead I added an ng-if into the same element to make sure it doesn't show at the document load:
<div class="..." ng-show="showPopup" ng-if="popupReady">
Afterwards I added the initialization into the controller responsible of this directive with a timeout:
$timeout(function () {
$scope.popupReady = true;
});
This way I eliminated the flickering issue and avoided the costly operation of DOM insertion at every single click. This came at an expense of using two scope variables for the same purpose instead of one, but so far this is definitely the best option.
You can get SQL Complete from devart.com, which not just expands the * wildcard just like SQL Prompt from Red Gate does (as described in cairnz's answer), but also provides a column picker drop down with checkboxes in which you can check all the columns that you want in the select list and they will be inserted automatically for you (and if you then uncheck a column it will be automatically removed from the select list).
You can use the with_entities()
method to restrict which columns you'd like to return in the result. (documentation)
result = SomeModel.query.with_entities(SomeModel.col1, SomeModel.col2)
Depending on your requirements, you may also find deferreds useful. They allow you to return the full object but restrict the columns that come over the wire.
Preferences -> Java -> Code Style -> Formatter / "Edit..."
Tabs: "Line wrapping" , "Comments"
Field: "Maximum line width"
Set both to make comments have the same length too. You might need to create a new profile if you don't have one already.
run composer update
. That's it
In EF 6.2 using FluentAPI, you can use HasIndex()
modelBuilder.Entity<User>().HasIndex(u => u.UserName).IsUnique();
Starting with docker-compose
1.28.0 the new service profiles are just made for that! With profiles
you can mark services to be only started in specific profiles:
services:
client:
# ...
db:
# ...
npm:
profiles: ["cli-only"]
# ...
docker-compose up # start main services, no npm
docker-compose run --rm npm # run npm service
docker-compose --profile cli-only # start main and all "cli-only" services
Since docker-compose
v1.5 it is possible to pass multiple docker-compose.yml
files with the -f
flag. This allows you to split your dev tools into a separate docker-compose.yml
which you then only include on-demand:
# start and attach to all your essential services
docker-compose up
# execute a defined command in docker-compose.dev.yml
docker-compose -f docker-compose.dev.yml run npm update
# if your command depends_on a service you need to include both configs
docker-compose -f docker-compose.yml -f docker-compose.dev.yml run npm update
For an in-depth discussion on this see docker/compose#1896.
I would recommend using Offset
assuming that the Headers are in Row 1. See this example
Option Explicit
Sub Sample()
Dim rRange As Range, filRange As Range, Rng as Range
'Remove any filters
ActiveSheet.AutoFilterMode = False
'~~> Set your range
Set rRange = Sheets("Sheet1").Range("A1:E10")
With rRange
'~~> Set your criteria and filter
.AutoFilter Field:=1, Criteria1:="=1"
'~~> Filter, offset(to exclude headers)
Set filRange = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
Debug.Print filRange.Address
For Each Rng In filRange
'~~> Your Code
Next
End With
'Remove any filters
ActiveSheet.AutoFilterMode = False
End Sub
You can use an Extension method to iterate the RadioButton's Parent.Controls collection. This allows you to query other RadioButtons in the same scope. Using two extension methods, you can use the first determine whether any RadioButtons in the group are selected, then use the second to get the selection. The RadioButton Tag field can be used to hold an Enum to identify each RadioButton in the group:
public static int GetRadioSelection(this RadioButton rb, int Default = -1) {
foreach(Control c in rb.Parent.Controls) {
RadioButton r = c as RadioButton;
if(r != null && r.Checked) return Int32.Parse((string)r.Tag);
}
return Default;
}
public static bool IsRadioSelected(this RadioButton rb) {
foreach(Control c in rb.Parent.Controls) {
RadioButton r = c as RadioButton;
if(r != null && r.Checked) return true;
}
return false;
}
Here's a typical use pattern:
if(!MyRadioButton.IsRadioSelected()) {
MessageBox.Show("No radio selected.");
return;
}
int selection = MyRadioButton.GetRadioSelection;
This is an old question, but here's another way to do it.
You can modify the R code itself instead of the chunk options, by wrapping the source
call in suppressPackageStartupMessages()
, suppressMessages()
, and/or suppressWarnings()
. E.g:
```{r echo=FALSE}
suppressWarnings(suppressMessages(suppressPackageStartupMessages({
source("C:/Rscripts/source.R")
})
```
You can also put those functions around your library()
calls inside the "source.R"
script.
Django needs your application-specific settings. Since it is already inside your manage.py
, just use that. The faster, but perhaps temporary, solution is:
python manage.py shell
Here is another solution, that has all the source available in a single, simple ZIP file.
It presents the OpenFileDialog with additional windows flags that makes it work like the Windows 7+ Folder Selection dialog.
Per the website, it is public domain: "There’s no license as such as you are free to take and do with the code what you will."
Archive.org links:
It could be used as a wrapper function for returning a reference to a private constant data type. For example in a linked list you have the constants tail and head, and if you want to determine if a node is a tail or head node, then you can compare it with the value returned by that function.
Though any optimizer would most likely optimize it out anyway...
Since your list is already in ascending order, we can simply reverse the list.
>>> timestamps.reverse()
>>> timestamps
['2010-04-20 10:25:38',
'2010-04-20 10:12:13',
'2010-04-20 10:12:13',
'2010-04-20 10:11:50',
'2010-04-20 10:10:58',
'2010-04-20 10:10:37',
'2010-04-20 10:09:46',
'2010-04-20 10:08:22',
'2010-04-20 10:08:22',
'2010-04-20 10:07:52',
'2010-04-20 10:07:38',
'2010-04-20 10:07:30']
I had the same issue, just opening another terminal with a bash on it worked for me :
create container:
docker run -d mcr.microsoft.com/mssql/server:2019-CTP3.0-ubuntu
containerid=52bbc9b30557
start container:
docker start 52bbc9b30557
start bash to keep container running:
docker exec -it 52bbc9b30557 bash
start process you need:
docker exec -it 52bbc9b30557 /path_to_cool_your_app
I do this with separate side-by-side enum wrapper classes which are generated with macros. There are several advantages:
The downside, of course, is that I need to duplicate the enum values in the formatter classes, and I don't have any script to generate them. Other than that, though, it seems to work pretty well.
Here's an example of an enum from my codebase, sans all the framework code which implements the macros and templates, but you can get the idea:
enum EHelpLocation
{
HELP_LOCATION_UNKNOWN = 0,
HELP_LOCAL_FILE = 1,
HELP_HTML_ONLINE = 2,
};
class CEnumFormatter_EHelpLocation : public CEnumDefaultFormatter< EHelpLocation >
{
public:
static inline CString FormatEnum( EHelpLocation eValue )
{
switch ( eValue )
{
ON_CASE_VALUE_RETURN_STRING_OF_VALUE( HELP_LOCATION_UNKNOWN );
ON_CASE_VALUE_RETURN_STRING_OF_VALUE( HELP_LOCAL_FILE );
ON_CASE_VALUE_RETURN_STRING_OF_VALUE( HELP_HTML_ONLINE );
default:
return FormatAsNumber( eValue );
}
}
};
DECLARE_RANGE_CHECK_CLASS( EHelpLocation, CRangeInfoSequential< HELP_HTML_ONLINE > );
typedef ESmartEnum< EHelpLocation, HELP_LOCATION_UNKNOWN, CEnumFormatter_EHelpLocation, CRangeInfo_EHelpLocation > SEHelpLocation;
The idea then is instead of using EHelpLocation, you use SEHelpLocation; everything works the same, but you get range checking and a 'Format()' method on the enum variable itself. If you need to format a stand-alone value, you can use CEnumFormatter_EHelpLocation::FormatEnum(...).
Hope this is helpful. I realize this also doesn't address the original question about a script to actually generate the other class, but I hope the structure helps someone trying to solve the same problem, or write such a script.
Because of %
operator cannot apply to BigDecimal and int (i.e. 1) directly, so I am using the following snippet to check if the BigDecimal is an integer:
value.stripTrailingZeros().scale() <= 0
You need to write the ftp commands in a text file and give it as a parameter for the ftp command like this:
ftp -s:filename
More info here: http://www.nsftools.com/tips/MSFTP.htm
I am not sure though if it would work with username and password prompt.
Use which:
set.seed(1)
x <- sample(10, 50, replace = TRUE)
length(which(x > 3 & x < 5))
# [1] 6
You can also use the join command (dplyr).
For example:
new_dataset <- dataset1 %>% right_join(dataset2, by=c("column1","column2"))
Imagine that you have a skilled secretary at your office that's a shared resource in the department. Once in a while, you rush towards them because you have a task, only to hope that another one of your co-workers has not already claimed them. Usually you only have to wait for a brief period of time.
Because caring is sharing, your manager decides that customers can use the secretary directly as well. But this has a side effect: A customer might even claim them while you're working for this customer and you also need them to execute part of the tasks. A deadlock occurs, because claiming is no longer a hierarchy. This could have been avoided all together by not allowing customers to claim them in the first place.
lock(this)
is bad as we've seen. An outside object might lock on the object and since you don't control who's using the class, anyone can lock on it... Which is the exact example as described above. Again, the solution is to limit exposure of the object. However, if you have a private
, protected
or internal
class you could already control who is locking on your object, because you're sure that you've written your code yourself. So the message here is: don't expose it as public
. Also, ensuring that a lock is used in similar scenario's avoids deadlocks.
The complete opposite of this is to lock on resources that are shared throughout the app domain -- the worst case scenario. It's like putting your secretary outside and allowing everyone out there to claim them. The result is utter chaos - or in terms of source code: it was a bad idea; throw it away and start over. So how do we do that?
Types are shared in the app domain as most people here point out. But there are even better things we can use: strings. The reason is that strings are pooled. In other words: if you have two strings that have the same contents in an app domain, there's a chance that they have the exact same pointer. Since the pointer is used as the lock key, what you basically get is a synonym for "prepare for undefined behavior".
Similarly, you shouldn't lock on WCF objects, HttpContext.Current, Thread.Current, Singletons (in general), etc. The easiest way to avoid all of this? private [static] object myLock = new object();
In my case someone had deleted APN SSL Certificates for my app in Apple development portal.
This solved the problem.
I found a nice work around that will allow it to work in IE7 here. It bypasses the validator for the frameBorder attribute but keeps css for future browsers as explained in the post.
Don't forget to add the
CONFIG += console
flag in the qmake .pro file.
For the rest is just using some of Qt classes. One way I use it is to spawn processes cross-platform.
You can index and use a negative sign to drop the 3rd column:
data[,-3]
Or you can list only the first 2 columns:
data[,c("c1", "c2")]
data[,1:2]
Don't forget the comma and referencing data frames works like this: data[row,column]
You are missing the dot on the selector, and you can use toggleClass method on jquery:
$(".result").hover(
function () {
$(this).toggleClass("result_hover")
}
);
document.getElementById('test').onclick = function () {_x000D_
document.getElementById('scripted').focus();_x000D_
};
_x000D_
div:focus {_x000D_
background-color: Aqua;_x000D_
}
_x000D_
<div>Element X (not focusable)</div>_x000D_
<div tabindex="0">Element Y (user or script focusable)</div>_x000D_
<div tabindex="-1" id="scripted">Element Z (script-only focusable)</div>_x000D_
<div id="test">Set Focus To Element Z</div>
_x000D_
Try this
getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath()
Another more versatile way is to use find
:
sed -i 's/asd/dsg/g' $(find . -type f -name 'xa*')
It's doubtful you can change it on click with the default myLocation Marker. However, if you would like the app to automatically zoom in on your location once it is found, I would check out my answer to this question
Note that the answer I provided does not zoom in, but if you modify the onLocationChanged method to be like the one below, you can choose whatever zoom level you like:
@Override
public void onLocationChanged(Location location)
{
if( mListener != null )
{
mListener.onLocationChanged( location );
//Move the camera to the user's location and zoom in!
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 12.0f));
}
}
You might no need to having export, just add this line in catalina.sh :
CATALINA_OPTS="-Xms512M -Xmx1024M"
try this (if your server is Linux):
$command="/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'";
$localIP = exec ($command);
echo $localIP;
You can put an image into ::before pseudoelement and set the same dimensions for as is the image + add overflow:hidden, like:
li a::before{
content:url('img');
width:20px;
height:10px
}
a {
overflow:hidden;
width:20px;
height:10px
}
Mark's idea was good, but maybe forgot some path have spaces in them. Replacing ';' with '" "' instead would cut all paths into quoted strings.
set _path="%PATH:;=" "%"
for %%p in (%_path%) do if not "%%~p"=="" echo %%~p
So here, you have your paths displayed.
FOR command in cmd has a tedious learning curve, notably because how variables react within ()'s statements... you can assign any variables, but you can't read then back within the ()'s, unless you use the "setlocal ENABLEDELAYEDEXPANSION" statement, and therefore also use the variables with !!'s instead of %%'s (!_var!)
I currently exclusively script with cmd, for work, had to learn all this :)
Here is the shortest method possible:
if (Math.abs(v-550)<50) console.log('short')
if ((v-500)*(v-600)<0) console.log('short')
Parametrized:
if (Math.abs(v-max+v-min)<max+min) console.log('short')
if ((v-min)*(v-max)<0) console.log('short')
You can divide both sides by 2 if you don't understand how the first one works;)
Some practical uses for the [Serializable]
attribute:
BinaryFormatter
class in System.Runtime.Serialization.Formatters.BinaryClipboard.SetData()
- nonserialisable classes cannot be placed on the clipboard.MarshalByRefObject
) must be serialisable.These are the most common usage cases that I have come across.
To go along with the previous answers, this is how I do it as a one-liner. This is for getting the actual text of the selected option. There are good examples for getting the index number already. (And for the text, I just wanted to show this way)
let selText = document.getElementById('elementId').options[document.getElementById('elementId').selectedIndex].text
In some rare instances you may need to use parentheses, but this would be very rare.
let selText = (document.getElementById('elementId')).options[(document.getElementById('elementId')).selectedIndex].text;
I doubt this processes any faster than the two line version. I simply like to consolidate my code as much as possible.
Unfortunately this still fetches the element twice, which is not ideal. A method that only grabs the element once would be more useful, but I have not figured that out yet, in regards to doing this with one line of code.
Right(A1, Len(A1)-Find("(asterisk)",Substitute(A1, "(space)","(asterisk)",Len(A1)-Len(Substitute(A1,"(space)", "(no space)")))))
Try this. Hope it works.
if linux
if install by apt-get
service memcached stop
service memcached restart
if install by source code
Usage: /etc/init.d/memcached {start|stop|restart|force-reload|status}
can also simply kill $pid to stop
var timeInterval = 5;
var blinkTime = 1;
var open_signal = 'top_left';
$(document).ready(function () {
$('#div_top_left .timer').html(timeInterval);
$('#div_top_right .timer').html(timeInterval);
$('#div_bottom_right .timer').html(timeInterval * 2);
$('#div_bottom_left .timer').html(timeInterval * 3);
$('#div_top_left .green').css('background-color', 'green');
$('#div_top_right .red').css('background-color', 'red');
$('#div_bottom_right .red').css('background-color', 'red');
$('#div_bottom_left .red').css('background-color', 'red');
setInterval(function () {
manageSignals();
}, 1000);
});
function manageSignals() {
var top_left_time = parseInt($('#div_top_left .timer').html()) - 1;
var top_right_time = parseInt($('#div_top_right .timer').html()) - 1;
var bottom_left_time = parseInt($('#div_bottom_left .timer').html()) - 1;
var bottom_right_time = parseInt($('#div_bottom_right .timer').html()) - 1;
if (top_left_time == -1 && open_signal == 'top_left') open_signal = 'top_right';
else if (top_right_time == -1 && open_signal == 'top_right') open_signal = 'bottom_right';
else if (bottom_right_time == -1 && open_signal == 'bottom_right') open_signal = 'bottom_left';
else if (bottom_left_time == -1 && open_signal == 'bottom_left') open_signal = 'top_left';
if (top_left_time == -1) {
if (open_signal == 'top_right') {
top_left_time = (timeInterval * 3) - 1;
$('#div_top_left .red').css('background-color', 'red');
$('#div_top_left .yellow').css('background-color', 'white');
$('#div_top_left .green').css('background-color', 'white');
}
else if (open_signal == 'top_left') {
top_left_time = timeInterval - 1;
$('#div_top_left .red').css('background-color', 'white');
$('#div_top_left .yellow').css('background-color', 'white');
$('#div_top_left .green').css('background-color', 'green');
}
}
if (top_right_time == -1) {
if (open_signal == 'bottom_right') {
top_right_time = (timeInterval * 3) - 1;
$('#div_top_right .red').css('background-color', 'red');
$('#div_top_right .yellow').css('background-color', 'white');
$('#div_top_right .green').css('background-color', 'white');
}
else if (open_signal == 'top_right') {
top_right_time = timeInterval - 1;
$('#div_top_right .red').css('background-color', 'white');
$('#div_top_right .yellow').css('background-color', 'white');
$('#div_top_right .green').css('background-color', 'green');
}
}
if (bottom_right_time == -1) {
if (open_signal == 'bottom_left') {
bottom_right_time = (timeInterval * 3) - 1;
$('#div_bottom_right .red').css('background-color', 'red');
$('#div_bottom_right .yellow').css('background-color', 'white');
$('#div_bottom_right .green').css('background-color', 'white');
}
else if (open_signal == 'bottom_right') {
bottom_right_time = timeInterval - 1;
$('#div_bottom_right .red').css('background-color', 'white');
$('#div_bottom_right .yellow').css('background-color', 'white');
$('#div_bottom_right .green').css('background-color', 'green');
}
}
if (bottom_left_time == -1) {
if (open_signal == 'top_left') {
bottom_left_time = (timeInterval * 3) - 1;
$('#div_bottom_left .red').css('background-color', 'red');
$('#div_bottom_left .yellow').css('background-color', 'white');
$('#div_bottom_left .green').css('background-color', 'white');
}
else if (open_signal == 'bottom_left') {
bottom_left_time = timeInterval - 1;
$('#div_bottom_left .red').css('background-color', 'white');
$('#div_bottom_left .yellow').css('background-color', 'white');
$('#div_bottom_left .green').css('background-color', 'green');
}
}
if (top_left_time == blinkTime && open_signal == 'top_left') {
$('#div_top_left .yellow').css('background-color', 'yellow');
$('#div_top_left .green').css('background-color', 'white');
}
if (top_right_time == blinkTime && open_signal == 'top_right') {
$('#div_top_right .yellow').css('background-color', 'yellow');
$('#div_top_right .green').css('background-color', 'white');
}
if (bottom_left_time == blinkTime && open_signal == 'bottom_left') {
$('#div_bottom_left .yellow').css('background-color', 'yellow');
$('#div_bottom_left .green').css('background-color', 'white');
}
if (bottom_right_time == blinkTime && open_signal == 'bottom_right') {
$('#div_bottom_right .yellow').css('background-color', 'yellow');
$('#div_bottom_right .green').css('background-color', 'white');
}
$('#div_top_left .timer').html(top_left_time);
$('#div_top_right .timer').html(top_right_time);
$('#div_bottom_left .timer').html(bottom_left_time);
$('#div_bottom_right .timer').html(bottom_right_time);
}
for /F "eol= delims=~" %%d in ('CD') do set curdir=%%d
pushd %curdir%
Actually you can do it.
Although, someone should note that repeating the CASE
statements are not bad as it seems. SQL Server's query optimizer is smart enough to not execute the CASE
twice so that you won't get any performance hit because of that.
Additionally, someone might use the following logic to not repeat the CASE (if it suits you..)
INSERT INTO dbo.T1
(
Col1,
Col2,
Col3
)
SELECT
1,
SUBSTRING(MyCase.MergedColumns, 0, CHARINDEX('%', MyCase.MergedColumns)),
SUBSTRING(MyCase.MergedColumns, CHARINDEX('%', MyCase.MergedColumns) + 1, LEN(MyCase.MergedColumns) - CHARINDEX('%', MyCase.MergedColumns))
FROM
dbo.T1 t
LEFT OUTER JOIN
(
SELECT CASE WHEN 1 = 1 THEN '2%3' END MergedColumns
) AS MyCase ON 1 = 1
This will insert the values (1, 2, 3) for each record in the table T1
. This uses a delimiter '%'
to split the merged columns. You can write your own split function depending on your needs (e.g. for handling null records or using complex delimiter for varchar
fields etc.). But the main logic is that you should join the CASE
statement and select from the result set of the join with using a split logic.
Finally, I solved it. Even though the solution is a bit lengthy, I think its the simplest. The solution is as follows:
- Install Visual Studio 2008
- Install the service Package 1 (SP1)
- Install SQL Server 2008 r2
You most probably don't need z-index to do that. You can use relative and absolute positioning.
I advise you to take a better look at css positioning and the difference between relative and absolute positioning... I saw you're setting position: absolute;
to an element and trying to float that element. It won't work friend! When you understand positioning in CSS it will make your work a lot easier! ;)
Edit: Just to be clear, positioning is not a replacement for them and I do use z-index
. I just try to avoid using them. Using z-indexes
everywhere seems easy and fun at first... until you have bugs related to them and find yourself having to revisit and manage z-indexes
.
That site makes use of the "fragment" part of a url: the stuff after the "#". This is not sent to the server by the browser as part of the GET request, but can be used to store page state. So yes you can change the fragment without causing a page refresh or reload. When the page loads, your javascript reads this fragment and updates the page content appropriately, fetching data from the server via ajax requests as required. To read the fragment in js:
var fragment = location.hash;
but note that this value will include the "#" character at the beginning. To set the fragment:
location.hash = "your_state_data";
I think you can use loc
if you need update two columns to same value:
df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'
print df1
stream feat another_feat
a 1 some_value some_value
b 2 aaaa aaaa
c 2 aaaa aaaa
d 3 some_value some_value
If you need update separate, one option is use:
df1.loc[df1['stream'] == 2, 'feat'] = 10
print df1
stream feat another_feat
a 1 some_value some_value
b 2 10 some_value
c 2 10 some_value
d 3 some_value some_value
Another common option is use numpy.where
:
df1['feat'] = np.where(df1['stream'] == 2, 10,20)
print df1
stream feat another_feat
a 1 20 some_value
b 2 10 some_value
c 2 10 some_value
d 3 20 some_value
EDIT: If you need divide all columns without stream
where condition is True
, use:
print df1
stream feat another_feat
a 1 4 5
b 2 4 5
c 2 2 9
d 3 1 7
#filter columns all without stream
cols = [col for col in df1.columns if col != 'stream']
print cols
['feat', 'another_feat']
df1.loc[df1['stream'] == 2, cols ] = df1 / 2
print df1
stream feat another_feat
a 1 4.0 5.0
b 2 2.0 2.5
c 2 1.0 4.5
d 3 1.0 7.0
If working with multiple conditions is possible use multiple numpy.where
or numpy.select
:
df0 = pd.DataFrame({'Col':[5,0,-6]})
df0['New Col1'] = np.where((df0['Col'] > 0), 'Increasing',
np.where((df0['Col'] < 0), 'Decreasing', 'No Change'))
df0['New Col2'] = np.select([df0['Col'] > 0, df0['Col'] < 0],
['Increasing', 'Decreasing'],
default='No Change')
print (df0)
Col New Col1 New Col2
0 5 Increasing Increasing
1 0 No Change No Change
2 -6 Decreasing Decreasing
I like the examples that use Object.fromEntries
such as this one, but still, they are not very easy to use. The answers that use Object.keys
and then look up the key
are actually doing multiple look-ups that may not be necessary.
I wished there was an Object.map
function, but we can create our own and call it objectMap
with the ability to modify both key
and value
:
Usage (JavaScript):
const myObject = { 'a': 1, 'b': 2, 'c': 3 };
// keep the key and modify the value
let obj = objectMap(myObject, val => val * 2);
// obj = { a: 2, b: 4, c: 6 }
// modify both key and value
obj = objectMap(myObject,
val => val * 2 + '',
key => (key + key).toUpperCase());
// obj = { AA: '2', BB: '4', CC: '6' }
Code (TypeScript):
interface Dictionary<T> {
[key: string]: T;
}
function objectMap<TValue, TResult>(
obj: Dictionary<TValue>,
valSelector: (val: TValue, obj: Dictionary<TValue>) => TResult,
keySelector?: (key: string, obj: Dictionary<TValue>) => string,
ctx?: Dictionary<TValue>
) {
const ret = {} as Dictionary<TResult>;
for (const key of Object.keys(obj)) {
const retKey = keySelector
? keySelector.call(ctx || null, key, obj)
: key;
const retVal = valSelector.call(ctx || null, obj[key], obj);
ret[retKey] = retVal;
}
return ret;
}
If you are not using TypeScript then copy the above code in TypeScript Playground to get the JavaScript code.
Also, the reason I put keySelector
after valSelector
in the parameter list, is because it is optional.
* Some credit go to alexander-mills' answer.
If there is XML file with 2 different tables then will:
LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table1
LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table2
work
It can be as simple as:
default_data['item3'] = 3
As Chris' answer says, you can use update to add more than one item. An example:
default_data.update({'item4': 4, 'item5': 5})
Please see the documentation about dictionaries as data structures and dictionaries as built-in types.
Store all the to be deleted ID's into a table. Then there are 3 ways. 1) loop through all the ID's in the table, then delete one row at a time for X commit interval. X can be a 100 or 1000. It works on OLTP environment and you can control the locks.
2) Use Oracle Bulk Delete
3) Use correlated delete query.
Single query is usually faster than multiple queries because of less context switching, and possibly less parsing.
Whenever a record has updated a record is "deleted". Here is my example:
ALTER TRIGGER [dbo].[UpdatePhyDate]
ON [dbo].[M_ContractDT1]
AFTER UPDATE
AS
BEGIN
-- on ContarctDT1 PhyQty is updated
-- I want system date in Phytate automatically saved
SET NOCOUNT ON;
declare @dt1ky as int
if(update(Phyqty))
begin
select @dt1ky = dt1ky from deleted
update M_ContractDT1 set PhyDate=GETDATE() where Dt1Ky= @dt1ky
end
END
It works fine
it could be a problem with your specific network adapter. I have a Dell 15R and there are no working drivers for ubuntu or ubuntu server; I even tried compiling wireless drivers myself, but to no avail.
However, in virtualbox, I was able to get wireless working by using the default configuration. It automatically bridged my internal wireless adapter and hence used my native OS's wireless connection for wireless.
If you are trying to get a separate wireless connection from within ubuntu in virtualbox, then it would take more configuring. If so, let me know, if not, I will not bother typing up instructions to something you are not looking to do, as it is quite complicated in some instances.
p.s. you should be using Windows 7 if you have any technical inclination. Do you live under a rock? No offense intended.
On CentOS (my version is 6.5) when editing crontab you must close the editor to reflect your changes in CRON.
crontab -e
After that command You can see that new entry appears in /var/log/cron
Sep 24 10:44:26 ***** crontab[17216]: (*****) BEGIN EDIT (*****)
But only saving crontab editor after making some changes does not work. You must leave the editor to reflect changes in cron. After exiting new entry appears in the log:
Sep 24 10:47:58 ***** crontab[17216]: (*****) END EDIT (*****)
From this point changes you made are visible to CRON.
Consider an example,
class Animal {
public void eat(String str) {
System.out.println("Eating for grass");
}
}
class Goat extends Animal {
public void eat(String str) {
System.out.println("blank");
}
}
class Another extends Goat{
public void eat(String str) {
System.out.println("another");
}
}
public class InheritanceSample {
public static void main(String[] args) {
Animal a = new Animal();
Another t5 = (Another) new Goat();
}
}
At Another t5 = (Another) new Goat()
: you will get a ClassCastException
because you cannot create an instance of the Another
class using Goat
.
Note: The conversion is valid only in cases where a class extends a parent class and the child class is casted to its parent class.
How to deal with the ClassCastException
:
A bit of a lengthier way (if interested in it):
In your typescript code do this:
this.objectLength = Object.keys(this.previous_info).length != 0;
And in the template:
ngIf="objectLength != 0"
try like this
= IIF( MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ) ) = -1, "", FormatNumber( MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ), "CellReading_Reading"),3)) )
Window -> Preferences -> JavaScript -> Validator (also per project settings possible)
or
Window -> Preferences -> Validation (disable validations and configure their settings)
String test = DateTime.Now.ToShortDateString();
One possibility, reducing the longer form before expanding all:
string.replaceAll("Milan Vasic", "Milan").replaceAll("Milan", "Milan Vasic")
Another way, treating Vasic as optional:
string.replaceAll("Milan( Vasic)?", "Milan Vasic")
Others have described solutions based on lookahead or alternation.
Just another solution, this one's cross platform (uses java
), and points you to the location of the jre.
java -XshowSettings:properties -version 2>&1 > /dev/null | grep 'java.home'
Outputs all of java
's current settings, and finds the one called java.home
.
For windows, you can go with findstr instead of grep.
java -XshowSettings:properties -version 2>&1 | findstr "java.home"
Try utilizing .one()
var button = $("#button"),_x000D_
result = $("#result"),_x000D_
buttonHandler = function buttonHandler(e) {_x000D_
result.html("processing...");_x000D_
$(this).fadeOut(1000, function() {_x000D_
// do stuff_x000D_
setTimeout(function() {_x000D_
// reset `click` event at `button`_x000D_
button.fadeIn({_x000D_
duration: 500,_x000D_
start: function() {_x000D_
result.html("done at " + $.now());_x000D_
}_x000D_
}).one("click", buttonHandler);_x000D_
_x000D_
}, 5000)_x000D_
})_x000D_
};_x000D_
_x000D_
button.one("click", buttonHandler);
_x000D_
#button {_x000D_
width: 50px;_x000D_
height: 50px;_x000D_
background: olive;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">_x000D_
</script>_x000D_
<div id="result"></div>_x000D_
<div id="button">click</div>
_x000D_
You can use ORDER BY ID DESC
, but it's WAY faster if you go that way:
SELECT * FROM bugs WHERE ID = (SELECT MAX(ID) FROM bugs WHERE user = 'me')
In case that you have a huge table, it could make a significant difference.
EDIT
You can even set a variable in case you need it more than once (or if you think it is easier to read).
SELECT @bug_id := MAX(ID) FROM bugs WHERE user = 'me';
SELECT * FROM bugs WHERE ID = @bug_id;
In my case, I accidentally added the package in the declaration but it should be in imports.
Edit the source (or turn off rich text) and replace the p tag with a div. Then style the div any which way you want.
ckEditor won't add any wrapper element on the next submit as you've got the div in there.
(This solved my issue, I'm using Drupal and need small snippets of html which the editor always added the extra, but the rest of the time I want the wrapping p tag).
I also spent quite some time with this issue, so that's my solution:
String urlString2Decode = "http://www.test.com/äüö/path with blanks/";
String decodedURL = URLDecoder.decode(urlString2Decode, "UTF-8");
URL url = new URL(decodedURL);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
String decodedURLAsString = uri.toASCIIString();
str.replace(/\s/g,'')
Works for me.
jQuery.trim
has the following hack for IE, although I'm not sure what versions it affects:
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
Just use your table inside a div with a class (.table1
for example) and don't set any border for this table in CSS. Then use CSS code for that class.
.table1 {border=1px solid black;}
If your software uses a ProxySelector
(for example for using a PAC-script instead of a static host/port) and your HTTPComponents is version 4.3 or above then you can use your ProxySelector
for your HttpClient
like this:
ProxySelector myProxySelector = ...;
HttpClient myHttpClient = HttpClientBuilder.create().setRoutePlanner(new SystemDefaultRoutePlanner(myProxySelector))).build();
And then do your requests as usual:
HttpGet myRequest = new HttpGet("/");
myHttpClient.execute(myRequest);
In Rabbit version 3.7.10 you can run below command with root permission:
rabbitmqctl list_queues | awk '{ print $1 }' | xargs -L1 rabbitmqctl delete_queue
It didn't work for me with all those steps. Strangely enough I noticed Intellisense was working for another solution in visual studio 2015, but not for a specific one.
I located and deleted the .suo file and restarted visual studio. That fixed it for me.
Single quotes are escaped by doubling them up, just as you've shown us in your example. The following SQL illustrates this functionality. I tested it on SQL Server 2008:
DECLARE @my_table TABLE (
[value] VARCHAR(200)
)
INSERT INTO @my_table VALUES ('hi, my name''s tim.')
SELECT * FROM @my_table
value
==================
hi, my name's tim.
Define it as
<return type> AnalyzeArray(ArrayList<Integer> list) {
I've used JavaService before with good success. It hasn't been updated in a couple of years, but was pretty rock solid back when I used it.
Regarding the PHP comment 'No, PHP wouldn't like it'. Actually, PHP would keep on chugging unless you set some very restrictive (for PHP) exception/error levels, (and maybe not even then).
What WILL happen by default is that an access to a non existing variable/out of bounds array element 'unsets' your value that you're assigning to. NO, that is NOT null. PHP has a Perl/C lineage, from what I understand. So there are: unset and non existing variables, values which ARE set but are NULL, Boolean False values, then everything else that standard langauges have. You have to test for those separately, OR choose the RIGHT evaluation built in function/syntax.
The
<%@include file="abc.jsp"%>
directive acts like C"#include"
, pulling in the text of the included file and compiling it as if it were part of the including file. The included file can be any type (including HTML or text).The <jsp:include page="abc.jsp"> tag compiles the file as a separate JSP file, and embeds a call to it in the compiled JSP.
Some JSP engines support the non-standard tags
<!--#include file="data.inc"-->
(NCSA-, or .shtml-style) and<%@ vinclude="data.inc" %>
(JRun-style), but these are not defined in the JSP spec and thus cannot be relied on.See also this question in the JSP FAQ.
Good Example can be when incase of writing it after the end of your query if you have joins or where close :
select 'idPago','fecha','lead','idAlumno','idTipoPago','idGpo'
union all
(select id_control_pagos, fecha, lead, id_alumno, id_concepto_pago, id_Gpo,id_Taller,
id_docente, Pagoimporte, NoFactura, FacturaImporte, Mensualidad_No, FormaPago,
Observaciones from control_pagos
into outfile 'c:\\data.csv'
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n');
Lets assume you are hearing songs.
As long as the current song is running, the next song wont play, i.e Sleep() called by next song
If you finish the song it will stop and until you select play button(notify()) it wont play, i.e wait() called by current song.
In this both cases songs going to Wait states.
The trick for me was not setting the height -- but instead setting the minHeight. This must be applied to the root view of whatever layout your custom adapter is using to render each row.
Like we have date "07/May/2018" and we need date "2018-05-07" as mysql compatible
if (!empty($date)) {
$timestamp = strtotime($date);
if ($timestamp === FALSE) {
$timestamp = strtotime(str_replace('/', '-', $date));
}
$date = date('Y-m-d', $timestamp);
}
It works for me. enjoy :)
Configure After pushing the code when you get a rejected message, click on configure and click Add spec as shown in this picture
Drop down and click on the ref/heads/yourbranchname and click on Add Spec again
Multi-threading with javascript is clearly possible using webworkers bring by HTML5.
Main difference between webworkers and a standard multi-threading environment is memory resources are not shared with the main thread, a reference to an object is not visible from one thread to another. Threads communicate by exchanging messages, it is therefore possible to implement a synchronzization and concurrent method call algorithm following an event-driven design pattern.
Many frameworks exists allowing to structure programmation between threads, among them OODK-JS, an OOP js framework supporting concurrent programming https://github.com/GOMServices/oodk-js-oop-for-js
You don't "commit the folder" - you add the folder, as you have done, and then simply commit all changes. The command should be:
git add foldername
git commit -m "commit operation"
Let's say this is your dataframe.
You can rename the columns using two methods.
Using dataframe.columns=[#list]
df.columns=['a','b','c','d','e']
The limitation of this method is that if one column has to be changed, full column list has to be passed. Also, this method is not applicable on index labels. For example, if you passed this:
df.columns = ['a','b','c','d']
This will throw an error. Length mismatch: Expected axis has 5 elements, new values have 4 elements.
Another method is the Pandas rename()
method which is used to rename any index, column or row
df = df.rename(columns={'$a':'a'})
Similarly, you can change any rows or columns.
Similar to Rory's answer, with ECMA 5 you can now just call str.trim().length
instead of using a regular expression. If the resulting value is 0 you know you have a string that contains only spaces.
if (!str.trim().length) {
console.log('str is empty!');
}
You can read more about trim here.
It can be changed in the $CATALINA_BASE/conf/server.xml
in the <Host />
. See the Tomcat documentation, specifically the section in regards to the Host container:
The default is webapps
relative to the $CATALINA_BASE
. An absolute pathname can be used.
Hope that helps.
Ok so here's how I figured this out. It all has to do with CORS policy. Before the POST request, Chrome was doing a preflight OPTIONS request, which should be handled and acknowledged by the server prior to the actual request. Now this is really not what I wanted for such a simple server. Hence, resetting the headers client side prevents the preflight:
app.config(function ($httpProvider) {
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
});
The browser will now send a POST directly. Hope this helps a lot of folks out there... My real problem was not understanding CORS enough.
Link to a great explanation: http://www.html5rocks.com/en/tutorials/cors/
Kudos to this answer for showing me the way.
You can pass in a pointer to a time_t
object that time will fill up with the current time (and the return value is the same one that you pointed to). If you pass in NULL
, it just ignores it and merely returns a new time_t
object that represents the current time.
Nb:time(&timer);
is equivalent to timer = time(NULL);
In case someone is still looking for the answer, this worked for me:
=COUNTIF(A2:A51, "*" & B1 & "*")
B1
containing the iPad
string.
This might work:
^(\*|\d+(\.\d+){0,2}(\.\*)?)$
At the top level, "*" is a special case of a valid version number. Otherwise, it starts with a number. Then there are zero, one, or two ".nn" sequences, followed by an optional ".*". This regex would accept 1.2.3.* which may or may not be permitted in your application.
The code for retrieving the matched sequences, especially the (\.\d+){0,2}
part, will depend on your particular regex library.
In Eclipse, actions like importing Maven projects or invoking "Update Sources" runs in the same JVM in which Eclipse is running. If that JVM comes from JRE that isn’t part of JDK, there would be no Java compiler (the tools.jar).
So to launch Maven from within Eclipse, JRE used for launch also need to come from JDK. By default Eclipse registers JRE it is started in, but this can be configured on "Window / Preferences… / Java / Installed JREs" preference page as mentioned above by Parthasarathy
Alternatively you can specify compilerId in the pom.xml, so Maven won’t be looking for JDK when compiling Java code:
<plugin>
<artifactid>maven-compiler-plugin</artifactid>
<configuration>
<compilerid>eclipse</compilerid>
</configuration>
<dependencies>
<dependency>
<groupid>org.codehaus.plexus</groupid>
<artifactid>plexus-compiler-eclipse</artifactid>
<version>xxxx</version>
</dependency>
</dependencies>
</plugin>
The best way to find the key for a particular value is to use key method that is available for a hash....
gender = {"MALE" => 1, "FEMALE" => 2}
gender.key(1) #=> MALE
I hope it solves your problem...
As per this post:
end((explode('-', $string)));
which won't cause E_STRICT warning in PHP 5 (PHP magic). Although the warning will be issued in PHP 7, so adding @
in front of it can be used as a workaround.
The way I fixed it: I went to the Valid OAuth Redirect URIs textbox and set the exact URL, not just the domain:
before: https://my-website.com
after: https://my-website.com/facebookoauth/facebooklogin
(the url may be different in your case, check it in the address bar of the browser).
This was caused by the setting Use Strict Mode for Redirect URIs, which was locked in the Yes position.
While a lot of others should be mentioned, Apache Wicket should be preferred.
Wicket doesn't just reduce lots of boilerplate code, it actually removes it entirely and you can work with excellent separation of business code and markup without mixing the two and a wide variety of other things you can read about from the website.
I want to add the important hint that converting a project like this can have side effects which are noticeable when you have a larger project. This is due the fact that Intellij Idea (2017) takes some important settings only from the pom.xml then which can lead to some confusion, following sections are affected at least:
All these points need review and adjusting but after this it works like charm.
Further more unfortunately there is no sufficient pom.xml template created, I have added an example which might help to solve most problems.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Name</groupId>
<artifactId>Artifact</artifactId>
<version>4.0</version>
<properties>
<!-- Generic properties -->
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<!--All dependencies to put here, including module dependencies-->
</dependencies>
<build>
<directory>${project.basedir}/target</directory>
<outputDirectory>${project.build.directory}/classes</outputDirectory>
<testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<testSourceDirectory> ${project.basedir}/src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>${project.basedir}/src/main/java</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
<includes>
<include>**/*</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<annotationProcessors/>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
Edit 2019:
exit(0); // at the end of main function before closing curly braces
With OpenSSL you can convert pfx to Apache compatible format with next commands:
openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer
openssl pkcs12 -in domain.pfx -nocerts -nodes -out domain.key
First command extracts public key to domain.cer
.
Second command extracts private key to domain.key
.
Update your Apache configuration file with:
<VirtualHost 192.168.0.1:443>
...
SSLEngine on
SSLCertificateFile /path/to/domain.cer
SSLCertificateKeyFile /path/to/domain.key
...
</VirtualHost>
Try this too,
private void getContactList() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if ((cur != null ? cur.getCount() : 0) > 0) {
while (cur != null && cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
if (cur.getInt(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i(TAG, "Name: " + name);
Log.i(TAG, "Phone Number: " + phoneNo);
}
pCur.close();
}
}
}
if(cur!=null){
cur.close();
}
}
If you need more reference means refer this link Read ContactList
case the column isn't string, use astype to convert:
df['col'] = df['col'].astype(str).str[:9]
System
: is predefined class of java.lang
package.
out
: is a static
member of printStream
class and its connect with console.
Println
: is a method of printstream
class and its not a static
.
Use -b:a
instead of -ab
as -ab
is outdated now, also make sure your input file path is correct.
To extract audio from a video I have used below command and its working fine.
String[] complexCommand = {"-y", "-i", inputFileAbsolutePath, "-vn", "-ar", "44100", "-ac", "2", "-b:a", "256k", "-f", "mp3", outputFileAbsolutePath};
Here,
-y
- Overwrite output files without asking.-i
- FFmpeg reads from an arbitrary number of input “files” specified by the -i
option-vn
- Disable video recording-ar
- sets the sampling rate for audio streams if encoded-ac
- Set the number of audio channels.-b:a
- Set the audio bitrate-f
- formatCheck out this for my complete sample FFmpeg android project on GitHub.
Jenkins Pipeline also provides the current build number as the property number
of the currentBuild
. It can be read as currentBuild.number
.
For example:
// Scripted pipeline
def buildNumber = currentBuild.number
// Declarative pipeline
echo "Build number is ${currentBuild.number}"
Other properties of currentBuild
are described in the Pipeline Syntax: Global Variables page that is included on each Pipeline job page. That page describes the global variables available in the Jenkins instance based on the current plugins.
Unlike centralized version control systems, Git clones the entire repository, so you don't only get the current remote files, but the whole history. You local repository will include all this.
There might have been tags to mark a particular version at the time. If not, you can create them yourself locally. A good way to do this is to use git log
or perhaps more visually with tools like gitk
(perhaps gitk --all
to see all the branches and tags). If you can spot the commits hashes that were used at the time, you can tag them using git tag <hash>
and then check those out in new working copies (for example git checkout -b new_branch_name tag_name
or directly with the hash instead of the tag name).
I had the same problem, My upload limit was 2 MB, I edited my php.ini, and I set it to 5 MB but still it was showing 2 MB even after restarting server. Than I compressed my .sql file to zip by keeping its name as xyz.sql.zip so it became 451 kb from 3.5 mb. Then I uploaded it again. It worked for me.
No need to downgrade the build tools back to 18.1.11, this issue is fixed with build tools 19.0.1.
If you can't use 19.0.1 for some reason then:
Make sure that the value of android:targetSdkVersion
in AndroidManifest.xml matches target=android-<value>
in project.properties. If these two values are not the same, building with build tools version 19.0.0 will end in the BufferOverflowException. Source
There is also some indication from comments on this post that you need to target at least 19 (android-19). Please leave a comment if this solution also works if your target is < 19.
This is how the fix looks for my project. The related AOSP issue is #61710.
1 If you really need to downgrade, you don't need to uninstall build tools 19.0.0, simply install 18.1.1 and add sdk.buildtools=18.1.1
to the local.properties
file.
My favourite UI tutorials all come from zetcode.com:
These are tutorials I'd consider to be "starting tutorials". The example tutorial gets you up and going, but doesn't show you anything too advanced or give much explanation. Still, often, I find the big problem is "how do I start?" and these have always proved useful to me.
The default behaviour of Newtonsoft.Json is going to find the public
constructors. If your default constructor is only used in containing class or the same assembly, you can reduce the access level to protected
or internal
so that Newtonsoft.Json will pick your desired public
constructor.
Admittedly, this solution is rather very limited to specific cases.
internal Result() { }
public Result(int? code, string format, Dictionary<string, string> details = null)
{
Code = code ?? ERROR_CODE;
Format = format;
if (details == null)
Details = new Dictionary<string, string>();
else
Details = details;
}
You can set a batch/environment variable as follows:
SET var=%cd%
ECHO %var%
sample screenshot from a Windows 7 x64 cmd.exe.
Update: if you do a SET var = %cd%
instead of SET var=%cd%
, below is what happens. Thanks to jeb.
You specify the escape character. Documentation here:
http://msdn.microsoft.com/en-us/library/ms179859.aspx
This is more for someone Searching for a result, than the original post-er. This worked for me...
declare @value varchar(max) = 'sad';
select sum(cast(iif(isnumeric(@value) = 1, @value, 0) as bigint));
returns 0
declare @value varchar(max) = '3';
select sum(cast(iif(isnumeric(@value) = 1, @value, 0) as bigint));
returns 3
In order to accomplish this, it is best to design fragment construct to receive that data and save that data in its bundle arguments.
class FragmentA extends Fragment{
public static FragmentA newInstance(YourDataClass data) {
FragmentA f = new FragmentA();
Bundle b = new Bundle();
b.putString("data", data);
f.setArguments(b);
return f;
}
}
In order to start the fragment from the class, you can do the following
Fragment newFragment = FragmentA.newInstance(objectofyourclassdata);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
However, the data class must be parceable or serializable.
For full information on fragments and best practices on use of fragments, please spend some time on official docs, it is super useful, at least my experience
https://developer.android.com/guide/components/fragments#java
It's overly-complicated and ugly but in my opinion this is the way to go:
$fp = fopen("php://memory", 'r+');
fputs($fp, $data);
rewind($fp);
while($line = fgets($fp)){
// deal with $line
}
fclose($fp);
Looks like moment.js is the most popular and with active development:
moment("2010-01-01T05:06:07", moment.ISO_8601);
I'm also in the middle of trying to understand how this all connects.
Here's what I've found so far in XCode, but I hope to be corrected or affirmed if my assumptions are correct. I haven't found an out of the box build to xcode from cordova that correctly applies the icons. Like you I've updated all the icons listed in the config.xml but no dice.
So...
First, I usually update the config.xml in the root of the project with the one in my "www" folder (this I do out of uncertainty that the www/config.xml has any precedence or if it's even applied)
Second, I update the "Build Phases" of the project. Expand "Copy Bundle Resources", you've already noticed all of the images in "Resources/icons", "Resources/splash". You can either:
As I was working this out, you might be able to minimally just update images from the "Summary" tab.
Drag-and-drop your images from your res folders to the appropriate image in the "Summary" tab. (res/icon/ios -> App icons and res/screen/ios -> Launch Images). I do it only for iPhone since my app is iPhone only. Check "prerendered" if you don't want gloss to appear.
Then update the "icon.png" referenced in the project's plist file: PROJECT_NAME-Info.plist or in the "Info" tab when looking at the project target. Rename it to "icon-57.png" (that now lives in your project root, this was automatically added to the root when you did the drag-and-drop.
Build and you should an updated app icon.
You can do this in your code:
final ListView lv = (ListView) convertView.findViewById(R.id.list_view);
for (int i = 0; i < lv.getChildCount(); i++) {
((TextView)lv.getChildAt(i)).setTextColor(getResources().getColor(R.color.black));
}
Your problem is probably that a
elements are display: inline
by nature. You can't set the width and height of inline elements.
You would have to set display: block
on the a
, but that will bring other problems because the links start behaving like block elements. The most common cure to that is giving them float: left
so they line up side by side anyway.
From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning
the following
Excessive GC Time and OutOfMemoryError
The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.
The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).
in conjunction with a passage further down
One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,
java -Dsun.rmi.dgc.client.gcInterval=3600000
-Dsun.rmi.dgc.server.gcInterval=3600000
specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.
Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.
Of course, other interpretations are possible.
No. This needs to be done in the HTML. You could set the value with Javascript if you need to though.
works for me
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
var isScroll = false
@objc func keyboardWillShow(sender: NSNotification) {
if( !isScroll ){
self.view.frame.origin.y -= 150
isScroll = true
}
}
@objc func keyboardWillHide(sender: NSNotification) {
if( isScroll ){
self.view.frame.origin.y += 150
isScroll = false
}
}
If you actually want arrays:
>>> from array import array
>>> text = "a,b,c"
>>> text = text.replace(',', '')
>>> myarray = array('c', text)
>>> myarray
array('c', 'abc')
>>> myarray[0]
'a'
>>> myarray[1]
'b'
If you do not need arrays, and only want to look by index at your characters, remember a string is an iterable, just like a list except the fact that it is immutable:
>>> text = "a,b,c"
>>> text = text.replace(',', '')
>>> text[0]
'a'
Example with some beautifying, similar to the sep option available in python 3.8
def prettyhex(nums, sep=''):
return sep.join(f'{a:02x}' for a in nums)
numbers = [0, 1, 2, 3, 127, 200, 255]
print(prettyhex(numbers,'-'))
output
00-01-02-03-7f-c8-ff
this is a bit late.. but i have seen this problem occurs when you want to insert or delete one line from/to DB but u put/pull more than one line or more than one value ,
E.g:
you want to delete one line from DB with a specific value such as id of an item but you've queried a list of ids then you will encounter the same exception message.
regards.
Download the following jars and add it to your WEB-INF/lib
directory:
If you want something more efficient in runtime condition, you can have a map that contains every possible choice of the enum by their value. But it'll be juste slower at initialisation of the JVM.
import java.util.HashMap;
import java.util.Map;
/**
* Example of enum with a getter that need a value in parameter, and that return the Choice/Instance
* of the enum which has the same value.
* The value of each choice can be random.
*/
public enum MyEnum {
/** a random choice */
Choice1(4),
/** a nother one */
Choice2(2),
/** another one again */
Choice3(9);
/** a map that contains every choices of the enum ordered by their value. */
private static final Map<Integer, MyEnum> MY_MAP = new HashMap<Integer, MyEnum>();
static {
// populating the map
for (MyEnum myEnum : values()) {
MY_MAP.put(myEnum.getValue(), myEnum);
}
}
/** the value of the choice */
private int value;
/**
* constructor
* @param value the value
*/
private MyEnum(int value) {
this.value = value;
}
/**
* getter of the value
* @return int
*/
public int getValue() {
return value;
}
/**
* Return one of the choice of the enum by its value.
* May return null if there is no choice for this value.
* @param value value
* @return MyEnum
*/
public static MyEnum getByValue(int value) {
return MY_MAP.get(value);
}
/**
* {@inheritDoc}
* @see java.lang.Enum#toString()
*/
public String toString() {
return name() + "=" + value;
}
/**
* Exemple of how to use this class.
* @param args args
*/
public static void main(String[] args) {
MyEnum enum1 = MyEnum.Choice1;
System.out.println("enum1==>" + String.valueOf(enum1));
MyEnum enum2GotByValue = MyEnum.getByValue(enum1.getValue());
System.out.println("enum2GotByValue==>" + String.valueOf(enum2GotByValue));
MyEnum enum3Unknown = MyEnum.getByValue(4);
System.out.println("enum3Unknown==>" + String.valueOf(enum3Unknown));
}
}