You should definitely have a look at this answer of mine:
and also have a look at all the links included therein.
Tabula/TabulaPDF is currently the best table extraction tool that is available for PDF scraping.
pyPDF works fine (assuming that you're working with well-formed PDFs). If all you want is the text (with spaces), you can just do:
import pyPdf
pdf = pyPdf.PdfFileReader(open(filename, "rb"))
for page in pdf.pages:
print page.extractText()
You can also easily get access to the metadata, image data, and so forth.
A comment in the extractText code notes:
Locate all text drawing commands, in the order they are provided in the content stream, and extract the text. This works well for some PDF files, but poorly for others, depending on the generator used. This will be refined in the future. Do not rely on the order of text coming out of this function, as it will change if this function is made more sophisticated.
Whether or not this is a problem depends on what you're doing with the text (e.g. if the order doesn't matter, it's fine, or if the generator adds text to the stream in the order it will be displayed, it's fine). I have pyPdf extraction code in daily use, without any problems.
How i do mine is pretty much as above ill show you my code and how to use it with a MYSSQL DB...
Document table in DB -
int Id ( PK ), string Url, string Description, CreatedBy, TenancyId DateUploaded
The above code ID, being the Primary key, URL being the name of the file ( with file type on the end ), file description to ouput on documents view, CreatedBy being who uploaded the file, tenancyId, dateUploaded
inside the view you must define the enctype or it will not work correctly.
@using (Html.BeginForm("Upload", "Document", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="input-group">
<label for="file">Upload a document:</label>
<input type="file" name="file" id="file" />
</div>
}
The above code will give you the browse button, then inside my project I have a class basically called IsValidImage which just checks the filesize is under your specified max size, checks if its an IMG file, this is all in a class bool function. So if true returns true.
public static bool IsValidImage(HttpPostedFileBase file, double maxFileSize, ModelState ms )
{
// make sur the file isnt null.
if( file == null )
return false;
// the param I normally set maxFileSize is 10MB 10 * 1024 * 1024 = 10485760 bytes converted is 10mb
var max = maxFileSize * 1024 * 1024;
// check if the filesize is above our defined MAX size.
if( file.ContentLength > max )
return false;
try
{
// define our allowed image formats
var allowedFormats = new[] { ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif, ImageFormat.Bmp };
// Creates an Image from the specified data stream.
using (var img = Image.FromStream(file.InputStream))
{
// Return true if the image format is allowed
return allowedFormats.Contains(img.RawFormat);
}
}
catch( Exception ex )
{
ms.AddModelError( "", ex.Message );
}
return false;
}
So in the controller:
if (!Code.Picture.IsValidUpload(model.File, 10, true))
{
return View(model);
}
// Set the file name up... Being random guid, and then todays time in ticks. Then add the file extension
// to the end of the file name
var dbPath = Guid.NewGuid().ToString() + DateTime.UtcNow.Ticks + Path.GetExtension(model.File.FileName);
// Combine the two paths together being the location on the server to store it
// then the actual file name and extension.
var path = Path.Combine(Server.MapPath("~/Uploads/Documents/"), dbPath);
// set variable as Parent directory I do this to make sure the path exists if not
// I will create the directory.
var directoryInfo = new FileInfo(path).Directory;
if (directoryInfo != null)
directoryInfo.Create();
// save the document in the combined path.
model.File.SaveAs(path);
// then add the data to the database
_db.Documents.Add(new Document
{
TenancyId = model.SelectedTenancy,
FileUrl = dbPath,
FileDescription = model.Description,
CreatedBy = loggedInAs,
CreatedDate = DateTime.UtcNow,
UpdatedDate = null,
CanTenantView = true
});
_db.SaveChanges();
model.Successfull = true;
In my case, this was the output:
LANGUAGE = (unset),
LC_ALL = (unset),
LC_PAPER = "ro_RO.UTF-8",
LC_ADDRESS = "ro_RO.UTF-8",
....
The solution was:
sudo locale-gen ro_RO.UTF-8
https://www.postgresql.org/docs/8.4/functions-formatting.html
SELECT to_char(date_field, 'DD/MM/YYYY')
FROM table
When Spring loads your bean definitions, and has been configured to look for @Transactional
annotations, it will create these proxy objects around your actual bean. These proxy objects are instances of classes that are auto-generated at runtime. The default behaviour of these proxy objects when a method is invoked is just to invoke the same method on the "target" bean (i.e. your bean).
However, the proxies can also be supplied with interceptors, and when present these interceptors will be invoked by the proxy before it invokes your target bean's method. For target beans annotated with @Transactional
, Spring will create a TransactionInterceptor
, and pass it to the generated proxy object. So when you call the method from client code, you're calling the method on the proxy object, which first invokes the TransactionInterceptor
(which begins a transaction), which in turn invokes the method on your target bean. When the invocation finishes, the TransactionInterceptor
commits/rolls back the transaction. It's transparent to the client code.
As for the "external method" thing, if your bean invokes one of its own methods, then it will not be doing so via the proxy. Remember, Spring wraps your bean in the proxy, your bean has no knowledge of it. Only calls from "outside" your bean go through the proxy.
Does that help?
array[index] == 'undefined'
compares the value of the array index to the string "undefined".
You're probably looking for typeof array[index] == 'undefined'
, which compares the type.
This is a CORS issue. There are some settings you can change in angular - these are the ones I typically set in the Angular .config method (not all are related to CORS):
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.withCredentials = true;
delete $httpProvider.defaults.headers.common["X-Requested-With"];
$httpProvider.defaults.headers.common["Accept"] = "application/json";
$httpProvider.defaults.headers.common["Content-Type"] = "application/json";
You also need to configure your webservice - the details of this will depend on the server side language you are using. If you use a network monitoring tool you will see it sends an OPTIONS request initially. Your server needs to respond appropriately to allow the CORS request.
The reason it works in your brower is because it isn't make a cross-origin request - whereas your Angular code is.
Adding to the other excellent posts.
Sometimes you don't want to specify the number of arguments and want to use keys for them (the compiler will complain if one argument passed in a dictionary is not used in the method).
def manyArgs1(args):
print args.a, args.b #note args.c is not used here
def manyArgs2(args):
print args.c #note args.b and .c are not used here
class Args: pass
args = Args()
args.a = 1
args.b = 2
args.c = 3
manyArgs1(args) #outputs 1 2
manyArgs2(args) #outputs 3
Then you can do things like
myfuns = [manyArgs1, manyArgs2]
for fun in myfuns:
fun(args)
Here's a more concrete example of how to access GET parameters. The Request
object has a method that parses them out for you called Query:
Assuming a request URL like http://host:port/something?param1=b
func newHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("GET params were:", r.URL.Query())
// if only one expected
param1 := r.URL.Query().Get("param1")
if param1 != "" {
// ... process it, will be the first (only) if multiple were given
// note: if they pass in like ?param1=¶m2= param1 will also be "" :|
}
// if multiples possible, or to process empty values like param1 in
// ?param1=¶m2=something
param1s := r.URL.Query()["param1"]
if len(param1s) > 0 {
// ... process them ... or you could just iterate over them without a check
// this way you can also tell if they passed in the parameter as the empty string
// it will be an element of the array that is the empty string
}
}
Also note "the keys in a Values map [i.e. Query() return value] are case-sensitive."
$( "#sortable" ).sortable({
change: function(event, ui) {
var pos = ui.helper.index() < ui.placeholder.index()
? { start: ui.helper.index(), end: ui.placeholder.index() }
: { start: ui.placeholder.index(), end: ui.helper.index() }
$(this)
.children().removeClass( 'highlight' )
.not( ui.helper ).slice( pos.start, pos.end ).addClass( 'highlight' );
},
stop: function(event, ui) {
$(this).children().removeClass( 'highlight' );
}
});
An example of how it could be done inside change event without storing arbitrary data into element storage. Since the element where drag starts is ui.helper
, and the element of current position is ui.placeholder
, we can take the elements between those two indexes and highlight them. Also, we can use this
inside handler since it refers to the element that the widget is attached. The example works with dragging in both directions.
This is what I came up with. Here is a fiddle.
First, I need three wrapper elements for both a square shape and centered text.
<div><div><div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit,
sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat
volutpat.</div></div></div>
This is the stylecheet. It makes use of two techniques, one for square shapes and one for centered text.
body > div {
position:relative;
height:0;
width:50%; padding-bottom:50%;
}
body > div > div {
position:absolute; top:0;
height:100%; width:100%;
display:table;
border:1px solid #000;
margin:1em;
}
body > div > div > div{
display:table-cell;
vertical-align:middle; text-align:center;
padding:1em;
}
$ git branch --set-upstream-to=heroku/master master
and
$ git pull
worked for me!
Actually whether there are digits or not is irrelevant. The . (dot) is forbidden if you want to cast to int. Dot can't - logically - be part of Integer definition, so even:
select cast ('7.0' as int)
select cast ('7.' as int)
will fail but both are fine for floats.
Add this at the start of main
ApplicationContext context = new ClassPathXmlApplicationContext("path/to/applicationContext.xml");
JobLauncher launcher=(JobLauncher)context.getBean("launcher");
Job job=(Job)context.getBean("job");
//Get as many beans you want
//Now do the thing you were doing inside test method
StopWatch sw = new StopWatch();
sw.start();
launcher.run(job, jobParameters);
sw.stop();
//initialize the log same way inside main
logger.info(">>> TIME ELAPSED:" + sw.prettyPrint());
I am using rails 6 and Model.all(:order 'columnName DESC') is not working. I have found the correct answer in OrderInRails
This is very simple.
@variable=Model.order('columnName DESC')
You need upper case property names in your structs in order to be used by the json packages.
Upper case property names are exported properties
. Lower case property names are not exported.
You also need to pass the your data object by reference (&data
).
package main
import "os"
import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"
type tracks struct {
Toptracks []toptracks_info
}
type toptracks_info struct {
Track []track_info
Attr []attr_info
}
type track_info struct {
Name string
Duration string
Listeners string
Mbid string
Url string
Streamable []streamable_info
Artist []artist_info
Attr []track_attr_info
}
type attr_info struct {
Country string
Page string
PerPage string
TotalPages string
Total string
}
type streamable_info struct {
Text string
Fulltrack string
}
type artist_info struct {
Name string
Mbid string
Url string
}
type track_attr_info struct {
Rank string
}
func get_content() {
// json data
url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
res, err := http.Get(url)
if err != nil {
panic(err.Error())
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err.Error())
}
var data tracks
json.Unmarshal(body, &data)
fmt.Printf("Results: %v\n", data)
os.Exit(0)
}
func main() {
get_content()
}
(//*[@attribute='value'])[index] to find target of element while your finding multiple matches in it
Can be browser related. If you are using IE, you can go to Advanced Settings and check you the "Enable Windows Integrated Authentication" checkbox is checked.
This the most recent way to do this, the above answer is outdated:
typings install --global es6-promise
If s
is your string than you could do it this way:
Mid(s, index, 1)
Edit based on comment below question.
It seems that you need a bit different approach which should be easier. Try in this way:
Dim character As String 'Integer if for numbers
's = ActiveDocument.Content.Text - we don't need it
character = Activedocument.Characters(index)
I had a similar problem after starting a new IntelliJ project. I found that the "module compile output path" for my module was not properly specified. When I assigned the path in the module's "compile output path" to the proper location, the problem was solved. The compile output path is assigned in the Project settings. Under Modules, select the module involved and select the Paths tab...
Paths tab in the Project Settings | Modules dialog
...I sent the compiler output to a folder named "output" that is present in the parent Project folder.
You can have multiple CTE
s in one query, as well as reuse a CTE
:
WITH cte1 AS
(
SELECT 1 AS id
),
cte2 AS
(
SELECT 2 AS id
)
SELECT *
FROM cte1
UNION ALL
SELECT *
FROM cte2
UNION ALL
SELECT *
FROM cte1
Note, however, that SQL Server
may reevaluate the CTE
each time it is accessed, so if you are using values like RAND()
, NEWID()
etc., they may change between the CTE
calls.
Assuming C++11, here is a one-liner loop body, if this is consistent with your programming style:
using Map = std::map<K,V>;
Map map;
// Erase members that satisfy needs_removing(itr)
for (Map::const_iterator itr = map.cbegin() ; itr != map.cend() ; )
itr = needs_removing(itr) ? map.erase(itr) : std::next(itr);
A couple of other minor style changes:
Map::const_iterator
) when possible/convenient, over using auto
.using
for template types, to make ancillary types (Map::const_iterator
) easier to read/maintain.Addition and subtraction in two's complement is the same for signed and unsigned numbers
The key observation is that CMP is basically subtraction, and:
In two's complement (integer representation used by x86), signed and unsigned addition are exactly the same operation
This allows for example hardware developers to implement it more efficiently with just one circuit.
So when you give input bytes to the x86 ADD instruction for example, it does not care if they are signed or not.
However, ADD does set a few flags depending on what happened during the operation:
carry: unsigned addition or subtraction result does not fit in bit size, e.g.: 0xFF + 0x01 or 0x00 - 0x01
For addition, we would need to carry 1 to the next level.
sign: result has top bit set. I.e.: is negative if interpreted as signed.
overflow: input top bits are both 0 and 0 or 1 and 1 and output inverted is the opposite.
I.e. signed operation changed sigedness in an impossible way (e.g. positive + positive or negative
We can then interpret those flags in a way that makes comparison match our expectations for signed or unsigned numbers.
This interpretation is exactly what JA vs JG and JB vs JL do for us!
Code example
Here is GNU GAS a code snippet to make this more concrete:
/* 0x0 ==
*
* * 0 in 2's complement signed
* * 0 in 2's complement unsigned
*/
mov $0, %al
/* 0xFF ==
*
* * -1 in 2's complement signed
* * 255 in 2's complement unsigned
*/
mov $0xFF, %bl
/* Do the operation "Is al < bl?" */
cmp %bl, %al
Note that AT&T syntax is "backwards": mov src, dst
. So you have to mentally reverse the operands for the condition codes to make sense with cmp
. In Intel syntax, this would be cmp al, bl
After this point, the following jumps would be taken:
Note how in this particular example the signedness mattered, e.g. JB is taken but not JL.
Runnable example with assertions.
Equals / Negated versions like JLE / JNG are just aliases
By looking at the Intel 64 and IA-32 Architectures Software Developer's Manuals Volume 2 section "Jcc - Jump if Condition Is Met" we see that the encodings are identical, for example:
Opcode Instruction Description
7E cb JLE rel8 Jump short if less or equal (ZF=1 or SF ? OF).
7E cb JNG rel8 Jump short if not greater (ZF=1 or SF ? OF).
To know where Python is installed you can execute where python
in your cmd.exe.
There are a number of Atom packages which give you access to the terminal from within Atom. Try a few out to find the best option for you.
Some recommendations which work in Ubuntu (with their primary keyboard shortcuts):
Edit: recommended plugin changed as terminal-plus
is no longer maintained. Thanks for the head's-up, @MorganRodgers.
If you want to open a terminal panel in Atom, try atom-ide-terminal
. Use the keyboard shortcut ctrl-`
to open a new terminal instance.
If you just want a shortcut to open your external terminal from within Atom, try atom-terminal
(this is what I use). You can use ctrl-shift-t
to open your external terminal in the current file's directory, or alt-shift-t
to open the terminal in the project's root directory.
To pass the parameter you need to use resolve and inject the items in controller
$scope.Edit = function (Id) {
var modalInstance = $modal.open({
templateUrl: '/app/views/admin/addeditphone.html',
controller: 'EditCtrl',
resolve: {
editId: function () {
return Id;
}
}
});
}
Now if you will use like this:
app.controller('EditCtrl', ['$scope', '$location'
, function ($scope, $location, editId)
in this case editId will be undefined. You need to inject it, like this:
app.controller('EditCtrl', ['$scope', '$location', 'editId'
, function ($scope, $location, editId)
Now it will work smooth, I face the same problem many time, once injected, everything start working!
You will also receive this error if you are passing an object back to the client that contains a property of type enum that is not set by default and that enum does not have a value that maps to 0. i.e enum MyEnum{ a=1, b=2};
Add padding. Padding the element will increase the space between its content and its border. However, note that a box-shadow will begin outside the border, not the content, meaning you can't put space between the shadow and the box. Alternatively you could use :before or :after pseudo selectors on the element to create a slightly bigger box that you place the shadow on, like so: http://jsbin.com/aqemew/edit#source
A Linq one-liner for converting a byte array byteArrFilename
read from a file to a pure ascii C-style zero-terminated string would be this: Handy for reading things like file index tables in old archive formats.
String filename = new String(byteArrFilename.TakeWhile(x => x != 0)
.Select(x => x < 128 ? (Char)x : '?').ToArray());
I use '?'
as default char for anything not pure ascii here, but that can be changed, of course. If you want to be sure you can detect it, just use '\0'
instead, since the TakeWhile
at the start ensures that a string built this way cannot possibly contain '\0'
values from the input source.
$input = "Test me more"; echo preg_replace("/\s.*$/","",$input); // "Test"
Reversing a ArrayList in a recursive way and without creating a new list for adding elements :
public class ListUtil {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
System.out.println("Reverse Order: " + reverse(arrayList));
}
public static <T> List<T> reverse(List<T> arrayList) {
return reverse(arrayList,0,arrayList.size()-1);
}
public static <T> List<T> reverse(List<T> arrayList,int startIndex,int lastIndex) {
if(startIndex<lastIndex) {
T t=arrayList.get(lastIndex);
arrayList.set(lastIndex,arrayList.get(startIndex));
arrayList.set(startIndex,t);
startIndex++;
lastIndex--;
reverse(arrayList,startIndex,lastIndex);
}
return arrayList;
}
}
Berkelium is a C++ tool for making chrome embeddable.
AwesomiumDotNet is a wrapper around both Berkelium and Awesomium
BTW, the link here to Awesomium appears to be more current.
You probably have a forward declaration of the class, but haven't included the header:
#include <sstream>
//...
QString Stats_Manager::convertInt(int num)
{
std::stringstream ss; // <-- also note namespace qualification
ss << num;
return ss.str();
}
It is a static initializer. It's executed when the class is loaded and a good place to put initialization of static variables.
From http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
If you have a class with a static look-up map it could look like this
class MyClass {
static Map<Double, String> labels;
static {
labels = new HashMap<Double, String>();
labels.put(5.5, "five and a half");
labels.put(7.1, "seven point 1");
}
//...
}
It's useful since the above static field could not have been initialized using labels = ...
. It needs to call the put-method somehow.
awk 'BEGIN {FS=" "} {printf "\047%s\047 ", $1}'
var temp1 = "";
var temp2 = "";
var str1 = fd;
var str2 = td;
var dt1 = str1.substring(0,2);
var dt2 = str2.substring(0,2);
var mon1 = str1.substring(3,5);
var mon2 = str2.substring(3,5);
var yr1 = str1.substring(6,10);
var yr2 = str2.substring(6,10);
temp1 = mon1 + "/" + dt1 + "/" + yr1;
temp2 = mon2 + "/" + dt2 + "/" + yr2;
var cfd = Date.parse(temp1);
var ctd = Date.parse(temp2);
var date1 = new Date(cfd);
var date2 = new Date(ctd);
if(date1 > date2) {
alert("FROM DATE SHOULD BE MORE THAN TO DATE");
}
This will give you the current screen based on the top left of the window just call this.CurrentScreen() to get info on the current screen.
using System.Windows;
using System.Windows.Forms;
namespace Common.Helpers
{
public static class WindowHelpers
{
public static Screen CurrentScreen(this Window window)
{
return Screen.FromPoint(new System.Drawing.Point((int)window.Left,(int)window.Top));
}
}
}
To add on Tzot's and gns answers, here's an alternative way of copying files and folders recursively. (Python 3.X)
import os, shutil
root_src_dir = r'C:\MyMusic' #Path/Location of the source directory
root_dst_dir = 'D:MusicBackUp' #Path to the destination folder
for src_dir, dirs, files in os.walk(root_src_dir):
dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
for file_ in files:
src_file = os.path.join(src_dir, file_)
dst_file = os.path.join(dst_dir, file_)
if os.path.exists(dst_file):
os.remove(dst_file)
shutil.copy(src_file, dst_dir)
Should it be your first time and you have no idea how to copy files and folders recursively, I hope this helps.
Internet Explorer 8 (and earlier versions) doesn't support rounded corners, however there are few other solutions you may consider:
Use Rounded Corners Images
instead (this generator is a good resource)
Use a jQuery Corner plugin
from here
Use a very good script called CSS3 PIE
from here (Pro's & Con's here)
Checkout CSS Juice
from here
Another good script is IE-CSS3
from here
Even though CSS PIE is the most popular solution, I'm suggesting you to review all other solutions and choose what works best for your needs.
Hope it was useful. Good Luck!
A simple way to do it without the use of such a complicated draw statement:
//Make a backup so that we can reset our graphics object after using it.
AffineTransform backup = g2d.getTransform();
//rx is the x coordinate for rotation, ry is the y coordinate for rotation, and angle
//is the angle to rotate the image. If you want to rotate around the center of an image,
//use the image's center x and y coordinates for rx and ry.
AffineTransform a = AffineTransform.getRotateInstance(angle, rx, ry);
//Set our Graphics2D object to the transform
g2d.setTransform(a);
//Draw our image like normal
g2d.drawImage(image, x, y, null);
//Reset our graphics object so we can draw with it again.
g2d.setTransform(backup);
Mamp user enable option Allow network access to MYSQL
I use this function to indent my output (for example to print a tree structure). The indent
is the number of spaces before the string.
void print_with_indent(int indent, char * string)
{
printf("%*s%s", indent, "", string);
}
In JavaScript, primitive types such as integers and strings are passed by value whereas objects are passed by reference. So in order to achieve this you need to use an object:
// declare an object with property x
var obj = { x: 1 };
var aliasToObj = obj;
aliasToObj.x ++;
alert( obj.x ); // displays 2
If you need a custom title for each option, ng-options
is not applicable. Instead use ng-repeat
with options:
<select ng-model="myVariable">
<option ng-repeat="item in items"
value="{{item.ID}}"
title="Custom title: {{item.Title}} [{{item.ID}}]">
{{item.Title}}
</option>
</select>
Here's what I do. I find the minimum first then after the minimum is found, it is removed from ArrayList.
ArrayList<Integer> a = new ArrayList<>();
a.add(3);
a.add(6);
a.add(2);
a.add(5);
while (a.size() > 0) {
int min = 1000;
for (int b:a) {
if (b < min)
min = b;
}
System.out.println("minimum: " + min);
System.out.println("index of min: " + a.indexOf((Integer) min));
a.remove((Integer) min);
}
I usually use: FS-Extra.
const fileNameArray = Fse.readdir('/some/path');
Result:
[
"b7c8a93c-45b3-4de8-b9b5-a0bf28fb986e.jpg",
"daeb1c5b-809f-4434-8fd9-410140789933.jpg"
]
Sometimes, this error occurs when you're trying to target an element that is wrapped in a condition, for example:
<div *ngIf="canShow"> <p #target>Targeted Element</p></div>
In this code, if canShow
is false on render, Angular won't be able to get that element as it won't be rendered, hence the error that comes up.
One of the solutions is to use a display: hidden
on the element instead of the *ngIf
so the element gets rendered but is hidden until your condition is fulfilled.
Read More over at Github
I know this is an old question, but if you ever want ot fix the malformed '&' signs in your HTML. You can use code similar to this:
$page = file_get_contents('http://www.example.com');
$page = preg_replace('/\s+/', ' ', trim($page));
fixAmps($page, 0);
$dom->loadHTML($page);
function fixAmps(&$html, $offset) {
$positionAmp = strpos($html, '&', $offset);
$positionSemiColumn = strpos($html, ';', $positionAmp+1);
$string = substr($html, $positionAmp, $positionSemiColumn-$positionAmp+1);
if ($positionAmp !== false) { // If an '&' can be found.
if ($positionSemiColumn === false) { // If no ';' can be found.
$html = substr_replace($html, '&', $positionAmp, 1); // Replace straight away.
} else if (preg_match('/&(#[0-9]+|[A-Z|a-z|0-9]+);/', $string) === 0) { // If a standard escape cannot be found.
$html = substr_replace($html, '&', $positionAmp, 1); // This mean we need to escape the '&' sign.
fixAmps($html, $positionAmp+5); // Recursive call from the new position.
} else {
fixAmps($html, $positionAmp+1); // Recursive call from the new position.
}
}
}
Contains(s2) is many times (in my computer 10 times) faster than IndexOf(s2) because Contains uses StringComparison.Ordinal that is faster than the culture sensitive search that IndexOf does by default (but that may change in .net 4.0 http://davesbox.com/archive/2008/11/12/breaking-changes-to-the-string-class.aspx).
Contains has exactly the same performance as IndexOf(s2,StringComparison.Ordinal) >= 0 in my tests but it's shorter and makes your intent clear.
Start by reading the fork man page as well as the getppid / getpid man pages.
From fork's
On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and errno will be set appropriately.
So this should be something down the lines of
if ((pid=fork())==0){
printf("yada yada %u and yada yada %u",getpid(),getppid());
}
else{ /* avoids error checking*/
printf("Dont yada yada me, im your parent with pid %u ", getpid());
}
As to your question:
This is the child process. My pid is 22163 and my parent's id is 0.
This is the child process. My pid is 22162 and my parent's id is 22163.
fork()
executes before the printf
. So when its done, you have two processes with the same instructions to execute. Therefore, printf will execute twice. The call to fork()
will return 0
to the child process, and the pid
of the child process to the parent process.
You get two running processes, each one will execute this instruction statement:
printf ("... My pid is %d and my parent's id is %d",getpid(),0);
and
printf ("... My pid is %d and my parent's id is %d",getpid(),22163);
~
To wrap it up, the above line is the child, specifying its pid
. The second line is the parent process, specifying its id (22162) and its child's (22163).
Yes, #id
selectors combined with a multiple selector (comma) is perfectly valid in both jQuery and CSS.
However, for your example, since <script>
comes before the elements, you need a document.ready
handler, so it waits until the elements are in the DOM to go looking for them, like this:
<script>
$(function() {
$("#segement1,#segement2,#segement3").hide()
});
</script>
<div id="segement1"></div>
<div id="segement2"></div>
<div id="segement3"></div>
Such difference between the output of du -sh
and df -h
may happen if some large file has been deleted, but is still opened by some process. Check with the command lsof | grep deleted
to see which processes have opened descriptors to deleted files. You can restart the process and the space will be freed.
Consider:
class Bike(object):
def __init__(self, name, weight, cost):
self.name = name
self.weight = weight
self.cost = cost
bikes = {
# Bike designed for children"
"Trike": Bike("Trike", 20, 100), # <--
# Bike designed for everyone"
"Kruzer": Bike("Kruzer", 50, 165), # <--
}
# Markup of 20% on all sales
margin = .2
# Revenue minus cost after sale
for bike in bikes.values():
profit = bike.cost * margin
print(profit)
Output:
33.0 20.0
The difference is that in your bikes
dictionary, you're initializing the values as lists [...]
. Instead, it looks like the rest of your code wants Bike
instances. So create Bike
instances: Bike(...)
.
As for your error
AttributeError: 'list' object has no attribute 'cost'
this will occur when you try to call .cost
on a list
object. Pretty straightforward, but we can figure out what happened by looking at where you call .cost
-- in this line:
profit = bike.cost * margin
This indicates that at least one bike
(that is, a member of bikes.values()
is a list). If you look at where you defined bikes
you can see that the values were, in fact, lists. So this error makes sense.
But since your class has a cost attribute, it looked like you were trying to use Bike
instances as values, so I made that little change:
[...] -> Bike(...)
and you're all set.
After adding files to the stage, you need to commit them with git commit -m "comment"
after git add .
. Finally, to push them to a remote repository, you need to git push <remote_repo> <local_branch>
.
I had this error message and for me the solution was to install Dot Net Framework 4.6 ,While my project targeted 4.5.2
For the sake of completeness, you may use std::stringstream
:
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string a = "a", b = "b", c = "c";
// apply formatting
std::stringstream s;
s << a << " " << b << " > " << c;
// assign to std::string
std::string str = s.str();
std::cout << str << "\n";
}
Or (in this case) std::string
's very own string concatenation capabilities:
#include <iostream>
#include <string>
int main() {
std::string a = "a", b = "b", c = "c";
std::string str = a + " " + b + " > " + c;
std::cout << str << "\n";
}
For reference:
If you really want to go the C way. Here you are:
#include <iostream>
#include <string>
#include <vector>
#include <cstdio>
int main() {
std::string a = "a", b = "b", c = "c";
const char fmt[] = "%s %s > %s";
// use std::vector for memory management (to avoid memory leaks)
std::vector<char>::size_type size = 256;
std::vector<char> buf;
do {
// use snprintf instead of sprintf (to avoid buffer overflows)
// snprintf returns the required size (without terminating null)
// if buffer is too small initially: loop should run at most twice
buf.resize(size+1);
size = std::snprintf(
&buf[0], buf.size(),
fmt, a.c_str(), b.c_str(), c.c_str());
} while (size+1 > buf.size());
// assign to std::string
std::string str(buf.begin(), buf.begin()+size);
std::cout << str << "\n";
}
For reference:
Then, there's the Boost Format Library. For the sake of your example:
#include <iostream>
#include <string>
#include <boost/format.hpp>
int main() {
std::string a = "a", b = "b", c = "c";
// apply format
boost::format fmt = boost::format("%s %s > %s") % a % b % c;
// assign to std::string
std::string str = fmt.str();
std::cout << str << "\n";
}
You need to specify a Main-Class in the jar file manifest.
Oracle's tutorial contains a complete demonstration, but here's another one from scratch. You need two files:
Test.java:
public class Test
{
public static void main(String[] args)
{
System.out.println("Hello world");
}
}
manifest.mf:
Manifest-version: 1.0
Main-Class: Test
Note that the text file must end with a new line or carriage return. The last line will not be parsed properly if it does not end with a new line or carriage return.
Then run:
javac Test.java
jar cfm test.jar manifest.mf Test.class
java -jar test.jar
Output:
Hello world
try this:
import pylab
from scipy import misc
pylab.imshow(misc.lena(),cmap=pylab.gray())
pylab.show()
As other posters have pointed out, there are some limitations with the AWS Transfer for SFTP service. You need to closely align requirements. For example, there are no quotas, whitelists/blacklists, file type limits, and non key based access requires external services. There is also a certain overhead relating to user management and IAM, which can get to be a pain at scale.
We have been running an SFTP S3 Proxy Gateway for about 5 years now for our customers. The core solution is wrapped in a collection of Docker services and deployed in whatever context is needed, even on-premise or local development servers. The use case for us is a little different as our solution is focused data processing and pipelines vs a file share. In a Salesforce example, a customer will use SFTP as the transport method sending email, purchase...data to an SFTP/S3 enpoint. This is mapped an object key on S3. Upon arrival, the data is picked up, processed, routed and loaded to a warehouse. We also have fairly significant auditing requirements for each transfer, something the Cloudwatch logs for AWS do not directly provide.
As other have mentioned, rolling your own is an option too. Using AWS Lightsail you can setup a cluster, say 4, of $10 2GB instances using either Route 53 or an ELB.
In general, it is great to see AWS offer this service and I expect it to mature over time. However, depending on your use case, alternative solutions may be a better fit.
Try this:
DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");
zzz
is the timezone offset.
Try this way,hope this will help you to solve your problem.
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
MyActivity.java
public class MyActivity extends Activity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webView = (WebView) findViewById(R.id.webView);
webView.loadData("<a href=\"tel:+1800229933\">Call us free!</a>", "text/html", "utf-8");
}
}
Please add this permission in AndroidManifest.xml
<uses-permission android:name="android.permission.CALL_PHONE"/>
Use hypertext reference and the ID tag,
Some paragraph text
Target Text<h1><a href="#target">Target Text Title</a></h1>
<p id="target">Target Text</p>
Assuming you have an ArrayList
that contains characters, you could do this:
List<Character> list = new ArrayList<Character>();
list.addAll(Arrays.asList('+', '-', '*', '^'));
In ECMAScript 6 there's no need to use ugly hacks like Array.prototype.slice()
. You can instead use spread syntax (...
).
(function() {_x000D_
console.log([...arguments]);_x000D_
}(1, 2, 3))
_x000D_
It may look strange, but it's fairly simple. It just extracts arguments
' elements and put them back into the array. If you still don't understand, see this examples:
console.log([1, ...[2, 3], 4]);_x000D_
console.log([...[1, 2, 3]]);_x000D_
console.log([...[...[...[1]]]]);
_x000D_
Note that it doesn't work in some older browsers like IE 11, so if you want to support these browsers, you should use Babel.
You can add this extension :
extension Double {
var clean: String {
return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(format: "%.2f", self)
}
}
and call it like this :
let ex: Double = 10.123546789
print(ex.clean) // 10.12
You may be an administrator on the workstation, but that means nothing to SQL Server. Your login has to be a member of the sysadmin role in order to perform the actions in question. By default, the local administrators group is no longer added to the sysadmin role in SQL 2008 R2. You'll need to login with something else (sa for example) in order to grant yourself the permissions.
In simple cases you can use next method which doesn`t require you to create a function or to copy code to several cells:
In any cell write next code
=Transpose(A1:A9)
Where A1:A9 are cells you would like to merge.
F9
After that, the cell will contain the string:
={A1,A2,A3,A4,A5,A6,A7,A8,A9}
Source: http://www.get-digital-help.com/2011/02/09/concatenate-a-cell-range-without-vba-in-excel/
Update: One part can be ambiguous. Without leaving the cell means having your cell in editor mode. Alternatevly you can press F9 while are in cell editor panel (normaly it can be found above the spreadsheet)
You could try this.
In windows go to Administrative Tools->Services And see scroll down to where it says Oracle[instanceNameHere] and see if the listener and the service itself are running. You might have to start it. You can also set it to start automatically when you right-click on it and go to properties.
First thing to do is run this:
SHOW GRANTS;
You will quickly see you were assigned the anonymous user to authenticate into mysql.
Instead of logging into mysql with
mysql
login like this:
mysql -uroot
By default, root@localhost has all rights and no password.
If you cannot login as root without a password, do the following:
Step 01) Add the two options in the mysqld section of my.ini:
[mysqld]
skip-grant-tables
skip-networking
Step 02) Restart mysql
net stop mysql
<wait 10 seconds>
net start mysql
Step 03) Connect to mysql
mysql
Step 04) Create a password from root@localhost
UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit
Step 05) Restart mysql
net stop mysql
<wait 10 seconds>
net start mysql
Step 06) Login as root with password
mysql -u root -p
You should be good from there.
If you removed the make all
line from your "fresh" target:
fresh :
rm -f *.o $(EXEC)
clear
You could simply run the command make fresh all
, which will execute as make fresh; make all
.
Some might consider this as a second instance of make, but it's certainly not a sub-instance of make (a make inside of a make), which is what your attempt seemed to result in.
public boolean isElementFound( String text) {
try{
WebElement webElement = appiumDriver.findElement(By.xpath(text));
System.out.println("isElementFound : true :"+text + "true");
}catch(NoSuchElementException e){
System.out.println("isElementFound : false :"+text);
return false;
}
return true;
}
text is the xpath which you would be passing when calling the function.
the return value will be true if the element is present else false if element is not pressent
Generics solution to covert any List<Type>
to String []
:
public static <T> String[] listToArray(List<T> list) {
String [] array = new String[list.size()];
for (int i = 0; i < array.length; i++)
array[i] = list.get(i).toString();
return array;
}
Note You must override toString()
method.
class Car {
private String name;
public Car(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
final List<Car> carList = new ArrayList<Car>();
carList.add(new Car("BMW"))
carList.add(new Car("Mercedes"))
carList.add(new Car("Skoda"))
final String[] carArray = listToArray(carList);
sum
is used to add elements; nrow
is used to count the number of rows in a rectangular array (typically a matrix or data.frame); length
is used to count the number of elements in a vector. You need to apply these functions correctly.
Let's assume your data is a data frame named "dat". Correct solutions:
nrow(dat[dat$sCode == "CA",])
length(dat$sCode[dat$sCode == "CA"])
sum(dat$sCode == "CA")
<xsl:call-template>
is a close equivalent to calling a function in a traditional programming language.
You can define functions in XSLT, like this simple one that outputs a string.
<xsl:template name="dosomething">
<xsl:text>A function that does something</xsl:text>
</xsl:template>
This function can be called via <xsl:call-template name="dosomething">
.
<xsl:apply-templates>
is a little different and in it is the real power of XSLT: It takes any number of XML nodes (whatever you define in the select
attribute), iterates them (this is important: apply-templates works like a loop!) and finds matching templates for them:
<!-- sample XML snippet -->
<xml>
<foo /><bar /><baz />
</xml>
<!-- sample XSLT snippet -->
<xsl:template match="xml">
<xsl:apply-templates select="*" /> <!-- three nodes selected here -->
</xsl:template>
<xsl:template match="foo"> <!-- will be called once -->
<xsl:text>foo element encountered</xsl:text>
</xsl:template>
<xsl:template match="*"> <!-- will be called twice -->
<xsl:text>other element countered</xsl:text>
</xsl:template>
This way you give up a little control to the XSLT processor - not you decide where the program flow goes, but the processor does by finding the most appropriate match for the node it's currently processing.
If multiple templates can match a node, the one with the more specific match expression wins. If more than one matching template with the same specificity exist, the one declared last wins.
You can concentrate more on developing templates and need less time to do "plumbing". Your programs will become more powerful and modularized, less deeply nested and faster (as XSLT processors are optimized for template matching).
A concept to understand with XSLT is that of the "current node". With <xsl:apply-templates>
the current node moves on with every iteration, whereas <xsl:call-template>
does not change the current node. I.e. the .
within a called template refers to the same node as the .
in the calling template. This is not the case with apply-templates.
This is the basic difference. There are some other aspects of templates that affect their behavior: Their mode
and priority
, the fact that templates can have both a name
and a match
. It also has an impact whether the template has been imported (<xsl:import>
) or not. These are advanced uses and you can deal with them when you get there.
Comprehension could be also convenient in this case:
# from a list
keys = ["k1", "k2"]
d = {k:None for k in keys}
# or from another dict
d1 = {"k1" : 1, "k2" : 2}
d2 = {k:None for k in d1.keys()}
d2
# {'k1': None, 'k2': None}
Short version: by undoing the undo. If you undo, and then do a non-editing command such as C-f, then the next undo will undo the undo, resulting in a redo.
Longer version:
You can think of undo as operating on a stack of operations. If you perform some command (even a navigation command such as C-f) after a sequence of undo operations, all the undos are pushed on to the operation stack. So the next undo undoes the last command. Suppose you do have an operation sequence that looks like this:
Now, you undo. It undoes the last action, resulting in the following list:
If you do something other than undo at this point - say, C-f, the operation stack looks like this:
Now, when you undo, the first thing that is undone is the undo. Resulting in your original stack (and document state):
If you do a modifying command to break the undo sequence, that command is added after the undo and is thus the first thing to be undone afterwards. Suppose you backspaced over "bar" instead of hitting C-f. Then you would have had
This adding/re-adding happens ad infinitum. It takes a little getting used to, but it really does give Emacs a highly flexible and powerful undo/redo mechanism.
There is now a much better solution, a lot more elegant, based on fenced div
, which have been implemented in pandoc
, as explained here:
::: {.center data-latex=""}
Some text here...
:::
All you need to do is to change your css
file accordingly. The following chunk for instance does the job:
```{cat, engine.opts = list(file = "style.css")}
.center {
text-align: center;
}
```
(Obviously, you can also directly type the content of the chunk into your .css
file...).
The tex
file includes the proper centering commands.
The crucial advantage of this method is that it allows writing markdown
code inside the block.
In my previous answer, r ctrFmt("Centered **text** in html and pdf!")
does not bold for the word "text", but it would if inside a fenced div
.
For images, etc... the lua
filter is available here
def to_infinity():
index = 0
while True:
yield index
index += 1
for i in to_infinity():
if i > 10:
break
Why is this happening?
The entire ext/mysql
PHP extension, which provides all functions named with the prefix mysql_
, was officially deprecated in PHP v5.5.0 and removed in PHP v7.
It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.
The manual has contained warnings against its use in new code since June 2011.
How can I fix it?
As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql
. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.
They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.
Hashphp.org has an excellent tutorial on migrating from ext/mysql
to PDO.
I understand that it's possible to suppress deprecation errors by setting
error_reporting
inphp.ini
to excludeE_DEPRECATED
:error_reporting = E_ALL ^ E_DEPRECATED
What will happen if I do that?
Yes, it is possible to suppress such error messages and continue using the old ext/mysql
extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.
Note also that this technique will suppress all E_DEPRECATED
messages, not just those to do with the ext/mysql
extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @
—however this will suppress all errors raised by that expression, not just E_DEPRECATED
ones.
You are starting a new project.
There is absolutely no reason to use ext/mysql
—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.
You have (your own) legacy codebase that currently depends upon ext/mysql
.
It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.
Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.
Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.
The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.
Consider whether you really need to upgrade to PHP v5.5 at this time.
You should begin planning to replace ext/mysql
with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.
However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
You are using a third party project that depends upon ext/mysql
.
Consider whether you really need to upgrade to PHP v5.5 at this time.
Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
It is absolutely essential to perform regression testing.
Using PHP i've found a quite simple way to do this. Guys, Just Use something like this
<input list="customers" name="customer_id" required class="form-control" placeholder="Customer Name">
<datalist id="customers">
<?php
$querySnamex = "SELECT * FROM `customer` WHERE fname!='' AND lname!='' order by customer_id ASC";
$resultSnamex = mysqli_query($con,$querySnamex) or die(mysql_error());
while ($row_this = mysqli_fetch_array($resultSnamex)) {
echo '<option data-value="'.$row_this['customer_id'].'">'.$row_this['fname'].' '.$row_this['lname'].'</option>
<input type="hidden" name="customer_id_real" value="'.$row_this['customer_id'].'" id="answerInput-hidden">';
}
?>
</datalist>
The Code Above lets the form carry the id of the option also selected.
imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
You can use fall-through:
switch (pageid)
{
case "listing-page":
case "home-page":
alert("hello");
break;
case "details-page":
alert("goodbye");
break;
}
VISITOR count should be available under your dashboard > Traffic (or stats or insights):
Just right click on the class in the project explorer and select "Refactor" -> "Rename". That it is is under the "Refactor" submenu.
If its javascript that runs on a button click, then making the change under Sources>Sources (in the developer tools in chrome ) and pressing Ctrl +S to save, is enough. I do this all the time.
If you refresh the page, your javascript changes would be gone, but chrome will still remember your break points.
As said in the post, React is a browser based technology. It only renders a view in an HTML document.
To be able to have access to your "React App", you need to:
You might have all the informations here: https://httpd.apache.org/docs/trunk/getting-started.html for the Apache server, and here to make your javascript bundle https://www.codementor.io/tamizhvendan/beginner-guide-setup-reactjs-environment-npm-babel-6-webpack-du107r9zr
Below is a implementation of Graph Data Structure in C++ as Adjacency List.
I have used STL vector for representation of vertices and STL pair for denoting edge and destination vertex.
#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;
struct vertex {
typedef pair<int, vertex*> ve;
vector<ve> adj; //cost of edge, destination vertex
string name;
vertex(string s) : name(s) {}
};
class graph
{
public:
typedef map<string, vertex *> vmap;
vmap work;
void addvertex(const string&);
void addedge(const string& from, const string& to, double cost);
};
void graph::addvertex(const string &name)
{
vmap::iterator itr = work.find(name);
if (itr == work.end())
{
vertex *v;
v = new vertex(name);
work[name] = v;
return;
}
cout << "\nVertex already exists!";
}
void graph::addedge(const string& from, const string& to, double cost)
{
vertex *f = (work.find(from)->second);
vertex *t = (work.find(to)->second);
pair<int, vertex *> edge = make_pair(cost, t);
f->adj.push_back(edge);
}
XAMPP only offers MySQL (Database Server) & Apache (Webserver) in one setup and you can manage them with the xampp starter.
After the successful installation navigate to your xampp folder and execute the xampp-control.exe
Press the start Button at the mysql row.
Now you've successfully started mysql. Now there are 2 different ways to administrate your mysql server and its databases.
But at first you have to set/change the MySQL Root password. Start the Apache server and type localhost
or 127.0.0.1
in your browser's address bar. If you haven't deleted anything from the htdocs folder the xampp status page appears. Navigate to security settings and change your mysql root password.
Now, you can browse to your phpmyadmin under http://localhost/phpmyadmin
or download a windows mysql client for example navicat lite or mysql workbench. Install it and log in to your mysql server with your new root password.
Do a git add -A
from the top of the working copy, take a look at git status
and/or git diff --cached
to review what you're about to do, then git commit
the result.
If you put "\n" in a string in the xml file, it's taken as "\\n"
So , I did :
text = text.Replace("\\\n", "\n"); ( text is taken from resX file)
And then I get a line jump on the screen
Hibernate support reattach detached entity by serval ways, see Hibernate user guide.
This works for me:
Console.OutputEncoding = System.Text.Encoding.Default;
To display some of the symbols, it's required to set Command Prompt's font to Lucida Console:
Open Command Prompt;
Right click on the top bar of the Command Prompt;
Click Properties;
If the font is set to Raster Fonts, change it to Lucida Console.
simply run npm install --save rxjs-compat
it fixes the error.
One has to group imagePullPolicy
inside the container data instead of inside the spec data. However, I filed an issue about this because I find it odd. Besides, there is no error message.
So, this spec snippet works:
spec:
containers:
- name: myapp
image: myregistry.com/myapp:5c3dda6b
ports:
- containerPort: 80
imagePullPolicy: Always
imagePullSecrets:
- name: myregistry.com-registry-key
You mean that your code is DDL? If so, MSSQL has no difference. Above examples well shows how to invoke this. Just ensure
CommandType = CommandType.Text
The DECLARE GLOBAL TEMPORARY TABLE statement defines a temporary table for the current connection.
These tables do not reside in the system catalogs and are not persistent.
Temporary tables exist only during the connection that declared them and cannot be referenced outside of that connection.
When the connection closes, the rows of the table are deleted, and the in-memory description of the temporary table is dropped.
For your reference http://docs.oracle.com/javadb/10.6.2.1/ref/rrefdeclaretemptable.html
There's no benefit to using properties with primitive types. @property
is used with heap allocated NSObjects
like NSString*
, NSNumber*
, UIButton*
, and etc, because memory managed accessors are created for free. When you create a BOOL
, the value is always allocated on the stack and does not require any special accessors to prevent memory leakage. isWorking
is simply the popular way of expressing the state of a boolean value.
In another OO language you would make a variable private bool working;
and two accessors: SetWorking
for the setter and IsWorking
for the accessor.
Use: location.pathname
alert(location.pathname);
https://developer.mozilla.org/en-US/docs/DOM/window.location
Like other have said, span is an in-line element.
See here: http://www.w3.org/TR/CSS2/visuren.html
Additionally, you can make a span behave like a div by applying a
style="display: block; margin: 0px auto; text-align: center;"
Add type="button"
to the button.
<button name="data" type="button" onclick="getData()">Click</button>
The default value of type
for a button is submit
, which self posts the form in your case and makes it look like a refresh.
Use the Bit
datatype. It has values 1 and 0 when dealing with it in native T-SQL
You are missing a semicolon at the end of your 'struct' definition.
Also,
*sotrudnik
needs to be
sotrudnik*
ORA-01861: literal does not match format string
This happens because you have tried to enter a literal with a format string, but the length of the format string was not the same length as the literal.
You can overcome this issue by carrying out following alteration.
TO_DATE('1989-12-09','YYYY-MM-DD')
As a general rule, if you are using the TO_DATE function, TO_TIMESTAMP function, TO_CHAR function, and similar functions, make sure that the literal that you provide matches the format string that you've specified
Use the $elemMatch
operator: according to the documentation
The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.
$elemMatches
makes sure that the value is an array and that it is not empty. So the query would be something like
ME.find({ pictures: { $elemMatch: {$exists: true }}})
PS A variant of this code is found in MongoDB University's M121 course.
You wont be able to do this from the client side because of the Same Origin Policy set by the browsers. You wont be able to get much information from the iFrame other than basic properties like its width and height.
Also, google sets in its response header an 'X-Frame-Options' of SAMEORIGIN.
Even if you did an ajax call to google you wont be able to inspect the response because the browser enforcing Same Origin Policy.
So, the only option is to make the request from your server to see if you can display the site in your IFrame.
So, on your server.. your web app would make a request to www.google.com and then inspect the response to see if it has a header argument of X-Frame-Options. If it does exist then you know the IFrame will error.
set height: auto;
If you want to have minimum height to x then you can write
height:auto;
min-height:30px;
height:auto !important; /* for IE as it does not support min-height */
height:30px; /* for IE as it does not support min-height */
As @AliK mentioned, this can be done easily by looking at the value of the submit buttons.
When you submit a form, unset variables will evaluate false. If you set both submit buttons to be part of the same form, you can just check and see which button has been set.
HTML:
<form action="handle_user.php" method="POST" /> <input type="submit" value="Save" name="save" /> <input type="submit" value="Submit for Approval" name="approve" /> </form>
PHP
if($_POST["save"]) { //User hit the save button, handle accordingly } //You can do an else, but I prefer a separate statement if($_POST["approve"]) { //User hit the Submit for Approval button, handle accordingly }
EDIT
Related:
Use this....
string popupScript = "<script language=JavaScript>";
popupScript += "alert('Please enter valid Email Id');";
popupScript += "</";
popupScript += "script>";
Page.RegisterStartupScript("PopupScript", popupScript);
I recognize that this is tagged for oauth 2.0 and NOT OIDC, however there is frequently a conflation between the 2 standards since both standards can use JWTs and the aud
claim. And one (OIDC) is basically an extension of the other (OAUTH 2.0). (I stumbled across this question looking for OIDC myself.)
For OAuth 2.0 Access tokens, existing answers pretty well cover it. Additionally here is one relevant section from OAuth 2.0 Framework (RFC 6749)
For public clients using implicit flows, this specification does not provide any method for the client to determine what client an access token was issued to.
...
Authenticating resource owners to clients is out of scope for this specification. Any specification that uses the authorization process as a form of delegated end-user authentication to the client (e.g., third-party sign-in service) MUST NOT use the implicit flow without additional security mechanisms that would enable the client to determine if the access token was issued for its use (e.g., audience- restricting the access token).
OIDC has ID Tokens in addition to Access tokens. The OIDC spec is explicit on the use of the aud
claim in ID Tokens. (openid-connect-core-1.0)
aud
REQUIRED. Audience(s) that this ID Token is intended for. It MUST contain the OAuth 2.0 client_id of the Relying Party as an audience value. It MAY also contain identifiers for other audiences. In the general case, the aud value is an array of case sensitive strings. In the common special case when there is one audience, the aud value MAY be a single case sensitive string.
furthermore OIDC specifies the azp
claim that is used in conjunction with aud
when aud
has more than one value.
azp
OPTIONAL. Authorized party - the party to which the ID Token was issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. This Claim is only needed when the ID Token has a single audience value and that audience is different than the authorized party. It MAY be included even when the authorized party is the same as the sole audience. The azp value is a case sensitive string containing a StringOrURI value.
If you use input property databinding with a JavaScript reference type (e.g., Object, Array, Date, etc.), then the parent and child will both have a reference to the same/one object. Any changes you make to the shared object will be visible to both parent and child.
In the parent's template:
<child [aList]="sharedList"></child>
In the child:
@Input() aList;
...
updateList() {
this.aList.push('child');
}
If you want to add items to the list upon construction of the child, use the ngOnInit()
hook (not the constructor(), since the data-bound properties aren't initialized at that point):
ngOnInit() {
this.aList.push('child1')
}
This Plunker shows a working example, with buttons in the parent and child component that both modify the shared list.
Note, in the child you must not reassign the reference. E.g., don't do this in the child: this.aList = someNewArray;
If you do that, then the parent and child components will each have references to two different arrays.
If you want to share a primitive type (i.e., string, number, boolean), you could put it into an array or an object (i.e., put it inside a reference type), or you could emit()
an event from the child whenever the primitive value changes (i.e., have the parent listen for a custom event, and the child would have an EventEmitter
output property. See @kit's answer for more info.)
Update 2015/12/22: the heavy-loader
example in the Structural Directives guides uses the technique I presented above. The main/parent component has a logs
array property that is bound to the child components. The child components push()
onto that array, and the parent component displays the array.
You forgot braces around the if block, and a semicolon between the statements in the block.
awk '{if($3 != 0) {a = ($3/$4); print $0, a;} else if($3==0) print $0, "-" }' file > out
ENV['RAILS_ENV']
is now deprecated.
You should use Rails.env
which is clearly much nicer.
If you are building an uberjar or "shaded jar", make sure your meta inf service files are merged. (This bit me multiple times on a dropwizard project.)
If you are using the gradle shadowJar plugin, you want to call mergeServiceFiles()
in your shadowJar
target: https://github.com/johnrengelman/shadow#merging-service-files
Not sure what the analogous commands are for maven or other build systems.
if(!strcmp(favoriteDairyProduct, "cheese"))
{
printf("You like cheese too!");
}
else
{
printf("I like cheese more.");
}
In my case I was using the wrong version of MSBuild.exe
.
The version you need to use depends on what version of Visual Studio you used to create your project. In my case I needed 14.0 (having used Visual Studio 2015).
This was found at:
C:\Program Files (x86)\MSBuild\14.0\Bin\msbuild.exe
You can look under:
C:\Program Files (x86)\MSBuild
To find other versions.
To make it easier add a custom function and call it when ever you want that changing the value also trigger change
$.fn.valAndTrigger = function (element) {
return $(this).val(element).trigger('change');
}
and
$("#sample").valAndTirgger("NewValue");
Or you can override the val function to always call the change when the val is called
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function (value) {
this.trigger("change");
return originalVal.call(this, value);
};
})(jQuery);
Sample at http://jsfiddle.net/r60bfkub/
Starting from pandas 0.20 ix is deprecated. The right way is to use df.loc
here is a working example
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({"A":[0,1,0], "B":[2,0,5]}, columns=list('AB'))
>>> df.loc[df.A == 0, 'B'] = np.nan
>>> df
A B
0 0 NaN
1 1 0
2 0 NaN
>>>
As explained in the doc here, .loc
is primarily label based, but may also be used with a boolean array.
So, what we are doing above is applying df.loc[row_index, column_index]
by:
loc
can take a boolean array as a mask that tells pandas which subset of rows we want to change in row_index
loc
is also label based to select the column using the label 'B'
in the column_index
We can use logical, condition or any operation that returns a series of booleans to construct the array of booleans. In the above example, we want any rows
that contain a 0
, for that we can use df.A == 0
, as you can see in the example below, this returns a series of booleans.
>>> df = pd.DataFrame({"A":[0,1,0], "B":[2,0,5]}, columns=list('AB'))
>>> df
A B
0 0 2
1 1 0
2 0 5
>>> df.A == 0
0 True
1 False
2 True
Name: A, dtype: bool
>>>
Then, we use the above array of booleans to select and modify the necessary rows:
>>> df.loc[df.A == 0, 'B'] = np.nan
>>> df
A B
0 0 NaN
1 1 0
2 0 NaN
For more information check the advanced indexing documentation here.
Constructor overloading is like method overloading. Constructors can be overloaded to create objects in different ways.
The compiler differentiates constructors based on how many arguments are present in the constructor and other parameters like the order in which the arguments are passed.
For further details about java constructor, please visit https://tecloger.com/constructor-in-java/
You declared them, but not initialized.
int a; // declaration, unknown value
a = 0; // initialization
int a = 0; // declaration with initialization
It's a setting in chrome. You can't control how the browser interprets the target _blank
.
<div class="centered_content"> content </div>
<style type="text/css">
.centered_content {
text-align: center;
position: absolute;
left: 0;
right: 0;
}
</style>
see demo on: http://jsfiddle.net/MohammadDayeh/HrZLC/
text-align: center
; works with a position: absolute
element when adding left: 0; right: 0;
The simple answer to this question is that a callback function is a function that is called through a function pointer. If you pass the pointer (address) of a function as an argument to another, when that pointer is used to call the function it points to it is said that a call back is made
s = s.substring(0, Math.min(s.length(), 10));
Using Math.min
like this avoids an exception in the case where the string is already shorter than 10
.
Notes:
The above does real trimming. If you actually want to replace the last three (!) characters with dots if it truncates, then use Apache Commons StringUtils.abbreviate
.
For typical implementations of String
, s.substring(0, s.length())
will return s
rather than allocating a new String
.
This may behave incorrectly1 if your String contains Unicode codepoints outside of the BMP; e.g. Emojis. For a (more complicated) solution that works correctly for all Unicode code-points, see @sibnick's solution.
1 - A Unicode codepoint that is not on plane 0 (the BMP) is represented as a "surrogate pair" (i.e. two char
values) in the String
. By ignoring this, we might trim to fewer than 10 code points, or (worse) truncate in the middle of a surrogate pair. On the other hand, String.length()
is no longer an ideal measure of Unicode text length, so trimming based on it may be the wrong thing to do.
The right way to do this, starting with Spring 4.1, is to use a @TestPropertySource
annotation.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
@TestPropertySource(properties = {"myproperty = foo"})
public class TestWarSpringContext {
...
}
See @TestPropertySource in the Spring docs and Javadocs.
Break out the LIKE
clauses into 2 separate statements, i.e.:
(fieldname1 LIKE '%this%' or fieldname1 LIKE '%that%' ) and something=else
This problem occurs because the password of your git account and your PC might be different. So include your user name as shown in the below example:
https://[email protected]/...
https: //[email protected]/...
You might want to try open source tinybus. With it shake detection is as easy as this.
public class MainActivity extends Activity {
private Bus mBus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
// Create a bus and attach it to activity
mBus = TinyBus.from(this).wire(new ShakeEventWire());
}
@Subscribe
public void onShakeEvent(ShakeEvent event) {
Toast.makeText(this, "Device has been shaken",
Toast.LENGTH_SHORT).show();
}
@Override
protected void onStart() {
super.onStart();
mBus.register(this);
}
@Override
protected void onStop() {
mBus.unregister(this);
super.onStop();
}
}
It uses seismic for shake detection.
First go through this link https://www.python.org/downloads/ to download python 3.6.1 or 2.7.13 either of your choice.I preferred to use python 2.7 or 3.4.4 .now after installation go to the folder name python27/python34 then click on script now here open the command prompt by left click ad run as administration. After the command prompt appear write their "pip install numpy" this will install the numpy latest version and installing it will show success comment that's all. Similarly matplotlib can be install by just typing "pip install matplotlip". And now if you want to download scipy then just write "pip install scipy" and if it doesn't work then you need to download python scipy from the link https://sourceforge.net/projects/scipy/ and install it.
I had the same problem and trouble getting it to work on all browsers.
So this is the best font stack for Helvetica Neue Condensed Bold I could find:
font-family: "HelveticaNeue-CondensedBold", "HelveticaNeueBoldCondensed", "HelveticaNeue-Bold-Condensed", "Helvetica Neue Bold Condensed", "HelveticaNeueBold", "HelveticaNeue-Bold", "Helvetica Neue Bold", "HelveticaNeue", "Helvetica Neue", 'TeXGyreHerosCnBold', "Helvetica", "Tahoma", "Geneva", "Arial Narrow", "Arial", sans-serif; font-weight:600; font-stretch:condensed;
Even more stacks to find at:
http://rachaelmoore.name/posts/design/css/web-safe-helvetica-font-stack/
For the searching, use querystrings. This is perfectly RESTful:
/cars?color=blue&type=sedan&doors=4
An advantage to regular querystrings is that they are standard and widely understood and that they can be generated from form-get.
You cannot do this:
vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);
in a class outside of a method.
You can initialize the data members at the point of declaration, but not with ()
brackets:
class Foo {
vector<string> name = vector<string>(5);
vector<int> val{vector<int>(5,0)};
};
Before C++11, you need to declare them first, then initialize them e.g in a contructor
class Foo {
vector<string> name;
vector<int> val;
public:
Foo() : name(5), val(5,0) {}
};
Answer is YES
<html>
<head>
</head>
<body>
<script language="javascript">
function WriteToFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\NewFile.txt", true);
var text=document.getElementById("TextArea1").innerText;
s.WriteLine(text);
s.WriteLine('***********************');
s.Close();
}
</script>
<form name="abc">
<textarea name="text">FIFA</textarea>
<button onclick="WriteToFile()">Click to save</Button>
</form>
</body>
</html>
There seems to be no way to place buttons (drawings, images) within cells in a way that would allow them to be linked to Apps Script functions.
This being said, there are some things that you can indeed do:
You can place images within cells using IMAGE(URL)
, but they cannot be linked to Apps Script functions.
You can place images within cells and link them to URLs using:
=HYPERLINK("http://example.com"; IMAGE("http://example.com/myimage.png"; 1))
You can create drawings as described in the answer of @Eduardo and they can be linked to Apps Script functions, but they will be stand-alone items that float freely "above" the spreadsheet and cannot be positioned in cells. They cannot be copied from cell to cell and they do not have a row or col position that the script function could read.
You can do the following:
private ToolStripMenuItem getToolStripMenuItemByName(string nameParam) { foreach (Control ctn in this.Controls) { if (ctn is ToolStripMenuItem) { if (ctn.Name = nameParam) { return ctn; } } } return null; }
on your child page, put these:
<script type="text/javascript">
function refreshAndClose() {
window.opener.location.reload(true);
window.close();
}
</script>
and
<body onbeforeunload="refreshAndClose();">
but as a good UI design, you should use a Close button
because it's more user friendly. see code below.
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
window.opener.location.reload(true);
window.close();
});
});
</script>
<input type='button' id='btn' value='Close' />
You should use g++
, not gcc
, to compile C++ programs.
For this particular program, I just typed
make avishay
and let make
figure out the rest. Gives your executable a decent name, too, instead of a.out
.
package Browser;
import org.openqa.selenium.WebDriver; import org.openqa.selenium.ie.InternetExplorerDriver;
public class Hello {
public static void main(String[] args) {
// setting IEdriver property
System.setProperty("webdriver.ie.driver",
"paste the path of the IEDriverserver.exe");
WebDriver driver = new InternetExplorerDriver();
// launching the google home screen
driver.get("https://www.google.com/?gws_rd=ssl");
}
} //Hope this will work
See jQuery's post
function.
I would create a button, and set an onClickListener
($('#button').on('click', function(){});
), and send the data in the function.
Also, see the preventDefault
function, of jQuery!
I had a different issue that brought me to this question, which will probably be more common than the overrelease issue in the accepted answer.
Root cause was our completion block being called twice due to bad if/else fallthrough in the network handler, leading to two calls of dispatch_group_leave
for every one call to dispatch_group_enter
.
dispatch_group_enter(group);
[self badMethodThatCallsMULTIPLECompletions:^(NSString *completion) {
// this block is called multiple times
// one `enter` but multiple `leave`
dispatch_group_leave(group);
}];
count
Upon the EXC_BAD_INSTRUCTION
, you should still have access to your dispatch_group in the debugger. DispatchGroup: check how many "entered"
Print out the dispatch_group and you'll see:
<OS_dispatch_group: group[0x60800008bf40] = { xrefcnt = 0x2, refcnt = 0x1, port = 0x0, count = -1, waiters = 0 }>
When you see count = -1
it indicates that you've over-left the dispatch_group. Be sure to dispatch_enter
and dispatch_leave
the group in matched pairs.
TLDR: Usually, you don't need to change the validation message but if you do use this:
<input
oninvalid="this.setCustomValidity('Your custom message / ???????')"
oninput="this.setCustomValidity('')"
required="required"
type="text"
name="text"
>
The validation messages are coming from your browser and if your browser is in English the message will be in English, if the browser is in French the message will be in French and so on.
If you an input for which the default validation messages doesn't work for you, the easiest solution is to provide your custom message to setCustomValidity
as a parameter.
...
oninvalid="this.setCustomValidity('Your custom message / ???????')"
...
This is a native input's method which overwrites the default message. But now we have one problem, once the validation is triggered, the message will keep showing while the user is typing. So to stop the message from showing you can set the validity message to empty string using the oninput
attribute.
...
oninput="this.setCustomValidity('')"
...
foo = [0, 1, 2, "", , false, 3, "four", null]
foo.filter(function(e) {
return e === 0 ? '0' : e
})
returns
[0, 1, 2, 3, "four"]
By default std::map
(and std::set
) use operator<
to determine sorting. Therefore, you need to define operator<
on your class.
Two objects are deemed equivalent if !(a < b) && !(b < a)
.
If, for some reason, you'd like to use a different comparator, the third template argument of the map
can be changed, to std::greater
, for example.
Abstraction is like using a computer.
You have absolutely no idea what's going on with it beyond what you see with the GUI (graphical user interface) and external hardware (e.g. screen). All those pretty colors and such. You're only presented the details relevant to you as a generic consumer.
Encapsulation is the actual act of hiding the irrelevant details.
You use your computer, but you don't see what its CPU (central processing unit) looks like (unless you try to break into it). It's hidden (or encapsulated) behind all that chrome and plastic.
In the context of OOP (object-oriented programming) languages, you usually have this kind of setup:
CLASS {
METHOD {
*the actual code*
}
}
An example of "encapsulation" would be having a METHOD that the regular user can't see (private). "Abstraction" is the regular user using the METHOD that they can (public) in order to use the private one.
We have used the combination of:
Cobian Backup for scheduling/maintenance
ExpressMaint for backup
Both of these are free. The process is to script ExpressMaint to take a backup as a Cobian "before Backup" event. I usually let this overwrite the previous backup file. Cobian then takes a zip/7zip out of this and archives these to the backup folder. In Cobian you can specify the number of full copies to keep, make multiple backup cycles etc.
ExpressMaint command syntax example:
expressmaint -S HOST\SQLEXPRESS -D ALL_USER -T DB -R logpath -RU WEEKS -RV 1 -B backuppath -BU HOURS -BV 3
I totally agree with Abacus (sorry - don't have enough points to comment).
Also, keep in mind it doesn't necessarily come down to how many records you have, but the size of your records.
For instance, have you considered the performance difference between 1,000 records with 50 columns each vs 100,000 records with only 5 columns each?
Lastly, maybe you're querying/storing more data than you need? Here's a good read on SQL optimization strategies. Limit the amount of data you're pulling, especially if you're not using it all (some SQL programmers do get lazy and just select everything even though they only use a tiny subset). Don't forget the SQL query analyzer may also become your best friend.
in my case, some characters like " , :"'{}[] " maybe corrupt the JSON format, so use try json.loads(str) except to check your input
First Button submits the form and second does not
<body>
<form ng-app="myApp" ng-controller="myCtrl" ng-submit="Sub()">
<div>
S:<input type="text" ng-model="v"><br>
<br>
<button>Submit</button>
//Dont Submit
<button type='button' ng-click="Dont()">Dont Submit</button>
</div>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.Sub=function()
{
alert('Inside Submit');
}
$scope.Dont=function()
{
$scope.v=0;
}
});
</script>
</body>
Assuming you're using bash
#!/bin/bash
current_dir=$(pwd)
script_dir=$(dirname "$0")
echo $current_dir
echo $script_dir
This script should print the directory that you're in, and then the directory the script is in. For example, when calling it from /
with the script in /home/mez/
, it outputs
/
/home/mez
Remember, when assigning variables from the output of a command, wrap the command in $(
and )
- or you won't get the desired output.
In gameprofile.html
please change the tag {% endblock content %}
to {% endblock %}
then it works otherwise django will not load the endblock and give error.
Working solution for Windows:
Control Panel > User Accounts > Credential Manager > Generic Credentials
I used the strip function to get rid of newline character as split lines was throwing memory errors on 4 gb File.
Sample Code:
with open('C:\\aapl.csv','r') as apple:
for apps in apple.readlines():
print(apps.strip())
or... you can just put some style like this.
.panel-title a.collapsed {
background: url(../img/arrow_right.png) center right no-repeat;
}
.panel-title a {
background: url(../img/arrow_down.png) center right no-repeat;
}
Maybe i am late here, but i have the same issue, so i wrote a unminified-webpack-plugin for this purpose.
Installation
npm install --save-dev unminified-webpack-plugin
Usage
var path = require('path');
var webpack = require('webpack');
var UnminifiedWebpackPlugin = require('unminified-webpack-plugin');
module.exports = {
entry: {
index: './src/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'library.min.js'
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
new UnminifiedWebpackPlugin()
]
};
By doing as above, you will get two files library.min.js and library.js. No need execute webpack twice, it just works!^^
Let us say we have to sort a list of objects in ascending order based on a particular property, in this example lets say we have to sort based on the "name" property, then below is the required code :
var list_Objects = [{"name"="Bob"},{"name"="Jay"},{"name"="Abhi"}];
Console.log(list_Objects); //[{"name"="Bob"},{"name"="Jay"},{"name"="Abhi"}]
list_Objects.sort(function(a,b){
return a["name"].localeCompare(b["name"]);
});
Console.log(list_Objects); //[{"name"="Abhi"},{"name"="Bob"},{"name"="Jay"}]
I use the file *nix command to convert a unknown charset file in a utf-8 file
# -*- encoding: utf-8 -*-
# converting a unknown formatting file in utf-8
import codecs
import commands
file_location = "jumper.sub"
file_encoding = commands.getoutput('file -b --mime-encoding %s' % file_location)
file_stream = codecs.open(file_location, 'r', file_encoding)
file_output = codecs.open(file_location+"b", 'w', 'utf-8')
for l in file_stream:
file_output.write(l)
file_stream.close()
file_output.close()
You have everything right, but the problem is with getLine1Number()
function.
getLine1Number()- this method returns the phone number string for line 1, i.e the MSISDN for a GSM phone. Return null if it is unavailable.
this method works only for few cell phone but not all phones.
So, if you need to perform operations according to the sim(other than calling), then you should use getSimSerialNumber()
. It is always unique, valid and it always exists.
If you need simplify code then live is better in the most cases. If you need to get the best performance then delegate will always better than live. bind (click) vs delegate isn't so simple question (if you have a lot of similar items then delegate will be better).
lxml.objectify is really simple.
Taking your sample text:
from lxml import objectify
from collections import defaultdict
count = defaultdict(int)
root = objectify.fromstring(text)
for item in root.bar.type:
count[item.attrib.get("foobar")] += 1
print dict(count)
Output:
{'1': 1, '2': 1}
It depends.
Start with Basic I/O, take a look at Properties, take a look at Preferences API and maybe even Java API for XML Processing and Java Architecture for XML Binding
And if none of those meet your particular needs, you could even look at using some kind of Database
You can try this, using apply()
function
> d
name plate value1 value2
1 A P1 1 100
2 B P2 2 200
3 C P3 3 300
> f <- function(x, output) {
wellName <- x[1]
plateName <- x[2]
wellID <- 1
print(paste(wellID, x[3], x[4], sep=","))
cat(paste(wellID, x[3], x[4], sep=","), file= output, append = T, fill = T)
}
> apply(d, 1, f, output = 'outputfile')
1 is most readable not compatible with all compilers.
No ISO C compiler has a built in type called bool
. ISO C99 compilers have a type _Bool
, and a header which typedef's bool
. So compatability is simply a case of providing your own header if the compiler is not C99 compliant (VC++ for example).
Of course a simpler approach is to compile your C code as C++.
The main reason is that deflate is faster to encode than gzip and on a busy server that might make a difference. With static pages it's a different question, since they can easily be pre-compressed once.
This code might work for non-.NET Core MVC controllers:
this.HttpContext.Response.StatusCode = 418; // I'm a teapot
return Json(new { status = "mer" }, JsonRequestBehavior.AllowGet);
I have tried xlrd, pandas, openpyxl and other such libraries and all of them seem to take exponential time as the file size increase as it reads the entire file. The other solutions mentioned above where they used 'on_demand' did not work for me. If you just want to get the sheet names initially, the following function works for xlsx files.
def get_sheet_details(file_path):
sheets = []
file_name = os.path.splitext(os.path.split(file_path)[-1])[0]
# Make a temporary directory with the file name
directory_to_extract_to = os.path.join(settings.MEDIA_ROOT, file_name)
os.mkdir(directory_to_extract_to)
# Extract the xlsx file as it is just a zip file
zip_ref = zipfile.ZipFile(file_path, 'r')
zip_ref.extractall(directory_to_extract_to)
zip_ref.close()
# Open the workbook.xml which is very light and only has meta data, get sheets from it
path_to_workbook = os.path.join(directory_to_extract_to, 'xl', 'workbook.xml')
with open(path_to_workbook, 'r') as f:
xml = f.read()
dictionary = xmltodict.parse(xml)
for sheet in dictionary['workbook']['sheets']['sheet']:
sheet_details = {
'id': sheet['@sheetId'],
'name': sheet['@name']
}
sheets.append(sheet_details)
# Delete the extracted files directory
shutil.rmtree(directory_to_extract_to)
return sheets
Since all xlsx are basically zipped files, we extract the underlying xml data and read sheet names from the workbook directly which takes a fraction of a second as compared to the library functions.
Benchmarking: (On a 6mb xlsx file with 4 sheets)
Pandas, xlrd: 12 seconds
openpyxl: 24 seconds
Proposed method: 0.4 seconds
Since my requirement was just reading the sheet names, the unnecessary overhead of reading the entire time was bugging me so I took this route instead.
Here is my solution if you need to change only color of title and not color of text in search widget.
layout/toolbar.xml
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:background="@color/toolbar_bg"
app:theme="@style/AppTheme.Toolbar"
app:titleTextAppearance="@style/AppTheme.Toolbar.Title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"/>
values/themes.xml
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="windowActionBar">false</item>
</style>
<style name="AppTheme.Toolbar" parent="ThemeOverlay.AppCompat.ActionBar">
<!-- Customize color of navigation drawer icon and back arrow -->
<item name="colorControlNormal">@color/toolbar_icon</item>
</style>
<style name="AppTheme.Toolbar.Title" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
<!-- Set proper title size -->
<item name="android:textSize">@dimen/abc_text_size_title_material_toolbar</item>
<!-- Set title color -->
<item name="android:textColor">@color/toolbar_title</item>
</style>
</resources>
In the similar way, you can set also subtitleTextAppearance.
Define a class like this :
public class myclass {
string id ;
string title ;
string content;
}
public class program {
public void Main () {
List<myclass> objlist = new List<myclass> () ;
foreach (var value in objlist) {
TextBox1.Text = value.id ;
TextBox2.Text= value.title;
TextBox3.Text= value.content ;
}
}
}
I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.
Although all the answers given are correct, in fact they do not completely answer the question which was about using the [] construct and more generally filling the array with objects.
A more relevant answer can be found in how to build arrays of objects in PHP without specifying an index number? which clearly shows how to solve the problem.
The way we have done it was using Broadcasts:
AppActivity.onCreate()
and unregister in AppActivity.onDestroy()
BroadcastReceiver.onReceive()
just restart the activity.AppActivity
is the parent activity which all other activities subclass.
Below is the snippet from my code, not tested outside the project, but should give you a nice idea.
When the user changes the language
sendBroadcast(new Intent("Language.changed"));
And in the parent activity
public class AppActivity extends Activity {
/**
* The receiver that will handle the change of the language.
*/
private BroadcastReceiver mLangaugeChangedReceiver;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
// Other code here
// ...
// Define receiver
mLangaugeChangedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
startActivity(getIntent());
finish();
}
};
// Register receiver
registerReceiver(mLangaugeChangedReceiver, new IntentFilter("Language.changed"));
}
@Override
protected void onDestroy() {
super.onDestroy();
// ...
// Other cleanup code here
// ...
// Unregister receiver
if (mLangaugeChangedReceiver != null) {
try {
unregisterReceiver(mLangaugeChangedReceiver);
mLangaugeChangedReceiver = null;
} catch (final Exception e) {}
}
}
}
This will also refresh the activity which changed the language (if it subclasses the above activity).
This will make you lose any data, but if it is important you should already have taken care of this using Actvity.onSaveInstanceState()
and Actvity.onRestoreInstanceState()
(or similar).
Let me know your thoughts about this.
Cheers!
change your
return @str1+'present in the string' ;
to
set @r = @str1+'present in the string'
If the user should select only one option at once, just remove the "multiple" - make a normal select:
<select name="mySelect" size="3">
<option>Foo</option>
<option>Bar</option>
<option>Foo Bar</option>
<option>Bar Foo</option>
</select>
Here is a multi-IP address version of jhurliman's answer:
function getIPAddresses() {
var ipAddresses = [];
var interfaces = require('os').networkInterfaces();
for (var devName in interfaces) {
var iface = interfaces[devName];
for (var i = 0; i < iface.length; i++) {
var alias = iface[i];
if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
ipAddresses.push(alias.address);
}
}
}
return ipAddresses;
}
You can achieve that by printing your string like:
<?php $string ='here is your string.'; print_r($string); ?>
No need to use jQuery, querystring
or manually assemble the payload. URLSearchParams
is a way to go and here is one of the most concise answers with the full request example:
fetch('https://example.com/login', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
'param': 'Some value',
'another_param': 'Another value'
})
})
.then(res => {
// Do stuff with the result
});
Yes, you can use Axios or whatever you want instead of fetch
.
P.S. URLSearchParams
is not supported in IE.
Add the following:
using System.Linq
...and call ToList()
on the IQueryable<>
.
Check out the ReadKey()
method on the System.Console
.NET class. I think that will do what you're looking for.
http://msdn.microsoft.com/en-us/library/system.console.readkey(v=vs.110).aspx
Example:
Write-Host -Object ('The key that was pressed was: {0}' -f [System.Console]::ReadKey().Key.ToString());
Put this .gitignore
into the folder, then git add .gitignore
.
*
*/
!.gitignore
The *
line tells git to ignore all files in the folder, but !.gitignore
tells git to still include the .gitignore
file. This way, your local repository and any other clones of the repository all get both the empty folder and the .gitignore
it needs.
Edit: May be obvious but also add */
to the .gitignore
to also ignore subfolders.
Change
keras.callbacks.TensorBoard(log_dir='/Graph', histogram_freq=0,
write_graph=True, write_images=True)
to
tbCallBack = keras.callbacks.TensorBoard(log_dir='Graph', histogram_freq=0,
write_graph=True, write_images=True)
and set your model
tbCallback.set_model(model)
Run in your terminal
tensorboard --logdir Graph/
I agree with zach that counting within dplyr is the best solution. I've found this to be the shortest version:
dplyr::count(theTable, Position) %>%
arrange(-n) %>%
mutate(Position = factor(Position, Position)) %>%
ggplot(aes(x=Position, y=n)) + geom_bar(stat="identity")
This will also be significantly faster than reordering the factor levels beforehand since the count is done in dplyr not in ggplot or using table
.
Use fabs() instead of abs(), it's the same but for floats instead of integers.
Another useful way of doing it that I use is unions:
union byteint
{
byte b[sizeof int];
int i;
};
byteint bi;
bi.i = 1337;
for(int i = 0; i<4;i++)
destination[i] = bi.b[i];
This will make it so that the byte array and the integer will "overlap"( share the same memory ). this can be done with all kinds of types, as long as the byte array is the same size as the type( else one of the fields will not be influenced by the other ). And having them as one object is also just convenient when you have to switch between integer manipulation and byte manipulation/copying.
Another scenario that can cause this exception is with DataBinding, that is when you use something like this in your layout
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="model"
type="point.to.your.model"/>
</data>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@{model.someIntegerVariable}"/>
</layout>
Notice that the variable I'm using is an Integer and I'm assigning it to the text field of the TextView. Since the TextView already has a method with signature of setText(int)
it will use this method instead of using the setText(String)
and cast the value. Thus the TextView thinks of your input number as a resource value which obviously is not valid.
Solution is to cast your int value to string like this
android:text="@{String.valueOf(model.someIntegerVariable)}"
If you just need to suspend for testing purpose you current thread execution try this:
function longExecFunc(callback, count) {
for (var j = 0; j < count; j++) {
for (var i = 1; i < (1 << 30); i++) {
var q = Math.sqrt(1 << 30);
}
}
callback();
}
longExecFunc(() => { console.log('done!')}, 5); //5, 6 ... whatever. Higher -- longer
jQuery stores events in the following:
$("a#somefoo").data("events")
Doing a console.log($("a#somefoo").data("events"))
should list the events attached to that element.
Sometimes renaming .cpp to .mm is not good idea, especially when project is crossplatform. In this case for xcode project I open xcode project file throught TextEdit, found string which contents interest file, it should be like:
/* OnlineManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = OnlineManager.cpp; sourceTree = "<group>"; };
and then change file type from sourcecode.cpp.cpp to sourcecode.cpp.objcpp
/* OnlineManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = **sourcecode.cpp.objcpp**; path = OnlineManager.cpp; sourceTree = "<group>"; };
It is equivalent to rename .cpp to .mm
As stated by David W. "First of all, check your URL" - Our dns entry changed breaking all svn repo connections. Connecting on ip instead of url as Wes stated worked - (now we have to fix our dns)
Select JoiningDate ,Dateadd (day , 30 , JoiningDate)
from Emp
Select JoiningDate ,DateAdd (month , 10 , JoiningDate)
from Emp
Select JoiningDate ,DateAdd (year , 10 , JoiningDate )
from Emp
Select DateAdd(Hour, 10 , JoiningDate )
from emp
Select dateadd (hour , 10 , getdate()), getdate()
Select dateadd (hour , 10 , joiningDate)
from Emp
Select DateAdd (Second , 120 , JoiningDate ) , JoiningDate
From EMP
Ultimately no. You can query for listings with a search string from an RSS feed such as this:
http://YOURCITY.craigslist.org/search/sss?format=rss&query=SearchString
As far as posting, craiglist has not opened their API. However, this SO Question may shed some light and a possible solution - although not a very reliable one.
Craigslist Automated Posting API?
Write a note to craigslist asking them to open their API,
I also had the same problem while accessing RESTful web services. And I their with the below code to overcome the issue:
public class Test {
//Bypassing the SSL verification to execute our code successfully
static {
disableSSLVerification();
}
public static void main(String[] args) {
//Access HTTPS URL and do something
}
//Method used for bypassing SSL verification
public static void disableSSLVerification() {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
SSLContext sc = null;
try {
sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
}
It worked for me. try it!!
Below code for an uploading a single file at a time. This is correct and perfect to upload a single file. Read all commented instructions and follow the code. Definitely, it is worked.
public function upload_file() {
***// Upload folder location***
$config['upload_path'] = './public/upload/';
***// Allowed file type***
$config['allowed_types'] = 'jpg|jpeg|png|pdf';
***// Max size, i will set 2MB***
$config['max_size'] = '2024';
$config['max_width'] = '1024';
$config['max_height'] = '768';
***// load upload library***
$this->load->library('upload', $config);
***// do_upload is the method, to send the particular image and file on that
// particular
// location that is detail in $config['upload_path'].
// In bracks will set name upload, here you need to set input name attribute
// value.***
if($this->upload->do_upload('upload')) {
$data = $this->upload->data();
$post['upload'] = $data['file_name'];
} else {
$error = array('error' => $this->upload->display_errors());
}
}
The performance benefit is from not having to reopen the file once the #pragma once have been read. With guards, the compiler have to open the file (that can be costly in time) to get the information that it shouldn't include it's content again.
That is theory only because some compilers will automatically not open files that didn't have any read code in, for each compilation unit.
Anyway, it's not the case for all compilers, so ideally #pragma once have to be avoided for cross-platform code has it's not standard at all / have no standardized definition and effect. However, practically, it's really better than guards.
In the end, the better suggestion you can get to be sure to have the best speed from your compiler without having to check the behavior of each compiler in this case, is to use both pragma once and guards.
#ifndef NR_TEST_H
#define NR_TEST_H
#pragma once
#include "Thing.h"
namespace MyApp
{
// ...
}
#endif
That way you get the best of both (cross-platform and help compilation speed).
As it's longer to type, I personally use a tool to help generate all that in a very wick way (Visual Assist X).
Method 1 - Very Simple
In Package.json
- you'll see bootstrap package installed with version mentioned.
"dependencies": {
// ...
"bootstrap": "x.x.x"
// ...
}
Method 2
node_modules
folder and under thatbootstrap
folderpackage.json
scss/bootstrap.scss
or css/bootstrap.css
README.md
Very simple to solve!!
I don't like an idea of having logic inside adapter as a different view type because every time it checks for the view type before returning the view. Below solution avoids extra checks.
Just add LinearLayout (vertical) header view + recyclerview + footer view inside android.support.v4.widget.NestedScrollView.
Check this out:
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<View
android:id="@+id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.v7.widget.RecyclerView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="LinearLayoutManager"/>
<View
android:id="@+id/footer"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
Add this line of code for smooth scrolling
RecyclerView v = (RecyclerView) findViewById(...);
v.setNestedScrollingEnabled(false);
This will lose all RV performance and RV will try to lay out all view holders regardless of the layout_height
of RV
Recommended using for the small size list like Nav drawer or settings etc.
Do you mean this?
var listOfList = new List<List<int>>() {
new List<int>() { 1, 2 },
new List<int>() { 3, 4 },
new List<int>() { 5, 6 }
};
var list = new List<int> { 9, 9, 9 };
var result = list.Concat(listOfList.SelectMany(x => x));
foreach (var x in result) Console.WriteLine(x);
Results in: 9 9 9 1 2 3 4 5 6
80 % of the times, this would due to wrong input by in soapRequest.xml file
I was having a lot of problems with justify-content, and I figured out the problem was "margin: 0 auto"
The auto part overrides the justify-content so its always displayed according to the margin and not to the justify-content.
Under Basic settings:
Then hit the advanced tab and scroll down to locate Valid OAuth redirect URIs its right below Client Token.
Then get back to your website or web page and refresh.
-u: disabled by default. When activated, an error message is displayed when using an unconfigured variable.
-v: inactive by default. After activation, the original content of the information will be displayed (without variable resolution) before the information is output.
-x: inactive by default. If activated, the command content will be displayed before the command is run (after variable resolution, there is a ++ symbol).
Compare the following differences:
/ # set -v && echo $HOME
/root
/ # set +v && echo $HOME
set +v && echo $HOME
/root
/ # set -x && echo $HOME
+ echo /root
/root
/ # set +x && echo $HOME
+ set +x
/root
/ # set -u && echo $NOSET
/bin/sh: NOSET: parameter not set
/ # set +u && echo $NOSET