The Java Secure Channel (JSCH) is a very popular library, used by maven, ant and eclipse. It is open source with a BSD style license.
In Matrix terms, the number of elements always has to equal the product of the number of rows and columns. In this particular case, the condition is not matching.
I had the same problem and found out that you have to escape spaces in the extra:
adb shell am broadcast -a com.whereismywifeserver.intent.TEST --es sms_body "test\ from\ adb"
So instead of "test from adb" it should be "test\ from\ adb"
Variations on a theme:
NSString *varying = @"whatever it is";
NSString *final = [NSString stringWithFormat:@"first part %@ third part", varying];
NSString *varying = @"whatever it is";
NSString *final = [[@"first part" stringByAppendingString:varying] stringByAppendingString:@"second part"];
NSMutableString *final = [NSMutableString stringWithString:@"first part"];
[final appendFormat:@"%@ third part", varying];
NSMutableString *final = [NSMutableString stringWithString:@"first part"];
[final appendString:varying];
[final appendString:@"third part"];
CSS code:
.header .navbar-default {
background: none;
}
HTML code:
<header>
<nav class="navbar navbar-default"></nav>
</header>
public static bool IsNumeric(this string input)
{
int n;
if (!string.IsNullOrEmpty(input)) //.Replace('.',null).Replace(',',null)
{
foreach (var i in input)
{
if (!int.TryParse(i.ToString(), out n))
{
return false;
}
}
return true;
}
return false;
}
There is now a beta available of Google Maps KML Importing Utility.
It is part of the Google Maps Android API Utility Library. As documented it allows loading KML files from streams
KmlLayer layer = new KmlLayer(getMap(), kmlInputStream, getApplicationContext());
or local resources
KmlLayer layer = new KmlLayer(getMap(), R.raw.kmlFile, getApplicationContext());
After you have created a KmlLayer, call addLayerToMap() to add the imported data onto the map.
layer.addLayerToMap();
Adding to jelovirt's answer, you can use number() to convert the value to a number, then round(), floor(), or ceiling() to get a whole integer.
Example
<xsl:variable name="MyValAsText" select="'5.14'"/>
<xsl:value-of select="number($MyValAsText) * 2"/> <!-- This outputs 10.28 -->
<xsl:value-of select="floor($MyValAsText)"/> <!-- outputs 5 -->
<xsl:value-of select="ceiling($MyValAsText)"/> <!-- outputs 6 -->
<xsl:value-of select="round($MyValAsText)"/> <!-- outputs 5 -->
If you have any text before a
header('Location: http://www.example.com/youformhere.php');
you'll have issues, because that must be sent before any other text is sent to the page.
Try using this code instead
<?php
$page = $_SERVER['PHP_SELF'];
echo '<meta http-equiv="Refresh" content="0;' . $page . '">';
?>
Just remember, this code will create and infinite loop, so you'll probably need to make some conditional changes to it.
$(document).ready( function() { YOUR CODE HERE } )
I have solved as plist file.
After a while of research and disappointments....I was able to make this up
<?php $conn = new mysqli('hostname', 'username', 'password','dbname') or die ('Cannot connect to db') $result = $conn->query("select * from table");?>
//insert the below code in the body
<table id="myTable"> <tr class="header"> <th style="width:20%;">Name</th>
<th style="width:20%;">Email</th>
<th style="width:10%;">City/ Region</th>
<th style="width:30%;">Details</th>
</tr>
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>".$row['username']."</td>";
echo "<td>".$row['city']."</td>";
echo "<td>".$row['details']."</td>";
echo "</tr>";
}
?>
</table>
Trust me it works :)
I get the same issue. In fact, the request didn't reach the jersey annoted method. I solved the problem with add the annotation: @Consumes(MediaType.APPLICATION_FORM_URLENCODED) The annotation @Consumes("/") don't work!
@Path("/"+PropertiesHabilitation.KEY_EstNouvelleGH)
@POST
//@Consumes("*/*")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void get__EstNouvelleGH( @Context HttpServletResponse response) {
...
}
java.sql.ResultSet rs;
//fill rs somehow
java.sql.Timestamp timestamp = rs.getTimestamp(1); //get first column
long milliseconds = timestamp.getTime() + (timestamp.getNanos() / 1000000);
java.util.Date date = return new java.util.Date(milliseconds);
In python, for loops iterate over iterables, instead of incrementing a counter, so you have a couple choices. Using a skip flag like Artsiom recommended is one way to do it. Another option is to make a generator from your range and manually advance it by discarding an element using next()
.
iGen = (i for i in range(0, 6))
for i in iGen:
print i
if not i % 2:
iGen.next()
But this isn't quite complete because next()
might throw a StopIteration if it reaches the end of the range, so you have to add some logic to detect that and break out of the outer loop if that happens.
In the end, I'd probably go with aw4ully's solution with the while loops.
Actually there are 3 places where gradle.properties
can be placed:
GRADLE_USER_HOME
environment variable, which if not set defaults to USER_HOME/.gradlemyProject2
in your case)myProject
)Gradle looks for gradle.properties
in all these places while giving precedence to properties definition based on the order above. So for example, for a property defined in gradle user home directory (#1) and the sub-project (#2) its value will be taken from gradle user home directory (#1).
You can find more details about it in gradle documentation here.
I have used it for my academic project which was online retail website similar to Amazon. JMS was used to handle following features :
We had multiple also implemented remote clients connected to main Server. If connection is available, they use to access the main database or if not use their own database. In order to handle data consistency, we had implemented 2PC mechanism. For this, we used JMS for exchange the messages between these systems i.e one acting as coordinator who will initiate the process by sending message on the queue and others will respond accordingly by sending back again a message on the queue. As others have already mentioned, this was similar to pub/sub model.
The elements of a sequence need to be indented at the same level. Assuming you want two jobs (A and B) each with an ordered list of key value pairs, you should use:
jobs:
- - name: A
- schedule: "0 0/5 * 1/1 * ? *"
- - type: mongodb.cluster
- config:
- host: mongodb://localhost:27017/admin?replicaSet=rs
- minSecondaries: 2
- minOplogHours: 100
- maxSecondaryDelay: 120
- - name: B
- schedule: "0 0/5 * 1/1 * ? *"
- - type: mongodb.cluster
- config:
- host: mongodb://localhost:27017/admin?replicaSet=rs
- minSecondaries: 2
- minOplogHours: 100
- maxSecondaryDelay: 120
Converting the sequences of (single entry) mappings to a mapping as @Tsyvarrev does is also possible, but makes you lose the ordering.
Add a connection string in the root web.config file of 'container' MVC project that references the class library as following:
<connectionStrings>
<add name="MyEntities" connectionString="complete connection string here" providerName="System.Data.SqlClient" />
</connectionStrings>
If you do not want to use "MyEntities" as connection name then change it as you wish but make the following change in your MyEntities DbContext class:
MyEntities: DbContext
{
public MyEntities():base("Name-Of-connection-string-you wish to connect"){ }
}
Reason for this error is, If we will not specify the name of connection string Or connect string in derived class of DbConext(In your case it is MyEntities) then DbContext will automatically search for a connection string in root web.config file whoes name is same as derived class name (In your case it is My Entities).
Ken has the right solution, but you don't want to add the picturebox.Image.Load() member method.
If you do it with a Load and the ImageLocation is not set, it will fail with a "Image Location must be set" exception. If you use the picturebox.Refresh() member method, it works without the exception.
Completed code below:
public void showAnimatedPictureBox(PictureBox thePicture)
{
thePicture.Image = Properties.Resources.hamster;
thePicture.Refresh();
thePicture.Visible = true;
}
It is invoked as: showAnimatedPictureBox( myPictureBox );
My XAML looks like:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
xmlns:winForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="myApp.MainWindow"
Title="myApp" Height="679.079" Width="986">
<StackPanel Width="136" Height="Auto" Background="WhiteSmoke" x:Name="statusPanel">
<wfi:WindowsFormsHost>
<winForms:PictureBox x:Name="myPictureBox">
</winForms:PictureBox>
</wfi:WindowsFormsHost>
<Label x:Name="myLabel" Content="myLabel" Margin="10,3,10,5" FontSize="20" FontWeight="Bold" Visibility="Hidden"/>
</StackPanel>
</Window>
I realize this is an old post, but loading the image directly from a resource is was extremely unclear on Microsoft's site, and this was the (partial) solution I came to. Hope it helps someone!
This was what I was searching online but unfortunately found not online but while experimenting on python interpreter.
>>> case = "caseCamel"
>>> label = "Case Camel"
>>> list = ["apple", "banana"]
>>>
>>> (case or label) in list
False
>>> list = ["apple", "caseCamel"]
>>> (case or label) in list
True
>>> (case and label) in list
False
>>> list = ["case", "caseCamel", "Case Camel"]
>>> (case and label) in list
True
>>>
and if you have a looong list of variables held in a sublist variable
>>>
>>> list = ["case", "caseCamel", "Case Camel"]
>>> label = "Case Camel"
>>> case = "caseCamel"
>>>
>>> sublist = ["unique banana", "very unique banana"]
>>>
>>> # example for if any (at least one) item contained in superset (or statement)
...
>>> next((True for item in sublist if next((True for x in list if x == item), False)), False)
False
>>>
>>> sublist[0] = label
>>>
>>> next((True for item in sublist if next((True for x in list if x == item), False)), False)
True
>>>
>>> # example for whether a subset (all items) contained in superset (and statement)
...
>>> # a bit of demorgan's law
...
>>> next((False for item in sublist if item not in list), True)
False
>>>
>>> sublist[1] = case
>>>
>>> next((False for item in sublist if item not in list), True)
True
>>>
>>> next((True for item in sublist if next((True for x in list if x == item), False)), False)
True
>>>
>>>
I can find following ways to do.
private static final String fileName = "C:/Input.txt";
public static void main(String[] args) throws IOException {
Stream<String> lines = Files.lines(Paths.get(fileName));
lines.toArray(String[]::new);
List<String> readAllLines = Files.readAllLines(Paths.get(fileName));
readAllLines.forEach(s -> System.out.println(s));
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
Maybe a lot of awnsers. But I like this in pure CSS with fa-buttons:
.divs {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
background-color: #fcc;_x000D_
}_x000D_
_x000D_
.inputs {_x000D_
position:absolute;_x000D_
left: 0px;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
opacity: 0;_x000D_
background: #00f;_x000D_
z-index:999;_x000D_
}_x000D_
_x000D_
.icons {_x000D_
position:relative;_x000D_
}
_x000D_
<div class="divs">_x000D_
<input type='file' id='image' class="inputs">_x000D_
<i class="fa fa-image fa-2x icons"></i>_x000D_
</div>_x000D_
_x000D_
<div class="divs">_x000D_
<input type='file' id='book' class="inputs">_x000D_
<i class="fa fa-book fa-5x icons"></i>_x000D_
</div>_x000D_
<br><br><br>_x000D_
<div class="divs">_x000D_
<input type='file' id='data' class="inputs">_x000D_
<i class="fa fa-id-card fa-3x icons"></i>_x000D_
</div>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
_x000D_
In response to the above post I think it needs this line instead of your line:-
var strMethodUrl = '@Url.Action("SubMenu_Click", "Logging")?param1='+value1+' ¶m2='+value2
Or else you send the actual strings value1 and value2 to the controller.
However, for me, it only calls the controller once. It seems to hit 'receieveResponse' each time, but a break point on the controller method shows it is only hit 1st time until a page refresh.
Here is a working solution. For the cshtml page:-
<button type="button" onclick="ButtonClick();"> Call »</button>
<script>
function ButtonClick()
{
callControllerMethod2("1", "2");
}
function callControllerMethod2(value1, value2)
{
var response = null;
$.ajax({
async: true,
url: "Logging/SubMenu_Click?param1=" + value1 + " ¶m2=" + value2,
cache: false,
dataType: "json",
success: function (data) { receiveResponse(data); }
});
}
function receiveResponse(response)
{
if (response != null)
{
for (var i = 0; i < response.length; i++)
{
alert(response[i].Data);
}
}
}
</script>
And for the controller:-
public class A
{
public string Id { get; set; }
public string Data { get; set; }
}
public JsonResult SubMenu_Click(string param1, string param2)
{
A[] arr = new A[] {new A(){ Id = "1", Data = DateTime.Now.Millisecond.ToString() } };
return Json(arr , JsonRequestBehavior.AllowGet);
}
You can see the time changing each time it is called, so there is no caching of the values...
You can edit the ~/.gitconfig
file to store your credentials
sudo nano ~/.gitconfig
Which should already have
[user]
email = [email protected]
user = gitUSER
You should add at the bottom of this file.
[credential]
helper = store
The reason I recommend this option is cause it is global and if at any point you need to remove the option you know where to go and change it.
ONLY USE THIS OPTION IN YOU PERSONAL COMPUTER.
Then when you pull | clone| enter you git password, in general, the password will be saved in ~/.git-credentials
in the format
https://GITUSER:[email protected]
WHERE DOMAIN.XXX COULD BE GITHUB.COM | BITBUCKET.ORG | OTHER
See Docs
Just put a
List<Person>
into the ViewBag and in the View cast it back to List
The approach I suggest works like the following. First, you create a basic datetime object from a mysql-formatted string; and then you format it the way you like. Luckily, mysql datetime is ISO8601-compliant, so the code itself could look quite simple and elegant. Keep in mind though that datetime
column doesn't have a timezone information, so you need to convert it appropriately.
Here's the code:
(new ISO8601Formatted(
new FromISO8601('2038-01-19 11:14:07'),
'm/d/Y h:iA'
))
->value();
It outputs 01/19/2038 11:14AM
-- hopefully what you expect.
This example uses meringue library. You can check out some more of it if you fancy.
You could try to find it via the command line.
find / -type f -name "php.ini"
Or you could add the following to a .htaccess
file in the root of your site.
php_value max_input_vars 6000
php_value suhosin.get.max_vars 6000
php_value suhosin.post.max_vars 6000
php_value suhosin.request.max_vars 6000
For Windows, CaptureStackBackTrace()
is also an option, which requires less preparation code on the user's end than StackWalk64()
does. (Also, for a similar scenario I had, CaptureStackBackTrace()
ended up working better (more reliably) than StackWalk64()
.)
<html>
<head>
<H1>
Automatically play music files on your website when a page loads
</H1>
</head>
<body>
<embed src="YourMusic.mp3" autostart="true" loop="true" width="2" height="0">
</embed>
</body>
</html>
There's a cool CSS-only solution to styling dropdowns here: http://bavotasan.com/2011/style-select-box-using-only-css/
Basically, wrap the select in a container div, style the select to be 18px wider than the container with a transparent background, give overflow:hidden to the container (to chop off the browser-generated arrow), and add your background image with stylized arrow to the container.
Doesn't work in IE7 (or 6), but seriously, I say if you're using IE7 you deserve a less-pretty dropdown experience.
use $unwind you will get the first object instead of array of objects
query:
db.getCollection('vehicles').aggregate([
{
$match: {
status: "AVAILABLE",
vehicleTypeId: {
$in: Array.from(newSet(d.vehicleTypeIds))
}
}
},
{
$lookup: {
from: "servicelocations",
localField: "locationId",
foreignField: "serviceLocationId",
as: "locations"
}
},
{
$unwind: "$locations"
}
]);
result:
{
"_id" : ObjectId("59c3983a647101ec58ddcf90"),
"vehicleId" : "45680",
"regionId" : 1.0,
"vehicleTypeId" : "10TONBOX",
"locationId" : "100",
"description" : "Isuzu/2003-10 Ton/Box",
"deviceId" : "",
"earliestStart" : 36000.0,
"latestArrival" : 54000.0,
"status" : "AVAILABLE",
"accountId" : 1.0,
"locations" : {
"_id" : ObjectId("59c3afeab7799c90ebb3291f"),
"serviceLocationId" : "100",
"regionId" : 1.0,
"zoneId" : "DXBZONE1",
"description" : "Masafi Park Al Quoz",
"locationPriority" : 1.0,
"accountTypeId" : 0.0,
"locationType" : "DEPOT",
"location" : {
"makani" : "",
"lat" : 25.123091,
"lng" : 55.21082
},
"deliveryDays" : "MTWRFSU",
"timeWindow" : {
"timeWindowTypeId" : "1"
},
"address1" : "",
"address2" : "",
"phone" : "",
"city" : "",
"county" : "",
"state" : "",
"country" : "",
"zipcode" : "",
"imageUrl" : "",
"contact" : {
"name" : "",
"email" : ""
},
"status" : "",
"createdBy" : "",
"updatedBy" : "",
"updateDate" : "",
"accountId" : 1.0,
"serviceTimeTypeId" : "1"
}
}
{
"_id" : ObjectId("59c3983a647101ec58ddcf91"),
"vehicleId" : "81765",
"regionId" : 1.0,
"vehicleTypeId" : "10TONBOX",
"locationId" : "100",
"description" : "Hino/2004-10 Ton/Box",
"deviceId" : "",
"earliestStart" : 36000.0,
"latestArrival" : 54000.0,
"status" : "AVAILABLE",
"accountId" : 1.0,
"locations" : {
"_id" : ObjectId("59c3afeab7799c90ebb3291f"),
"serviceLocationId" : "100",
"regionId" : 1.0,
"zoneId" : "DXBZONE1",
"description" : "Masafi Park Al Quoz",
"locationPriority" : 1.0,
"accountTypeId" : 0.0,
"locationType" : "DEPOT",
"location" : {
"makani" : "",
"lat" : 25.123091,
"lng" : 55.21082
},
"deliveryDays" : "MTWRFSU",
"timeWindow" : {
"timeWindowTypeId" : "1"
},
"address1" : "",
"address2" : "",
"phone" : "",
"city" : "",
"county" : "",
"state" : "",
"country" : "",
"zipcode" : "",
"imageUrl" : "",
"contact" : {
"name" : "",
"email" : ""
},
"status" : "",
"createdBy" : "",
"updatedBy" : "",
"updateDate" : "",
"accountId" : 1.0,
"serviceTimeTypeId" : "1"
}
}
You can simply use the toUTCString
(or toISOString
) methods of the date object.
Example:
new Date("Fri Jan 20 2012 11:51:36 GMT-0500").toUTCString()
// Output: "Fri, 20 Jan 2012 16:51:36 GMT"
If you prefer better control of the output format, consider using a library such as date-fns or moment.js.
Also, in your question, you've actually converted the time incorrectly. When an offset is shown in a timestamp string, it means that the date and time values in the string have already been adjusted from UTC by that value. To convert back to UTC, invert the sign before applying the offset.
11:51:36 -0300 == 14:51:36Z
After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.
* The arguments which may be supplied in the recovery.command file:
* --send_intent=anystring - write the text out to recovery.intent
* --update_package=path - verify install an OTA package file
* --wipe_data - erase user data (and cache), then reboot
* --wipe_cache - wipe cache (but not user data), then reboot
* --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:
adb shell
recovery --wipe_data
Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.
EDIT:
For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command
For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c
You don't use the :
syntax - pull
always modifies the currently checked-out branch. Thus:
git pull origin my_remote_branch
while you have my_local_branch
checked out will do what you want.
Since you already have the tracking branch set, you don't even need to specify - you could just do...
git pull
while you have my_local_branch
checked out, and it will update from the tracked branch.
There are multiple nuget packages read in the following order:
NuGetDefaults.Config file
. You will find this in %ProgramFiles(x86)%\NuGet\Config
.%APPDATA%\NuGet\nuget.config
.nuget.config
beginning from the root of your drive up to the directory where nuget.exe is called.You can find more information here.
Because it makes these things so easy, you could consider using a JavaScript library like jQuery to do this:
<script>
$(document).ready(function() {
$('img.thumbnail').click(function() {
window.location.href = this.id + '.html';
});
});
</script>
Basically, it attaches an onClick
event to all images with class thumbnail
to redirect to the corresponding HTML page (id
+ .html
). Then you only need the images in your HTML (without the a
elements), like this:
<img src="bottle.jpg" alt="bottle" class="thumbnail" id="bottle" />
<img src="glass.jpg" alt="glass" class="thumbnail" id="glass" />
In the browser's developer console (press F12 to open it), you can type the following,
angular.version.full
it will give you the full version, e.g. (depending on your current version). [It actually gets the full
property of angular.version
object.]
"1.4.3"
So, to see the full object, if you type
angular.version
It will give you the full version object containing version information like full, major, minor and also the codeName, e.g.
Object {full: "1.4.3", major: 1, minor: 4, dot: 3, codeName: "foam-acceleration"}
For me, first disabling and then re-enabling calculation (e.g. for the active worksheet) solved the problem:
ThisWorkbook.ActiveSheet.EnableCalculation = False
ThisWorkbook.ActiveSheet.EnableCalculation = True
Maybe execute twice in succession. All charts in the worksheet update entirely.
Just select range row from df like this
row_count = df.shape[0]
split_point = int(row_count*1/5)
test_data, train_data = df[:split_point], df[split_point:]
The query execution happens on all get methods like
$this->db->get('table_name');
$this->db->get_where('table_name',$array);
While last_query contains the last query which was run
$this->db->last_query();
If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now you can write query and get it in a variable
$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();
Now reset query so if you want to write another query the object will be cleared.
$this->db->_reset_select();
And the thing is done. Cheers!!! Note : While using this way you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
You can use the :contains()
selector to select elements that contain specific text.
For example:
$('#mySelect option:contains(abc)')
To check whether a given <select>
element has such an option, use the .has()
method:
if (mySelect.has('option:contains(abc)').length)
To find all <select>
s that contain such an option, use the :has()
selector:
$('select:has(option:contains(abc))')
Make sure that you place the @JsonIgnoreProperties(ignoreUnknown = true)
annotation to the parent POJO class which you want to populate as a result of parsing the JSON response and not the class where the conversion from JSON to Java Object is taking place.
There is org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean
for a long time. Starting from 1.2 release of Spring Boot there is org.springframework.http.converter.json.Jackson2ObjectMapperBuilder
for Java Config.
In String Boot configuration can be as simple as:
spring.jackson.deserialization.<feature_name>=true|false
spring.jackson.generator.<feature_name>=true|false
spring.jackson.mapper.<feature_name>=true|false
spring.jackson.parser.<feature_name>=true|false
spring.jackson.serialization.<feature_name>=true|false
spring.jackson.default-property-inclusion=always|non_null|non_absent|non_default|non_empty
in classpath:application.properties
or some Java code in @Configuration
class:
@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.indentOutput(true).dateFormat(new SimpleDateFormat("yyyy-MM-dd"));
return builder;
}
See:
I too had the same error in trace logs. My newly created function in API was throwing the same error but to my surprise, the old functions were performing good. The issue was - My contract data members had few variables of type object. soap-xml was not able to handle it well, however, I can see that array of object types (object[]) were getting passed without any issues. Only a simple object type was not getting parsed by soap. This could be one more reason why the services throw the above error.
Highly recommend something more like this:
public class Person {
public string Name {get; set;}
public string Email {get; set;}
}
var people = new List<Person>();
Easier to read, easy to code.
In window form c#. If you use Enter event it will not work. try to use MouseUp event
bool FlagEntered;
private void textBox1_MouseUp(object sender, MouseEventArgs e)
{
if ((sender as TextBox).SelectedText == "" && !FlagEntered)
{
(sender as TextBox).SelectAll();
FlagEntered = true;
}
}
private void textBox1_Leave(object sender, EventArgs e)
{
FlagEntered = false;
}
The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple print
statement you can see that each file is found:
import os
rootdir = 'C:/Users/sid/Desktop/test'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
print os.path.join(subdir, file)
If you still get errors when running the above, please provide the error message.
Updated for Python3
import os
rootdir = 'C:/Users/sid/Desktop/test'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
print(os.path.join(subdir, file))
For Pip installation on Windows and 64-bit Python 3.5:
CPU only version:
C:\> pip install --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-0.12.0rc0-cp35-cp35m-win_amd64.whl
For the GPU version:
C:\> pip install --upgrade https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-0.12.0rc0-cp35-cp35m-win_amd64.whl
https://www.tensorflow.org/versions/r0.12/get_started/os_setup.html
Also see tensorflow not found in pip.
The following appears to work:
table td {
vertical-align: middle !important;
}
You can apply to a specific table as well like so:
#some_table td {
vertical-align: middle !important;
}
This line:
layout = (LinearLayout) findViewById(R.id.statsviewlayout);
Looks for the "statsviewlayout" id in your current 'contentview'. Now you've set that here:
setContentView(new GraphTemperature(getApplicationContext()));
And i'm guessing that new "graphTemperature" does not set anything with that id.
It's a common mistake to think you can just find any view with findViewById. You can only find a view that is in the XML (or appointed by code and given an id).
The nullpointer will be thrown because the layout you're looking for isn't found, so
layout.addView(buyButton);
Throws that exception.
addition: Now if you want to get that view from an XML, you should use an inflater:
layout = (LinearLayout) View.inflate(this, R.layout.yourXMLYouWantToLoad, null);
assuming that you have your linearlayout in a file called "yourXMLYouWantToLoad.xml"
You can solve the problem by checking if your date matches a REGEX pattern. If not, then NULL (or something else you prefer).
In my particular case it was necessary because I have >20 DATE columns saved as CHAR, so I don't know from which column the error is coming from.
Returning to your query:
1. Declare a REGEX pattern.
It is usually a very long string which will certainly pollute your code (you may want to reuse it as well).
define REGEX_DATE = "'your regex pattern goes here'"
Don't forget a single quote inside a double quote around your Regex :-)
A comprehensive thread about Regex date validation you'll find here.
2. Use it as the first CASE condition:
To use Regex validation in the SELECT
statement, you cannot use REGEXP_LIKE
(it's only valid in WHERE
. It took me a long time to understand why my code was not working. So it's certainly worth a note.
Instead, use REGEXP_INSTR
For entries not found in the pattern (your case) use REGEXP_INSTR (variable, pattern) = 0
.
DEFINE REGEX_DATE = "'your regex pattern goes here'"
SELECT c.contract_num,
CASE
WHEN REGEXP_INSTR(c.event_dt, ®EX_DATE) = 0 THEN NULL
WHEN ( MAX (TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD'))
- MIN (TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD')))
/ COUNT (c.event_occurrence) < 32
THEN
'Monthly'
WHEN ( MAX (
TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD'))
- MIN (
TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD')))
/ COUNT (c.event_occurrence) >= 32
AND ( MAX (
TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD'))
- MIN (
TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD')))
/ COUNT (c.event_occurrence) < 91
THEN
'Quarterley'
ELSE
'Yearly'
END
FROM ps_ca_bp_events c
GROUP BY c.contract_num;
I have a slightly different way of doing this than the accepted answer. This way you can avoid using GROUP_CONCAT which has a limit of 1024 characters and will not work if you have a lot of fields.
SET @sql = '';
SELECT
@sql := CONCAT(@sql,if(@sql='','',', '),temp.output)
FROM
(
SELECT
DISTINCT
CONCAT(
'MAX(IF(pa.fieldname = ''',
fieldname,
''', pa.fieldvalue, NULL)) AS ',
fieldname
) as output
FROM
product_additional
) as temp;
SET @sql = CONCAT('SELECT p.id
, p.name
, p.description, ', @sql, '
FROM product p
LEFT JOIN product_additional AS pa
ON p.id = pa.id
GROUP BY p.id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Since swift 3.0 there is more convenient way: #imageLiterals here is text example. And below animated example from here:
String termsOfCondition="<font color=#cc0029>Terms of Use </font>";
String commma="<font color=#000000>, </font>";
String privacyPolicy="<font color=#cc0029>Privacy Policy </font>";
Spanned text=Html.fromHtml("I am of legal age and I have read, understood, agreed and accepted the "+termsOfCondition+commma+privacyPolicy);
secondCheckBox.setText(text);
In SQL Server 2000, objects created were linked to that particular user, like if a user, say Sam creates an object, say, Employees, that table would appear like: Sam.Employees. What about if Sam is leaving the compnay or moves to so other business area. As soon you delete the user Sam, what would happen to Sam.Employees table? Probably, you would have to change the ownership first from Sam.Employees to dbo.Employess. Schema provides a solution to overcome this problem. Sam can create all his object within a schemam such as Emp_Schema. Now, if he creates an object Employees within Emp_Schema then the object would be referred to as Emp_Schema.Employees. Even if the user account Sam needs to be deleted, the schema would not be affected.
Use Default toolkit for this
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("Icon.png"));
build.gradle
implementation 'com.google.android.material:material:1.2.0-alpha02'
styles.xml
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
the articles posted by Ricky are very good, but unfortunately they don't answer your question.
To solve your problem you should try this piece of code:
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = @"d:\test\justAConfigFile.config.whateverYouLikeExtension";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
If need to access a value within the config you can use the index operator:
config.AppSettings.Settings["test"].Value;
As of 2013: This would be my approach. jsFiddle:
HTML
<header class="container global-header">
<h1>Header (fixed)</h1>
</header>
<div class="container main-content">
<div class="inner-w">
<h1>Main Content</h1>
</div><!-- .inner-w -->
</div> <!-- .main-content -->
<footer class="container global-footer">
<h3>Footer (fixed)</h3>
</footer>
SCSS
// User reset
* { // creates a natural box model layout
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
} // asume normalize.css
// structure
.container {
position: relative;
width: 100%;
float: left;
padding: 1em;
}
// type
body {
font-family: arial;
}
.main-content {
h1 {
font-size: 2em;
font-weight: bold;
margin-bottom: .2em;
}
} // .main-content
// style
// variables
$global-header-height: 8em;
$global-footer-height: 6em;
.global-header {
position: fixed;
top: 0; left: 0;
background-color: gray;
height: $global-header-height;
}
.main-content {
background-color: orange;
margin-top: $global-header-height;
margin-bottom: $global-footer-height;
z-index: -1; // so header will be on top
min-height: 50em; // to make it long so you can see the scrolling
}
.global-footer {
position: fixed;
bottom: 0;
left: 0;
height: $global-footer-height;
background-color: gray;
}
var inp = $("#txt").val();
if(jQuery.trim(inp).length > 0)
{
//do something
}
Removes white space before checking. If the user entered only spaces then this will still work.
In javascript without using jquery:
document.body.innerText = document.body.innerText.replace('actualword', 'replacementword');
You don't need to use any library. Just only write system("color 4f");
At this moment, PHP itself does not provide a way to get the project's root directory for sure.
But you can implement a very simple method yourself that will do exactly what you're looking for.
Solution
Create a new file in your project, let say D:/workspace/MySystem/Code/FilesManager.php
(use whatever name and path suit you the best). Then, use the following code:
<?php
class FilesManager
{
public static function rootDirectory()
{
// Change the second parameter to suit your needs
return dirname(__FILE__, 2);
}
}
Now you can do this in, let's say D:/workspace/MySystem/Code/a/b/c/Feature.php
:
echo FilesManager::rootDirectory();
And the expected result should be:
"D:/workspace/MySystem"
The output will be the same no matter where your "feature" file is located in the project.
Explanation
dirname is used to return the parent directory of the first parameter. We use the magic constant __FILE__
to give it FilesManager.php
's path. The second parameter tells how many times to go up in the hierarchy. In this case, we need to do it twice, but it really depends where you put your file in the hierarchy. You can omit the second parameter if you only need to got up once, meaning the file is located in the root. But then, you can return __DIR__
directly instead.
This solution is guaranteed to work, no matter where the root is located on your server. Unless you end up moving the utility class somewhere else in the hierarchy.
Additional note
I'd avoid using DOCUMENT_ROOT for the following reasons (according to this answer):
The other fun thing about null, compared to undefined, is that it can be incremented.
x = undefined_x000D_
x++_x000D_
y = null_x000D_
y++_x000D_
console.log(x) // NaN_x000D_
console.log(y) // 0
_x000D_
This is useful for setting default numerical values for counters. How many times have you set a variable to -1 in its declaration?
FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.
Some references:
Though you can use any other client that allows automation.
You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).
Combine WinSCP scripting capabilities with Windows Scheduler:
A typical WinSCP script for upload (with SFTP) looks like:
open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close
With FTP, just replace the sftp://
with the ftp://
and remove the -hostkey="..."
switch.
Similarly for download: How to schedule an automatic FTP download on Windows?
WinSCP can even generate a script from an imported FileZilla session.
For details, see the guide to FileZilla automation.
(I'm the author of WinSCP)
Another option, if you are using SFTP, is the psftp.exe
client from PuTTY suite.
Just an extension on the previous answers here. Two parts to ensure, Make sure that you add in extraData and that your keyExtractor is unique. If your keyExtractor is constant a rerender will not be triggered.
<FlatList
data={this.state.AllArray}
extraData={this.state.refresh}
renderItem={({ item,index })=>this.renderPhoto(item,index)}
keyExtractor={item => item.id}
>
</FlatList>
I had some problems with pending request for mp3 files. I had a list of mp3 files and one player to play them. If I picked a file that had already been downloaded, Chrome would block the request and show "pending request" in the network tab of the developer tools.
All versions of Chrome seem to be affected.
Here is a solution I found:
player[0].setAttribute('src','video.webm?dummy=' + Date.now());
You just add a dummy query string to the end of each url. This forces Chrome to download the file again.
Another example with popcorn player (using jquery) :
url = $(this).find('.url_song').attr('url');
pop = Popcorn.smart( "#player_", url + '?i=' + Date.now());
This works for me. In fact, the resource is not stored in the cache system. This should also work in the same way for .csv files.
This is a general rambling on Parallelism in SQL Server, it might not answer your question directly.
From Books Online, on MAXDOP:
Sets the maximum number of processors the query processor can use to execute a single index statement. Fewer processors may be used depending on the current system workload.
See Rickie Lee's blog on parallelism and CXPACKET wait type. It's quite interesting.
Generally, in an OLTP database, my opinion is that if a query is so costly it needs to be executed on several processors, the query needs to be re-written into something more efficient.
Why you get better results adding MAXDOP(1)? Hard to tell without the actual execution plans, but it might be so simple as that the execution plan is totally different that without the OPTION, for instance using a different index (or more likely) JOINing differently, using MERGE or HASH joins.
I'm not sure there is an event handle for this, so you would have to keep a copy of the DOM and compare to the existing DOM in some kind of polling loop - which could be quite nasty. Firebug does this though - if you inspect the HTML and run some DOM-changes, it highlights the changes in yellow in the Firebug console for a short time.
Alternatively, you could create a remove function...
var removeElements = function(selector) {
var elems = jQuery(selector);
// Your code to notify the removal of the element here...
alert(elems.length + " elements removed");
jQuery(selector).remove();
};
// Sample usage
removeElements("#some-element");
removeElements("p");
removeElements(".myclass");
sys_guid() is a poor option, as other answers have mentioned. One way to generate UUIDs and avoid sequential values is to generate random hex strings yourself:
select regexp_replace(
to_char(
DBMS_RANDOM.value(0, power(2, 128)-1),
'FM0xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'),
'([a-f0-9]{8})([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{12})',
'\1-\2-\3-\4-\5') from DUAL;
this code adds horizontal line to a linear layout
View view = new View(this);
LinearLayout.LayoutParams lpView = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1); // --> horizontal
view.setLayoutParams(lpView);
view.setBackgroundColor(Color.DKGRAY);
linearLayout.addView(view);
You can use setCustomValidity
function when oninvalid
event occurs.
Like below:-
<input class="form-control" type="email" required=""
placeholder="username" oninvalid="this.setCustomValidity('Please Enter valid email')">
</input>
To clear the message once you start entering use oninput="setCustomValidity('')
attribute to clear the message.
<input class="form-control" type="email" required="" placeholder="username"
oninvalid="this.setCustomValidity('Please Enter valid email')"
oninput="setCustomValidity('')"></input>
I would like to share a great tool being used in the WordPress community called Scatter
Git WordPress plugins and a bit of sanity scatter
This enables users to be able to send their Git repository to wordpress.org SVN automatically. In theory, this code can be applied to any SVN repository.
JQuery is looking for a json type result, but because the redirect is processed automatically, it will receive the generated html source of your login.htm
page.
One idea is to let the the browser know that it should redirect by adding a redirect
variable to to the resulting object and checking for it in JQuery:
$(document).ready(function(){
jQuery.ajax({
type: "GET",
url: "populateData.htm",
dataType:"json",
data:"userId=SampleUser",
success:function(response){
if (response.redirect) {
window.location.href = response.redirect;
}
else {
// Process the expected results...
}
},
error: function(xhr, textStatus, errorThrown) {
alert('Error! Status = ' + xhr.status);
}
});
});
You could also add a Header Variable to your response and let your browser decide where to redirect. In Java, instead of redirecting, do response.setHeader("REQUIRES_AUTH", "1")
and in JQuery you do on success(!):
//....
success:function(response){
if (response.getResponseHeader('REQUIRES_AUTH') === '1'){
window.location.href = 'login.htm';
}
else {
// Process the expected results...
}
}
//....
Hope that helps.
My answer is heavily inspired by this thread which shouldn't left any questions in case you still have some problems.
I believe the easiest solution for finding the Nth occurrence of a String is to use StringUtils.ordinalIndexOf() from Apache Commons.
Example:
StringUtils.ordinalIndexOf("aabaabaa", "b", 2) == 5
You can give variable names as project files. For instance in you plugin configuration give only one tag as below:-
<projectFile>${projectName}</projectFile>
Then on command line you can pass the project name as parameter:-
mvn [your-command] -DprojectName=[name of project]
See the documentation on plt.axis()
. This:
plt.axis('equal')
doesn't work because it changes the limits of the axis to make circles appear circular. What you want is:
plt.axis('square')
This creates a square plot with equal axes.
Here is how i did it.
I used the 'beforeunload' event to set a boolean. Then I set a timeout to watch if the 'beforeunload' fired.
var $window = $(window),
$trigger = $('.select_your_link'),
fallback = 'your_fallback_url';
hasHistory = false;
$window.on('beforeunload', function(){
hasHistory = true;
});
$trigger.on('click', function(){
window.history.go(-1);
setTimeout(function(){
if (!hasHistory){
window.location.href = fallback;
}
}, 200);
return false;
});
Seems to work in major browsers (tested FF, Chrome, IE11 so far).
Yes, Spring framework logging is very detailed, You did not mention in your post, if you are already using a logging framework or not. If you are using log4j then just add spring appenders to the log4j config (i.e to log4j.xml or log4j.properties), If you are using log4j xml config you can do some thing like this
<category name="org.springframework.beans">
<priority value="debug" />
</category>
or
<category name="org.springframework">
<priority value="debug" />
</category>
I would advise you to test this problem in isolation using JUnit test, You can do this by using spring testing module in conjunction with Junit. If you use spring test module it will do the bulk of the work for you it loads context file based on your context config and starts container so you can just focus on testing your business logic. I have a small example here
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:springContext.xml"})
@Transactional
public class SpringDAOTest
{
@Autowired
private SpringDAO dao;
@Autowired
private ApplicationContext appContext;
@Test
public void checkConfig()
{
AnySpringBean bean = appContext.getBean(AnySpringBean.class);
Assert.assertNotNull(bean);
}
}
I am not advising you to change the way you load logging but try this in your dev environment, Add this snippet to your web.xml file
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
UPDATE log4j config file
I tested this on my local tomcat and it generated a lot of logging on application start up. I also want to make a correction: use debug not info as @Rayan Stewart mentioned.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{HH:mm:ss} %p [%t]:%c{3}.%M()%L - %m%n" />
</layout>
</appender>
<appender name="springAppender" class="org.apache.log4j.RollingFileAppender">
<param name="file" value="C:/tomcatLogs/webApp/spring-details.log" />
<param name="append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{MM/dd/yyyy HH:mm:ss} [%t]:%c{5}.%M()%L %m%n" />
</layout>
</appender>
<category name="org.springframework">
<priority value="debug" />
</category>
<category name="org.springframework.beans">
<priority value="debug" />
</category>
<category name="org.springframework.security">
<priority value="debug" />
</category>
<category
name="org.springframework.beans.CachedIntrospectionResults">
<priority value="debug" />
</category>
<category name="org.springframework.jdbc.core">
<priority value="debug" />
</category>
<category name="org.springframework.transaction.support.TransactionSynchronizationManager">
<priority value="debug" />
</category>
<root>
<priority value="debug" />
<appender-ref ref="springAppender" />
<!-- <appender-ref ref="STDOUT"/> -->
</root>
</log4j:configuration>
If you are using Visual Studio Community 2015 and trying to Install GLUT you should place the header file glut.h
in
C:\Program Files (x86)\Windows Kits\8.1\Include\um\gl
Since the loop below only modifies elements already seen, it would be considered acceptable:
a = ['a',' b', 'c ', ' d ']
for i, s in enumerate(a):
a[i] = s.strip()
print(a) # -> ['a', 'b', 'c', 'd']
Which is different from:
a[:] = [s.strip() for s in a]
in that it doesn't require the creation of a temporary list and an assignment of it to replace the original, although it does require more indexing operations.
Caution: Although you can modify entries this way, you can't change the number of items in the list
without risking the chance of encountering problems.
Here's an example of what I mean—deleting an entry messes-up the indexing from that point on:
b = ['a', ' b', 'c ', ' d ']
for i, s in enumerate(b):
if s.strip() != b[i]: # leading or trailing whitespace?
del b[i]
print(b) # -> ['a', 'c '] # WRONG!
(The result is wrong because it didn't delete all the items it should have.)
Update
Since this is a fairly popular answer, here's how to effectively delete entries "in-place" (even though that's not exactly the question):
b = ['a',' b', 'c ', ' d ']
b[:] = [entry for entry in b if entry.strip() == entry]
print(b) # -> ['a'] # CORRECT
it depends on your php settings...
use phpinfo()
and take a look at the session chapter. There are values like session.gc_maxlifetime
and session.cache_expire
and session.cookie_lifetime
which affects the sessions lifetime
EDIT: it's like Martin write before
Another approach is to use the CommaDelimitedStringCollection class from System.Configuration namespace/assembly. It behaves like a list plus it has an overriden ToString method that returns a comma-separated string.
Pros - More flexible than an array.
Cons - You can't pass a string containing a comma.
CommaDelimitedStringCollection list = new CommaDelimitedStringCollection();
list.AddRange(new string[] { "Huey", "Dewey" });
list.Add("Louie");
//list.Add(",");
string s = list.ToString(); //Huey,Dewey,Louie
Perhaps something like this, assuming that there are many of these rows inside of the datatable and that each row is row
:
List<string[]> MyStringArrays = new List<string[]>();
foreach( var row in datatable.rows )//or similar
{
MyStringArrays.Add( new string[]{row.Name,row.Address,row.Age.ToString()} );
}
You could then access one:
MyStringArrays.ElementAt(0)[1]
If you use linqpad, here is a very simple scenario of your example:
class Datatable
{
public List<data> rows { get; set; }
public Datatable(){
rows = new List<data>();
}
}
class data
{
public string Name { get; set; }
public string Address { get; set; }
public int Age { get; set; }
}
void Main()
{
var datatable = new Datatable();
var r = new data();
r.Name = "Jim";
r.Address = "USA";
r.Age = 23;
datatable.rows.Add(r);
List<string[]> MyStringArrays = new List<string[]>();
foreach( var row in datatable.rows )//or similar
{
MyStringArrays.Add( new string[]{row.Name,row.Address,row.Age.ToString()} );
}
var s = MyStringArrays.ElementAt(0)[1];
Console.Write(s);//"USA"
}
db.collection.remove(<query>,
{
justOne: <boolean>,
writeConcern: <document>
})
img {max-width:100%;}
is one way of doing this. Just add it to your CSS code.
This can be done with a single statement and some XML magic:
select table_name,
to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from '||owner||'.'||table_name)),'/ROWSET/ROW/C')) as count
from all_tables
where owner = 'FOOBAR'
$(document).ready(function() {
$('#reset').click(function() {
$('#compose_form').find("input[type=text] , textarea ").each(function() {
$(this).val('');
});
});
});
Rule 1: You can not add a new table without specifying the primary key
constraint[not a good practice if you create it somehow].
So the code:
CREATE TABLE transactions(
id int NOT NULL AUTO_INCREMENT,
location varchar(50) NOT NULL,
description varchar(50) NOT NULL,
category varchar(50) NOT NULL,
amount double(10,9) NOT NULL,
type varchar(6) NOT NULL,
notes varchar(512),
receipt int(10),
PRIMARY KEY(id));
Rule 2: You are not allowed to use the keywords(words with predefined meaning) as a field name. Here type is something like that is used(commonly used with Join Types). So the code:
CREATE TABLE transactions(
id int NOT NULL AUTO_INCREMENT,
location varchar(50) NOT NULL,
description varchar(50) NOT NULL,
category varchar(50) NOT NULL,
amount double(10,9) NOT NULL,
transaction_type varchar(6) NOT NULL,
notes varchar(512),
receipt int(10),
PRIMARY KEY(id));
Now you please try with this code. First check it in your database user interface(I am running HeidiSQL, or you can try it in your xampp/wamp server also)and make sure this code works. Now delete the table from your db and execute the code in your program. Thank You.
A variation using just standard color code:
android:textColor="#ff0000"
It's the new build tool that Google wants to use for Android. It's being used due to it being more extensible, and useful than ant. It is meant to enhance developer experience.
You can view a talk by Xavier Ducrohet from the Android Developer Team on Google I/O here.
There is also another talk on Android Studio by Xavier and Tor Norbye, also during Google I/O here.
If maven is not creating Local Repository i.e .m2/repository folder then try below step.
In your Eclipse\Spring Tool Suite, Go to Window->preferences-> maven->user settings-> click on Restore Defaults-> Apply->Apply and close
You should be able to do this via the command line arguments, assuming these are Sun VMs installed using the usual Windows InstallShield mechanisms with the JVM finder EXE in system32.
Type java -help for the options. In particular, see:
-version:<value>
require the specified version to run
-jre-restrict-search | -jre-no-restrict-search
include/exclude user private JREs in the version search
Based on the statements:
SELECT DATEADD(MONTH, 1, @x) -- Add a month to the supplied date @x
and
SELECT DATEADD(DAY, 0 - DAY(@x), @x) -- Get last day of month previous to the supplied date @x
how about adding a month to date @x and then retrieving the last day of the month previous to that (i.e. The last day of the month of the supplied date)
DECLARE @x DATE = '20-Feb-2012'
SELECT DAY(DATEADD(DAY, 0 - DAY(DATEADD(MONTH, 1, @x)), DATEADD(MONTH, 1, @x)))
Note: This was test using SQL Server 2008 R2
Create a .bat
file and write two commands:
cd C:\ Path to your tomcat directory \ bin
startup.bat
Now on double-click, Tomcat server will start.
Or you can use:
ssh -oStrictHostKeyChecking=no host
This will be insecure (man in the middle attacks) but easiest solution.
The better way to do that is to generate correct mappings between host and ip address, so ssh
will not complain:
#!/bin/bash
for domain in "github.com" "bitbucket.org"; do
sed -i "/$domain/d" ~/.ssh/known_hosts
line=$(ssh-keyscan $domain,`nslookup $domain | awk '/^Address: / { print $2 ; exit }'`)
echo $line >> ~/.ssh/known_hosts
done
Excerpt from gist.
For posterity, this post mentions,
in the latest release of Visual Studio Code (May 2016) it is now possible to list the installed extension in the command line
code --list-extensions
On Mac, execute something like:
"/Applications/Visual Studio Code.app//Contents/Resources/app/bin/code" --list-extensions
To install, use:
--install-extension <ext> //see 'code --help'
Deleting .idea
and re-importing the SBT project solved this issue for me.
plot(t)
is in this case the same as
plot(t[[1]], t[[2]])
As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1
:
> length(t)
[1] 4
> length(1)
[1] 1
In your second example you plot a list with elements named x
and y
, both vectors of length 2,
so plot
plots these two vectors.
Edit:
If you want to plot lines use
plot(t, type="l")
if you define a/A as 0
char res;
if (i>25 || i<0){
res = null;
}
res = (i) + 65
}
return res;
65 for captitals; 97 for non captitals
It might be easiest to just handle all cases of the new line character instead of checking which case then applying it. For example, if you need to replace the newline then do the following:
htmlstring = stringContainingNewLines.replace(/(\r\n|\n|\r)/gm, "<br>");
To temporarily work around this problem, I found the following to be the quickest way:
export JAVA_TOOL_OPTIONS="-Xmx1024m -Xms1024m"
There is no need to install virtualenv. Just create a workfolder and open your editor in it. Assuming you are using vscode,
$mkdir Directory && cd Directory
$code .
It is the best way to avoid breaking Ubuntu/linux dependencies by messing around with environments. In case anything goes wrong, you can always delete that folder and begin afresh. Otherwise, messing up with the ubuntu/linux python environments could mess up system apps/OS (including the terminal). Then you can press shift+P and type python:select interpreter. Choose any version above 3. After that you can do
$pip3 -v
It will display the pip version. You can then use it for installations as
$pip3 install Library
A variable is declared if accessing the variable name will not produce a ReferenceError
. The expression typeof variableName !== 'undefined'
will be false
in only one of two cases:
var variableName
in scope), orundefined
(i.e., the variable's value is not defined)Otherwise, the comparison evaluates to true
.
If you really want to test if a variable is declared or not, you'll need to catch
any ReferenceError
produced by attempts to reference it:
var barIsDeclared = true;
try{ bar; }
catch(e) {
if(e.name == "ReferenceError") {
barIsDeclared = false;
}
}
If you merely want to test if a declared variable's value is neither undefined
nor null
, you can simply test for it:
if (variableName !== undefined && variableName !== null) { ... }
Or equivalently, with a non-strict equality check against null
:
if (variableName != null) { ... }
Both your second example and your right-hand expression in the &&
operation tests if the value is "falsey", i.e., if it coerces to false
in a boolean context. Such values include null
, false
, 0
, and the empty string, not all of which you may want to discard.
EDIT: The other two answers make a good point. I'm assuming that you want to order them into some other structure, or in order to print them out.
"Best" can mean a number of different things. Do you mean "easiest," "fastest," "most efficient," "least code," "most readable?"
The most obvious approach is to loop through twice. On the first pass, order the values:
if(current_value > examined_value)
{
current_value = examined_value
(and then swap them, however you like)
}
Then on the second pass, alphabetize the words, but only if their values match.
if(current_value == examined_value)
{
(alphabetize the two)
}
Strictly speaking, this is a "bubble sort" which is slow because every time you make a swap, you have to start over. One "pass" is finished when you get through the whole list without making any swaps.
There are other sorting algorithms, but the principle would be the same: order by value, then alphabetize.
One difference that's not at the language level but the popular implementation level: certain versions of gcc will remove unreferenced static inline
functions from output by default, but will keep plain static
functions even if unreferenced. I'm not sure which versions this applies to, but from a practical standpoint it means it may be a good idea to always use inline
for static
functions in headers.
I want to share the one I am using:
import time
# provide a waiting-time list:
lst = [1,2,7,4,5,6,4,3]
# set the timeout limit
timeLimit = 4
for i in lst:
timeCheck = time.time()
while True:
time.sleep(i)
if time.time() <= timeCheck + timeLimit:
print ([i,'looks ok'])
break
else:
print ([i,'too long'])
break
Then you will get:
[1, 'looks ok']
[2, 'looks ok']
[7, 'too long']
[4, 'looks ok']
[5, 'too long']
[6, 'too long']
[4, 'looks ok']
[3, 'looks ok']
You may also use the stringr
package
library(dplyr)
library(stringr)
My.Data %>% filter(str_detect(x, '^G45'))
You may not use '^'
(starts with) in this case, to obtain the results you need
SELECT getdate()
Result: 2012-12-14 16:03:33.360
SELECT convert(datetime,convert(bigint, getdate()))
Result 2012-12-15 00:00:00.000
Incase their is local uncommitted changes and avoid merge conflict while pulling.
git stash save
git pull
git stash pop
In case of Allow IP to mysql server linux machine. you can do following command--
nano /etc/httpd/conf.d/phpMyAdmin.conf and add Desired IP.
<Directory /usr/share/phpMyAdmin/>
AddDefaultCharset UTF-8
Order allow,deny
allow from all
<IfModule mod_authz_core.c>
# Apache 2.4
<RequireAny>
Require ip 192.168.9.1(Desired IP)
</RequireAny>
</IfModule>
<IfModule !mod_authz_core.c>
# Apache 2.2
Order Deny,Allow
#Allow from All
Allow from 192.168.9.1(Desired IP)
</IfModule>
And after Update, please restart using following command--
sudo systemctl restart httpd.service
Yes. But place your "test" after the comma if you want the column...
> A <- matrix(sample(1:12,12,T),ncol=4)
> rownames(A) <- letters[1:3]
> colnames(A) <- letters[11:14]
> A[,"l"]
a b c
6 10 1
see also help(Extract)
You can't run two SQL statements into one like you are doing.
You can't "execute" a select query.
db is an object and you haven't set it to anything: (e.g. set db = currentdb)
In VBA integer types can hold up to max of 32767 - I would be tempted to use Long.
You might want to be a bit more specific about the date you are inserting:
INSERT INTO Test (Start_Date) VALUES ('#" & format(InDate, "mm/dd/yyyy") & "#' );"
To fix that issue, I searched where is my docker and docker-compose installed. In my case, docker
was installed in /usr/bin/docker
and docker-compose
was installed in /usr/local/bin/docker-compose
path. Then, I write this in my terminal:
To docker:
sudo chmod +x /usr/bin/docker
To docker-compose
:
sudo chmod +x /usr/local/bin/docker-compose
Now I don't need write in my commands docker the word sudo
/***********************************************************************/
ERRATA:
The best solution of this issue was commented by @mkasberg. I quote comment:
That might work, you might run into issues down the road. Also, it's a security vulnerability. You'd be better off just adding yourself to the docker group, as the docs say. sudo groupadd docker, sudo usermod -aG docker $USER.
Docs:
https://docs.docker.com/install/linux/linux-postinstall/
Thanks a lot!
I created a new Cordova project, which created with latest android target android level 23. when i run it works. if i changed desire android target value from 23 to 22. and refresh the Gradle build from the Andoid Studio. now it's fail when i run it. i got the following build error.
project-android /CordovaLib/src/org/apache/cordova/CordovaInterfaceImpl.java Error:(217, 22) error: cannot find symbol method requestPermissions(String[],int)
I changed the target level in these files.
project.properties
AndroidManifest.xml
and inside CordovaLib folder.
project.properties
However, i also have another project which is using the android target level 22, whenever i run that project, it runs. Now my question is can we specify the desire android level at the time of creating the project?
If you want to have bare run
command in gdb
to execute your program with redirections and arguments, you can use set args
:
% gdb ./a.out
(gdb) set args arg1 arg2 <file
(gdb) run
I was unable to achieve the same behaviour with --args
parameter, gdb
fiercely escapes the redirections, i.e.
% gdb --args echo 1 2 "<file"
(gdb) show args
Argument list to give program being debugged when it is started is "1 2 \<file".
(gdb) run
...
1 2 <file
...
This one actually redirects the input of gdb itself, not what we really want here
% gdb --args echo 1 2 <file
zsh: no such file or directory: file
It will also generate error when you pass large string in ajax call parameter.
so for that alway use type post in ajax will resolve your issue 100% and no need to set the length in web.config.
// var UserId= array of 1000 userids
$.ajax({ global: false, url: SitePath + "/User/getAussizzMembersData", "data": { UserIds: UserId}, "type": "POST", "dataType": "JSON" }}
Newtang's observation about the security rules aside, how are you going to know that anyone who views your page will have the correct images at c:\localfile.jpg
? You can't. Even if you think you can, you can't. It presupposes a windows environment, for one thing.
Worked for me -
$scope.downloadFile = function () {
Resource.downloadFile().then(function (response) {
var blob = new Blob([response.data], { type: "application/pdf" });
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
},
function (error) {
debugger;
});
};
Which calls the following from my resource factory-
downloadFile: function () {
var downloadRequst = {
method: 'GET',
url: 'http://localhost/api/downloadFile?fileId=dfckn4niudsifdh.pdf',
headers: {
'Content-Type': "application/pdf",
'Accept': "application/pdf"
},
responseType: 'arraybuffer'
}
return $http(downloadRequst);
}
Make sure your API sets the header content type too -
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
It is never a good idea to break out of a for-loop. If you are using a for-loop it means that you know how many times you want to iterate. Use a while-loop with 2 conditions.
for example
var done = false
while (i <= length && !done) {
if (sum > 1000) {
done = true
}
}
You could also use the String-Editor of Android Studio, it automatically generates line brakes and stuff like that...
As apparantly no one mentioned it: you can also use the Numpy Docstring Standard. It is widely used in the scientific community.
The Napolean sphinx extension to parse Google-style docstrings (recommended in the answer of @Nathan) also supports Numpy-style docstring, and makes a short comparison of both.
And last a basic example to give an idea how it looks like:
def func(arg1, arg2):
"""Summary line.
Extended description of function.
Parameters
----------
arg1 : int
Description of arg1
arg2 : str
Description of arg2
Returns
-------
bool
Description of return value
See Also
--------
otherfunc : some related other function
Examples
--------
These are written in doctest format, and should illustrate how to
use the function.
>>> a=[1,2,3]
>>> print [x + 3 for x in a]
[4, 5, 6]
"""
return True
For me works using &autoplay=1&mute=1
I had the same problem which I solved the following way:
GET Method test
https://54wtstq8d2.execute-api.ap-southeast-2.amazonaws.com/dev/echo/hello
Authorization tab ->
• select type(AWS signature)
• Add AccessKey and SecretKey
Create a element to be appended to the document. Set its value to the string that we want to copy to the clipboard. Append said element to the current HTML document. Use HTMLInputElement.select() to select the contents of the element. Use Document.execCommand('copy') to copy the contents of the to the clipboard. Remove the element from the document
function copyToClipboard(containertext) {
var el = document.createElement('textarea');
el.value = containertext;
el.text = containertext;
el.setAttribute('id', 'copyText');
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
var coptTextArea = document.getElementById('copyText');
$('#copyText').text(containertext);
coptTextArea.select();
document.execCommand('copy');
document.body.removeChild(el);
/* Alert the copied text */
alert("Copied : "+containertext, 1000);
}
If to summ up what people say here, json_decode/encode seems faster than serialize/unserialize BUT If you do var_dump the type of the serialized object is changed. If for some reason you want to keep the type, go with serialize!
(try for example stdClass vs array)
serialize/unserialize:
Array cache:
array (size=2)
'a' => string '1' (length=1)
'b' => int 2
Object cache:
object(stdClass)[8]
public 'field1' => int 123
This cache:
object(Controller\Test)[8]
protected 'view' =>
json encode/decode
Array cache:
object(stdClass)[7]
public 'a' => string '1' (length=1)
public 'b' => int 2
Object cache:
object(stdClass)[8]
public 'field1' => int 123
This cache:
object(stdClass)[8]
As you can see the json_encode/decode converts all to stdClass, which is not that good, object info lost... So decide based on needs, especially if it is not only arrays...
You can use this code if you have a bunch of hosts in text file
$a = get-content "C:\Users\host.txt"(file path)
foreach ($i in $a )
{
$i + "`n" + "==========================";[System.Net.Dns]::GetHostAddresses($i)
}
I wrote utility functions to do this. Now that I know about gdata's drop.levels, it looks pretty similar. Here they are (from here):
present_levels <- function(x) intersect(levels(x), x)
trim_levels <- function(...) UseMethod("trim_levels")
trim_levels.factor <- function(x) factor(x, levels=present_levels(x))
trim_levels.data.frame <- function(x) {
for (n in names(x))
if (is.factor(x[,n]))
x[,n] = trim_levels(x[,n])
x
}
You can use the wmic command:
wmic path CIM_LogicalDevice where "Description like 'USB%'" get /value
Fun fact!
The 'modulus' operation is defined as:
a % n ==> a - (a/n) * n
So you could roll your own, although it will be FAR slower than the built in % operator:
public static int Mod(int a, int n)
{
return a - (int)((double)a / n) * n;
}
Edit: wow, misspoke rather badly here originally, thanks @joren for catching me
Now here I'm relying on the fact that division + cast-to-int in C# is equivalent to Math.Floor
(i.e., it drops the fraction), but a "true" implementation would instead be something like:
public static int Mod(int a, int n)
{
return a - (int)Math.Floor((double)a / n) * n;
}
In fact, you can see the differences between % and "true modulus" with the following:
var modTest =
from a in Enumerable.Range(-3, 6)
from b in Enumerable.Range(-3, 6)
where b != 0
let op = (a % b)
let mod = Mod(a,b)
let areSame = op == mod
select new
{
A = a,
B = b,
Operator = op,
Mod = mod,
Same = areSame
};
Console.WriteLine("A B A%B Mod(A,B) Equal?");
Console.WriteLine("-----------------------------------");
foreach (var result in modTest)
{
Console.WriteLine(
"{0,-3} | {1,-3} | {2,-5} | {3,-10} | {4,-6}",
result.A,
result.B,
result.Operator,
result.Mod,
result.Same);
}
Results:
A B A%B Mod(A,B) Equal?
-----------------------------------
-3 | -3 | 0 | 0 | True
-3 | -2 | -1 | -1 | True
-3 | -1 | 0 | 0 | True
-3 | 1 | 0 | 0 | True
-3 | 2 | -1 | 1 | False
-2 | -3 | -2 | -2 | True
-2 | -2 | 0 | 0 | True
-2 | -1 | 0 | 0 | True
-2 | 1 | 0 | 0 | True
-2 | 2 | 0 | 0 | True
-1 | -3 | -1 | -1 | True
-1 | -2 | -1 | -1 | True
-1 | -1 | 0 | 0 | True
-1 | 1 | 0 | 0 | True
-1 | 2 | -1 | 1 | False
0 | -3 | 0 | 0 | True
0 | -2 | 0 | 0 | True
0 | -1 | 0 | 0 | True
0 | 1 | 0 | 0 | True
0 | 2 | 0 | 0 | True
1 | -3 | 1 | -2 | False
1 | -2 | 1 | -1 | False
1 | -1 | 0 | 0 | True
1 | 1 | 0 | 0 | True
1 | 2 | 1 | 1 | True
2 | -3 | 2 | -1 | False
2 | -2 | 0 | 0 | True
2 | -1 | 0 | 0 | True
2 | 1 | 0 | 0 | True
2 | 2 | 0 | 0 | True
Take a look at this article which shows the registry keys you need to look for and provides a .NET library that will do this for you.
First, you should to determine if .NET 3.5 is installed by looking at HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Install, which is a DWORD value. If that value is present and set to 1, then that version of the Framework is installed.
Look at HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\SP, which is a DWORD value which indicates the Service Pack level (where 0 is no service pack).
To be correct about things, you really need to ensure that .NET Fx 2.0 and .NET Fx 3.0 are installed first and then check to see if .NET 3.5 is installed. If all three are true, then you can check for the service pack level.
When you send bytes from a buffer with a normal TCP socket, the send function returns the number of bytes of the buffer that were sent. If it is a non-blocking socket or a non-blocking send then the number of bytes sent may be less than the size of the buffer. If it is a blocking socket or blocking send, then the number returned will match the size of the buffer but the call may block. With WebSockets, the data that is passed to the send method is always either sent as a whole "message" or not at all. Also, browser WebSocket implementations do not block on the send call.
But there are more important differences on the receiving side of things. When the receiver does a recv
(or read
) on a TCP socket, there is no guarantee that the number of bytes returned corresponds to a single send (or write) on the sender side. It might be the same, it may be less (or zero) and it might even be more (in which case bytes from multiple send/writes are received). With WebSockets, the recipient of a message is event-driven (you generally register a message handler routine), and the data in the event is always the entire message that the other side sent.
Note that you can do message based communication using TCP sockets, but you need some extra layer/encapsulation that is adding framing/message boundary data to the messages so that the original messages can be re-assembled from the pieces. In fact, WebSockets is built on normal TCP sockets and uses frame headers that contains the size of each frame and indicate which frames are part of a message. The WebSocket API re-assembles the TCP chunks of data into frames which are assembled into messages before invoking the message event handler once per message.
Try this:
filed like "*AA*" and filed not like "*BB*"
I hope this explaination gives a more intuitive appeal to dependency than the answers previously given.
An analysis of dependency operates on the attribute level, i.e. one or more attribute is determined by another attribute, it comes before the concept of keys. 'The role of a key is based on the concept of determination. 'Determination is the state in which knowing the value of one attribute makes it possible to determine the value of another.' Database Systems 12ed
Functional dependency is when one or more attributes determine one or more attributes. For instance:
Social Security Number -> First Name, Last Name.
However, by definition of functional dependency:
(SSN, First Name) -> Last Name
This is also a valid functional dependency. The determinants (The attribute that which determines another attribution) are called super key.
Thus, as a subset of functional dependency, there is the concept of full functional dependency, where the bare minimal determinant is considered. We refer those bare minimal determinants collectively as one candidate key (weird linguistic quirk in my opinion, like the concept of vector).
However, sometimes one of the attributes in the candidate key is sufficient to determine another attribute(s), BUT not all, in a relation (a table with no rows). That, is when you have a partial functional dependency within a relation.
ExecuteScalar()
is what you need here
you can do it with pd.date_range() and Timestamp. Let's say you have read a csv file with a date column using parse_dates option:
df = pd.read_csv('my_file.csv', parse_dates=['my_date_col'])
Then you can define a date range index :
rge = pd.date_range(end='15/6/2020', periods=2)
and then filter your values by date thanks to a map:
df.loc[df['my_date_col'].map(lambda row: row.date() in rge)]
Just for clarity: GZip is not an MS-only algorithm as suggested by Guy Starbuck in his comment from August. The GZipStream in System.IO.Compression uses the Deflate algorithm, just the same as the zlib library, and many other zip tools. That class is fully interoperable with unix utilities like gzip.
The GZipStream class is not scriptable from the commandline or VBScript, to produce ZIP files, so it alone would not be an answer the original poster's request.
The free DotNetZip library does read and produce zip files, and can be scripted from VBScript or Powershell. It also includes command-line tools to produce and read/extract zip files.
Here's some code for VBScript:
dim filename
filename = "C:\temp\ZipFile-created-from-VBScript.zip"
WScript.echo("Instantiating a ZipFile object...")
dim zip
set zip = CreateObject("Ionic.Zip.ZipFile")
WScript.echo("using AES256 encryption...")
zip.Encryption = 3
WScript.echo("setting the password...")
zip.Password = "Very.Secret.Password!"
WScript.echo("adding a selection of files...")
zip.AddSelectedFiles("*.js")
zip.AddSelectedFiles("*.vbs")
WScript.echo("setting the save name...")
zip.Name = filename
WScript.echo("Saving...")
zip.Save()
WScript.echo("Disposing...")
zip.Dispose()
WScript.echo("Done.")
Here's some code for Powershell:
[System.Reflection.Assembly]::LoadFrom("c:\\dinoch\\bin\\Ionic.Zip.dll");
$directoryToZip = "c:\\temp";
$zipfile = new-object Ionic.Zip.ZipFile;
$e= $zipfile.AddEntry("Readme.txt", "This is a zipfile created from within powershell.")
$e= $zipfile.AddDirectory($directoryToZip, "home")
$zipfile.Save("ZipFiles.ps1.out.zip");
In a .bat or .cmd file, you can use the zipit.exe or unzip.exe tools. Eg:
zipit NewZip.zip -s "This is string content for an entry" Readme.txt src
If you are using Jekyll or octopress following will also work.
{% comment %}
These commments will not include inside the source.
{% endcomment %}
The Liquid tags {% comment %}
are parsed first and removed before the MarkDown processor even gets to it. Visitors will not see when they try to view source from their browser.
You should use .keydown()
because .keypress()
will ignore "Arrows", for catching the key type use e.which
Press the result screen to focus (bottom right on fiddle screen) and then press arrow keys to see it work.
Notes:
.keypress()
will never be fired with Shift, Esc, and Delete but .keydown()
will..keypress()
in some browser will be triggered by arrow keys but its not cross-browser so its more reliable to use .keydown()
.More useful information
.which
Or .keyCode
of the event object - Some browsers won't support one of them but when using jQuery its safe to use the both since jQuery standardizes things. (I prefer .which
never had a problem with).ctrl | alt | shift | META
press with the actual captured key you should check the following properties of the event object - They will be set to TRUE if they were pressed:
event.ctrlKey
- ctrl event.altKey
- altevent.shiftKey
- shiftevent.metaKey
- META ( Command ? OR Windows Key )Finally - here are some useful key codes ( For a full list - keycode-cheatsheet ):
Some reading to get you started on character encodings: Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
By the way - ASP.NET has nothing to do with it. Encodings are universal.
You haven't provided your javascript code, but the usual cause of this type of issue is not waiting till the page is loaded. Remember that most javascript is executed before the DOM is loaded, so code trying to manipulate it won't work.
To run code after the page has finished loading, use the $(document).ready callback:
$(document).ready(function(){
$('#some-id').trigger('click');
});
You have to manually filter result based on change of input each time by keeping listener over input
event. While doing manually filtering make sure you should maintain two copy of variable, one would be original collection copy & second would be filteredCollection
copy. The advantage for going this way could save your couple of unnecessary filtering on change detection cycle. You may see a more code, but this would be more performance friendly.
Markup - HTML Template
<md-input #myInput placeholder="Item name..." [(ngModel)]="name" (input)="filterItem(myInput.value)"></md-input>
<div *ngFor="let item of filteredItems">
{{item.name}}
</div>
Code
assignCopy(){
this.filteredItems = Object.assign([], this.items);
}
filterItem(value){
if(!value){
this.assignCopy();
} // when nothing has typed
this.filteredItems = Object.assign([], this.items).filter(
item => item.name.toLowerCase().indexOf(value.toLowerCase()) > -1
)
}
this.assignCopy();//when you fetch collection from server.
Close the modal with universal $().hide()
method:
$('#product-options').hide();
I think the following is the easiest way to do it.
<asp:TextBox ID="DateControl" runat="server" Visible="False"></asp:TextBox>
<asp:RangeValidator ID ="rvDate" runat ="server" ControlToValidate="DateControl" ErrorMessage="Invalid Date" Type="Date" MinimumValue="01/01/1900" MaximumValue="01/01/2100" Display="Dynamic"></asp:RangeValidator>
Use screen: Start screen
, start your script, press Ctrl+A, D. Reattach with screen -r
.
Make a script that takes your "1" as a parameter, run nohup yourscript
:
#!/bin/bash
(time bash executeScript $1 input fileOutput $> scrOutput) &> timeUse.txt
This SO thread will solve your problem. Solution in short:
$url = 'http://www.google.co.in/intl/en_com/images/srpr/logo1w.png';
$img = '/my/folder/my_image.gif';
file_put_contents($img, file_get_contents($url));
Java EE is a collection of specifications for developing and deploying enterprise applications.
In general, enterprise applications refer to software hosted on servers that provide the applications that support the enterprise.
The specifications (defined by Sun) describe services, application programming interfaces (APIs), and protocols.
The 13 core technologies that make up Java EE are:
The Java EE product provider is typically an application-server, web-server, or database-system vendor who provides classes that implement the interfaces defined in the specifications. These vendors compete on implementations of the Java EE specifications.
When a company requires Java EE experience what are they really asking for is experience using the technologies that make up Java EE. Frequently, a company will only be using a subset of the Java EE technologies.
Quick note: if you're also using coord_flip()
to flip the x and the y axis, you won't be able to set range limits using coord_cartesian()
because those two functions are exclusive (see here).
Fortunately, this is an easy fix; set your limits within coord_flip()
like so:
p + coord_flip(ylim = c(3,5), xlim = c(100, 400))
This just alters the visible range (i.e. doesn't remove data points).
What about jQuery Hotkeys?
jQuery Hotkeys lets you watch for keyboard events anywhere in your code supporting almost any key combination.
To bind Ctrl+c to a function (f
), for example:
$(document).bind('keydown', 'ctrl+c', f);
C# will allow you to have a string split over multiple lines, the term is called verbatim literal
:
string myString = @"this is a
test
to see how long my string
can be
and it can be quite long";
If you are looking for the alternative to & _
from VB, use the +
to join your lines.
Here is simple code:
func scanbarcode()
{
view.backgroundColor = UIColor.blackColor()
captureSession = AVCaptureSession()
let videoCaptureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
let videoInput: AVCaptureDeviceInput
do {
videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice)
} catch {
return
}
if (captureSession.canAddInput(videoInput)) {
captureSession.addInput(videoInput)
} else {
failed();
return;
}
let metadataOutput = AVCaptureMetadataOutput()
if (captureSession.canAddOutput(metadataOutput)) {
captureSession.addOutput(metadataOutput)
metadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
metadataOutput.metadataObjectTypes = [AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypePDF417Code]
} else {
failed()
return
}
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession);
previewLayer.frame = view.layer.bounds;
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
view.layer.addSublayer(previewLayer);
view.addSubview(closeBtn)
view.addSubview(backimg)
captureSession.startRunning();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func failed() {
let ac = UIAlertController(title: "Scanning not supported", message: "Your device does not support scanning a code from an item. Please use a device with a camera.", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
captureSession = nil
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if (captureSession?.running == false) {
captureSession.startRunning();
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
if (captureSession?.running == true) {
captureSession.stopRunning();
}
}
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
captureSession.stopRunning()
if let metadataObject = metadataObjects.first {
let readableObject = metadataObject as! AVMetadataMachineReadableCodeObject;
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
foundCode(readableObject.stringValue);
}
// dismissViewControllerAnimated(true, completion: nil)
}
func foundCode(code: String) {
var createAccountErrorAlert: UIAlertView = UIAlertView()
createAccountErrorAlert.delegate = self
createAccountErrorAlert.title = "Alert"
createAccountErrorAlert.message = code
createAccountErrorAlert.addButtonWithTitle("ok")
createAccountErrorAlert.addButtonWithTitle("Retry")
createAccountErrorAlert.show()
NSUserDefaults.standardUserDefaults().setObject(code, forKey: "barcode")
NSUserDefaults.standardUserDefaults().synchronize()
ItemBarcode = code
print(code)
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return .Portrait
}
<pre>
function sortObjectByVal(obj){
var keysSorted = Object.keys(obj).sort(function(a,b){return obj[b]-obj[a]});
var newObj = {};
for(var x of keysSorted){
newObj[x] = obj[x];
}
return newObj;
}
var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};
console.log(sortObjectByVal(list));
</pre>
You can use an echo with a pipe to avoid prompts or confirmation.
echo "This is the body" | mail -s "This is the subject" [email protected]
In addition to existing answers it is often desired to format the REST output (typically JSON and XML lacks indentation). Try this:
$ curl https://api.twitter.com/1/help/configuration.xml | xmllint --format -
$ curl https://api.twitter.com/1/help/configuration.json | python -mjson.tool
Tested on Ubuntu 11.0.4/11.10.
Another issue is the desired content type. Twitter uses .xml
/.json
extension, but more idiomatic REST would require Accept
header:
$ curl -H "Accept: application/json"
You can also use the Number
constructor/function (no need for a radix and usable for both integers and floats):
Number('09'); /=> 9
Number('09.0987'); /=> 9.0987
Alternatively like Andy E said in the comments you can use +
for conversion
+'09'; /=> 9
+'09.0987'; /=> 9.0987
Why can't you just sed 1d sh*.csv > merged.csv
?
Sometimes you don't even have to use python!
The reason for this is "hamcrest-core" jar is not in classpath as it doesn't comes directly with junit jar. So there are two ways to resolve this:
To address why CMD is designed to run only one service per container, let's just realize what would happen if the secondary servers run in the same container are not trivial / auxiliary but "major" (e.g. storage bundled with the frontend app). For starters, it would break down several important containerization features such as horizontal (auto-)scaling and rescheduling between nodes, both of which assume there is only one application (source of CPU load) per container. Then there is the issue of vulnerabilities - more servers exposed in a container means more frequent patching of CVEs...
So let's admit that it is a 'nudge' from Docker (and Kubernetes/Openshift) designers towards good practices and we should not reinvent workarounds (SSH is not necessary - we have docker exec / kubectl exec / oc rsh
designed to replace it).
This works well and an angular way to focus input control
angular.element('#elementId').focus()
This is although not a pure angular way of doing the task yet the syntax follows angular style. Jquery plays role indirectly and directly access DOM using Angular (jQLite => JQuery Light).
If required, this code can easily be put inside a simple angular directive where element is directly accessible.
I hope you find this helpful.
HTML :
<html>
<head>
<link rel = "stylesheet" href = "test.css">
<body>
</body>
<script src = "test.js"></script>
</head>
</html>
JAVASCRIPT :
var tableString = "<table>",
body = document.getElementsByTagName('body')[0],
div = document.createElement('div');
for (row = 1; row < 101; row += 1) {
tableString += "<tr>";
for (col = 1; col < 11; col += 1) {
tableString += "<td>" + "row [" + row + "]" + "col [" + col + "]" + "</td>";
}
tableString += "</tr>";
}
tableString += "</table>";
div.innerHTML = tableString;
body.appendChild(div);
In case you want to match multiple words to your magic word, you can pass the words to match as a tuple:
>>> magicWord = 'zzzTest'
>>> magicWord.startswith(('zzz', 'yyy', 'rrr'))
True
startswith
takes a string or a tuple of strings.
That number indicates Date and Time Styles
You need to look at CAST and CONVERT (Transact-SQL). Here you can find the meaning of all these Date and Time Styles.
Styles with century (e.g. 100, 101 etc) means year will come in yyyy
format. While styles without century (e.g. 1,7,10) means year will come in yy
format.
You can also refer to SQL Server Date Formats. Here you can find all date formats with examples.
The official Jenkins documentation only mentions single line commands like the following:
// Declarative //
and (see)
pipeline {
/* insert Declarative Pipeline here */
}
The syntax of the Jenkinsfile is based on Groovy so it is also possible to use groovy syntax for comments. Quote:
/* a standalone multiline comment
spanning two lines */
println "hello" /* a multiline comment starting
at the end of a statement */
println 1 /* one */ + 2 /* two */
or
/**
* such a nice comment
*/
The easiest way to compare dates in javascript is to first convert it to a Date object and then compare these date-objects.
Below you find an object with three functions:
dates.compare(a,b)
Returns a number:
dates.inRange (d,start,end)
Returns a boolean or NaN:
dates.convert
Used by the other functions to convert their input to a date object. The input can be
.
// Source: http://stackoverflow.com/questions/497790
var dates = {
convert:function(d) {
// Converts the date in d to a date-object. The input can be:
// a date object: returned without modification
// an array : Interpreted as [year,month,day]. NOTE: month is 0-11.
// a number : Interpreted as number of milliseconds
// since 1 Jan 1970 (a timestamp)
// a string : Any format supported by the javascript engine, like
// "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
// an object : Interpreted as an object with year, month and date
// attributes. **NOTE** month is 0-11.
return (
d.constructor === Date ? d :
d.constructor === Array ? new Date(d[0],d[1],d[2]) :
d.constructor === Number ? new Date(d) :
d.constructor === String ? new Date(d) :
typeof d === "object" ? new Date(d.year,d.month,d.date) :
NaN
);
},
compare:function(a,b) {
// Compare two dates (could be of any type supported by the convert
// function above) and returns:
// -1 : if a < b
// 0 : if a = b
// 1 : if a > b
// NaN : if a or b is an illegal date
// NOTE: The code inside isFinite does an assignment (=).
return (
isFinite(a=this.convert(a).valueOf()) &&
isFinite(b=this.convert(b).valueOf()) ?
(a>b)-(a<b) :
NaN
);
},
inRange:function(d,start,end) {
// Checks if date in d is between dates in start and end.
// Returns a boolean or NaN:
// true : if d is between start and end (inclusive)
// false : if d is before start or after end
// NaN : if one or more of the dates is illegal.
// NOTE: The code inside isFinite does an assignment (=).
return (
isFinite(d=this.convert(d).valueOf()) &&
isFinite(start=this.convert(start).valueOf()) &&
isFinite(end=this.convert(end).valueOf()) ?
start <= d && d <= end :
NaN
);
}
}
Try this function:
function formDataToObject(formData) {
return Array.from(formData.entries()).reduce((old, pair) => ({
...old,
[pair[0]]: pair[1],
}), {});
}
I was looking for an integer value in named column, so I did the below:
int index = dgv_myDataGridView.CurrentCell.RowIndex;
int id = Convert.ToInt32(dgv_myDataGridView["ID", index].Value)
The good thing about this is that the column can be in any position in the grid view and you will still get the value.
Cheers
I had the same problem. The problem is remote had something preventing this.
I first created a local repository. I added a LICENSE
and README.md
file to my local and committed.
Then I wanted a remote repository so I created one on GitHub. Here I made a mistake of checking "Initialize this repository with a README", which created a README.md in remote too.
So now when I ran
git push --set-upstream origin master
I got:
error: failed to push some refs to 'https://github.com/lokeshub/myTODs.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes
(e.g. hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
Now to overcome this I did
git pull origin master
Which resulted in the below error:
From https://github.com/lokeshub/myTODs
branch master -> FETCH_HEAD
fatal: refusing to merge unrelated histories**
I tried:
git pull origin master --allow-unrelated-histories
Result:
From https://github.com/lokeshub/myTODs
* branch master -> FETCH_HEAD
Auto-merging README.md
CONFLICT (add/add): Merge conflict in README.md
Automatic merge failed;
fix conflicts and then commit the result.
Solution:
I removed the remote repository and created a new (I think only removing file README
could have worked) and after that the below worked:
git remote rm origin
git remote add origin https://github.com/lokeshub/myTODOs.git
git push --set-upstream origin master
I consider Ashwin's answer to be the most correct, my old answer is below.
docker run -dti foo bash
You can then enter the container and run bash with
docker exec -ti ID_of_foo bash
No need to install sshd :)
You can't do this with a UNIQUE
constraint, but you can do this in a trigger.
CREATE TRIGGER [dbo].[OnInsertMyTableTrigger]
ON [dbo].[MyTable]
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Column1 INT;
DECLARE @Column2 INT; -- allow nulls on this column
SELECT @Column1=Column1, @Column2=Column2 FROM inserted;
-- Check if an existing record already exists, if not allow the insert.
IF NOT EXISTS(SELECT * FROM dbo.MyTable WHERE Column1=@Column1 AND Column2=@Column2 @Column2 IS NOT NULL)
BEGIN
INSERT INTO dbo.MyTable (Column1, Column2)
SELECT @Column2, @Column2;
END
ELSE
BEGIN
RAISERROR('The unique constraint applies on Column1 %d, AND Column2 %d, unless Column2 is NULL.', 16, 1, @Column1, @Column2);
ROLLBACK TRANSACTION;
END
END
Status 422 seems most appropiate based on the spec.
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
They state that malformed xml is an example of bad syntax (calling for a 400). A malformed query string seems analogous to this, so 400 doesn't seem appropriate for a well-formed query-string which is missing a param.
UPDATE @DavidV correctly points out that this spec is for WebDAV, not core HTTP. But some popular non-WebDAV APIs are using 422 anyway, for lack of a better status code (see this).
You can use echo and prefix "\033", simple:
Artisan::command('mycommand', function () {
echo "\033======== Start ========\n";
});
And change color text:
if (App::environment() === 'production') {
echo "\033[0;33m======== WARNING ========\033[0m\n";
}
If you plan on putting the files on a machine supporting only 8.3 naming convention, you should limit the extension to 3 characters.
Otherwise, better choose the more descriptive .html version.
In my case was that I changed a line in a script of my Xcode project and that line was badly written (I forgot to add ";" at the end of the line). So I added the ";" and clean and build project.
There is an implementation in my TypeScript utilities based on JavaScript GUID generators.
Here is the code:
class Guid {_x000D_
static newGuid() {_x000D_
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
var r = Math.random() * 16 | 0,_x000D_
v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
return v.toString(16);_x000D_
});_x000D_
}_x000D_
}_x000D_
_x000D_
// Example of a bunch of GUIDs_x000D_
for (var i = 0; i < 100; i++) {_x000D_
var id = Guid.newGuid();_x000D_
console.log(id);_x000D_
}
_x000D_
Please note the following:
C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.
JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).
Above answer is correct but there is still one thing that might create issues (At least it did create an issue for me)
I used the following and it doesn't work properly on older devices -
android:contentInsetStart="0dp"
android:contentInsetLeft="0dp"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
The trick is here just use the following -
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
and get rid of -
android:contentInsetStart="0dp"
android:contentInsetLeft="0dp"
And now it should work fine throughout all the devices.
Hope it helps.
If my understanding is correct then you want to match any line which has Clinton and Reagan, in any order, but not Bush. As suggested by Stuck, here is a version with lookahead assertions:
#!/usr/bin/perl
use strict;
use warnings;
my $regex = qr/
(?=.*clinton)
(?!.*bush)
.*reagan
/ix;
while (<DATA>) {
chomp;
next unless (/$regex/);
print $_, "\n";
}
__DATA__
shouldn't match - reagan came first, then clinton, finally bush
first match - first two: reagan and clinton
second match - first two reverse: clinton and reagan
shouldn't match - last two: clinton and bush
shouldn't match - reverse: bush and clinton
shouldn't match - and then came obama, along comes mary
shouldn't match - to clinton with perl
Results
first match - first two: reagan and clinton
second match - first two reverse: clinton and reagan
as desired it matches any line which has Reagan and Clinton in any order.
You may want to try reading how lookahead assertions work with examples at http://www252.pair.com/comdog/mastering_perl/Chapters/02.advanced_regular_expressions.html
they are very tasty :)
For 2005 up, you can use
SELECT
[name]
,create_date
,modify_date
FROM
sys.tables
I think for 2000, you need to have enabled auditing.
In your example, the variable a
is just a reference to an instance of a string object. When you say a = "ty"
, you are not actually changing the string object, but rather pointing the reference at an entirely different instance of the string class.
Also you can have the selected value using following code:
alert("Selected option value is: "+$('#SelectelementId').select2("val"));
if type(varA) == str or type(varB) == str:
print 'string involved'
from EDX - online course MITx: 6.00.1x Introduction to Computer Science and Programming Using Python
You are using aggregate
function which not getting the items to perform action , you must verify linq query is giving some result as below:
var maxOrderLevel =sdv.Any()? sdv.Max(s => s.nOrderLevel):0
SELECT * FROM service s WHERE s.service_id = ?;
IF @@rowcount = 0
begin
select 'no data'
end
Expanding on this answer written in Objective C, I wrote the following for those writing in Swift
The idea is to use sections within the table and set the number of rows in the section to 1 (collapsed) and 3(expanded) when the first row in that section is tapped
The table decides how many rows to draw based on an array of Boolean values
You'll need to create two rows in storyboard and give them the reuse identifiers 'CollapsingRow' and 'GroupHeading'
import UIKit
class CollapsingTVC:UITableViewController{
var sectionVisibilityArray:[Bool]!// Array index corresponds to section in table
override func viewDidLoad(){
super.viewDidLoad()
sectionVisibilityArray = [false,false,false]
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func numberOfSections(in tableView: UITableView) -> Int{
return sectionVisibilityArray.count
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
return 0
}
// numberOfRowsInSection - Get count of entries
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rowsToShow:Int = 0
if(sectionVisibilityArray[section]){
rowsToShow = 3 // Or however many rows should be displayed in that section
}else{
rowsToShow = 1
}
return rowsToShow
}// numberOfRowsInSection
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
if(indexPath.row == 0){
if(sectionVisibilityArray[indexPath.section]){
sectionVisibilityArray[indexPath.section] = false
}else{
sectionVisibilityArray[indexPath.section] = true
}
self.tableView.reloadSections([indexPath.section], with: .automatic)
}
}
// cellForRowAtIndexPath - Get table cell corresponding to this IndexPath
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:UITableViewCell
if(indexPath.row == 0){
cell = tableView.dequeueReusableCell(withIdentifier: "GroupHeading", for: indexPath as IndexPath)
}else{
cell = tableView.dequeueReusableCell(withIdentifier: "CollapsingRow", for: indexPath as IndexPath)
}
return cell
}// cellForRowAtIndexPath
}
RFID tag has more standards. I have developed the RFID tag on Mifare card (ISO 14443A,B) and ISO 15693. Both of them, you can read/write or modify the data in the block data of RFID tag.
Declare
public static int[] locations={1,2,3};
outside of the main method.
open is only for another module for example: cocoa pods, or unit test, we can inherit or override
The join feature supported by Mongodb 3.2 and later versions. You can use joins by using aggregate query.
You can do it using below example :
db.users.aggregate([
// Join with user_info table
{
$lookup:{
from: "userinfo", // other table name
localField: "userId", // name of users table field
foreignField: "userId", // name of userinfo table field
as: "user_info" // alias for userinfo table
}
},
{ $unwind:"$user_info" }, // $unwind used for getting data in object or for one record only
// Join with user_role table
{
$lookup:{
from: "userrole",
localField: "userId",
foreignField: "userId",
as: "user_role"
}
},
{ $unwind:"$user_role" },
// define some conditions here
{
$match:{
$and:[{"userName" : "admin"}]
}
},
// define which fields are you want to fetch
{
$project:{
_id : 1,
email : 1,
userName : 1,
userPhone : "$user_info.phone",
role : "$user_role.role",
}
}
]);
This will give result like this:
{
"_id" : ObjectId("5684f3c454b1fd6926c324fd"),
"email" : "[email protected]",
"userName" : "admin",
"userPhone" : "0000000000",
"role" : "admin"
}
Hope this will help you or someone else.
Thanks
based on accepted answer
$output = some_function();
echo $output;
if it results array then use json_encode it will result json array which is supportable by javascript
$output = some_function();
echo json_encode($output);
If someone wants to stop execution after you echo some result use exit method of php. It will work like return keyword
$output = some_function();
echo $output;
exit;
Note that the link you provided does is not an HTML page, but rather a JSON document. The formatting is done by the browser.
You have to decide if:
If you want 1., just tell your application to render a response body with the JSON, set the MIME type (application/json), etc. In this case, formatting is dealt by the browser (and/or browser plugins)
If 2., it's a matter of rendering a simple minimal HTML page with the JSON where you can highlight it in several ways:
If you give more details about your stack, it's easier to provide examples or resources.
EDIT: For client side JS highlighting you can try higlight.js, for instance.
This is how I do. I have added explanation to understand what the heck is going on.
Initialize Local Repository
first initialize Git with
git init
Add all Files for version control with
git add .
Create a commit with message of your choice
git commit -m 'AddingBaseCode'
Initialize Remote Repository
Link Remote repo with Local repo
Now use copied URL to link your local repo with remote GitHub repo. When you clone a repository with git clone, it automatically creates a remote connection called origin pointing back to the cloned repository. The command remote is used to manage set of tracked repositories.
git remote add origin https://github.com/hiteshsahu/Hassium-Word.git
Synchronize
Now we need to merge local code with remote code. This step is critical otherwise we won't be able to push code on GitHub. You must call 'git pull' before pushing your code.
git pull origin master --allow-unrelated-histories
Commit your code
Finally push all changes on GitHub
git push -u origin master
I was looking into this and loved the approach from peege using a for loop! (because I'm learning VBA at the moment)
However, if we are trying to match "any" value of another column, how about using nested loops like the following?
Sub MatchAndColor()
Dim lastRow As Long
Dim sheetName As String
sheetName = "Sheet1" 'Insert your sheet name here
lastRow = Sheets(sheetName).Range("A" & Rows.Count).End(xlUp).Row
For lRowA = 1 To lastRow 'Loop through all rows
For lRowB = 1 To lastRow
If Sheets(sheetName).Cells(lRowA, "A") = Sheets(sheetName).Cells(lRowB, "B") Then
Sheets(sheetName).Cells(lRowA, "A").Interior.ColorIndex = 3 'Set Color to RED
End If
Next lRowB
Next lRowA
End Sub
For the ones who are getting the error while requesting JSON data:
If your are requesting JSON data, the JSON might be too large and that what cause the error to happen.
My solution is to copy the request link to new tab (get
request from browser)
copy the data to JSON viewer online where you have auto parsing and work on it there.
for (i=1;i<=5;i++){
idname = "Usert" + i;
document.getElementById(idname).style.width = "100%";
}
I used this way to showed the drop down list when the width is not showed correctly.
It work for IE6, Firefox and Chrome.
public changeAttr(int id)
{
list.Find(p => p.IdItem == id).FieldToModify = newValueForTheFIeld;
}
With:
IdItem is the id of the element you want to modify
FieldToModify is the Field of the item that you want to update.
NewValueForTheField is exactly that, the new value.
(It works perfect for me, tested and implemented)