you'd use another join, something along these lines:
SELECT toD.dom_url AS ToURL,
fromD.dom_url AS FromUrl,
rvw.*
FROM reviews AS rvw
LEFT JOIN domain AS toD
ON toD.Dom_ID = rvw.rev_dom_for
LEFT JOIN domain AS fromD
ON fromD.Dom_ID = rvw.rev_dom_from
EDIT:
All you're doing is joining in the table multiple times. Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM).
At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM.
Then in the SELECT list, you will select the DOM_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl.
For more info about aliasing in SQL, read here.
One issue that I've come across is that to have a scrollbar a n element needs a height to be specified (and not as a %).
The trick is to nest another set of divs within each column, and set the column parent's display to flex with flex-direction: column.
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
body {
overflow-y: hidden;
overflow-x: hidden;
color: white;
}
.base-container {
display: flex;
flex: 1;
flex-direction: column;
width: 100%;
height: 100%;
overflow-y: hidden;
align-items: stretch;
}
.title {
flex: 0 0 50px;
color: black;
}
.container {
flex: 1 1 auto;
display: flex;
flex-direction: column;
}
.container .header {
flex: 0 0 50px;
background-color: red;
}
.container .body {
flex: 1 1 auto;
display: flex;
flex-direction: row;
}
.container .body .left {
display: flex;
flex-direction: column;
flex: 0 0 80px;
background-color: blue;
}
.container .body .left .content,
.container .body .main .content,
.container .body .right .content {
flex: 1 1 auto;
overflow-y: auto;
height: 100px;
}
.container .body .main .content.noscrollbar {
overflow-y: hidden;
}
.container .body .main {
display: flex;
flex-direction: column;
flex: 1 1 auto;
background-color: green;
}
.container .body .right {
display: flex;
flex-direction: column;
flex: 0 0 300px;
background-color: yellow;
color: black;
}
.test {
margin: 5px 5px;
border: 1px solid white;
height: calc(100% - 10px);
}
</style>
And here's the html:
<div class="base-container">
<div class="title">
Title
</div>
<div class="container">
<div class="header">
Header
</div>
<div class="body">
<div class="left">
<div class="content">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>12</li>
<li>13</li>
<li>14</li>
<li>15</li>
<li>16</li>
<li>17</li>
<li>18</li>
<li>19</li>
<li>20</li>
<li>21</li>
<li>22</li>
<li>23</li>
<li>24</li>
</ul>
</div>
</div>
<div class="main">
<div class="content noscrollbar">
<div class="test">Test</div>
</div>
</div>
<div class="right">
<div class="content">
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>Right</div>
<div>End</div>
</div>
</div>
</div>
</div>
</div>
This is part of C, so it's not Objective-C specific. Here's a translation into an if
statement:
if (inPseudoEditMode)
label.frame = kLabelIndentedRec;
else
label.frame = kLabelRect;
My application is using Mura CMS and I faced this issue. However the solution was the password mismatch between my mysql local server and the password in the config files. As soon as I synched them it worked.
In rxjs
v6, of
operator should be imported as import { of } from 'rxjs';
Verified: it works well in Docker 1.7.0.
Don't specify --pull=true
when running the docker build
command
From this thread on reference locally-built image using FROM at dockerfile:
If you want use the local image as the base image, pass without the option
--pull=true
--pull=true
will always attempt to pull a newer version of the image.
I found the error when using a combination of the Ajax Control Toolkit ToolkitScriptManager and URL Write 2.0.
In my <rewrite> <outboundRules>
I had a precondition:
<preConditions>
<preCondition name="IsHTML">
<add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html"/>
</preCondition>
</preConditions>
But apparently some of my outbound rules weren't set to use the precondition.
Once I had that preCondition set on all my outbound rules:
<rule preCondition="IsHTML" name="MyOutboundRule">
No more problem.
you could use
line-height:35px;
You really shouldnt set a height on paragraph as its not good for accessibility (what happens if the user increase text size etc)
Instead use a Div with a hight and the p inside it with the correct line-height:
<div style="height:35px;"><p style="line-height:35px;">text</p></div>
There are three ways to save objects from your R session:
The save.image()
function will save all objects currently in your R session:
save.image(file="1.RData")
These objects can then be loaded back into a new R session using the load()
function:
load(file="1.RData")
If you want to save some, but not all objects, you can use the save()
function:
save(city, country, file="1.RData")
Again, these can be reloaded into another R session using the load()
function:
load(file="1.RData")
If you want to save a single object you can use the saveRDS()
function:
saveRDS(city, file="city.rds")
saveRDS(country, file="country.rds")
You can load these into your R session using the readRDS()
function, but you will need to assign the result into a the desired variable:
city <- readRDS("city.rds")
country <- readRDS("country.rds")
But this also means you can give these objects new variable names if needed (i.e. if those variables already exist in your new R session but contain different objects):
city_list <- readRDS("city.rds")
country_vector <- readRDS("country.rds")
I may sound quite naive, and may attract quite a criticism, but here's how I did it,
(It doesn't involve ajax
for export, but it doesn't do a full postback either )
Thanks for this post and this answer.
Create a simple controller
public class HomeController : Controller
{
/* A demo action
public ActionResult Index()
{
return View(model);
}
*/
[HttpPost]
public FileResult ExportData()
{
/* An example filter
var filter = TempData["filterKeys"] as MyFilter;
TempData.Keep(); */
var someList = db.GetDataFromDb(/*filter*/) // filter as an example
/*May be here's the trick, I'm setting my filter in TempData["filterKeys"]
in an action,(GetFilteredPartial() illustrated below) when 'searching' for the data,
so do not really need ajax here..to pass my filters.. */
//Some utility to convert list to Datatable
var dt = Utility.ConvertToDataTable(someList);
// I am using EPPlus nuget package
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");
ws.Cells["A1"].LoadFromDataTable(dt, true);
using (var memoryStream = new MemoryStream())
{
pck.SaveAs(memoryStream);
return File(memoryStream.ToArray(),
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"ExportFileName.xlsx");
}
}
}
//This is just a supporting example to illustrate setting up filters ..
/* [HttpPost]
public PartialViewResult GetFilteredPartial(MyFilter filter)
{
TempData["filterKeys"] = filter;
var filteredData = db.GetConcernedData(filter);
var model = new MainViewModel();
model.PartialViewModel = filteredData;
return PartialView("_SomePartialView", model);
} */
}
And here are the Views..
/*Commenting out the View code, in order to focus on the imp. code
@model Models.MainViewModel
@{Layout...}
Some code for, say, a partial View
<div id="tblSampleBody">
@Html.Partial("_SomePartialView", Model.PartialViewModel)
</div>
*/
//The actual part.. Just **posting** this bit of data from the complete View...
//Here, you are not posting the full Form..or the complete View
@using (Html.BeginForm("ExportData", "Home", FormMethod.Post))
{
<input type="submit" value="Export Data" />
}
//...
//</div>
/*And you may require to pass search/filter values.. as said in the accepted answer..
That can be done while 'searching' the data.. and not while
we need an export..for instance:-
<script>
var filterData = {
SkipCount: someValue,
TakeCount: 20,
UserName: $("#UserName").val(),
DepartmentId: $("#DepartmentId").val(),
}
function GetFilteredData() {
$("#loader").show();
filterData.SkipCount = 0;
$.ajax({
url: '@Url.Action("GetFilteredPartial","Home")',
type: 'POST',
dataType: "html",
data: filterData,
success: function (dataHTML) {
if ((dataHTML === null) || (dataHTML == "")) {
$("#tblSampleBody").html('<tr><td>No Data Returned</td></tr>');
$("#loader").hide();
} else {
$("#tblSampleBody").html(dataHTML);
$("#loader").hide();
}
}
});
}
</script>*/
The whole point of the trick seems that, we are posting a form (a part of the Razor View ) upon which we are calling an Action method
, which returns: a FileResult
, and this FileResult
returns the Excel File
..
And for posting the filter values, as said, ( and if you require to), I am making a post request to another action, as has been attempted to describe..
This one did it for me:
var input = $("<input>")
.attr("type", "hidden")
.attr("name", "mydata").val("bla");
$('#form1').append(input);
is based on the Daff's answer, but added the NAME attribute to let it show in the form collection and changed VALUE to VAL Also checked the ID of the FORM (form1 in my case)
used the Firefox firebug to check whether the element was inserted.
Hidden elements do get posted back in the form collection, only read-only fields are discarded.
Michel
Sub Addrisk()
Dim rActive As Range
Dim Count_Id_Column as long
Set rActive = ActiveCell
Application.ScreenUpdating = False
with thisworkbook.sheets(1) 'change to "sheetname" or sheetindex
for i = 1 to .range("A1045783").end(xlup).row
if 'something' = 'something' then
.range("A" & i).EntireRow.Copy 'add thisworkbook.sheets(index_of_sheet) if you copy from another sheet
.range("A" & i).entirerow.insert shift:= xldown 'insert and shift down, can also use xlup
.range("A" & i + 1).EntireRow.paste 'paste is all, all other defs are less.
'change I to move on to next row (will get + 1 end of iteration)
i = i + 1
end if
On Error Resume Next
.SpecialCells(xlCellTypeConstants).ClearContents
On Error GoTo 0
End With
next i
End With
Application.CutCopyMode = False
Application.ScreenUpdating = True 're-enable screen updates
End Sub
If your UIBarButtonItem is already allocated like in a storyboard. (printBtn)
let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
btn.setImage(UIImage(named: Constants.ImageName.print)?.withRenderingMode(.alwaysTemplate), for: .normal)
btn.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handlePrintPress(tapGesture:))))
printBtn.customView = btn
Try this
<select class="form-control" name="country_code" value="{{ old('country_code') }}">
@foreach (\App\SystemCountry::orderBy('country')->get() as $country)
<option value="{{ $country->country_code }}"
@if ($country->country_code == "LKA")
{{'selected="selected"'}}
@endif
>
{{ $country->country }}
</option>
@endforeach
</select>
Objective C for iOS 13+, courtesy of Wasif Saood's answer
Copy and paste below code into AppDelegate.m to print the device APN token.
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSUInteger dataLength = deviceToken.length;
if (dataLength == 0) {
return;
}
const unsigned char *dataBuffer = (const unsigned char *)deviceToken.bytes;
NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
for (int i = 0; i < dataLength; ++i) {
[hexString appendFormat:@"%02x", dataBuffer[i]];
}
NSLog(@"APN token:%@", hexString);
}
Here are custom icons with the updated "visual refresh" style that you can generate quickly via a simple .vbs script. I also included a large pre-generated set that you can use immediately with multiple color options: https://github.com/Concept211/Google-Maps-Markers
Use the following format when linking to the GitHub-hosted image files:
https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_[color][character].png
color
red, black, blue, green, grey, orange, purple, white, yellow
character
A-Z, 1-100, !, @, $, +, -, =, (%23 = #), (%25 = %), (%26 = &), (blank = •)
Examples:
https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_red1.png
https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_blue2.png
https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_green3.png
This question is the first one that shows up on Google when one looks up "Python how to add elements to set", so it's worth noting explicitly that, if you want to add a whole string to a set, it should be added with .add()
, not .update()
.
Say you have a string foo_str
whose contents are 'this is a sentence'
, and you have some set bar_set
equal to set()
.
If you do
bar_set.update(foo_str)
, the contents of your set will be {'t', 'a', ' ', 'e', 's', 'n', 'h', 'c', 'i'}
.
If you do bar_set.add(foo_str)
, the contents of your set will be {'this is a sentence'}
.
In main.xml
(or wherever your item is defined) make sure that the ID for the R
item is defined with @+id/...
Here is an example with a button:
<Button android:text="B1" android:id="@+id/button_one"
android:layout_gravity="center_horizontal|center"
android:layout_height="fill_parent" android:layout_width="wrap_content" />
Each of these is important because:
@
must precede the string+
indicates it will create if not existing (whatever your item is)you can use following command to create directory and give permissions at the same time
mkdir -m777 path/foldername
The easiest way to use PhantomJS in python is via Selenium. The simplest installation method is
npm -g install phantomjs-prebuilt
After installation, you may use phantom as simple as:
from selenium import webdriver
driver = webdriver.PhantomJS() # or add to your PATH
driver.set_window_size(1024, 768) # optional
driver.get('https://google.com/')
driver.save_screenshot('screen.png') # save a screenshot to disk
sbtn = driver.find_element_by_css_selector('button.gbqfba')
sbtn.click()
If your system path environment variable isn't set correctly, you'll need to specify the exact path as an argument to webdriver.PhantomJS()
. Replace this:
driver = webdriver.PhantomJS() # or add to your PATH
... with the following:
driver = webdriver.PhantomJS(executable_path='/usr/local/lib/node_modules/phantomjs/lib/phantom/bin/phantomjs')
References:
just delete this part Class.forName("com.mysql.jdbc.Driver")
from your code
because the machine is throwing a warning that
The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary."
meaning that no need to include it beacuse the driver is automatically registered for you by default.
Its a good idea to call the solutions above to update layer on the
viewDidLayoutSubviews
to get the views updated correctly
Try below code :
Assign the path of the folder to variable FolderPath
before running the below code.
Sub sample()
Dim FolderPath As String, path As String, count As Integer
FolderPath = "C:\Documents and Settings\Santosh\Desktop"
path = FolderPath & "\*.xls"
Filename = Dir(path)
Do While Filename <> ""
count = count + 1
Filename = Dir()
Loop
Range("Q8").Value = count
'MsgBox count & " : files found in folder"
End Sub
Sure.
Use Generate Getters and Setters from the Source menu or the context menu on a selected field or type, or a text selection in a type to open the dialog. The Generate Getters and Setters dialog shows getters and setters for all fields of the selected type. The methods are grouped by the type's fields.
Take a look at the help documentation for more information.
float b = (float)Math.ceil(a);
or
float b = (float)Math.round(a);
Depending on whether you meant "round to the nearest whole number" (round) or "round up" (ceil).
Beware of loss of precision in converting a double to a float, but that shouldn't be an issue here.
This error occurred in my application with the CIP-protocol whenever I didn't Send or received data in less than 10s.
This was caused by the use of the forward open method. You can avoid this by working with an other method, or to install an update rate of less the 10s that maintain your forward-open-connection.
When you write .class
after a class name, it references the class literal -
java.lang.Class
object that represents information about given class.
For example, if your class is Print
, then Print.class
is an object that represents the class Print
on runtime. It is the same object that is returned by the getClass()
method of any (direct) instance of Print
.
Print myPrint = new Print();
System.out.println(Print.class.getName());
System.out.println(myPrint.getClass().getName());
There is no built-in method that allows what you intend to do.
You have to add a method to your repository, like this:
public function getWhatYouWant()
{
$qb = $this->createQueryBuilder('u');
$qb->where('u.id != :identifier')
->setParameter('identifier', 1);
return $qb->getQuery()
->getResult();
}
Hope this helps.
You can create your own AuthorizationHandler that will find custom attributes on your Controllers and Actions, and pass them to the HandleRequirementAsync method.
public abstract class AttributeAuthorizationHandler<TRequirement, TAttribute> : AuthorizationHandler<TRequirement> where TRequirement : IAuthorizationRequirement where TAttribute : Attribute
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement)
{
var attributes = new List<TAttribute>();
var action = (context.Resource as AuthorizationFilterContext)?.ActionDescriptor as ControllerActionDescriptor;
if (action != null)
{
attributes.AddRange(GetAttributes(action.ControllerTypeInfo.UnderlyingSystemType));
attributes.AddRange(GetAttributes(action.MethodInfo));
}
return HandleRequirementAsync(context, requirement, attributes);
}
protected abstract Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement, IEnumerable<TAttribute> attributes);
private static IEnumerable<TAttribute> GetAttributes(MemberInfo memberInfo)
{
return memberInfo.GetCustomAttributes(typeof(TAttribute), false).Cast<TAttribute>();
}
}
Then you can use it for any custom attributes you need on your controllers or actions. For example to add permission requirements. Just create your custom attribute.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class PermissionAttribute : AuthorizeAttribute
{
public string Name { get; }
public PermissionAttribute(string name) : base("Permission")
{
Name = name;
}
}
Then create a Requirement to add to your Policy
public class PermissionAuthorizationRequirement : IAuthorizationRequirement
{
//Add any custom requirement properties if you have them
}
Then create the AuthorizationHandler for your custom attribute, inheriting the AttributeAuthorizationHandler that we created earlier. It will be passed an IEnumerable for all your custom attributes in the HandleRequirementsAsync method, accumulated from your Controller and Action.
public class PermissionAuthorizationHandler : AttributeAuthorizationHandler<PermissionAuthorizationRequirement, PermissionAttribute>
{
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionAuthorizationRequirement requirement, IEnumerable<PermissionAttribute> attributes)
{
foreach (var permissionAttribute in attributes)
{
if (!await AuthorizeAsync(context.User, permissionAttribute.Name))
{
return;
}
}
context.Succeed(requirement);
}
private Task<bool> AuthorizeAsync(ClaimsPrincipal user, string permission)
{
//Implement your custom user permission logic here
}
}
And finally, in your Startup.cs ConfigureServices method, add your custom AuthorizationHandler to the services, and add your Policy.
services.AddSingleton<IAuthorizationHandler, PermissionAuthorizationHandler>();
services.AddAuthorization(options =>
{
options.AddPolicy("Permission", policyBuilder =>
{
policyBuilder.Requirements.Add(new PermissionAuthorizationRequirement());
});
});
Now you can simply decorate your Controllers and Actions with your custom attribute.
[Permission("AccessCustomers")]
public class CustomersController
{
[Permission("AddCustomer")]
IActionResult AddCustomer([FromBody] Customer customer)
{
//Add customer
}
}
1 - Your malloc() is wrong.
2 - You are overstepping the bounds of the allocated memory
3 - You should initialize your allocated memory
Here is the program with all the changes needed. I compiled and ran... no errors or warnings.
#include <stdio.h>
#include <stdlib.h> //malloc
#include <math.h> //sine
#include <string.h>
#define TIME 255
#define HARM 32
int main (void) {
double sineRads;
double sine;
int tcount = 0;
int hcount = 0;
/* allocate some heap memory for the large array of waveform data */
double *ptr = malloc(sizeof(double) * TIME);
//memset( ptr, 0x00, sizeof(double) * TIME); may not always set double to 0
for( tcount = 0; tcount < TIME; tcount++ )
{
ptr[tcount] = 0;
}
tcount = 0;
if (NULL == ptr) {
printf("ERROR: couldn't allocate waveform memory!\n");
} else {
/*evaluate and add harmonic amplitudes for each time step */
for(tcount = 0; tcount < TIME; tcount++){
for(hcount = 0; hcount <= HARM; hcount++){
sineRads = ((double)tcount / (double)TIME) * (2*M_PI); //angular frequency
sineRads *= (hcount + 1); //scale frequency by harmonic number
sine = sin(sineRads);
ptr[tcount] += sine; //add to other results for this time step
}
}
free(ptr);
ptr = NULL;
}
return 0;
}
I'm using this for string values:
<%#(String.IsNullOrEmpty(Eval("Data").ToString()) ? "0" : Eval("Data"))%>
You can also use following for nullable values:
<%#(Eval("Data") == null ? "0" : Eval("Data"))%>
Also if you're using .net 4.5 and above I suggest you use strongly typed data binding:
<asp:Repeater runat="server" DataSourceID="odsUsers" ItemType="Entity.User">
<ItemTemplate>
<%# Item.Title %>
</ItemTemplate>
</asp:Repeater>
And don't forget to create a __init__.py
with each folder/subfolder (even if they are empty)
quote
and hashtag
parameters work as of Dec 2018.Does anyone know if there have been recent changes which could have suddenly stopped this from working?
The parameters have changed. The currently accepted answer states:
Facebook no longer supports custom parameters in
sharer.php
But this is not entirely correct. Well, maybe they do not support or endorse them, but custom parameters can be used if you know the correct names. These include:
u
picture
title
quote
description
caption
For instance, you can share this very question with the following URL:
https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fstackoverflow.com%2Fq%2F20956229%2F1101509&picture=http%3A%2F%2Fwww.applezein.net%2Fwordpress%2Fwp-content%2Fuploads%2F2015%2F03%2Ffacebook-logo.jpg&title=A+nice+question+about+Facebook"e=Does+anyone+know+if+there+have+been+recent+changes+which+could+have+suddenly+stopped+this+from+working%3F&description=Apparently%2C+the+accepted+answer+is+not+correct.
I've built a tool which makes it easier to share URLs on Facebook with custom parameters. You can use it to generate your sharer.php
link, just press the button and copy the URL from the tab that opens.
Use the "indirect" function on conditional formatting.
=INDIRECT("g"&ROW())="X"
=$A$1:$Z$1500
(or however wide/long you want the conditional formatting to extend depending on your worksheet)For every row in the G column that has an X, it will now turn to the format you specified. If there isn't an X in the column, the row won't be formatted.
You can repeat this to do multiple row formatting depending on a column value. Just change either the g
column or x
specific text in the formula and set different formats.
For example, if you add a new rule with the formula, =INDIRECT("h"&ROW())="CAR"
, then it will format every row that has CAR
in the H Column as the format you specified.
A couple of notes first: when you use Data/data1.txt
as an argument, should it really be /Data/data1.txt
(with a leading slash)? Also, should the outer loop scan only for .txt files, or all files in /Data? Here's an answer, assuming /Data/data1.txt
and .txt files only:
#!/bin/bash
for filename in /Data/*.txt; do
for ((i=0; i<=3; i++)); do
./MyProgram.exe "$filename" "Logs/$(basename "$filename" .txt)_Log$i.txt"
done
done
Notes:
/Data/*.txt
expands to the paths of the text files in /Data (including the /Data/ part)$( ... )
runs a shell command and inserts its output at that point in the command linebasename somepath .txt
outputs the base part of somepath, with .txt removed from the end (e.g. /Data/file.txt
-> file
)If you needed to run MyProgram with Data/file.txt
instead of /Data/file.txt
, use "${filename#/}"
to remove the leading slash. On the other hand, if it's really Data
not /Data
you want to scan, just use for filename in Data/*.txt
.
CSS Cursor:Pointer;
is a great solution. FastClick https://github.com/ftlabs/fastclick is another solution which doesn't require you to change css if you didn't want Cursor:Pointer;
on an element for some reason. I use fastclick now anyway to eliminate the 300ms delay on iOS devices.
<script type="text/javascript" src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script> <script type="text/javascript"> $(document).ready(function() { function myDate(){ var now = new Date(); var outHour = now.getHours(); if (outHour >12){newHour = outHour-12;outHour = newHour;} if(outHour<10){document.getElementById('HourDiv').innerHTML="0"+outHour;} else{document.getElementById('HourDiv').innerHTML=outHour;} var outMin = now.getMinutes(); if(outMin<10){document.getElementById('MinutDiv').innerHTML="0"+outMin;} else{document.getElementById('MinutDiv').innerHTML=outMin;} var outSec = now.getSeconds(); if(outSec<10){document.getElementById('SecDiv').innerHTML="0"+outSec;} else{document.getElementById('SecDiv').innerHTML=outSec;}} myDate(); setInterval(function(){ myDate();}, 1000); }); </script> <style> body {font-family:"Comic Sans MS", cursive;} h1 {text-align:center;background: gray;color:#fff;padding:5px;padding-bottom:10px;} #Content {margin:0 auto;border:solid 1px gray;width:140px;display:table;background:gray;} #HourDiv, #MinutDiv, #SecDiv {float:left;color:#fff;width:40px;text-align:center;font-size:25px;} span {float:left;color:#fff;font-size:25px;} </style> <div id="clockDiv"></div> <h1>My jQery Clock</h1> <div id="Content"> <div id="HourDiv"></div><span>:</span><div id="MinutDiv"></div><span>:</span><div id="SecDiv"></div> </div>
This also balances HTML tags so that they won't be left open and doesn't break words.
add_filter("the_content", "break_text");
function break_text($text){
$length = 500;
if(strlen($text)<$length+10) return $text;//don't cut if too short
$break_pos = strpos($text, ' ', $length);//find next space after desired length
$visible = substr($text, 0, $break_pos);
return balanceTags($visible) . " […]";
}
In Anjuta, go to the Build menu, then Configure Project. In the Configure Options box, add:
LDFLAGS='-lpthread'
Hope it'll help somebody too...
I got the error in the following case:
I simply avoided the obfuscation and the error is gone. not a real solution, but at least I know what caused it...
Add to the main __init__.py
in YourClassParentDir, e.g.:
from .YourClass import YourClass
Then, you will have an instance of your class ready when you import it into another script:
from YourClassParentDir import YourClass
In phpmyadmin, you can assign Foreign key simply by its GUI. Click on the table and go to Structure tab. find the Relation View on just bellow of table (shown in below image).
You can assign the forging key from the list box near by the primary key.(See image below). and save
corresponding SQL query automatically generated and executed.
The PowerShell string evaluation is calling ToString() on the DataSet. In order to evaluate any properties (or method calls), you have to force evaluation by enclosing the expression in $()
for($i=0;$i -lt $ds.Tables[1].Rows.Count;$i++)
{
write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"
}
Additionally foreach
allows you to iterate through a collection or array without needing to figure out the length.
Rewritten (and edited for compile) -
foreach ($Row in $ds.Tables[1].Rows)
{
write-host "value is : $($Row[0])"
}
:goto 21490
will take you to the 21490th byte in the buffer.
You can also do it with xargs
:
cat old | xargs -n1 > new
or
xargs -n1 < old > new
req
is an object containing information about the HTTP request that raised the event. In response to req
, you use res
to send back the desired HTTP response.
Those parameters can be named anything. You could change that code to this if it's more clear:
app.get('/user/:id', function(request, response){
response.send('user ' + request.params.id);
});
Edit:
Say you have this method:
app.get('/people.json', function(request, response) { });
The request will be an object with properties like these (just to name a few):
request.url
, which will be "/people.json"
when this particular action is triggeredrequest.method
, which will be "GET"
in this case, hence the app.get()
call.request.headers
, containing items like request.headers.accept
, which you can use to determine what kind of browser made the request, what sort of responses it can handle, whether or not it's able to understand HTTP compression, etc.request.query
(e.g. /people.json?foo=bar
would result in request.query.foo
containing the string "bar"
).To respond to that request, you use the response object to build your response. To expand on the people.json
example:
app.get('/people.json', function(request, response) {
// We want to set the content-type header so that the browser understands
// the content of the response.
response.contentType('application/json');
// Normally, the data is fetched from a database, but we can cheat:
var people = [
{ name: 'Dave', location: 'Atlanta' },
{ name: 'Santa Claus', location: 'North Pole' },
{ name: 'Man in the Moon', location: 'The Moon' }
];
// Since the request is for a JSON representation of the people, we
// should JSON serialize them. The built-in JSON.stringify() function
// does that.
var peopleJSON = JSON.stringify(people);
// Now, we can use the response object's send method to push that string
// of people JSON back to the browser in response to this request:
response.send(peopleJSON);
});
First things first, the definition of "peak" is vague if without further specifications. For example, for the following series, would you call 5-4-5 one peak or two?
1-2-1-2-1-1-5-4-5-1-1-5-1
In this case, you'll need at least two thresholds: 1) a high threshold only above which can an extreme value register as a peak; and 2) a low threshold so that extreme values separated by small values below it will become two peaks.
Peak detection is a well-studied topic in Extreme Value Theory literature, also known as "declustering of extreme values". Its typical applications include identifying hazard events based on continuous readings of environmental variables e.g. analysing wind speed to detect storm events.
db:migrate runs (single) migrations that have not run yet.
db:create creates the database
db:drop deletes the database
db:schema:load creates tables and columns within the existing database following schema.rb. This will delete existing data.
db:setup does db:create, db:schema:load, db:seed
db:reset does db:drop, db:setup
db:migrate:reset does db:drop, db:create, db:migrate
Typically, you would use db:migrate after having made changes to the schema via new migration files (this makes sense only if there is already data in the database). db:schema:load is used when you setup a new instance of your app.
I hope that helps.
UPDATE for rails 3.2.12:
I just checked the source and the dependencies are like this now:
db:create creates the database for the current env
db:create:all creates the databases for all envs
db:drop drops the database for the current env
db:drop:all drops the databases for all envs
db:migrate runs migrations for the current env that have not run yet
db:migrate:up runs one specific migration
db:migrate:down rolls back one specific migration
db:migrate:status shows current migration status
db:rollback rolls back the last migration
db:forward advances the current schema version to the next one
db:seed (only) runs the db/seed.rb file
db:schema:load loads the schema into the current env's database
db:schema:dump dumps the current env's schema (and seems to create the db as well)
db:setup runs db:schema:load, db:seed
db:reset runs db:drop db:setup
db:migrate:redo runs (db:migrate:down db:migrate:up) or (db:rollback db:migrate) depending on the specified migration
db:migrate:reset runs db:drop db:create db:migrate
For further information please have a look at https://github.com/rails/rails/blob/v3.2.12/activerecord/lib/active_record/railties/databases.rake (for Rails 3.2.x) and https://github.com/rails/rails/blob/v4.0.5/activerecord/lib/active_record/railties/databases.rake (for Rails 4.0.x)
Use beforeSend
:
$.ajax({
url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
data: { signature: authHeader },
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('X-Test-Header', 'test-value');},
success: function() { alert('Success!' + authHeader); }
});
http://api.jquery.com/jQuery.ajax/
http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method
RookieRick is right, using DataGridTemplateColumn
instead of DataGridComboBoxColumn
gives a much simpler XAML.
Moreover, putting the CompanyItem
list directly accessible from the GridItem
allows you to get rid of the RelativeSource
.
IMHO, this give you a very clean solution.
XAML:
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding GridItems}" >
<DataGrid.Resources>
<DataTemplate x:Key="CompanyDisplayTemplate" DataType="vm:GridItem">
<TextBlock Text="{Binding Company}" />
</DataTemplate>
<DataTemplate x:Key="CompanyEditingTemplate" DataType="vm:GridItem">
<ComboBox SelectedItem="{Binding Company}" ItemsSource="{Binding CompanyList}" />
</DataTemplate>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" />
<DataGridTemplateColumn CellTemplate="{StaticResource CompanyDisplayTemplate}"
CellEditingTemplate="{StaticResource CompanyEditingTemplate}" />
</DataGrid.Columns>
</DataGrid>
View model:
public class GridItem
{
public string Name { get; set; }
public CompanyItem Company { get; set; }
public IEnumerable<CompanyItem> CompanyList { get; set; }
}
public class CompanyItem
{
public int ID { get; set; }
public string Name { get; set; }
public override string ToString() { return Name; }
}
public class ViewModel
{
readonly ObservableCollection<CompanyItem> companies;
public ViewModel()
{
companies = new ObservableCollection<CompanyItem>{
new CompanyItem { ID = 1, Name = "Company 1" },
new CompanyItem { ID = 2, Name = "Company 2" }
};
GridItems = new ObservableCollection<GridItem> {
new GridItem { Name = "Jim", Company = companies[0], CompanyList = companies}
};
}
public ObservableCollection<GridItem> GridItems { get; set; }
}
sudo /Applications/XAMPP/xamppfiles/bin/apachectl start
sudo /Applications/XAMPP/xamppfiles/bin/mysql.server start
Both commands are working like charm :)
You're trying to use key functions with lambda functions.
Python and other languages like C# or F# use lambda functions.
Also, when it comes to key functions and according to the documentation
Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons.
...
The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.
So, key functions have a parameter key and it can indeed receive a lambda function.
In Real Python there's a nice example of its usage. Let's say you have the following list
ids = ['id1', 'id100', 'id2', 'id22', 'id3', 'id30']
and want to sort through its "integers". Then, you'd do something like
sorted_ids = sorted(ids, key=lambda x: int(x[2:])) # Integer sort
and printing it would give
['id1', 'id2', 'id3', 'id22', 'id30', 'id100']
In your particular case, you're only missing to write key=
before lambda. So, you'd want to use the following
a = sorted(a, key=lambda x: x.modified, reverse=True)
To obtain "10-Aug-2010", try:
var date = new Date('2010-08-10 00:00:00');
date = date.toLocaleDateString(undefined, {day:'2-digit'}) + '-' + date.toLocaleDateString(undefined, {month:'short'}) + '-' + date.toLocaleDateString(undefined, {year:'numeric'})
For browser support, see toLocaleDateString.
ls -lR
is to display all files, directories and sub directories of the current directory
ls -lR | more
is used to show all the files in a flow.
set a style for the image
<asp:Image ID="Image1" runat="server" style="max-height:1000px;max-width:900px;height:auto;width:auto;" />
A lot of great answers here but in my case did not solve what I wanted out of an "string enum", which was:
1,2 & 4 can actually be solved with a C# Typedef of a string (since strings are switchable in c#)
3 can be solved by static const strings. So if you have the same needs, this is the simplest approach:
public sealed class Types
{
private readonly String name;
private Types(String name)
{
this.name = name;
}
public override String ToString()
{
return name;
}
public static implicit operator Types(string str)
{
return new Types(str);
}
public static implicit operator string(Types str)
{
return str.ToString();
}
#region enum
public const string DataType = "Data";
public const string ImageType = "Image";
public const string Folder = "Folder";
#endregion
}
This allows for example:
public TypeArgs(Types SelectedType)
{
Types SelectedType = SelectedType
}
and
public TypeObject CreateType(Types type)
{
switch (type)
{
case Types.ImageType:
//
break;
case Types.DataType:
//
break;
}
}
Where CreateType can be called with a string or a type. However the downside is that any string is automatically a valid enum, this could be modified but then it would require some kind of init function...or possibly make they explicit cast internal?
Now if an int value was important to you (perhaps for comparison speed), you could use some ideas from Jakub Šturc fantastic answer and do something a bit crazy, this is my stab at it:
public sealed class Types
{
private static readonly Dictionary<string, Types> strInstance = new Dictionary<string, Types>();
private static readonly Dictionary<int, Types> intInstance = new Dictionary<int, Types>();
private readonly String name;
private static int layerTypeCount = 0;
private int value;
private Types(String name)
{
this.name = name;
value = layerTypeCount++;
strInstance[name] = this;
intInstance[value] = this;
}
public override String ToString()
{
return name;
}
public static implicit operator Types(int val)
{
Types result;
if (intInstance.TryGetValue(val, out result))
return result;
else
throw new InvalidCastException();
}
public static implicit operator Types(string str)
{
Types result;
if (strInstance.TryGetValue(str, out result))
{
return result;
}
else
{
result = new Types(str);
return result;
}
}
public static implicit operator string(Types str)
{
return str.ToString();
}
public static bool operator ==(Types a, Types b)
{
return a.value == b.value;
}
public static bool operator !=(Types a, Types b)
{
return a.value != b.value;
}
#region enum
public const string DataType = "Data";
public const string ImageType = "Image";
#endregion
}
but of course "Types bob = 4;" would be meaningless unless you had initialized them first which would sort of defeat the point...
But in theory TypeA == TypeB would be quicker...
$ irb --simple-prompt
class TestClass
def method1
end
def method2
end
def method3
end
end
tc_list = TestClass.instance_methods(false)
#[:method1, :method2, :method3]
puts tc_list
#method1
#method2
#method3
Yes, I know I'm late to this party but it might help others.
The servlet container chooses the mapping based on the longest path that matches. So you can put this mapping in for your JSPs and it will be chosen over the /* mapping.
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>/WEB-INF/pages/*</url-pattern>
</servlet-mapping>
Actually for Tomcat that's all you'll need since jsp is a servlet that exists out of the box. For other containers you either need to find out the name of the JSP servlet or add a servlet definition like:
<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
</servlet>
You have to check your quotes
properly,
$sql = $wpdb->prepare(
"INSERT INTO `wp_submitted_form`
(`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`)
values ($name, $email, $phone, $country, $course, $message, $datesent)");
$wpdb->query($sql);
OR you can use like,
$sql = "INSERT INTO `wp_submitted_form`
(`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`)
values ($name, $email, $phone, $country, $course, $message, $datesent)";
$wpdb->query($sql);
There is a new parameter expansion added in bash 4.4
that interprets escape sequences:
${parameter@operator} - E operator
The expansion is a string that is the value of parameter with backslash escape sequences expanded as with the
$'…'
quoting mechanism.
$ foo='hello\nworld'
$ echo "${foo@E}"
hello
world
If you are needing this to get user's home dir, below could be considered as portable (win32 and linux at least), part of a standard library.
>>> os.path.expanduser('~')
'C:\\Documents and Settings\\johnsmith'
Also you could parse such string to get only last path component (ie. user name).
See: os.path.expanduser
Any custom file extension can be associated with standard syntax highlighting with
custom files association
in User Settings as follows.
Note that this will be a permanent setting. In order to set for the current session alone, type in the preferred language in
Select Language Mode
box (without changingfile association
settings)
If the required syntax package is not available by default, you can add them via the Extension Marketplace (Ctrl+Shift+X) and search for the language package.
You can further reproduce the above steps to map the file extensions with the new syntax package.
If you want to get a long-as-possible (not sure what limits there are), similar to Solaris' pargs, you can use this on Linux & OSX:
ps -ww -o pid,command [-p <pid> ... ]
{'document_root', settings.STATIC_ROOT}
needs to be
{'document_root': settings.STATIC_ROOT}
or you'll get an error like
dictionary update sequence element #0 has length 6; 2 is required
From James Gosling in "The Java Programming Language":
"...There is exactly one parameter passing mode in Java - pass by value - and that keeps things simple. .."
Wrong quoting: (and missing option closing tag xd)
$out.='<option value="'.$key.'">'.$value["name"].'</option>';
You could create a function who consumes an list of int, transforms in string to concatenate and cast do int again, something like this:
import random
def generate_random_number(length):
return int(''.join([str(random.randint(0,10)) for _ in range(length)]))
Using Spark 2.0+, we can load multiple CSV files from different directories using
df = spark.read.csv(['directory_1','directory_2','directory_3'.....], header=True)
. For more information, refer the documentation
here
In most cases, when you find yourself using forEach
on a Stream, you should rethink whether you are using the right tool for your job or whether you are using it the right way.
Generally, you should look for an appropriate terminal operation doing what you want to achieve or for an appropriate Collector. Now, there are Collectors for producing Map
s and List
s, but no out of-the-box collector for combining two different collectors, based on a predicate.
Now, this answer contains a collector for combining two collectors. Using this collector, you can achieve the task as
Pair<Map<KeyType, Animal>, List<KeyType>> pair = animalMap.entrySet().stream()
.collect(conditional(entry -> entry.getValue() != null,
Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue),
Collectors.mapping(Map.Entry::getKey, Collectors.toList()) ));
Map<KeyType,Animal> myMap = pair.a;
List<KeyType> myList = pair.b;
But maybe, you can solve this specific task in a simpler way. One of you results matches the input type; it’s the same map just stripped off the entries which map to null
. If your original map is mutable and you don’t need it afterwards, you can just collect the list and remove these keys from the original map as they are mutually exclusive:
List<KeyType> myList=animalMap.entrySet().stream()
.filter(pair -> pair.getValue() == null)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
animalMap.keySet().removeAll(myList);
Note that you can remove mappings to null
even without having the list of the other keys:
animalMap.values().removeIf(Objects::isNull);
or
animalMap.values().removeAll(Collections.singleton(null));
If you can’t (or don’t want to) modify the original map, there is still a solution without a custom collector. As hinted in Alexis C.’s answer, partitioningBy
is going into the right direction, but you may simplify it:
Map<Boolean,Map<KeyType,Animal>> tmp = animalMap.entrySet().stream()
.collect(Collectors.partitioningBy(pair -> pair.getValue() != null,
Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
Map<KeyType,Animal> myMap = tmp.get(true);
List<KeyType> myList = new ArrayList<>(tmp.get(false).keySet());
The bottom line is, don’t forget about ordinary Collection operations, you don’t have to do everything with the new Stream API.
I don't have enough rep to put this under comments to the existing answers:
unescape
is only deprecated for working with URIs (or any encoded utf-8) which is probably the case for most people's needs. encodeURIComponent
converts a js string to escaped UTF-8 and decodeURIComponent
only works on escaped UTF-8 bytes. It throws an error for something like decodeURIComponent('%a9'); // error
because extended ascii isn't valid utf-8 (even though that's still a unicode value), whereas unescape('%a9'); // ©
So you need to know your data when using decodeURIComponent.
decodeURIComponent won't work on "%C2"
or any lone byte over 0x7f
because in utf-8 that indicates part of a surrogate. However decodeURIComponent("%C2%A9") //gives you ©
Unescape wouldn't work properly on that // ©
AND it wouldn't throw an error, so unescape can lead to buggy code if you don't know your data.
For Pip 8.1.2 you can use pip download -r requ.txt
to download packages to your local machine.
Expanding upon @freakish answer, async also offers a each method, which seems especially suited for your case:
var async = require('async');
async.each(['aaa','bbb','ccc'], function(name, callback) {
conn.collection(name).drop( callback );
}, function(err) {
if( err ) { return console.log(err); }
console.log('all dropped');
});
IMHO, this makes the code both more efficient and more legible. I've taken the liberty of removing the console.log('dropped')
- if you want it, use this instead:
var async = require('async');
async.each(['aaa','bbb','ccc'], function(name, callback) {
// if you really want the console.log( 'dropped' ),
// replace the 'callback' here with an anonymous function
conn.collection(name).drop( function(err) {
if( err ) { return callback(err); }
console.log('dropped');
callback()
});
}, function(err) {
if( err ) { return console.log(err); }
console.log('all dropped');
});
On Mac OS X Catalina it appears to follow the Linux path. Using any of:
pip install pipenv
pip3 install pipenv
sudo pip install pipenv
sudo pip3 install pipenv
Essentially installs pipenv here:
/Users/mike/Library/Python/3.7/lib/python/site-packages/pipenv
But its not the executable and so is never found. The only thing that worked for me was
pip install --user pipenv
This seems to result in an __init__.py
file in the above directory that has contents to correctly expose the pipenv
command.
and everything started working, when all other posted and commented suggestions on this question failed.
The pipenv package certainly seems quite picky.
encodeURI
and encodeURIComponent
:encodeURIComponent(value)
is mainly used to encode queryString parameter values, and it encodes every applicable character in value
. encodeURI
ignores protocol prefix (http://
) and domain name.
In very, very rare cases, when you want to implement manual encoding to encode additional characters (though they don't need to be encoded in typical cases) like: ! *
, then
you might use:
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
(source)
There are two ways to resize an image. The new size can be specified:
Manually;
height, width = src.shape[:2]
dst = cv2.resize(src, (2*width, 2*height), interpolation = cv2.INTER_CUBIC)
By a scaling factor.
dst = cv2.resize(src, None, fx = 2, fy = 2, interpolation = cv2.INTER_CUBIC)
,
where fx is the scaling factor along the horizontal axis and fy along the vertical axis.
To shrink an image, it will generally look best with INTER_AREA interpolation, whereas to enlarge an image, it will generally look best with INTER_CUBIC (slow) or INTER_LINEAR (faster but still looks OK).
import cv2
img = cv2.imread('YOUR_PATH_TO_IMG')
height, width = img.shape[:2]
max_height = 300
max_width = 300
# only shrink if img is bigger than required
if max_height < height or max_width < width:
# get scaling factor
scaling_factor = max_height / float(height)
if max_width/float(width) < scaling_factor:
scaling_factor = max_width / float(width)
# resize image
img = cv2.resize(img, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA)
cv2.imshow("Shrinked image", img)
key = cv2.waitKey()
import cv2 as cv
im = cv.imread(path)
height, width = im.shape[:2]
thumbnail = cv.resize(im, (round(width / 10), round(height / 10)), interpolation=cv.INTER_AREA)
cv.imshow('exampleshq', thumbnail)
cv.waitKey(0)
cv.destroyAllWindows()
I would guess it makes an infinite loop bc you skip the number 100. If you set the critera to be less than 101 it should do the trick :)
def gukan(count):
while count<100:
print(count)
count=count+3;
gukan(0)
your id attribute is not set. this MAY be due to the fact that the DB field is not set to auto increment? what DB are you using? MySQL? is your field set to AUTO INCREMENT?
You can force cut to display all fields and subsequent ones adding -
to field number.
NAME=`basename "$FILE"`
EXTENSION=`echo "$NAME" | cut -d'.' -f2-`
So if FILE is eth0.pcap.gz
, the EXTENSION will be pcap.gz
Using the same logic, you can also fetch the file name using '-' with cut as follows :
NAME=`basename "$FILE" | cut -d'.' -f-1`
This works even for filenames that do not have any extension.
You can get the bounding box of any element by calling getBoundingClientRect
var rect = document.getElementById("myElement").getBoundingClientRect();
That will return an object with left, top, width and height fields.
>>> class X(object):
... pass
...
>>> type(X)
<type 'type'>
>>> isinstance(X,type)
True
We faced the same problem:
ORA-29913: error in executing ODCIEXTTABLEOPEN callout
ORA-29400: data cartridge error error opening file /fs01/app/rms01/external/logs/SH_EXT_TAB_VGAG_DELIV_SCHED.log
In our case we had a RAC with 2 nodes. After giving write permission on the log directory, on both sides, everything worked fine.
I have had a similar scenario where I needed to set the focus on a text box within a panel when the panel was shown. The panel was loaded on application startup, so I couldn't set the focus in the constructor. As the panel wasn't being loaded or being given focus on show, this meant that I had no event to fire the focus request from.
To solve this, I added a global method to my main that called a method in the panel that invoked requestFocusInWindow()
on the text area. I put the call to the global method in the button that showed the panel, after the call to show. This meant that the panel would be shown and then the text area assigned the focus after showing the panel. Hope that makes sense and helps!
Also, you can edit most of the auto-generated code by right clicking on the object in design view and selecting customize code, however I don't think that it allows you to edit panels.
As mentioned before, you need more than a css selector because it doesn't access the stored value of the node, so javascript is definitely needed. Heres another possible solution:
<style>
input:not([value=""]){
border:2px solid red;
}
</style>
<input type="text" onkeyup="this.setAttribute('value', this.value);"/>
+
presents one of the relative selectors. Here is a list of all relative selectors:
div p
- All <p>
elements inside of a <div>
element are selected.
div > p
- All <p>
elements whose direct parent is <div>
are selected. It works backwards too (p < div
)
div + p
- All <p>
elements placed immediately after a <div>
element are selected.
div ~ p
- All <p>
elements that are preceded by a <div>
element are selected.
In Ruby, any variable whose name starts with a capital letter is a constant and you can only assign to it once. Choose one of these alternatives:
class MyClass
MYCONSTANT = "blah"
def mymethod
MYCONSTANT
end
end
class MyClass
def mymethod
my_constant = "blah"
end
end
More flexible way is to use FileTimeFilterJS.bat
:
@echo off
::::::::::::::::::::::
set "_DIR=C:\Users\npocmaka\Downloads"
set "_DAYS=-5"
::::::::::::::::::::::
for /f "tokens=* delims=" %%# in ('FileTimeFilterJS.bat "%_DIR%" -dd %_DAYS%') do (
echo deleting "%%~f#"
echo del /q /f "%%~f#"
)
The script will allow you to use measurements like days, minutes ,seconds or hours. To choose weather to filter the files by time of creation, access or modification To list files before or after a certain date (or between two dates) To choose if to show files or dirs (or both) To be recursive or not
the first command is correct but change from convert to export to csv, as below,
Get-ADUser -Filter * -Properties * `
| Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,whenCreated,Enabled,Organization `
| Sort-Object -Property Name `
| Export-Csv -path C:\Users\*\Desktop\file1.csv
My case: Seeing the same INFO message.
Centos 6.2 x86_64 Tomcat 6.0.24
This fixed the problem for me:
yum install tomcat-native
boom!
You need to include your pipe in module declaration:
declarations: [ UsersPipe ],
providers: [UsersPipe]
In your public View getView
method change return null;
to return convertView;
.
I had the same "TypeError: an integer is required" error message when attempting to write. Thanks, the .encode() solved it for me. I'm running python 3.4 on a Dell D530 running 32 bit Windows XP Pro.
I'm omitting the com port settings here:
>>>import serial
>>>ser = serial.Serial(5)
>>>ser.close()
>>>ser.open()
>>>ser.write("1".encode())
1
>>>
If you want a function to do this
Object array = new String[10];
int size = Array.getlength(array);
This can be useful if you don't know what type of array you have e.g. int[], byte[] or Object[].
Read the tutorial on Java Web applications.
Basically Web applications are a part of the Java EE standard. A lot of people only use the Web (servlets) part with additional frameworks thrown in, most notably Spring but also Struts, Seam and others.
All you need is an IDE like IntelliJ, Eclipse or Netbeans, the JDK, the Java EE download and a servlet container like Tomcat (or a full-blown application server like Glassfish or JBoss).
Here is a Tomcat tutorial.
The "encoded_c" mentioned in the @smehmood's Vigenere cipher answer should be "key_c".
Here are working encode/decode functions.
import base64
def encode(key, clear):
enc = []
for i in range(len(clear)):
key_c = key[i % len(key)]
enc_c = chr((ord(clear[i]) + ord(key_c)) % 256)
enc.append(enc_c)
return base64.urlsafe_b64encode("".join(enc))
def decode(key, enc):
dec = []
enc = base64.urlsafe_b64decode(enc)
for i in range(len(enc)):
key_c = key[i % len(key)]
dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256)
dec.append(dec_c)
return "".join(dec)
Disclaimer: As implied by the comments, this should not be used to protect data in a real application, unless you read this and don't mind talking with lawyers:
This problem has very simple solution. Just open your SmartGit, then go to Repository option(On top left), then go to settings. It will open a dialog box of Repository Settings. Now, click on Commit TAB and write your UserName and EmailId which you give on BitBucke website. Now click ok and again try to Commit and it works fine now.
For me the only thing that worked is been:
For example
import subprocess
proc = subprocess.Popen(["pkill", "-f", "scriptName.py"], stdout=subprocess.PIPE)
proc.wait()
Try this:
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
// comboBox1 is readonly
e.SuppressKeyPress = true;
}
Using RandomAccessFile
would be simple and handy.
RandomAccessFile f = new RandomAccessFile(filepath, "r");
byte[] bytes = new byte[(int) f.length()];
f.read(bytes);
f.close();
Just use this
$i=0;
foreach ($object as $key =>$value)
{
$i++;
}
the variable $i
is number of keys.
I had the similar issue. I solved it the following way after a number of attempts to follow the pieces of advice in the forums. I am reposting the solution because it could be helpful for others.
I am running Windows 7 (Apache 2.2 & PHP 5.2.17 & MySQL 5.0.51a), the syntax in the file "httpd.conf" (C:\Program Files (x86)\Apache Software Foundation\Apache2.2\conf\httpd.conf) was sensitive to slashes. You can check if "php.ini" is read from the right directory. Just type in your browser "localhost/index.php". The code of index.php is the following:
<?php
echo phpinfo();
?>
There is the row (not far from the top) called "Loaded Configuration File". So, if there is nothing added, then the problem could be that your "php.ini" is not read, even you uncommented (extension=php_mysql.dll and extension=php_mysqli.dll). So, in order to make it work I did the following step. I needed to change from
PHPIniDir 'c:\PHP\'
to
PHPIniDir 'c:\PHP'
Pay the attention that the last slash disturbed everything!
Now the row "Loaded Configuration File" gets "C:\PHP\php.ini" after refreshing "localhost/index.php" (before I restarted Apache2.2) as well as mysql block is there. MySQL and PHP are working together!
Your question 1 has been already extensively discussed in several excellent answers here.
I thought to share with you a few lines of code that allow you to compute the autocorrelation of a signal based only on the mathematical properties of the autocorrelation. That is, the autocorrelation may be computed in the following way:
subtract the mean from the signal and obtain an unbiased signal
compute the Fourier transform of the unbiased signal
compute the power spectral density of the signal, by taking the square norm of each value of the Fourier transform of the unbiased signal
compute the inverse Fourier transform of the power spectral density
normalize the inverse Fourier transform of the power spectral density by the sum of the squares of the unbiased signal, and take only half of the resulting vector
The code to do this is the following:
def autocorrelation (x) :
"""
Compute the autocorrelation of the signal, based on the properties of the
power spectral density of the signal.
"""
xp = x-np.mean(x)
f = np.fft.fft(xp)
p = np.array([np.real(v)**2+np.imag(v)**2 for v in f])
pi = np.fft.ifft(p)
return np.real(pi)[:x.size/2]/np.sum(xp**2)
This is because Oracle internally changes empty string to NULL values. Oracle simply won't let insert an empty string.
On the other hand, SQL Server would let you do what you are trying to achieve.
There are 2 workarounds here:
Both are, of course, stupid workarounds :)
You may drag'n'drop your folder to Side bar. To enable Side bar you should do View -> Side bar -> show opened files. You'll got opened files (tabs) tree and folder structure at Side bar.
Import the following class:
#import <QuartzCore/QuartzCore.h>
//Code for setting the grey color for the border of the text field
[[textField layer] setBorderColor:[[UIColor colorWithRed:171.0/255.0
green:171.0/255.0
blue:171.0/255.0
alpha:1.0] CGColor]];
Replace 171.0
with the respective color number as required.
If you have a class on your element, then you can try the following:
if( $('.exists_content').hasClass('exists_content') ){
//element available
}
imho: Apache HTTP Client
usage example:
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;
import java.io.*;
public class HttpClientTutorial {
private static String url = "http://www.apache.org/";
public static void main(String[] args) {
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
// Create a method instance.
GetMethod method = new GetMethod(url);
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
System.out.println(new String(responseBody));
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
}
}
}
some highlight features:
If you have the table definition to have an IDENTITY column e.g. IDENTITY(1,1) then don't include MyId in your INSERT INTO statement. The point of IDENTITY is it gives it the next unused value as the primary key value.
insert into MYDB.dbo.MainTable (MyFirstName, MyLastName, MyAddress, MyPort)
values(@myFirstName, @myLastName, @myAddress, @myPort)
There is then no need to pass the @MyId parameter into your stored procedure either. So change it to:
CREATE PROCEDURE [dbo].[sp_Test]
@myFirstName nvarchar(50)
,@myLastName nvarchar(50)
,@myAddress nvarchar(MAX)
,@myPort int
AS
If you want to know what the ID of the newly inserted record is add
SELECT @@IDENTITY
to the end of your procedure. e.g. http://msdn.microsoft.com/en-us/library/ms187342.aspx
You will then be able to pick this up in which ever way you are calling it be it SQL or .NET.
P.s. a better way to show you table definision would have been to script the table and paste the text into your stackoverflow browser window because your screen shot is missing the column properties part where IDENTITY is set via the GUI. To do that right click the table 'Script Table as' --> 'CREATE to' --> Clipboard. You can also do File or New Query Editor Window (all self explanitory) experient and see what you get.
This is very weird behavior of PostgreSQL, it is even not " in-line with the PostgreSQL philosophy of forcing the user to make everything explicit" - as the exception was caught and ignored explicitly. So even this defense does not hold. Oracle in this case behaves much more user-friendly and (as for me) correctly - it leaves a choice to the developer.
module
is a plain JavaScript object with an exports
property. exports
is a plain JavaScript variable that happens to be set to module.exports
.
At the end of your file, node.js will basically 'return' module.exports
to the require
function. A simplified way to view a JS file in Node could be this:
var module = { exports: {} };
var exports = module.exports;
// your code
return module.exports;
If you set a property on exports
, like exports.a = 9;
, that will set module.exports.a
as well because objects are passed around as references in JavaScript, which means that if you set multiple variables to the same object, they are all the same object; so then exports
and module.exports
are the same object.
But if you set exports
to something new, it will no longer be set to module.exports
, so exports
and module.exports
are no longer the same object.
I notice that sometimes in Chrome when autofill is on and the fields are field by the autofill browser build in method, it bypasses the minlength validation rules, so in this case you will have to disable autofill by the following attribute:
autocomplete="off"
<input autocomplete="new-password" name="password" id="password" type="password" placeholder="Password" maxlength="12" minlength="6" required />
This may be helpful
byte[] bytes = System.Convert.FromBase64String(stringInBase64);
INSERT into table_name (
`product_id`,
`other_products_url_id`,
`brand`,
`title`,
`price`,
`category`,
`sub_category`,
`quantity`,
`buy_now`,
`buy_now_url`,
`is_available`,
`description`,
`image_url`,
`image_type`,
`server_image_url`,
`reviews`,
`hits`,
`rating`,
`seller_name`,
`seller_desc`,
`created_on`,
`modified_on`,
`status`)
SELECT
`product_id`,
`other_products_url_id`,
`brand`,
`title`,
`price`,
`category`,
`sub_category`,
`quantity`,
`buy_now`,
concat(`buy_now_url`,'','#test123456'),
`is_available`,
`description`,
`image_url`,
`image_type`,
`server_image_url`,
`reviews`,
`hits`,
`rating`,
`seller_name`,
`seller_desc`,
`created_on`,
`modified_on`,
`status`
FROM `table_name` WHERE id='YourRowID';
"files" in *nix type systems are very much an abstract concept.
They can be areas on disk organized by a file system, but they could equally well be a network connection, a bit of shared memory, the buffer output from another process, a screen or a keyboard.
In order for perl to be really useful it mirrors this model very closely, and does not treat files by emulating a magnetic tape as many 4gls do.
So it tried an "IOCTL" operation 'open for write' on a file handle which does not allow write operations which is an inappropriate IOCTL operation for that device/file.
The easiest thing to do is stick an " or die 'Cannot open $myfile'
statement at the end of you open and you can choose your own meaningful message.
You could move the div when the table is drawn using the fnDrawCallback
function.
$("#myTable").dataTable({
"fnDrawCallback": function (oSettings) {
$(".dataTables_filter").each(function () {
$(this).appendTo($(this).parent().siblings(".panel-body"));
});
}
});
As AlienWebGuy said, you can use background-image. I'd suggest you use background, but it will need three more properties after the URL:
background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") 0 0 no-repeat;
Explanation: the two zeros are x and y positioning for the image; if you want to adjust where the background image displays, play around with these (you can use both positive and negative values, e.g: 1px or -1px).
No-repeat says you don't want the image to repeat across the entire background. This can also be repeat-x and repeat-y.
I just modified hhafez's test to include StringBuilder. StringBuilder is 33 times faster than String.format using jdk 1.6.0_10 client on XP. Using the -server switch lowers the factor to 20.
public class StringTest {
public static void main( String[] args ) {
test();
test();
}
private static void test() {
int i = 0;
long prev_time = System.currentTimeMillis();
long time;
for ( i = 0; i < 1000000; i++ ) {
String s = "Blah" + i + "Blah";
}
time = System.currentTimeMillis() - prev_time;
System.out.println("Time after for loop " + time);
prev_time = System.currentTimeMillis();
for ( i = 0; i < 1000000; i++ ) {
String s = String.format("Blah %d Blah", i);
}
time = System.currentTimeMillis() - prev_time;
System.out.println("Time after for loop " + time);
prev_time = System.currentTimeMillis();
for ( i = 0; i < 1000000; i++ ) {
new StringBuilder("Blah").append(i).append("Blah");
}
time = System.currentTimeMillis() - prev_time;
System.out.println("Time after for loop " + time);
}
}
While this might sound drastic, I consider it to be relevant only in rare cases, because the absolute numbers are pretty low: 4 s for 1 million simple String.format calls is sort of ok - as long as I use them for logging or the like.
Update: As pointed out by sjbotha in the comments, the StringBuilder test is invalid, since it is missing a final .toString()
.
The correct speed-up factor from String.format(.)
to StringBuilder
is 23 on my machine (16 with the -server
switch).
If you are using Talend MDM Server, the login is: login: admin password: talend
See more: http://wiki.glitchdata.com/index.php?title=TOS:_Accessing_the_Talend_MDM_Server
This differs from the default JBoss login of admin/admin The password setup file is also login-config.xml in this case.
1) Launch Ubuntu Instance on EC2.
2) Open SSH Port in instance security.
3) Do SSH to instance.
4) Execute:
sudo apt-get update sudo apt-get upgrade
5) Because you will be connecting from Windows Remote Desktop, edit the sshd_config file on your Linux instance to allow password authentication.
sudo vim /etc/ssh/sshd_config
6) Change PasswordAuthentication to yes from no, then save and exit.
7) Restart the SSH daemon to make this change take effect.
sudo /etc/init.d/ssh restart
8) Temporarily gain root privileges and change the password for the ubuntu user to a complex password to enhance security. Press the Enter key after typing the command passwd ubuntu, and you will be prompted to enter the new password twice.
sudo –i
passwd ubuntu
9) Switch back to the ubuntu user account and cd to the ubuntu home directory.
su ubuntu
cd
10) Install Ubuntu desktop functionality on your Linux instance, the last command can take up to 15 minutes to complete.
export DEBIAN_FRONTEND=noninteractive
sudo -E apt-get update
sudo -E apt-get install -y ubuntu-desktop
11) Install xrdp
sudo apt-get install xfce4
sudo apt-get install xfce4 xfce4-goodies
12) Make xfce4 the default window manager for RDP connections.
echo xfce4-session > ~/.xsession
13) Copy .xsession to the /etc/skel folder so that xfce4 is set as the default window manager for any new user accounts that are created.
sudo cp /home/ubuntu/.xsession /etc/skel
14) Open the xrdp.ini file to allow changing of the host port you will connect to.
sudo vim /etc/xrdp/xrdp.ini
(xrdp is not installed till now. First Install the xrdp with sudo apt-get install xrdp then edit the above mentioned file)
15) Look for the section [xrdp1] and change the following text (then save and exit [:wq]).
port=-1
- to -
port=ask-1
16) Restart xrdp.
sudo service xrdp restart
17) On Windows, open the Remote Desktop Connection client, paste the fully qualified name of your Amazon EC2 instance for the Computer, and then click Connect.
18) When prompted to Login to xrdp, ensure that the sesman-Xvnc module is selected, and enter the username ubuntu with the new password that you created in step 8. When you start a session, the port number is -1.
19) When the system connects, several status messages are displayed on the Connection Log screen. Pay close attention to these status messages and make note of the VNC port number displayed. If you want to return to a session later, specify this number in the port field of the xrdp login dialog box.
See more details:
https://aws.amazon.com/premiumsupport/knowledge-center/connect-to-linux-desktop-from-windows/
http://c-nergy.be/blog/?p=5305
Check out mycrypt(): http://us.php.net/manual/en/book.mcrypt.php
And if you're using postgres there's pgcrypto for database level encryption. (makes it easier to search and sort)
Came across this question researching some aberrant behavior in IE, specifically IE9, didn't check older versions. It seems
window.location.reload();
results in a refresh that blanks out the entire screen for a second, where as
window.location = document.URL;
refreshes the page much more quickly, almost imperceptibly.
Doing a bit more research, and some experimentation with fiddler, it seems that window.location.reload()
will bypass the cache and reload from the server regardless if you pass the boolean with it or not, this includes getting all of your assets (images, scripts, style sheets, etc) again. So if you just want the page to refresh the HTML, the window.location = document.URL
will return much quicker and with less traffic.
A difference in behavior between browsers is that when IE9 uses the reload method it clears the visible page and seemingly rebuilds it from scratch, where FF and chrome wait till they get the new assets and rebuild them if they are different.
I solved:
Just turn off USB debugging and re-enable debugging it immediately
Since version 2.11, it's pretty easy, you can use the N stack number instead of saying "stash@{n}"
.
So now instead of using:
git stash apply "stash@{n}"
You can type:
git stash apply n
For example, in your list:
stash@{0}: WIP on design: f2c0c72... Adjust Password Recover Email
stash@{1}: WIP on design: f2c0c72... Adjust Password Recover Email
stash@{2}: WIP on design: eb65635... Email Adjust
stash@{3}: WIP on design: eb65635... Email Adjust
If you want to apply stash@{1}
you could type:
git stash apply 1
Otherwise, you can use it even if you have some changes in your directory since 1.7.5.1, but you must be sure the stash won't overwrite your working directory changes if it does you'll get an error:
error: Your local changes to the following files would be overwritten by merge:
file
Please commit your changes or stash them before you merge.
In versions prior to 1.7.5.1, it refused to work if there was a change in the working directory.
Git release notes:
The user always has to say "stash@{$N}" when naming a single element in the default location of the stash, i.e. reflogs in refs/stash. The "git stash" command learned to accept "git stash apply 4" as a short-hand for "git stash apply stash@{4}"
git stash apply" used to refuse to work if there was any change in the working tree, even when the change did not overlap with the change the stash recorded
its work for me set the User-Agent in the addRequestProperty.
URL url = new URL(<URL>);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0");
This will disable autorotation of the view:
override func shouldAutorotate() -> Bool {
return false;
}
Update
override func shouldAutorotate() -> Bool {
if (UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeLeft ||
UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeRight ||
UIDevice.currentDevice().orientation == UIDeviceOrientation.Unknown) {
return false;
}
else {
return true;
}
}
If app is in landscape mode and you show a view which must be showed in portrait mode, this will allow app to change it's orientation to portrait (of course when device will be rotated to such orientation).
I think currently the application-context.xml file is into src/main/resources AND the social.properties file is into src/main/java... so when you package (mvn package) or when you run tomcat (mvn tomcat:run) your social.properties disappeared (I know you said when you checked into the .war the files are here... but your exception says the opposite).
The solution is simply to put all your configuration files (application-context.xml and social.properties) into src/main/resources to follow the maven standard structure.
Log in :URL = "localhost:8080/" Enter username and pass word Click Manager App Scroll Down and find "WAR file to deploy" Chose file and click deploy
Done
Go to Webapp folder of you Apache tomcat you will see a folder name matching with your war file name.
Type link in your url address bar:: localhost:8080/HelloWorld/HelloWorld.html and press enter
Done
The following is the code which I used to display all activity in landscape mode:
<activity android:screenOrientation="landscape"
android:configChanges="orientation|keyboardHidden"
android:name="abcActivty"/>
From the documentation:
Named exports are useful to export several values. During the import, one will be able to use the same name to refer to the corresponding value.
Concerning the default export, there is only a single default export per module. A default export can be a function, a class, an object or anything else. This value is to be considered as the "main" exported value since it will be the simplest to import.
Here's a simple script that generally does the trick for me:
SELECT command, percent_complete,total_elapsed_time, estimated_completion_time, start_time
FROM sys.dm_exec_requests
WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE')
There are two ways of solving this problem. Go to the AndroidManifist.xml, and in the name of your activity, add this line
android:windowSoftInputMode="adjustPan"
As in the below code, I have added to the Register Activity.
<activity android:name=".Register"
android:windowSoftInputMode="adjustPan">
In the second way, go to your activity, and in your onCreate method, add this code.
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
This answer is totally unrelated to the OP's situation, and is a very unlikely scenario for anyone else too, but just in case it may help someone ...
In my case I was getting "Could not load file or assembly 'System.Windows.Forms, Version=4.0.0.0 ..." because I had disassembled and reassembled the program using ILDAsm.exe and ILAsm.exe from .Net Framework / SDK version 2. Switching to ILDAsm.exe and ILAsm.exe from .Net Framework / SDK version 4 fixed the problem.
(Strangely, even though doing what I did may seem like an obvious error, the resulting EXE file that didn't work did indicate that it targeted .Net 4 when examined with JetBrains dotPeek.)
Java 7 to the rescue!
You can either pass the file or the file name and it will return the MIME type.
String mimeType = MimetypesFileTypeMap
.getDefaultFileTypeMap()
.getContentType(attachment.getFileName());
http://docs.oracle.com/javase/7/docs/api/javax/activation/MimetypesFileTypeMap.html
What worked for me was to create a viewmodel that contained the date property as a string. Assigning the DateTime property from the domain model and calling the .ToString() on the date property while assigning the value to the viewmodel.
A JSON result from an MVC action method will return the date in a format compatible with the view.
public class TransactionsViewModel
{
public string DateInitiated { get; set; }
public string DateCompleted { get; set; }
}
public class Transaction{
public DateTime? DateInitiated {get; set;}
public DateTime? DateCompleted {get; set;}
}
public JsonResult GetTransactions(){
var transactions = _transactionsRepository.All;
var model = new List<TransactionsViewModel>();
foreach (var transaction in transactions)
{
var item = new TransactionsViewModel
{
...............
DateInitiated = transaction.DateInitiated.ToString(),
DateCompleted = transaction.DateCompleted.ToString(),
};
model.Add(item);
}
return Json(model, JsonRequestBehavior.AllowGet);
}
Once you have the source trees, e.g.
diff -ENwbur repos1/ repos2/
Even better
diff -ENwbur repos1/ repos2/ | kompare -o -
and have a crack at it in a good gui tool :)
yuna and bnl code failed in the case below;
failing example:
1st one waits for completed.but, 2nd one with the invokemember("submit") didnt . invoke works. but ReadyState.Complete acts like its Completed before its REALLY completed:
wb.Navigate(url);
while(wb.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
MessageBox.Show("ok this waits Complete");
//navigates to new page
wb.Document.GetElementById("formId").InvokeMember("submit");
while(wb.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
MessageBox.Show("webBrowser havent navigated yet. it gave me previous page's html.");
var html = wb.Document.GetElementsByTagName("HTML")[0].OuterHtml;
how to fix this unwanted situation:
usage
public myForm1 {
myForm1_load() { }
// func to make browser wait is inside the Extended class More tidy.
WebBrowserEX wbEX = new WebBrowserEX();
button1_click(){
wbEX.Navigate("site1.com");
wbEX.waitWebBrowserToComplete(wb);
wbEX.Document.GetElementById("input1").SetAttribute("Value", "hello");
//submit does navigation
wbEX.Document.GetElementById("formid").InvokeMember("submit");
wbEX.waitWebBrowserToComplete(wb);
// this actually waits for document Compelete. worked for me.
var processedHtml = wbEX.Document.GetElementsByTagName("HTML")[0].OuterHtml;
var rawHtml = wbEX.DocumentText;
}
}
//put this extended class in your code.
//(ie right below form class, or seperate cs file doesnt matter)
public class WebBrowserEX : WebBrowser
{
//ctor
WebBrowserEX()
{
//wired aumatically here. we dont need to worry our sweet brain.
this.DocumentCompleted += (o, e) => { webbrowserDocumentCompleted = true;};
}
//instead of checking readState, get state from DocumentCompleted Event
// via bool value
bool webbrowserDocumentCompleted = false;
public void waitWebBrowserToComplete()
{
while (!webbrowserDocumentCompleted )
{ Application.DoEvents(); }
webbrowserDocumentCompleted = false;
}
}
This answer is based on this excellent answer by 18446744073709551615. Their solution, though helpful, does not size the image icon with the surrounding text. It also doesn't set the icon colour to that of the surrounding text.
The solution below takes a white, square icon and makes it fit the size and colour of the surrounding text.
public class TextViewWithImages extends TextView {
private static final String DRAWABLE = "drawable";
/**
* Regex pattern that looks for embedded images of the format: [img src=imageName/]
*/
public static final String PATTERN = "\\Q[img src=\\E([a-zA-Z0-9_]+?)\\Q/]\\E";
public TextViewWithImages(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public TextViewWithImages(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TextViewWithImages(Context context) {
super(context);
}
@Override
public void setText(CharSequence text, BufferType type) {
final Spannable spannable = getTextWithImages(getContext(), text, getLineHeight(), getCurrentTextColor());
super.setText(spannable, BufferType.SPANNABLE);
}
private static Spannable getTextWithImages(Context context, CharSequence text, int lineHeight, int colour) {
final Spannable spannable = Spannable.Factory.getInstance().newSpannable(text);
addImages(context, spannable, lineHeight, colour);
return spannable;
}
private static boolean addImages(Context context, Spannable spannable, int lineHeight, int colour) {
final Pattern refImg = Pattern.compile(PATTERN);
boolean hasChanges = false;
final Matcher matcher = refImg.matcher(spannable);
while (matcher.find()) {
boolean set = true;
for (ImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), ImageSpan.class)) {
if (spannable.getSpanStart(span) >= matcher.start()
&& spannable.getSpanEnd(span) <= matcher.end()) {
spannable.removeSpan(span);
} else {
set = false;
break;
}
}
final String resName = spannable.subSequence(matcher.start(1), matcher.end(1)).toString().trim();
final int id = context.getResources().getIdentifier(resName, DRAWABLE, context.getPackageName());
if (set) {
hasChanges = true;
spannable.setSpan(makeImageSpan(context, id, lineHeight, colour),
matcher.start(),
matcher.end(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
);
}
}
return hasChanges;
}
/**
* Create an ImageSpan for the given icon drawable. This also sets the image size and colour.
* Works best with a white, square icon because of the colouring and resizing.
*
* @param context The Android Context.
* @param drawableResId A drawable resource Id.
* @param size The desired size (i.e. width and height) of the image icon in pixels.
* Use the lineHeight of the TextView to make the image inline with the
* surrounding text.
* @param colour The colour (careful: NOT a resource Id) to apply to the image.
* @return An ImageSpan, aligned with the bottom of the text.
*/
private static ImageSpan makeImageSpan(Context context, int drawableResId, int size, int colour) {
final Drawable drawable = context.getResources().getDrawable(drawableResId);
drawable.mutate();
drawable.setColorFilter(colour, PorterDuff.Mode.MULTIPLY);
drawable.setBounds(0, 0, size, size);
return new ImageSpan(drawable, ImageSpan.ALIGN_BOTTOM);
}
}
How to use:
Simply embed references to the desired icons in the text. It doesn't matter whether the text is set programatically through textView.setText(R.string.string_resource);
or if it's set in xml.
To embed a drawable icon named example.png, include the following string in the text: [img src=example/]
.
For example, a string resource might look like this:
<string name="string_resource">This [img src=example/] is an icon.</string>
Please try this:
CREATE TABLE article (
article_id bigint(20) NOT NULL serial,
article_name varchar(20) NOT NULL,
article_desc text NOT NULL,
date_added datetime default NULL,
PRIMARY KEY (article_id)
);
We have Collection as below:
Syntax:
{{(Collection/array/list | filter:{Value : (object value)})[0].KeyName}}
Example:
{{(Collectionstatus | filter:{Value:dt.Status})[0].KeyName}}
-OR-
Syntax:
ng-bind="(input | filter)"
Example:
ng-bind="(Collectionstatus | filter:{Value:dt.Status})[0].KeyName"
I just ran into this issue and checked all of the above answers to make sure I wasn't missing anything obvious. Well, I had a semi-obvious issue. My casing of my classname in code and the classname I used in the configuration file didn't match.
For example: if the class name is CalculatorService and the configuration file refers to Calculatorservice ... you will get this error.
What you have from the server is a string like below:
var data = '[{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}]';
Then you can use JSON.parse
function to change it to an object. Then you access the category like below:
var dataObj = JSON.parse(data);
console.log(dataObj[0].category); //will return Damskie
console.log(dataObj[1].category); //will return Meskie
I made the following script:
#!/bin/bash
# Target installation location
MAVEN_HOME="/your/path/here"
# Link to binary tar.gz archive
# See https://maven.apache.org/download.cgi?html_a_name#Files
MAVEN_BINARY_TAR_GZ_ARCHIVE="http://www.trieuvan.com/apache/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.tar.gz"
# Configuration parameters used to start up the JVM running Maven, i.e. "-Xms256m -Xmx512m"
# See https://maven.apache.org/configure.html
MAVEN_OPTS="" # Optional (not needed)
if [[ ! -d $MAVEN_HOME ]]; then
# Create nonexistent subdirectories recursively
mkdir -p $MAVEN_HOME
# Curl location of tar.gz archive & extract without first directory
curl -L $MAVEN_BINARY_TAR_GZ_ARCHIVE | tar -xzf - -C $MAVEN_HOME --strip 1
# Creating a symbolic/soft link to Maven in the primary directory of executable commands on the system
ln -s $MAVEN_HOME/bin/mvn /usr/bin/mvn
# Permanently set environmental variable (if not null)
if [[ -n $MAVEN_OPTS ]]; then
echo "export MAVEN_OPTS=$MAVEN_OPTS" >> ~/.bashrc
fi
# Using MAVEN_HOME, MVN_HOME, or M2 as your env var is irrelevant, what counts
# is your $PATH environment.
# See http://stackoverflow.com/questions/26609922/maven-home-mvn-home-or-m2-home
echo "export PATH=$MAVEN_HOME/bin:$PATH" >> ~/.bashrc
else
# Do nothing if target installation directory already exists
echo "'$MAVEN_HOME' already exists, please uninstall existing maven first."
fi
You don't really need a sub-select:
SELECT a, COUNT(*) AS b,
SUM( CASE WHEN c = 'const' THEN 1 ELSE 0 END ) as d,
from t group by a order by b desc
Something like the following would get you closer
class Clazz
{
public static <U extends Clazz> void doIt(U thing)
{
}
}
EDIT: Updated example with more detail
public abstract class Thingo
{
public static <U extends Thingo> void doIt(U p_thingo)
{
p_thingo.thing();
}
protected abstract void thing();
}
class SubThingoOne extends Thingo
{
@Override
protected void thing()
{
System.out.println("SubThingoOne");
}
}
class SubThingoTwo extends Thingo
{
@Override
protected void thing()
{
System.out.println("SuThingoTwo");
}
}
public class ThingoTest
{
@Test
public void test()
{
Thingo t1 = new SubThingoOne();
Thingo t2 = new SubThingoTwo();
Thingo.doIt(t1);
Thingo.doIt(t2);
// compile error --> Thingo.doIt(new Object());
}
}
Add gesture on that view. Add an image into that view, and then it would be detecting a gesture on the image too. You could try with the delegate method of the touch event. Then in that case it also might be detecting.
Have you tried just
dictionary["cat"] = 5;
:)
Update
dictionary["cat"] = 5+2;
dictionary["cat"] = dictionary["cat"]+2;
dictionary["cat"] += 2;
Beware of non-existing keys :)
There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).
Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.
Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.
<select name="aa" onchange="report(this.value)">
<option value="">Please select</option>
<option value="daily">daily</option>
<option value="monthly">monthly</option>
</select>
using
function report(period) {
if (period=="") return; // please select - possibly you want something else here
const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
loadXMLDoc(report,'responseTag');
document.getElementById('responseTag').style.visibility='visible';
document.getElementById('list_report').style.visibility='hidden';
document.getElementById('formTag').style.visibility='hidden';
}
Unobtrusive version:
<select id="aa" name="aa">
<option value="">Please select</option>
<option value="daily">daily</option>
<option value="monthly">monthly</option>
</select>
using
window.addEventListener("load",function() {
document.getElementById("aa").addEventListener("change",function() {
const period = this.value;
if (period=="") return; // please select - possibly you want something else here
const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
loadXMLDoc(report,'responseTag');
document.getElementById('responseTag').style.visibility='visible';
document.getElementById('list_report').style.visibility='hidden';
document.getElementById('formTag').style.visibility='hidden';
});
});
jQuery version - same select with ID
$(function() {
$("#aa").on("change",function() {
const period = this.value;
if (period=="") return; // please select - possibly you want something else here
var report = "script/"+((period == "daily")?"d":"m")+"_report.php";
loadXMLDoc(report,'responseTag');
$('#responseTag').show();
$('#list_report').hide();
$('#formTag').hide();
});
});
When you say
enum {RANDOM, IMMEDIATE, SEARCH} strategy;
you create a single instance variable, called 'strategy' of a nameless enum. This is not a very useful thing to do - you need a typedef:
typedef enum {RANDOM, IMMEDIATE, SEARCH} StrategyType;
StrategyType strategy = IMMEDIATE;
List<Person> roster = ...;
Map<String, Person> map =
roster
.stream()
.collect(
Collectors.toMap(p -> p.getLast(), p -> p)
);
that would be the translation, but i havent run this or used the API. most likely you can substitute p -> p, for Function.identity(). and statically import toMap(...)
If you set the trunc flag.
#include<fstream>
using namespace std;
fstream ofs;
int main(){
ofs.open("test.txt", ios::out | ios::trunc);
ofs<<"Your content here";
ofs.close(); //Using microsoft incremental linker version 14
}
I tested this thouroughly for my own needs in a common programming situation I had. Definitely be sure to preform the ".close();" operation. If you don't do this there is no telling whether or not you you trunc or just app to the begging of the file. Depending on the file type you might just append over the file which depending on your needs may not fullfill its purpose. Be sure to call ".close();" explicity on the fstream you are trying to replace.
you can use jQuery to achieve this easily.
CSS
.left, .right {border:1px solid #cccccc;}
jQuery
$(document).ready(function() {
var leftHeight = $('.left').height();
$('.right').css({'height':leftHeight});
});
HTML
<div class="left">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi malesuada, lacus eu dapibus tempus, ante odio aliquet risus, ac ornare orci velit in sapien. Duis suscipit sapien vel nunc scelerisque in pretium velit mattis. Cras vitae odio sed eros mollis malesuada et eu nunc.</p>
</div>
<div class="right">
<p>Lorem ipsum dolor sit amet.</p>
</div>
You'll need to include jQuery
A solution using java.util.regex.Pattern / java.util.regex.Matcher
String test = "foo bar baz ";
Pattern pattern = Pattern.compile(" ");
Matcher matcher = pattern.matcher(test);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println(count);
Override all methods
@Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
}
@Override
public void onStartTrackingTouch(SeekBar arg0) {
}
@Override
public void onStopTrackingTouch(SeekBar arg0) {
}
Simply changing HTTP to HTTPS solved this issue for me.
WRONG :
<script src="http://code.jquery.com/jquery-3.5.1.js"></script>
CORRECT :
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
I completely respect using Beautiful Soup to get rendered content, but it may not be the ideal package for acquiring the rendered content on a page.
I had a similar problem to get rendered content, or the visible content in a typical browser. In particular I had many perhaps atypical cases to work with such a simple example below. In this case the non displayable tag is nested in a style tag, and is not visible in many browsers that I have checked. Other variations exist such as defining a class tag setting display to none. Then using this class for the div.
<html>
<title> Title here</title>
<body>
lots of text here <p> <br>
<h1> even headings </h1>
<style type="text/css">
<div > this will not be visible </div>
</style>
</body>
</html>
One solution posted above is:
html = Utilities.ReadFile('simple.html')
soup = BeautifulSoup.BeautifulSoup(html)
texts = soup.findAll(text=True)
visible_texts = filter(visible, texts)
print(visible_texts)
[u'\n', u'\n', u'\n\n lots of text here ', u' ', u'\n', u' even headings ', u'\n', u' this will not be visible ', u'\n', u'\n']
This solution certainly has applications in many cases and does the job quite well generally but in the html posted above it retains the text that is not rendered. After searching SO a couple solutions came up here BeautifulSoup get_text does not strip all tags and JavaScript and here Rendered HTML to plain text using Python
I tried both these solutions: html2text and nltk.clean_html and was surprised by the timing results so thought they warranted an answer for posterity. Of course, the speeds highly depend on the contents of the data...
One answer here from @Helge was about using nltk of all things.
import nltk
%timeit nltk.clean_html(html)
was returning 153 us per loop
It worked really well to return a string with rendered html. This nltk module was faster than even html2text, though perhaps html2text is more robust.
betterHTML = html.decode(errors='ignore')
%timeit html2text.html2text(betterHTML)
%3.09 ms per loop
[^,;]+
You haven't specified the regex implementation you are using. Most of them have a Split
method that takes delimiters and split by them. You might want to use that one with a "normal" (without ^
) character class:
[,;]+
Here is a clean method I've discovered:
$myArray = [];
array_push($myArray, (object)[
'key1' => 'someValue',
'key2' => 'someValue2',
'key3' => 'someValue3',
]);
return $myArray;
If you are using eloquent model (by looking at your code, i think you are), you dont need to convert it into array. Just use it as object. Becaus elike Thomas Kim said, by default it is a Carbon instance
So it should be
$suborder['payment_date'] = $item->created_at->format('Y-m-d')
But if it is not then, you need convert it to Carbon object as Milan Maharjan answer
$createdAt = Carbon::parse($item['created_at']);
Ref - Refresh Expired JWT Example
Another alternative is that once the JWT has expired, the user/system will make a call to another url suppose /refreshtoken. Also along with this request the expired JWT should be passed. The Server will then return a new JWT which can be used by the user/system.
The classpath setting of the compiler plugin are two args. Changed it like this and it worked for me:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<compilerArgs>
<arg>-cp</arg>
<arg>${cp}:${basedir}/lib/bad.jar</arg>
</compilerArgs>
</configuration>
I used the gmavenplus-plugin to read the path and create the property 'cp':
<plugin>
<!--
Use Groovy to read classpath and store into
file named value of property <cpfile>
In second step use Groovy to read the contents of
the file into a new property named <cp>
In the compiler plugin this is used to create a
valid classpath
-->
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>1.12.0</version>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<!-- any version of Groovy \>= 1.5.0 should work here -->
<version>3.0.6</version>
<type>pom</type>
<scope>runtime</scope>
</dependency>
</dependencies>
<executions>
<execution>
<id>read-classpath</id>
<phase>validate</phase>
<goals>
<goal>execute</goal>
</goals>
</execution>
</executions>
<configuration>
<scripts>
<script><![CDATA[
def file = new File(project.properties.cpfile)
/* create a new property named 'cp'*/
project.properties.cp = file.getText()
println '<<< Retrieving classpath into new property named <cp> >>>'
println 'cp = ' + project.properties.cp
]]></script>
</scripts>
</configuration>
</plugin>
txtarea = new JTextArea();
txtarea.setRows(25);
txtarea.setColumns(25);
txtarea.setWrapStyleWord(true);
JScrollPane scroll = new JScrollPane (txtarea);
panel2.add(scroll); //Object of Jpanel
Above given lines automatically shows you both horizontal & vertical Scrollbars..
You shouldn't be calling .ToString()
.
As the error message clearly states, you're writing a conditional in which one half is an IHtmlString
and the other half is a string.
That doesn't make sense, since the compiler doesn't know what type the entire expression should be.
There is never a reason to call Html.Raw(...).ToString()
.
Html.Raw
returns an HtmlString
instance that wraps the original string.
The Razor page output knows not to escape HtmlString
instances.
However, calling HtmlString.ToString()
just returns the original string
value again; it doesn't accomplish anything.
There is no documented LEFT() function in Oracle. Find the full set here.
Probably what you have is a user-defined function. You can check that easily enough by querying the data dictionary:
select * from all_objects
where object_name = 'LEFT'
But there is the question of why the stored procedure works and the query doesn't. One possible solution is that the stored procedure is owned by another schema, which also owns the LEFT() function. They have granted rights on the procedure but not its dependencies. This works because stored procedures run with DEFINER privileges by default, so you run the stored procedure as if you were its owner.
If this is so then the data dictionary query I listed above won't help you: it will only return rows for objects you have rights on. In which case you will need to run the query as the stored procedure's owner or connect as a user with the rights to query DBA_OBJECTS instead.
I am using this solution
public class ReceiverManager {
private WeakReference<Context> cReference;
private static List<BroadcastReceiver> receivers = new ArrayList<BroadcastReceiver>();
private static ReceiverManager ref;
private ReceiverManager(Context context) {
cReference = new WeakReference<>(context);
}
public static synchronized ReceiverManager init(Context context) {
if (ref == null) ref = new ReceiverManager(context);
return ref;
}
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter intentFilter) {
receivers.add(receiver);
Intent intent = cReference.get().registerReceiver(receiver, intentFilter);
Log.i(getClass().getSimpleName(), "registered receiver: " + receiver + " with filter: " + intentFilter);
Log.i(getClass().getSimpleName(), "receiver Intent: " + intent);
return intent;
}
public boolean isReceiverRegistered(BroadcastReceiver receiver) {
boolean registered = receivers.contains(receiver);
Log.i(getClass().getSimpleName(), "is receiver " + receiver + " registered? " + registered);
return registered;
}
public void unregisterReceiver(BroadcastReceiver receiver) {
if (isReceiverRegistered(receiver)) {
receivers.remove(receiver);
cReference.get().unregisterReceiver(receiver);
Log.i(getClass().getSimpleName(), "unregistered receiver: " + receiver);
}
}
}
_x000D_
There isn't really a way to do this without the css getting a little convoluted, but here's the cleanest solution I could put together (the breakpoints in this are just for example purposes, change them to whatever breakpoints you're actually using.) The key is :nth-of-type
(or :nth-child
-- either would work in this case.)
Smallest viewport:
@media (max-width:$smallest-breakpoint) {
.row div {
background: #eee;
}
.row div:nth-of-type(2n) {
background: #fff;
}
}
Medium viewport:
@media (min-width:$smallest-breakpoint) and (max-width:$mid-breakpoint) {
.row div {
background: #eee;
}
.row div:nth-of-type(4n+1), .row div:nth-of-type(4n+2) {
background: #fff;
}
}
Largest viewport:
@media (min-width:$mid-breakpoint) and (max-width:9999px) {
.row div {
background: #eee;
}
.row div:nth-of-type(6n+4),
.row div:nth-of-type(6n+5),
.row div:nth-of-type(6n+6) {
background: #fff;
}
}
Working fiddle here
byte[] strToByteArray(string str)
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
return enc.GetBytes(str);
}
Enter this line into Hive command line interface:
insert overwrite directory '/data/test' row format delimited fields terminated by '\t' stored as textfile select * from testViewQuery;
testViewQuery
- some specific view
Arrays are values... slices are more like pointers. That is [n]type
is not compatible with []type
as they are fundamentally two different things. You can get a slice that points to an array by using arr[:]
which returns a slice that has arr
as it's backing storage.
One way to convert a slice of for example []byte
to [20]byte
is to actually allocate a [20]byte
which you can do by using var [20]byte
(as it's a value... no make
needed) and then copy data into it:
buf := make([]byte, 10)
var arr [10]byte
copy(arr[:], buf)
Essentially what a lot of other answers get wrong is that []type
is NOT an array.
[n]T
and []T
are completely different things!
When using reflect []T
is not of kind Array but of kind Slice and [n]T
is of kind Array.
You also can't use map[[]byte]T
but you can use map[[n]byte]T
.
This can sometimes be cumbersome because a lot of functions operate for example on []byte
whereas some functions return [n]byte
(most notably the hash functions in crypto/*
).
A sha256 hash for example is [32]byte
and not []byte
so when beginners try to write it to a file for example:
sum := sha256.Sum256(data)
w.Write(sum)
they will get an error. The correct way of is to use
w.Write(sum[:])
However, what is it that you want? Just accessing the string bytewise? You can easily convert a string
to []byte
using:
bytes := []byte(str)
but this isn't an array, it's a slice. Also, byte
!= rune
. In case you want to operate on "characters" you need to use rune
... not byte
.
This worked for me on Kali-linux 2018 :
apt-get install php7.0-mbstring
service apache2 restart
In C/C++, pointers and arrays are (almost) equivalent.
int *a; a[0];
will return *a
, and a[1];
will return *(a + 1)
But array can't change the pointer it points to while pointer can.
new int[n]
will allocate some spaces for the "array"
Well, you can do it like so:
(function() {
var localByaka;
Object.defineProperty(window, 'Byaka', {
get: function() {
return localByaka;
},
set: function(val) {
localByaka = window.Byaka || val;
}
});
}());
window.Byaka = "foo"; //set constant
window.Byaka = "bar"; // try resetting it for shits and giggles
window.Byaka; // will allways return foo!
If you do this as above in global scope this will be a true constant, because you cannot overwrite the window object.
I've created a library to create constants and immutable objects in javascript. Its still version 0.2 but it does the trick nicely. http://beckafly.github.io/insulatejs
The problem could be that we need to specifically give adb root access in the developnent options in the latest CMs.. Here is what i did.
abc@abc-L655:~$ sudo adb kill-server
abc@abc-L655:~$ sudo adb root start-server * daemon not running. starting it now on port 5037 * * daemon started successfully * root access is disabled by system setting - enable in settings -> development options
after altering the development options...
abc@abc-L655:~$ sudo adb kill-server
abc@abc-L655:~$ sudo adb root start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
restarting adbd as root
abc@abc-L655:~$ adb shell
root@android:/ # ls /data/ .... good to go..
A complete example which leaves the fields as NULL-terminated strings in the original input buffer and provides access to them via an array of char pointers. The CSV processor has been confirmed to work with fields enclosed in "double quotes", ignoring any delimiter chars within them.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// adjust BUFFER_SIZE to suit longest line
#define BUFFER_SIZE 1024 * 1024
#define NUM_FIELDS 10
#define MAXERRS 5
#define RET_OK 0
#define RET_FAIL 1
#define FALSE 0
#define TRUE 1
// char* array will point to fields
char *pFields[NUM_FIELDS];
// field offsets into pFields array:
#define LP 0
#define IMIE 1
#define NAZWISKo 2
#define ULICA 3
#define NUMER 4
#define KOD 5
#define MIEJSCOw 6
#define TELEFON 7
#define EMAIL 8
#define DATA_UR 9
long loadFile(FILE *pFile, long *errcount);
static int loadValues(char *line, long lineno);
static char delim;
long loadFile(FILE *pFile, long *errcount){
char sInputBuf [BUFFER_SIZE];
long lineno = 0L;
if(pFile == NULL)
return RET_FAIL;
while (!feof(pFile)) {
// load line into static buffer
if(fgets(sInputBuf, BUFFER_SIZE-1, pFile)==NULL)
break;
// skip first line (headers)
if(++lineno==1)
continue;
// jump over empty lines
if(strlen(sInputBuf)==0)
continue;
// set pFields array pointers to null-terminated string fields in sInputBuf
if(loadValues(sInputBuf,lineno)==RET_FAIL){
(*errcount)++;
if(*errcount > MAXERRS)
break;
} else {
// On return pFields array pointers point to loaded fields ready for load into DB or whatever
// Fields can be accessed via pFields, e.g.
printf("lp=%s, imie=%s, data_ur=%s\n", pFields[LP], pFields[IMIE], pFields[DATA_UR]);
}
}
return lineno;
}
static int loadValues(char *line, long lineno){
if(line == NULL)
return RET_FAIL;
// chop of last char of input if it is a CR or LF (e.g.Windows file loading in Unix env.)
// can be removed if sure fgets has removed both CR and LF from end of line
if(*(line + strlen(line)-1) == '\r' || *(line + strlen(line)-1) == '\n')
*(line + strlen(line)-1) = '\0';
if(*(line + strlen(line)-1) == '\r' || *(line + strlen(line)-1 )== '\n')
*(line + strlen(line)-1) = '\0';
char *cptr = line;
int fld = 0;
int inquote = FALSE;
char ch;
pFields[fld]=cptr;
while((ch=*cptr) != '\0' && fld < NUM_FIELDS){
if(ch == '"') {
if(! inquote)
pFields[fld]=cptr+1;
else {
*cptr = '\0'; // zero out " and jump over it
}
inquote = ! inquote;
} else if(ch == delim && ! inquote){
*cptr = '\0'; // end of field, null terminate it
pFields[++fld]=cptr+1;
}
cptr++;
}
if(fld > NUM_FIELDS-1){
fprintf(stderr, "Expected field count (%d) exceeded on line %ld\n", NUM_FIELDS, lineno);
return RET_FAIL;
} else if (fld < NUM_FIELDS-1){
fprintf(stderr, "Expected field count (%d) not reached on line %ld\n", NUM_FIELDS, lineno);
return RET_FAIL;
}
return RET_OK;
}
int main(int argc, char **argv)
{
FILE *fp;
long errcount = 0L;
long lines = 0L;
if(argc!=3){
printf("Usage: %s csvfilepath delimiter\n", basename(argv[0]));
return (RET_FAIL);
}
if((delim=argv[2][0])=='\0'){
fprintf(stderr,"delimiter must be specified\n");
return (RET_FAIL);
}
fp = fopen(argv[1] , "r");
if(fp == NULL) {
fprintf(stderr,"Error opening file: %d\n",errno);
return(RET_FAIL);
}
lines=loadFile(fp,&errcount);
fclose(fp);
printf("Processed %ld lines, encountered %ld error(s)\n", lines, errcount);
if(errcount>0)
return(RET_FAIL);
return(RET_OK);
}
For an ES6 implementation, use something like the following:
const millisToMinutesAndSeconds = (millis) => {
const minutes = Math.floor(millis / 60000);
const seconds = ((millis % 60000) / 1000).toFixed(0);
return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
}
Use:
create table new_table_name
as
select column_name,[more columns] from Existed_table;
Example:
create table dept
as
select empno, ename from emp;
If the table already exists:
insert into new_tablename select columns_list from Existed_table;
I had a requirement to provide a report showing details by month where the date field was formatted as date & time, I simply changed the formatting of the date column to "General" and then used the following formula in a new column,
=CONCATENATE(YEAR(C2),MONTH(C2))
Did you try the python script by Bryan Maupin found here ? (I've modified it a little bit to be more generic)
#!/usr/bin/env python
import sys
input_file_name = sys.argv[1]
output_file_name = sys.argv[2]
input_file = open(input_file_name)
output_file = open(output_file_name, 'w')
line_number = 0
for input_line in input_file:
line_number += 1
try: # first try to decode it using cp1252 (Windows, Western Europe)
output_line = input_line.decode('cp1252').encode('utf8')
except UnicodeDecodeError, error: # if there's an error
sys.stderr.write('ERROR (line %s):\t%s\n' % (line_number, error)) # write to stderr
try: # then if that fails, try to decode using latin1 (ISO 8859-1)
output_line = input_line.decode('latin1').encode('utf8')
except UnicodeDecodeError, error: # if there's an error
sys.stderr.write('ERROR (line %s):\t%s\n' % (line_number, error)) # write to stderr
sys.exit(1) # and just keep going
output_file.write(output_line)
input_file.close()
output_file.close()
You can use that script with
$ ./cp1252_utf8.py file_cp1252.sql file_utf8.sql
Question 3: Can you offer me some hints how to optimize these implementations without changing the way I determine the factors? Optimization in any way: nicer, faster, more "native" to the language.
The C implementation is suboptimal (as hinted at by Thomas M. DuBuisson), the version uses 64-bit integers (i.e. long datatype). I'll investigate the assembly listing later, but with an educated guess, there are some memory accesses going on in the compiled code, which make using 64-bit integers significantly slower. It's that or generated code (be it the fact that you can fit less 64-bit ints in a SSE register or round a double to a 64-bit integer is slower).
Here is the modified code (simply replace long with int and I explicitly inlined factorCount, although I do not think that this is necessary with gcc -O3):
#include <stdio.h>
#include <math.h>
static inline int factorCount(int n)
{
double square = sqrt (n);
int isquare = (int)square;
int count = isquare == square ? -1 : 0;
int candidate;
for (candidate = 1; candidate <= isquare; candidate ++)
if (0 == n % candidate) count += 2;
return count;
}
int main ()
{
int triangle = 1;
int index = 1;
while (factorCount (triangle) < 1001)
{
index++;
triangle += index;
}
printf ("%d\n", triangle);
}
Running + timing it gives:
$ gcc -O3 -lm -o euler12 euler12.c; time ./euler12
842161320
./euler12 2.95s user 0.00s system 99% cpu 2.956 total
For reference, the haskell implementation by Thomas in the earlier answer gives:
$ ghc -O2 -fllvm -fforce-recomp euler12.hs; time ./euler12 [9:40]
[1 of 1] Compiling Main ( euler12.hs, euler12.o )
Linking euler12 ...
842161320
./euler12 9.43s user 0.13s system 99% cpu 9.602 total
Conclusion: Taking nothing away from ghc, its a great compiler, but gcc normally generates faster code.
Using collections.defaultdict
is a big time-saver when you're building dicts and don't know beforehand which keys you're going to have.
Here it's used twice: for the resulting dict, and for each of the values in the dict.
import collections
def aggregate_names(errors):
result = collections.defaultdict(lambda: collections.defaultdict(list))
for real_name, false_name, location in errors:
result[real_name][false_name].append(location)
return result
Combining this with your code:
dictionary = aggregate_names(previousFunction(string))
Or to test:
EXAMPLES = [
('Fred', 'Frad', 123),
('Jim', 'Jam', 100),
('Fred', 'Frod', 200),
('Fred', 'Frad', 300)]
print aggregate_names(EXAMPLES)
There are two general approaches here:
nan
and take any
.nan
s (like sum
) and check its result.While the first approach is certainly the cleanest, the heavy optimization of some of the cumulative operations (particularly the ones that are executed in BLAS, like dot
) can make those quite fast. Note that dot
, like some other BLAS operations, are multithreaded under certain conditions. This explains the difference in speed between different machines.
import numpy
import perfplot
def min(a):
return numpy.isnan(numpy.min(a))
def sum(a):
return numpy.isnan(numpy.sum(a))
def dot(a):
return numpy.isnan(numpy.dot(a, a))
def any(a):
return numpy.any(numpy.isnan(a))
def einsum(a):
return numpy.isnan(numpy.einsum("i->", a))
perfplot.show(
setup=lambda n: numpy.random.rand(n),
kernels=[min, sum, dot, any, einsum],
n_range=[2 ** k for k in range(20)],
logx=True,
logy=True,
xlabel="len(a)",
)
use test1
insert into employee(deptid) select deptid from test2.dbo.employee
Since you're already using Google's Json-Simple
library, you can parse the json from an InputStream
like this:
InputStream inputStream = ... //Read from a file, or a HttpRequest, or whatever.
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject)jsonParser.parse(
new InputStreamReader(inputStream, "UTF-8"));
If you're using Android Studio you can:
You will see a list of all Languages and if you choose them you will see Specific Regions for each. You can also type in the list to filter languages.
In the list of arguments, each entry must be on its own. Using
output = subprocess.check_output(["ping", "-c","2", "-W","2", "1.1.1.1"])
should fix your problem.
in a Visual Basic Macro you would use
pName = ActiveWorkbook.Path ' the path of the currently active file
wbName = ActiveWorkbook.Name ' the file name of the currently active file
shtName = ActiveSheet.Name ' the name of the currently selected worksheet
The first sheet in a workbook can be referenced by
ActiveWorkbook.Worksheets(1)
so after deleting the [Report] tab you would use
ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name
to "work on that sheet later on" you can create a range object like
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]
and continue working on MySheet(rowNum, colNum)
etc. ...
shortcut creation of a range object without defining shtName:
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]
Array.indexOf
doesnt work in some versions of internet explorer - there are lots of alternative ways of doing it though ... see this question / answer : How do I check if an array includes an object in JavaScript?
Use
following methods to switch to modelframe
driver.switchTo().frame("ModelFrameTitle");
or
driver.switchTo().activeElement()
Hope this will work
Your modifications are in a different branch than the original branch, which simplifies stuff because you get updates in one branch, and your work is in another branch.
Assuming the original branch is named master
, which the case in 99% of git repos, you have to fetch the state of origin, and merge origin/master
updates into your local master
:
git fetch origin
git checkout master
git merge origin/master
To switch to your branch, just do
git checkout branch1
For future Google'rs that use Laravel 5, you can now also use it with includes,
@include('views.otherView', ['variable' => 1])
try this. ^[0-9]\d{0,9}(\.\d{1,3})?%?$
it is tested and worked for me.
Do you really want the result to come up in an input box? If not, consider a table with borders set to other than transparent and use
document.getElementById('sum').innerHTML = sum;
var myobj = {"A":["Abe"], "B":["Bob"]};
var keysArray = Object.keys(myobj);
var valuesArray = Object.keys(myobj).map(function(k) {
return String(myobj[k]);
});
var mydata = valuesArray[keysArray.indexOf("A")]; // Abe
You can use a CompletionService to receive the futures as soon as they are ready and if one of them throws an exception cancel the processing. Something like this:
Executor executor = Executors.newFixedThreadPool(4);
CompletionService<SomeResult> completionService =
new ExecutorCompletionService<SomeResult>(executor);
//4 tasks
for(int i = 0; i < 4; i++) {
completionService.submit(new Callable<SomeResult>() {
public SomeResult call() {
...
return result;
}
});
}
int received = 0;
boolean errors = false;
while(received < 4 && !errors) {
Future<SomeResult> resultFuture = completionService.take(); //blocks if none available
try {
SomeResult result = resultFuture.get();
received ++;
... // do something with the result
}
catch(Exception e) {
//log
errors = true;
}
}
I think you can further improve to cancel any still executing tasks if one of them throws an error.
Vertex *f=(findvertex(from));
if(!f) {
cerr << "vertex not found" << endl;
exit(1) // or return;
}
Because findVertex
can return NULL
if it can't find the vertex.
Otherwise this f->adj;
is trying to do
NULL->adj;
Which causes access violation.
I like the explanation From EdX (Microsoft: DEV210x Introduction to C++) for a similar problem:
"The enum represents the literal values of days as integers. Referring to the numeric types table, you see that an int takes 4 bytes of memory. 7 days x 4 bytes each would require 28 bytes of memory if the entire enum were stored but the compiler only uses a single element of the enum, therefore the size in memory is actually 4 bytes."
This solution works fine for all major browsers, except IE. So keep that in mind.
In this example, basicaly I use positioning, horizontal and vertical transform for the UI element to center it.
.container {_x000D_
/* set the the position to relative */_x000D_
position: relative;_x000D_
width: 30rem;_x000D_
height: 20rem;_x000D_
background-color: #2196F3;_x000D_
}_x000D_
_x000D_
_x000D_
.paragh {_x000D_
/* set the the position to absolute */_x000D_
position: absolute;_x000D_
/* set the the position of the helper container into the middle of its space */_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
font-size: 30px;_x000D_
/* make sure padding and margin do not disturb the calculation of the center point */_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
/* using centers for the transform */_x000D_
transform-origin: center center;_x000D_
/* calling calc() function for the calculation to move left and up the element from the center point */_x000D_
transform: translateX(calc((100% / 2) * (-1))) translateY(calc((100% / 2) * (-1)));_x000D_
}
_x000D_
<div class="container">_x000D_
<p class="paragh">Text</p>_x000D_
</div>
_x000D_
I hope this help.
The discussion I had with Asaph may be unclear to follow as we went back and forth quite a bit.
I thought that I might clarify the upshot of our discourse for others who might face similar situations in the future to benefit from:
ENUM
-type columns are very difficult beasts to manipulate. I wanted to add two countries (Malaysia & Sweden) to the existing set of countries in my ENUM.
It seems that MySQL 5.1 (which is what I am running) can only update the ENUM by redefining the existing set in addition to what I want:
This did not work:
ALTER TABLE carmake CHANGE country country ENUM('Sweden','Malaysia') DEFAULT NULL;
The reason was that the MySQL statement was replacing the existing ENUM with another containing the entries 'Malaysia'
and 'Sweden'
only. MySQL threw up an error because the carmake
table already had values like 'England'
and 'USA'
which were not part of the new ENUM
's definition.
Surprisingly, the following did not work either:
ALTER TABLE carmake CHANGE country country ENUM('Australia','England','USA'...'Sweden','Malaysia') DEFAULT NULL;
It turns out that even the order of elements of the existing ENUM
needs to be preserved while adding new members to it. So if my existing ENUM
looks something like ENUM('England','USA')
, then my new ENUM
has to be defined as ENUM('England','USA','Sweden','Malaysia')
and not ENUM('USA','England','Sweden','Malaysia')
. This problem only becomes manifest when there are records in the existing table that use 'USA'
or 'England'
values.
BOTTOM LINE:
Only use ENUM
s when you do not expect your set of members to change once defined. Otherwise, lookup tables are much easier to update and modify.
Use a "Here-String" and cast to XML.
[xml]$myxml = @"
<stuff>
<item name="Joe" age="32">
<info>something about him</info>
</item>
<item name="Sue" age="29">
<info>something about her</info>
</item>
<item name="Cat" age="12">
<info>something else</info>
</item>
</stuff>
"@
[array]$myitems = $myxml.stuff.Item
$myitems
You can avoid making a copy of the object using Wen's solution and inplace=True:
df.fillna({'a':0, 'b':0}, inplace=True)
print(df)
Which yields:
a b c
0 1.0 4.0 NaN
1 2.0 5.0 NaN
2 3.0 0.0 7.0
3 0.0 6.0 8.0