This is in no way specific to std::unique_ptr
, but applies to any class that is movable. It's guaranteed by the language rules since you are returning by value. The compiler tries to elide copies, invokes a move constructor if it can't remove copies, calls a copy constructor if it can't move, and fails to compile if it can't copy.
If you had a function that accepts std::unique_ptr
as an argument you wouldn't be able to pass p to it. You would have to explicitly invoke move constructor, but in this case you shouldn't use variable p after the call to bar()
.
void bar(std::unique_ptr<int> p)
{
// ...
}
int main()
{
unique_ptr<int> p = foo();
bar(p); // error, can't implicitly invoke move constructor on lvalue
bar(std::move(p)); // OK but don't use p afterwards
return 0;
}
You start looking near that code that you know ran, and you stop looking when you reach the code you know didn't run.
What you're looking for is probably some place where your program calls a function through a function pointer, but that pointer is null.
It's also possible you have stack corruption. You might have overwritten a function's return address with zero, and the exception occurs at the end of the function. Check for possible buffer overflows, and if you are calling any DLL functions, make sure you used the right calling convention and parameter count.
This isn't an ordinary case of using a null pointer, like an unassigned object reference or PChar. In those cases, you'll have a non-zero "at address x" value. Since the instruction occurred at address zero, you know the CPU's instruction pointer was not pointing at any valid instruction. That's why the debugger can't show you which line of code caused the problem — there is no line of code. You need to find it by finding the code that lead up to the place where the CPU jumped to the invalid address.
The call stack might still be intact, which should at least get you pretty close to your goal. If you have stack corruption, though, you might not be able to trust the call stack.
Strings are a great example of uses of double pointers. The string itself is a pointer, so any time you need to point to a string, you'll need a double pointer.
Completing the answer from @xanblax
private static string getUserName()
{
SelectQuery query = new SelectQuery(@"Select * from Win32_Process");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
{
foreach (System.Management.ManagementObject Process in searcher.Get())
{
if (Process["ExecutablePath"] != null &&
string.Equals(Path.GetFileName(Process["ExecutablePath"].ToString()), "explorer.exe", StringComparison.OrdinalIgnoreCase))
{
string[] OwnerInfo = new string[2];
Process.InvokeMethod("GetOwner", (object[])OwnerInfo);
return OwnerInfo[0];
}
}
}
return "";
}
->where()
support passing any string to it and it will use it in the query.
You can try using this:
$this->db->select('*')->from('certs');
$this->db->where('`id` NOT IN (SELECT `id_cer` FROM `revokace`)', NULL, FALSE);
The ,NULL,FALSE
in the where()
tells CodeIgniter not to escape the query, which may mess it up.
UPDATE: You can also check out the subquery library I wrote.
$this->db->select('*')->from('certs');
$sub = $this->subquery->start_subquery('where_in');
$sub->select('id_cer')->from('revokace');
$this->subquery->end_subquery('id', FALSE);
Use the str
accessor with square brackets:
df['col'] = df['col'].str[:9]
Or str.slice:
df['col'] = df['col'].str.slice(0, 9)
for github pages I Use
ng build --prod --base-href "https://<username>.github.io/<RepoName>/" --output-path=docs
This is what that copies output into the docs folder : --output-path=docs
$default = [ ... ];
$turnOffSSL = [
'stream' => [
'ssl' => [
'allow_self_signed' => true,
'verify_peer' => false,
'verify_peer_name' => false,
],
],
];
$environment = env('APP_ENV');
if ($environment === 'local') {
return array_merge($default, $turnOffSSL);
}
return $default;
Note that increasing a browser's max connections per server to an excessive number (as some sites suggest) can and does lock other users out of small sites with hosting plans that limit the total simultaneous connections on the server.
Yet another approach: use rbind
on out
:
before <- data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))
out <- strsplit(as.character(before$type),'_and_')
do.call(rbind, out)
[,1] [,2]
[1,] "foo" "bar"
[2,] "foo" "bar_2"
[3,] "foo" "bar"
[4,] "foo" "bar_2"
And to combine:
data.frame(before$attr, do.call(rbind, out))
Try using max-width
instead of width
, the table will still calculate the width automatically.
Works even in ie11
(with ie8 compatibility mode).
td.max-width-50 {_x000D_
border: 1px solid black;_x000D_
max-width: 50px;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
white-space: nowrap;_x000D_
}
_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td class="max-width-50">Hello Stack Overflow</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Hello Stack Overflow</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Hello Stack Overflow</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
your print comes after you return -- you can never reach that statement. Also, you never declared anyItem to be a variable. You might want
public Item anyItem()
{
int index = randomGenerator.nextInt(catalogue.size());
Item randomItem = catalogue.get(index);
System.out.println("Managers choice this week" + randomItem.toString() + "our recommendation to you");
return randomItem;
}
The toString part is just a quickie -- you might want to add a method 'getItemDescription' that returns a useful String for this purpose...
In Android Studio, open the Device Manager: Tools -> Android -> Android Device Monitor
In Eclipse open the Device Manager:
In the device manager you can add files to the SD Card here:
Try this: if you need pass values between the activities you use this...
This is code for Main_Activity put the values to intent
String name="aaaa";
Intent intent=new Intent(Main_Activity.this,Other_Activity.class);
intent.putExtra("name", name);
startActivity(intent);
This code for Other_Activity and get the values form intent
Bundle b = new Bundle();
b = getIntent().getExtras();
String name = b.getString("name");
start from
JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");
you can iterate through JSONArray and use values directly or create Objects of your own type
which will handle data fields inside of each deletedtrs_array
member
Iterating
for(int i = 0; i < deletedtrs_array.length(); i++){
JSONObject obj = deletedtrs_array.getJSONObject(i);
Log.d("Item no."+i, obj.toString());
// create object of type DeletedTrsWrapper like this
DeletedTrsWrapper dtw = new DeletedTrsWrapper(obj);
// String company_id = obj.getString("companyid");
// String username = obj.getString("username");
// String date = obj.getString("date");
// int report_id = obj.getInt("reportid");
}
Own object type
class DeletedTrsWrapper {
public String company_id;
public String username;
public String date;
public int report_id;
public DeletedTrsWrapper(JSONObject obj){
company_id = obj.getString("companyid");
username = obj.getString("username");
date = obj.getString("date");
report_id = obj.getInt("reportid");
}
}
SOLUTION
This means that you are missing the right for using it. Create it with Netsh Commands for Hypertext Transfer Protocol > add urlacl.
1) Open "Command Line Interface (CLI)" called "Command shell" with Win+R write "cmd"
2) Open CLI windows like administrator with mouse context menu on opened windows or icon "Run as administrator"
3) Insert command to register url
netsh http add urlacl url=http://{ip_addr}:{port}/ user=everyone
NOTE:
netsh http delete urlacl url=http://{ip_addr}:{port}/
To convert a string to lower case in Python, use something like this.
list.append(sentence.lower())
I found this in the first result after searching for "python upper to lower case".
undefined
It means the variable is not yet intialized .
Example :
var x;
if(x){ //you can check like this
//code.
}
equals(==)
It only check value is equals not datatype .
Example :
var x = true;
var y = new Boolean(true);
x == y ; //returns true
Because it checks only value .
Strict Equals(===)
Checks the value and datatype should be same .
Example :
var x = true;
var y = new Boolean(true);
x===y; //returns false.
Because it checks the datatype x is a primitive type and y is a boolean object .
A one-liner solution, similar to python, would be (std::set<int> {1, 2, 3, 4}).count(my_var) > 0
.
Minimal working example
int my_var = 3;
bool myVarIn = (std::set<int> {1, 2, 3, 4}).count(my_var) > 0;
std::cout << std::boolalpha << myVarIn << std::endl;
prints true
or false
dependent of the value of my_var.
Use padding-top:50px
for outer div. Something like this:
#outer {
width:500px;
height:200px;
background:#FFCCCC;
margin:50px auto 0 auto;
display:table;}
Note: padding will increase the size of your div. In this case if the size of your div is important, I mean if it must have a specific height. decrease the height by 50px.:
#outer {
width:500px;
height:150px;
background:#FFCCCC;
margin:50px auto 0 auto;
display:table;}
You can try the .delay()
$(".formSentMsg").delay(3200).fadeOut(300);
call the div set the delay time in milliseconds and set the property you want to change, in this case I used .fadeOut() so it could be animated, but you can use .hide() as well.
The following does not plot anything in the plot and it will remain empty.
plot(NULL, xlim=c(0,1), ylim=c(0,1), ylab="y label", xlab="x lablel")
This is useful when you want to add lines or dots afterwards within a for
loop or something similar. Just remember to change the xlim
and ylim
values based on the data you want to plot.
As a side note:
This can also be used for Boxplot, Violin plots and swarm plots. for those remember to add add = TRUE
to their plotting function and also specify at =
to specify on which number you want to plot them (default is x axis unless you have set horz = TRUE
in these functions.
To initialize long you need to append "L" to the end.
It can be either uppercase or lowercase.
All the numeric values are by default int
. Even when you do any operation of byte
with any integer, byte
is first promoted to int
and then any operations are performed.
Try this
byte a = 1; // declare a byte
a = a*2; // you will get error here
You get error because 2
is by default int
.
Hence you are trying to multiply byte
with int
.
Hence result gets typecasted to int
which can't be assigned back to byte
.
public static Dictionary<string, IEnumerable<int>> GetWordsPositions(this string input, string[] Susbtrings)
{
Dictionary<string, IEnumerable<int>> WordsPositions = new Dictionary<string, IEnumerable<int>>();
IEnumerable<int> IndexOfAll = null;
foreach (string st in Susbtrings)
{
IndexOfAll = Regex.Matches(input, st).Cast<Match>().Select(m => m.Index);
WordsPositions.Add(st, IndexOfAll);
}
return WordsPositions;
}
As a follow-up to the accepted answer, this is a minimal definition of the IHTMLScriptElement
interface which does not require to include additional type libraries:
[ComImport, ComVisible(true), Guid(@"3050f28b-98b5-11cf-bb82-00aa00bdce0b")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
[TypeLibType(TypeLibTypeFlags.FDispatchable)]
public interface IHTMLScriptElement
{
[DispId(1006)]
string text { set; [return: MarshalAs(UnmanagedType.BStr)] get; }
}
So a full code inside a WebBrowser control derived class would look like:
protected override void OnDocumentCompleted(
WebBrowserDocumentCompletedEventArgs e)
{
base.OnDocumentCompleted(e);
// Disable text selection.
var doc = Document;
if (doc != null)
{
var heads = doc.GetElementsByTagName(@"head");
if (heads.Count > 0)
{
var scriptEl = doc.CreateElement(@"script");
if (scriptEl != null)
{
var element = (IHTMLScriptElement)scriptEl.DomElement;
element.text =
@"function disableSelection()
{
document.body.onselectstart=function(){ return false; };
document.body.ondragstart=function() { return false; };
}";
heads[0].AppendChild(scriptEl);
doc.InvokeScript(@"disableSelection");
}
}
}
}
You may use the ==
operator to compare unicode objects for equality.
>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>>
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>>
But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode
object to a str
object, like so:
>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False
See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.
Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.
I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."
foreach (DataGridViewRow row in GridView2.Rows)
{
if ( ! row.IsNewRow)
{
for (int i = 0; i < GridView2.Columns.Count; i++)
{
String header = GridView2.Columns[i].HeaderText;
String cellText = Convert.ToString(row.Cells[i].Value);
}
}
}
Here Before Iterating for cell Values need to check for NewRow.
barcode often consist of large number so i think your app crashes because of the size of the string that you are trying to convert to int
. you can use BigInteger
BigInteger reallyBig = new BigInteger(myString);
Isn't this the simplest way?
By column name:
In [20]: df = pd.DataFrame({'x' : [1, 2, 3, 4], 'y' : [4, 5, 6, 7]})
In [21]: df
Out[21]:
x y
0 1 4
1 2 5
2 3 6
3 4 7
In [23]: df.x
Out[23]:
0 1
1 2
2 3
3 4
Name: x, dtype: int64
In [24]: type(df.x)
Out[24]:
pandas.core.series.Series
I got stuck in 'rebase status', I got
On branch master
Your branch is up to date with 'origin/master'.
You are currently rebasing.
(all conflicts fixed: run "git rebase --continue")
nothing to commit, working tree clean
but running git rebase --skip
yielded error: could not read '.git/rebase-apply/head-name': No such file or directory
.
Running rm -fr ".git/rebase-apply"
helped.
Note: of course, do it only if you don't care about the rebase or if you're stuck on a previous rebase you don't want anymore.
In case this is of interest to anyone, I had the same problem when I was running Python in Cygwin, in my case it was complaning that pandas wasn't installed even though it was. The problem was that I had 2 installations of python - one in windows and another one in cygwin (using the cygwin installer) and although both were the same versions of Python, the Cygwin installation was confused about where Pandas was installed. When i uninstalled cygwin's Python and pointed Cygwin at the windows installation everything was fine
You could capture the (2001)
part and replace the rest with nothing.
public static string extractYearString(string input) {
return input.replaceAll(".*\(([0-9]{4})\).*", "$1");
}
var subject = "(2001) (asdf) (dasd1123_asd 21.01.2011 zqge)(dzqge) name (20019)";
var result = extractYearString(subject);
System.out.println(result); // <-- "2001"
.*\(([0-9]{4})\).*
means
.*
match anything\(
match a (
character(
begin capture[0-9]{4}
any single digit four times)
end capture\)
match a )
character.*
anything (rest of string)this is how you can parse iCal files with javascript
function calParse(str) {
function parse() {
var obj = {};
while(str.length) {
var p = str.shift().split(":");
var k = p.shift(), p = p.join();
switch(k) {
case "BEGIN":
obj[p] = parse();
break;
case "END":
return obj;
default:
obj[k] = p;
}
}
return obj;
}
str = str.replace(/\n /g, " ").split("\n");
return parse().VCALENDAR;
}
example =
'BEGIN:VCALENDAR\n'+
'VERSION:2.0\n'+
'PRODID:-//hacksw/handcal//NONSGML v1.0//EN\n'+
'BEGIN:VEVENT\n'+
'DTSTART:19970714T170000Z\n'+
'DTEND:19970715T035959Z\n'+
'SUMMARY:Bastille Day Party\n'+
'END:VEVENT\n'+
'END:VCALENDAR\n'
cal = calParse(example);
alert(cal.VEVENT.SUMMARY);
Mongodb v3.4
You need to do the following to create a secure database:
Make sure the user starting the process has permissions and that the directories exist (/data/db
in this case).
1) Start MongoDB without access control.
mongod --port 27017 --dbpath /data/db
2) Connect to the instance.
mongo --port 27017
3) Create the user administrator (in the admin authentication database).
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
4) Re-start the MongoDB instance with access control.
mongod --auth --port 27017 --dbpath /data/db
5) Connect and authenticate as the user administrator.
mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"
6) Create additional users as needed for your deployment (e.g. in the test authentication database).
use test
db.createUser(
{
user: "myTester",
pwd: "xyz123",
roles: [ { role: "readWrite", db: "test" },
{ role: "read", db: "reporting" } ]
}
)
7) Connect and authenticate as myTester.
mongo --port 27017 -u "myTester" -p "xyz123" --authenticationDatabase "test"
I basically just explained the short version of the official docs here: https://docs.mongodb.com/master/tutorial/enable-authentication/
Use request.args
to get parsed contents of query string:
from flask import request
@app.route(...)
def login():
username = request.args.get('username')
password = request.args.get('password')
Update
I found another simple way
simply declare a property :-
@property( strong , nonatomic) UITextfield *currentTextfield;
and a Tap Gesture Gecognizer:-
@property (strong , nonatomic) UITapGestureRecognizer *resignTextField;
In ViewDidLoad
_currentTextfield=[[UITextField alloc]init];
_resignTextField=[[UITapGestureRecognizer alloc]initWithTarget:@selector(tapMethod:)];
[self.view addGestureRecognizer:_resignTextField];
Implement the textfield delegate method didBeginEditing
-(void)textFieldDidBeginEditing:(UITextField *)textField{
_currentTextfield=textField;
}
Implement Your Tap Gesture Method (_resignTextField)
-(void)tapMethod:(UITapGestureRecognizer *)Gesture{
[_currentTextfield resignFirstResponder];
}
I realize this is quite late, but I needed something like this so I whipped up a quick and dirty method to do this.
+ (UIImage *) image:(UIImage *)image withAlpha:(CGFloat)alpha{
// Create a pixel buffer in an easy to use format
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
UInt8 * m_PixelBuf = malloc(sizeof(UInt8) * height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(m_PixelBuf, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
//alter the alpha
int length = height * width * 4;
for (int i=0; i<length; i+=4)
{
m_PixelBuf[i+3] = 255*alpha;
}
//create a new image
CGContextRef ctx = CGBitmapContextCreate(m_PixelBuf, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGImageRef newImgRef = CGBitmapContextCreateImage(ctx);
CGColorSpaceRelease(colorSpace);
CGContextRelease(ctx);
free(m_PixelBuf);
UIImage *finalImage = [UIImage imageWithCGImage:newImgRef];
CGImageRelease(newImgRef);
return finalImage;
}
It's the response code a SIP User Agent Server (UAS) will send to the client after the client sends a CANCEL request for the original unanswered INVITE request (yet to receive a final response).
Here is a nice CANCEL SIP Call Flow illustration.
I think it is because clr virtual machine uses cpu directly without code opcode translation. It may be optimization for clr application or may be windows mobile/window phone 7 started on INTEL proccessor. Android platform based on linux and theoretically you can start android on virtual machine in i686 environment. In this case virtual machines such as vmware could execute some opcodes direcly. But this option will be allowed only if you write on the Java. Because the Java interpret their byte-code or precompile it before execution. see: http://www.taranfx.com/how-to-run-google-android-in-virtualbox-vmware-on-netbooks
Short function to remove all non-numeric characters but keep the decimal (and return the number):
parseNum = str => +str.replace(/[^.\d]/g, '');_x000D_
let str = 'a1b2c.d3e';_x000D_
console.log(parseNum(str));
_x000D_
at least in Windows it has to be enough and you do not have to take care about path to the browser.
import webbrowser
url = 'https://stackoverflow.com'
webbrowser.open(url)
Note: With the above lines of code, it only opens in windows defualt browser(Microsoft Edge).
Turning off my VPN resolved the issue.
Date userDob = new SimpleDateFormat("yyyy-MM-dd").parse(dob);
Date today = new Date();
long diff = today.getTime() - userDob.getTime();
int numOfDays = (int) (diff / (1000 * 60 * 60 * 24));
int hours = (int) (diff / (1000 * 60 * 60));
int minutes = (int) (diff / (1000 * 60));
int seconds = (int) (diff / (1000));
This article describes how to render a View to a string in different scenarios:
The solution/code is provided as a class called ViewRenderer. It is part of Rick Stahl's WestwindToolkit at GitHub.
Usage (3. - WebAPI example):
string html = ViewRenderer.RenderView("~/Areas/ReportDetail/Views/ReportDetail/Index.cshtml", ReportVM.Create(id));
Try this instead:
var myArray = [];
myArray.push({ id: 0, value: 1 });
myArray.push({ id: 2, value: 3 });
or will this not work for your situation?
For those of you struggling with getting this done trying every possible answer you can find on SO. Here's what worked for me on a VPS running Windows 2012 R2 :
Place your sql file wherever the bin is for me it is located at C:\Program Files\MySQL\MySQL Server 8.0\bin
Open windows command prompt (cmd)
C:\Program Files\MySQL\MySQL Server 8.0\bin > mysql -u [username] -p
use [database_name]
;C://Program Files//MySQL//MySQL Server 8.0//bin//mydatabasename.sql
It did it for me as everything else had failed. It might help you too.
In my case, the problem was fixed by going into my build.gradle
and changing
dependencies {
testImplementation 'junit:junit:4.12'
}
to
dependencies {
testCompile 'junit:junit:4.12'
}
The logic you present is not MVC, then not Rails, compatible.
A controller renders a view or redirect
A method executes code
From these considerations, I advise you to create methods in your controller and call them from your action.
Example:
def index
get_variable
end
private
def get_variable
@var = Var.all
end
That said you can do exactly the same through different controllers and summon a method from controller A while you are in controller B.
Vocabulary is extremely important that's why I insist much.
If table has foreign keys then I always use following code:
SET FOREIGN_KEY_CHECKS = 0; -- disable a foreign keys check
SET AUTOCOMMIT = 0; -- disable autocommit
START TRANSACTION; -- begin transaction
/*
DELETE FROM table_name;
ALTER TABLE table_name AUTO_INCREMENT = 1;
-- or
TRUNCATE table_name;
-- or
DROP TABLE table_name;
CREATE TABLE table_name ( ... );
*/
SET FOREIGN_KEY_CHECKS = 1; -- enable a foreign keys check
COMMIT; -- make a commit
SET AUTOCOMMIT = 1 ;
But difference will be in execution time. Look at above Sorin's answer.
$('#table_id').dataTable({
"bInfo": false, //Dont display info e.g. "Showing 1 to 4 of 4 entries"
"paging": false,//Dont want paging
"bPaginate": false,//Dont want paging
})
Try this code
In the possibility that the second page doesn't have shared access to the session cookie, you'll need to set the session cookie path using session_set_cookie_params:
<?php
session_set_cookie_params( $lifetime, '/shared/path/to/files/' );
session_start();
$_SESSION['myvar']='myvalue';
And
<?php
session_set_cookie_params( $lifetime, '/shared/path/to/files/' );
session_start();
echo("1");
if(isset($_SESSION['myvar']))
{
echo("2");
if($_SESSION['myvar'] == 'myvalue')
{
echo("3");
exit;
}
}
Use clear: both;
I spent over a week trying to figure this out!
If I want to edit a specified comment, how do I get its content and its question?
If you had kept track of the number of comments and the index of the comment you wanted to alter, you could use the dot operator (SO example).
You could do f.ex.
db.questions.update(
{
"title": "aaa"
},
{
"comments.0.contents": "new text"
}
)
(as another way to edit the comments inside the question)
For a list of elements
List<string> lstTest = new List<string>();
lstTest.Add("test1");
lstTest.Add("test2");
lstTest.Add("test3");
lstTest.Add("test4");
lstTest.Add("test5");
lstTest.Add("test6");
If you want to copy all the elements
List<string> lstNew = new List<string>();
lstNew.AddRange(lstTest);
If you want to copy the first 3 elements
List<string> lstNew = lstTest.GetRange(0, 3);
Use the dec argument to set ","
as the decimal point by adding:
ce <- read.table("file.txt", header = TRUE, dec = ",")
In MSDN, Assembly.GetExecutingAssembly Method, is remark about method "getexecutingassembly", that for performance reasons, you should call this method only when you do not know at design time what assembly is currently executing.
The recommended way to retrieve an Assembly object that represents the current assembly is to use the Type.Assembly
property of a type found in the assembly.
The following example illustrates:
using System;
using System.Reflection;
public class Example
{
public static void Main()
{
Console.WriteLine("The version of the currently executing assembly is: {0}",
typeof(Example).Assembly.GetName().Version);
}
}
/* This example produces output similar to the following:
The version of the currently executing assembly is: 1.1.0.0
Of course this is very similar to the answer with helper class "public static class CoreAssembly", but, if you know at least one type of executing assembly, it isn't mandatory to create a helper class, and it saves your time.
I put up this piece of code which explains 3 key concepts about generators:
def numbers():
for i in range(10):
yield i
gen = numbers() #this line only returns a generator object, it does not run the code defined inside numbers
for i in gen: #we iterate over the generator and the values are printed
print(i)
#the generator is now empty
for i in gen: #so this for block does not print anything
print(i)
It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.
Are you doing heavy DOM manipulation? I would use jQuery and Backbone.
Very data driven app? Angular with its nice data binding.
Game programming? None - direct to canvas; maybe a game engine.
You have to put your script tag after the one that references Angular. Move it out of the head
:
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>
The way you've set it up now, your script runs before Angular is loaded on the page.
Does this help?
$("#SelectName option[value='theValueOfOption']")[0].selected = true;
A simple solution is to do this formula:
A1*7+DATE(A2,1,1)
If it returns a Wednesday, simply change the formula to:
(A1*7+DATE(A2,1,1))-2
This will only work for dates within one calendar year.
Well I always use the same easy way and it works for me. In your HTML keep the type as text (like this):
<input type="text" class="textfield" value="" id="onlyNumbers" name="onlyNumbers" onkeypress="return isNumber(event)" onpaste="return false;"/>
After this you only need to add a method on javascript
<script type="text/javascript">
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if ( (charCode > 31 && charCode < 48) || charCode > 57) {
return false;
}
return true;
}
</script>
With this easy validation you will only get positive numbers as you wanted. You can modify the charCodes to add more valid keys to your method.
Here´s the code working: Only numbers validation
Since id is an attribute don't create an id element, just do this:
myPara.setAttribute("id", "id_you_like");
That’s a typo. You’ve accidently set "user.mail" with no "e". Fix it by setting "user.email" in the global configuration with
git config --global user.email "[email protected]"
Found solution here
var a = 'something' + Array(10).fill('\xa0').join('') + 'something'
number inside Array(10)
can be changed to needed number of spaces
Blank screen also happens when your Laravel app tries to display too much information and PHP limits kick in (for example displaying tens of thousands of database records on a single page). The worst part is, you won't see any errors in the Laravel logs. You probably won't see any errors in the PHP FPM logs as well. You might find errors in your http server logs, for example nginx throws something like FastCGI sent in stderr: "PHP message: PHP Fatal error: Allowed memory size of XXX bytes exhausted
.
Short tip: add ->limit(1000)
where 1000
is your limit, on your query object.
there's an interesting way to achive another goal which is to have a strongly type class base on json with a very powerfull tools that i used few days ago for first time to translate tradedoubler json result into classes
Is a simple tool: copy your json source paste and in few second you will have a strongly typed class json oriented . In this manner you will use these classes which is more powerful and simply to use.
<Resource>
tag with your DB details inside <GlobalNamingResources>
<Resource name="jdbc/mydb"
global="jdbc/mydb"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test"
username="root"
password=""
maxActive="10"
maxIdle="10"
minIdle="5"
maxWait="10000"/>
<ResourceLink>
inside the <Context>
tag.<ResourceLink name="jdbc/mydb"
global="jdbc/mydb"
auth="Container"
type="javax.sql.DataSource" />
Adding:
-------
<property name="connection.datasource">java:comp/env/jdbc/mydb</property>
Removing:
--------
<!--<property name="connection.url">jdbc:mysql://localhost:3306/mydb</property> -->
<!--<property name="connection.username">root</property> -->
<!--<property name="connection.password"></property> -->
The 'react-json-view' provides solution rendering json string.
import ReactJson from 'react-json-view';
<ReactJson src={my_important_json} theme="monokai" />
For me the issue resolved when I set the principal section like this:
env.put(Context.SECURITY_PRINCIPAL, userId@domainWithoutProtocolAndPortNo);
DECLARE @MYVAR NVARCHAR(100)
DECLARE @step int
SET @step = 0;
DECLARE MYTESTCURSOR CURSOR
DYNAMIC
FOR
SELECT col FROM [dbo].[table]
OPEN MYTESTCURSOR
FETCH LAST FROM MYTESTCURSOR INTO @MYVAR
print @MYVAR;
WHILE @step < 10
BEGIN
FETCH PRIOR FROM MYTESTCURSOR INTO @MYVAR
print @MYVAR;
SET @step = @step + 1;
END
CLOSE MYTESTCURSOR
DEALLOCATE MYTESTCURSOR
Configuration that I've got on my server was customized a lot and I managed to change password only after I set trust authentication in the pg_hba.conf
file:
local all all trust
Don't forget to change this back to password or md5
\config\backup.php on line 123
'mail' => [
'to' => '',
],
See pjebs comment on Jan 5 on Github.
Method1 :
if (error.code == -1005)
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
dispatch_group_t downloadGroup = dispatch_group_create();
dispatch_group_enter(downloadGroup);
dispatch_group_wait(downloadGroup, dispatch_time(DISPATCH_TIME_NOW, 5000000000)); // Wait 5 seconds before trying again.
dispatch_group_leave(downloadGroup);
dispatch_async(dispatch_get_main_queue(), ^{
//Main Queue stuff here
[self redoRequest]; //Redo the function that made the Request.
});
});
return;
}
Also some suggests to re-connect to the site,
i.e. Firing the POST request TWICE
Solution: Use a method to do connection to the site, return (id), if the network connection was lost, return to use the same method.
Method 2
-(id) connectionSitePost:(NSString *) postSender Url:(NSString *) URL {
// here set NSMutableURLRequest => Request
NSHTTPURLResponse *UrlResponse = nil;
NSData *ResponseData = [[NSData alloc] init];
ResponseData = [NSURLConnection sendSynchronousRequest:Request returningResponse:&UrlResponse error:&ErrorReturn];
if ([UrlResponse statusCode] != 200) {
if ([UrlResponse statusCode] == 0) {
/**** here re-use method ****/
return [self connectionSitePost: postSender Url: URL];
}
} else {
return ResponseData;
}
}
I've had the same problem, This was due to the firewall. I use windows server,
Can you allow the connection permission for program, intead of port 21,22 permission.
Windows Firewall with Advanced Security->
Inbound Rules->
Add Rule->
Program->
"Select Filezilla path with Browse button"->
Allow the Connection
This query works in SQL*PLUS to find out the 2nd Highest Salary -
SELECT * FROM EMP
WHERE SAL = (SELECT MAX(SAL) FROM EMP
WHERE SAL < (SELECT MAX(SAL) FROM EMP));
This is double sub-query.
I hope this helps you..
Add a control, where you want to set focus then change its property like below
<asp:TextBox ID="txtDummy" runat="server" Text="" Width="2" ReadOnly="true" BorderStyle="None" BackColor="Transparent"></asp:TextBox>
In the codebehind, just call like below
txtDummy.Focus()
this method is working in all browser.
Integrated Security=true;
doesn't work in all SQL providers, it throws an exception when used with the OleDb
provider.
So basically Integrated Security=SSPI;
is preferred since works with both SQLClient
& OleDB
provider.
Here's the full set of syntaxes according to MSDN - Connection String Syntax (ADO.NET)
Here's how to get the filepath of the file in Excel 2010.
1) Right click on the Ribbon.
2) Click on "Customize the Ribbon"
3) On the right hand side, click "New Group." This will add a new tab to the Ribbon.
If you want to, click on the "Rename" button the right side and name your tab. For example, I named the tab "Doc Path." This step is optional
4) Under "Choose Commands From" on the left hand side, choose "Commands Not in the Ribbon."
5) Select "Document Location" and "Add" it to your newly created group.
6) The filepath should now appear under the newly created tab on the ribbon.
use ack its simple.
just type ack <string to be searched>
In Swift 4 You can use
->Go Info.plist
-> Click plus of Information properties list
->Add App Transport Security Settings as dictionary
-> Click Plus icon App Transport Security Settings
-> Add Allow Arbitrary Loads set YES
Bellow image look like
I believe what you are looking for is functional approach
const arr = ['a', 'a', 'b', 'g', 'a', 'e'];
const count = arr.filter(elem => elem === 'a').length;
console.log(count); // Prints 3
elem === 'a' is the condition, replace it with your own.
DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.
That is, try adding -lpthread
to your command line.
Just use substring: "apple".substring(3);
will return le
I like this question because this is an area where there's continuous innovation and there's always a need to have a light server especially when talking about embedded servers in small(er) devices. I think answers fall into two broad groups.
While I might consider HTTP libraries like: Jetty, Apache Http Components, Netty and others to be more like a raw HTTP processing facilities. The labelling is very subjective, and depends on the kinds of thing you've been call-on to deliver for small-sites. I make this distinction in the spirit of the question, particularly the remark about...
These raw tools let you do that (as described in other answers). They don't really lend themselves to a ready-set-go style of making a light, embedded or mini-server. A mini-server is something that can give you similar functionality to a full-function web server (like say, Tomcat) without bells and whistles, low volume, good performance 99% of the time. A thin-server seems closer to the original phrasing just a bit more than raw perhaps with a limited subset functionality, enough to make you look good 90% of the time. My idea of raw would be makes me look good 75% - 89% of the time without extra design and coding. I think if/when you reach the level of WAR files, we've left the "small" for bonsi servers that looks like everything a big server does smaller.
Thin-server options
Mini-server options:
Among the other things to consider, I'd include authentication, validation, internationalisation, using something like FreeMaker or other template tool to render page output. Otherwise managing HTML editing and parameterisation is likely to make working with HTTP look like noughts-n-crosses. Naturally it all depends on how flexible you need to be. If it's a menu-driven FAX machine it can be very simple. The more interactions, the 'thicker' your framework needs to be. Good question, good luck!
The answer by Craig Ringer is correct. Here's a little more info for Postgres 9.1 and later…
You can only install an extension if it has already been built for your Postgres installation (your cluster in Postgres lingo). For example, I found the uuid-ossp extension included as part of the installer for Mac OS X kindly provided by EnterpriseDB.com. Any of a few dozen extensions may be available.
To see if the uuid-ossp extension is available in your Postgres cluster, run this SQL to query the pg_available_extensions
system catalog:
SELECT * FROM pg_available_extensions;
To install that UUID-related extension, use the CREATE EXTENSION command as seen in this this SQL:
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
Beware: I found the QUOTATION MARK characters around extension name to be required, despite documentation to the contrary.
The SQL standards committee or Postgres team chose an odd name for that command. To my mind, they should have chosen something like "INSTALL EXTENSION" or "USE EXTENSION".
You can verify the extension was successfully installed in the desired database by running this SQL to query the pg_extension
system catalog:
SELECT * FROM pg_extension;
For more info, see the Question: Default value for UUID column in Postgres
The information above uses the new Extensions feature added to Postgres 9.1. In previous versions, we had to find and run a script in a .sql file. The Extensions feature was added to make installation easier, trading a bit more work for the creator of an extension for less work on the part of the user/consumer of the extension. See my blog post for more discussion.
By the way, the code in the Question calls the function uuid_generate_v4()
. This generates a type known as Version 4 where nearly all of the 128 bits are randomly generated. While this is fine for limited use on smaller set of rows, if you want to virtually eliminate any possibility of collision, use another "version" of UUID.
For example, the original Version 1 combines the MAC address of the host computer with the current date-time and an arbitrary number, the chance of collisions is practically nil.
For more discussion, see my Answer on related Question.
I've made an alternative to the other good answers on here that uses PowerShell, but mine also saves the list to a file. Will share it here in case anyone else needs wants something like that.
Warning: Code overwrites "longfilepath.txt" in the current working directory. I know it's unlikely you'd have one already, but just in case!
Purposely wanted it in a single line:
Out-File longfilepath.txt ; cmd /c "dir /b /s /a" | ForEach-Object { if ($_.length -gt 250) {$_ | Out-File -append longfilepath.txt}}
Detailed instructions:
cat longfilepath.txt | sort
Explanation:
Out-File longfilepath.txt ;
– Create (or overwrite) a blank file titled 'longfilepath.txt'. Semi-colon to separate commands.
cmd /c "dir /b /s /a" |
– Run dir command on PowerShell, /a
to show all files including hidden files. |
to pipe.
ForEach-Object { if ($_.length -gt 250) {$_ | Out-File -append longfilepath.txt}}
– For each line (denoted as $_), if the length is greater than 250, append that line to the file.
For the future I would recommend Eran Harel's answer (refactoring moving new
to factory that can be mocked). But if you don't want to change the original source code, use very handy and unique feature: spies. From the documentation:
You can create spies of real objects. When you use the spy then the real methods are called (unless a method was stubbed).
Real spies should be used carefully and occasionally, for example when dealing with legacy code.
In your case you should write:
TestedClass tc = spy(new TestedClass());
LoginContext lcMock = mock(LoginContext.class);
when(tc.login(anyString(), anyString())).thenReturn(lcMock);
Ok, this is pretty weird. I have a couple of projects: one is a UI project (an ASP.NET MVC project) and the others are projects for stuff like repositories. The repositories project had a reference to EF, but the UI project didn't (because it didn't need one, it just needed to reference the other projects). After I installed EF for the UI project as well, everything started working. This is why, it added this piece of code to my Web.config:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
Step 1
Search
→ Find
→ (goto Tab) Mark
Find what
: ^Session.*$ Bookmark line
Regular expression
(under Search Mode
)Mark All
(this will find the regex and highlights all the lines and bookmark them) Step 2
Search
→ Bookmark
→ Remove Bookmarked Lines
Using filter()
and lambda
would provide a neat and terse method of removing unwanted values:
newEmails = list(filter(lambda x : x != '[email protected]', emails))
This does not modify emails. It creates the new list newEmails containing only elements for which the anonymous function returned True.
Within an event handler function or object method, one way to access the properties of "the containing element" is to use the special this keyword. The this keyword represents the owner of the function or method currently being processed. So:
For a global function, this represents the window.
For an object method, this represents the object instance.
And in an event handler, this represents the element that received the event.
For example:
<!DOCTYPE html>
<html>
<head>
<script>
function mouseDown() {
alert(this);
}
</script>
</head>
<body>
<p onmouseup="mouseDown();alert(this);">Hi</p>
</body>
</html>
The content of alert windows after rendering this html respectively are:
object Window
object HTMLParagraphElement
An Event object is associated with all events. It has properties that provide information "about the event", such as the location of a mouse click in the web page.
For example:
<!DOCTYPE html>
<html>
<head>
<script>
function mouseDown(event) {
var theEvent = event ? event : window.event;
var locString = "X = " + theEvent.screenX + " Y = " + theEvent.screenY;
alert(event);
alert(locString);
}
</script>
</head>
<body>
<p onmouseup="mouseDown(event);">Hi</p>
</body>
</html>
The content of alert windows after rendering this html respectively are:
object MouseEvent
X = 982 Y = 329
Mark all the desired projects in solution explorer.
Press Alt-F7 or right click in solution explorer and select "Properties"
Configurations:All Configurations
Click on the Preprocessor Definitions line to invoke its editor
Choose Edit...
Copy "_CRT_SECURE_NO_WARNINGS" into the Preprocessor Definitions white box on the top.
Unfortuantely composer requires a lot of RAM & processing power. Here are a few things that I did, which combined, made the process bearable. This was on my cloud playpen env.
service mysql stop
(kill your DB/mem-hog services to free some RAM - don't forget to start it again!) top
to watch memory/swap consumption until process is complete.composer.phar update --prefer-dist -vvv
(verbose output [still hangs at some points when working] and use distro zip files). Maybe try a --dry-run
too? The **
never properly worked before, but since git 1.8.2 (March, 8th 2013), it seems to be explicitly mentioned and supported:
The patterns in
.gitignore
and.gitattributes
files can have**/
, as a pattern that matches 0 or more levels of subdirectory.E.g. "
foo/**/bar
" matches "bar
" in "foo
" itself or in a subdirectory of "foo
".
In your case, that means this line might now be supported:
/main/**/bin/
You need to run Set-ExecutionPolicy
:
Set-ExecutionPolicy Restricted <-- Will not allow any powershell scripts to run. Only individual commands may be run.
Set-ExecutionPolicy AllSigned <-- Will allow signed powershell scripts to run.
Set-ExecutionPolicy RemoteSigned <-- Allows unsigned local script and signed remote powershell scripts to run.
Set-ExecutionPolicy Unrestricted <-- Will allow unsigned powershell scripts to run. Warns before running downloaded scripts.
Set-ExecutionPolicy Bypass <-- Nothing is blocked and there are no warnings or prompts.
I believe that you can also do this:
git checkout alpha-0.3.0
git reset --hard cc4b63bebb6
git push origin +alpha-0.3.0
This is very similar to the last method, except you don't have to muck around in the remote repo.
What do I need to do to make this function wait for the result of the promise?
Use async/await
(NOT Part of ECMA6, but
available for Chrome, Edge, Firefox and Safari since end of 2017, see canIuse)
MDN
async function waitForPromise() {
// let result = await any Promise, like:
let result = await Promise.resolve('this is a sample promise');
}
Added due to comment: An async function always returns a Promise, and in TypeScript it would look like:
async function waitForPromise(): Promise<string> {
// let result = await any Promise, like:
let result = await Promise.resolve('this is a sample promise');
}
Months in Calendar object start from 0
0 = January = Calendar.JANUARY
1 = february = Calendar.FEBRUARY
In my situation, I needed to retain unique keys with the array values, so I just used a second array:
$arr1 = array("alpha"=>"bravo","charlie"=>"delta","echo"=>"foxtrot");
unset($arr1);
$arr2 = array();
foreach($arr1 as $key=>$value) $arr2[$key] = $value;
$arr1 = $arr2
unset($arr2);
Swift 2.0 solution is here:
let urlStr = “http://url_to_manage_post_requests”
let url = NSURL(string: urlStr)
let request: NSMutableURLRequest =
NSMutableURLRequest(URL: url!) request.HTTPMethod = "POST"
request.setValue(“application/json” forHTTPHeaderField:”Content-Type”)
request.timeoutInterval = 60.0
//additional headers
request.setValue(“deviceIDValue”, forHTTPHeaderField:”DeviceId”)
let bodyStr = “string or data to add to body of request”
let bodyData = bodyStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
request.HTTPBody = bodyData
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request){
(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if let httpResponse = response as? NSHTTPURLResponse {
print("responseCode \(httpResponse.statusCode)")
}
if error != nil {
// You can handle error response here
print("\(error)")
}else {
//Converting response to collection formate (array or dictionary)
do{
let jsonResult: AnyObject = (try NSJSONSerialization.JSONObjectWithData(data!, options:
NSJSONReadingOptions.MutableContainers))
//success code
}catch{
//failure code
}
}
}
task.resume()
For the 24-hour time, you need to use HH24
instead of HH
.
For the 12-hour time, the AM/PM indicator is written as A.M.
(if you want periods in the result) or AM
(if you don't). For example:
SELECT invoice_date,
TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
FROM invoices
;
For more information on the format models you can use with TO_CHAR
on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.
The CLR uses it when it is compiling at runtime. Here is a link to MSDN that explains further.
Android studio 4.0.1 Kotlin 1.3.72
Android Navigation architecture component.
The following code works for me:
findNavController().popBackStack()
It doesn't work because it's not supported
The
DEFAULT
clause specifies a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression. This means, for example, that you cannot set the default for a date column to be the value of a function such asNOW()
orCURRENT_DATE
. The exception is that you can specifyCURRENT_TIMESTAMP
as the default for aTIMESTAMP
column
I am on Windows 8.1, and I tried everything from the other answers and nothing worked. Finally, I decided to try "Pick from a list of drivers" and found "LGE Mobile Sooner Single ADB Interface" under "ADB Interface". ADB.exe was finally able to find the Nexus 5 and sideload 4.4.1.
I hope this helps.
Perhaps the question needs to be slightly more precise here about what is required because it can be read it two different ways. i.e.
Given the accepted answer, the OP clearly intended it to be interpreted the first way. For anybody reading the question the other way try
SELECT `table_schema`
FROM `information_schema`.`tables`
WHERE `table_name` = 'whatever';
you should convert test type >>>> test.tostring();
change the last line to this :
Label1.Text = "Du har nu lånat filmen:" + test.tostring();
After trying all these procedures it still didn't work for me. What did work was
Our current work required integrating a number of disparate projects so unfortunately use of SNAPSHOTs in a production environment were required (taboo in Maven circles)!
I'm not sure that i know exactly what you mean.
But to get the length of an initialized array,
doesn't strlen(string) work ??
As @Graham42 said, from version 2.1 mouse options has been renamed but you can use the mouse with any version of tmux adding this to your ~/.tmux.conf:
Bash shells:
is_pre_2_1="[[ $(tmux -V | cut -d' ' -f2) < 2.1 ]] && echo true || echo false"
if-shell "$is_pre_2_1" "setw -g mode-mouse on; set -g mouse-resize-pane on;\
set -g mouse-select-pane on; set -g mouse-select-window on" "set -g mouse on"
Sh (Bourne shell) shells:
is_pre_2_1="tmux -V | cut -d' ' -f2 | awk '{print ($0 < 2.1) ? "true" : "false"}'"
if-shell "$is_pre_2_1" "setw -g mode-mouse on; set -g mouse-resize-pane on;\
set -g mouse-select-pane on; set -g mouse-select-window on" "set -g mouse on"
Hope this helps
I figured out how to get the Cygwin cron service running automatically when I logged on to Windows 7. Here's what worked for me:
Using Notepad, create file C:\cygwin\bin\Cygwin_launch_crontab_service_input.txt
with content no
on the first line and yes
on the second line (without the quotes). These are your two responses to prompts for cron-config
.
Create file C:\cygwin\Cygwin_launch_crontab_service.bat
with content:
@echo off
C:
chdir C:\cygwin\bin
bash cron-config < Cygwin_launch_crontab_service_input.txt
Add a Shortcut to the following in the Windows Startup folder:
Cygwin_launch_crontab_service.bat
See http://www.sevenforums.com/tutorials/1401-startup-programs-change.html if you need help on how to add to Startup. BTW, you can optionally add these in Startup if you would like:
Cygwin
XWin Server
The first one executes
C:\cygwin\Cygwin.bat
and the second one executes
C:\cygwin\bin\run.exe /usr/bin/bash.exe -l -c /usr/bin/startxwin.exe
The following is another method that will work, although as with some of the other methods it will strip decimal places.
a = 1,112
b = a.scan(/\d+/).join().to_i => 1112
Here is some one liner xpath 1.0 expressions for IndexOf( $text, $searchString ):
If you need the position of the FIRST character of the sought string, or 0 if it is not present:
contains($text,$searchString)*(1 + string-length(substring-before($text,$searchString)))
If you need the position of the first character AFTER the found string, or 0 if it is not present:
contains($text,$searchString)*(1 + string-length(substring-before($text,$searchString)) + string-length($searchString))
Alternatively if you need the position of the first character AFTER the found string, or length+1 if it is not present:
1 + string-length($right) - string-length(substring-after($right,$searchString))
That should cover most cases that you need.
Note: The multiplication by contains( ... ) causes the true or false result of the contains( ... ) function to be converted to 1 or 0, which elegantly provides the "0 when not found" part of the logic.
You can use the CSS property background-size
and set it to cover
or contain
, depending your preference. Cover will cover the window entirely, while contain will make one side fit the window thus not covering the entire page (unless the aspect ratio of the screen is equal to the image).
Please note that this is a CSS3 property. In older browsers, this property is ignored. Alternatively, you can use javascript to change the CSS settings depending on the window size, but this isn't preferred.
body {
background-image: url(image.jpg); /* image */
background-position: center; /* center the image */
background-size: cover; /* cover the entire window */
}
Something throws an exception of type std::bad_alloc
, indicating that you ran out of memory. This exception is propagated through until main
, where it "falls off" your program and causes the error message you see.
Since nobody here knows what "RectInvoice", "rectInvoiceVector", "vect", "im" and so on are, we cannot tell you what exactly causes the out-of-memory condition. You didn't even post your real code, because w h
looks like a syntax error.
DELETE FROM on_search WHERE search_date < NOW() - INTERVAL N DAY
Replace N with your day count
You need to create fonts folder under assets folder in your project and put your TTF into it. Then in your Activity onCreate()
TextView myTextView=(TextView)findViewById(R.id.textBox);
Typeface typeFace=Typeface.createFromAsset(getAssets(),"fonts/mytruetypefont.ttf");
myTextView.setTypeface(typeFace);
Please note that not all TTF will work. While I was experimenting, it worked just for a subset (on Windows the ones whose name is written in small caps).
If you need to store just simple values like API token or login data (not passwords!), here is what I used:
import 'package:shared_preferences/shared_preferences.dart';
asyncFunc() async { // Async func to handle Futures easier; or use Future.then
SharedPreferences prefs = await SharedPreferences.getInstance();
}
...
// Set
prefs.setString('apiToken', token);
// Get
String token = prefs.getString('apiToken');
// Remove
prefs.remove('apiToken');
Don't forget to add shared_preferences
dependency in your pubspec.yaml (preserve spacing format):
dependencies:
shared_preferences: any
You could try always sending the first 4 bytes of your data as data size and then read complete data in one shot. Use the below functions on both client and server-side to send and receive data.
def send_data(conn, data):
serialized_data = pickle.dumps(data)
conn.sendall(struct.pack('>I', len(serialized_data)))
conn.sendall(serialized_data)
def receive_data(conn):
data_size = struct.unpack('>I', conn.recv(4))[0]
received_payload = b""
reamining_payload_size = data_size
while reamining_payload_size != 0:
received_payload += conn.recv(reamining_payload_size)
reamining_payload_size = data_size - len(received_payload)
data = pickle.loads(received_payload)
return data
you could find sample program at https://github.com/vijendra1125/Python-Socket-Programming.git
The short answer:
Use the click
event, which won't fire until after the value has been updated, and fires when you want it to:
<label><input type='checkbox' onclick='handleClick(this);'>Checkbox</label>
function handleClick(cb) {
display("Clicked, new value = " + cb.checked);
}
The longer answer:
The change
event handler isn't called until the checked
state has been updated (live example | source), but because (as Tim Büthe points out in the comments) IE doesn't fire the change
event until the checkbox loses focus, you don't get the notification proactively. Worse, with IE if you click a label for the checkbox (rather than the checkbox itself) to update it, you can get the impression that you're getting the old value (try it with IE here by clicking the label: live example | source). This is because if the checkbox has focus, clicking the label takes the focus away from it, firing the change
event with the old value, and then the click
happens setting the new value and setting focus back on the checkbox. Very confusing.
But you can avoid all of that unpleasantness if you use click
instead.
I've used DOM0 handlers (onxyz
attributes) because that's what you asked about, but for the record, I would generally recommend hooking up handlers in code (DOM2's addEventListener
, or attachEvent
in older versions of IE) rather than using onxyz
attributes. That lets you attach multiple handlers to the same element and lets you avoid making all of your handlers global functions.
An earlier version of this answer used this code for handleClick
:
function handleClick(cb) {
setTimeout(function() {
display("Clicked, new value = " + cb.checked);
}, 0);
}
The goal seemed to be to allow the click to complete before looking at the value. As far as I'm aware, there's no reason to do that, and I have no idea why I did. The value is changed before the click
handler is called. In fact, the spec is quite clear about that. The version without setTimeout
works perfectly well in every browser I've tried (even IE6). I can only assume I was thinking about some other platform where the change isn't done until after the event. In any case, no reason to do that with HTML checkboxes.
A notice about IList:
MSDN IList Remarks:
"IList implementations fall into three categories: read-only, fixed-size, and variable-size. (...). For the generic version of this interface, see
System.Collections.Generic.IList<T>
."
IList<T>
does NOT inherits from IList
(but List<T>
does implement both IList<T>
and IList
), but is always variable-size.
Since .NET 4.5, we have also IReadOnlyList<T>
but AFAIK, there is no fixed-size generic List which would be what you are looking for.
GitLab's "merge request" feature is equivalent to GitHub's "pull request" feature. Both are means of pulling changes from another branch or fork into your branch and merging the changes with your existing code. They are useful tools for code review and change management.
An article from GitLab discusses the differences in naming the feature:
Merge or pull requests are created in a git management application and ask an assigned person to merge two branches. Tools such as GitHub and Bitbucket choose the name pull request since the first manual action would be to pull the feature branch. Tools such as GitLab and Gitorious choose the name merge request since that is the final action that is requested of the assignee. In this article we'll refer to them as merge requests.
A "merge request" should not be confused with the git merge
command. Neither should a "pull request" be confused with the git pull
command. Both git
commands are used behind the scenes in both pull requests and merge requests, but a merge/pull request refers to a much broader topic than just these two commands.
You can use the extend function from JQuery:
var newClone= jQuery.extend({}, oldObject);
var deepClone = jQuery.extend(true, {}, oldObject);
There is a Node.js Plugin too:
https://github.com/shimondoodkin/nodejs-clone-extend
To do it without JQuery or Plugin read this here:
There are 3 ways that you can do:
1) Using Laravel Model
$user = \App\User::find(1);
$newDateFormat = $user->created_at->format('d/m/Y');
dd($newDateFormat);
2) Using PHP strtotime
$user = \App\User::find(1);
$newDateFormat2 = date('d/m/Y', strtotime($user->created_at));
dd($newDateFormat2);
3) Using Carbon
$user = \App\User::find(1);
$newDateFormat3 = \Carbon\Carbon::parse($user->created_at)->format('d/m/Y');
dd($newDateFormat3);
this query will alter the multiple column test it.
create table test(a int,B int,C int);
alter table test drop(a,B);
We would create our own function in js like echo "Hello world".
function echo( ...s ) // rest operator
{
for(var i = 0; i < s.length; i++ ) {
document.write(s[i] + ' '); // quotes for space
}
}
// Now call to this function like echo
echo('Hellow', "World");
Note: (...
) rest operator dotes for access more parameters in one as object/array, to get value from object/array we should iterate the whole object/array by using for loop, like above and s
is name i just kept you can write whatever you want.
from datetime import datetime
datetime.strptime(date_string, "%Y-%m-%d")
..this raises a ValueError
if it receives an incompatible format.
..if you're dealing with dates and times a lot (in the sense of datetime objects, as opposed to unix timestamp floats), it's a good idea to look into the pytz module, and for storage/db, store everything in UTC.
Try PowerPivot from Microsoft. Here you can find a step by step tutorial. It worked for my 4M+ rows!
If you want to add a flag to every link, e.g. -fsanitize=address
then I would not recommend using CMAKE_*_LINKER_FLAGS
. Even with them all set it still doesn't use the flag when linking a framework on OSX, and maybe in other situations. Instead use link_libraries()
:
add_compile_options("-fsanitize=address")
link_libraries("-fsanitize=address")
This works for everything.
The two main problems with your code are:
else
clause with the loop to print "prime" only if the loop exits without breaking.A couple pretty significant inefficiencies:
Epoch is the number of seconds since Jan 1, 1970..
So:
String epochString = "1081157732";
long epoch = Long.parseLong( epochString );
Date expiry = new Date( epoch * 1000 );
For more information: http://www.epochconverter.com/
I'm using n (Node version management)
You can install it in two ways
brew install n
or
npm install -g n
You can switch between different version of node and io. Here's an example from my current env when I call n without params:
$ n
io/3.3.1
node/0.12.7
node/4.0.0
node/5.0.0
? node/5.10.1
Here is a working example. I changed the code to output to a div instead of an alert box. Your issue was item.innerHTML
I believe. I use the jQuery html
function instead and that seemed to resolve the issue.
<table id='thisTable' class='disptable' style='margin-left:auto;margin-right:auto;' >
<tr>
<th>Fund</th>
<th>Organization</th>
<th>Access</th>
<th>Delete</th>
</tr>
<tr>
<td class='fund'>100000</td><td class='org'>10110</td><td>OWNED</td><td><a class='delbtn'ref='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>170252</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67150</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67120</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a>
</td>
</tr>
</table>
<div id="output"></div>?
the javascript:
$('#thisTable tr').on('click', function(event) {
var tds = $(this).addClass('row-highlight').find('td');
var values = '';
tds.each(function(index, item) {
values = values + 'td' + (index + 1) + ':' + $(item).html() + '<br/>';
});
$("#output").html(values);
});
If you're looking for something that behaves like an enumeration (because I see you are defining an object and attaching a sequential ID 0, 1, 2 and contains a name field that you don't want to misspell (e.g. name vs naaame), you're better off defining an enumeration because the sequential ID is taken care of automatically, and provides type verification for you out of the box.
enum TestStatus {
Available, // 0
Ready, // 1
Started, // 2
}
class Test {
status: TestStatus
}
var test = new Test();
test.status = TestStatus.Available; // type and spelling is checked for you,
// and the sequence ID is automatic
The values above will be automatically mapped, e.g. "0" for "Available", and you can access them using TestStatus.Available
. And Typescript will enforce the type when you pass those around.
You wanted an array of objects, (not exactly an object with keys "0", "1" and "2"), so let's define the type of the object, first, then a type of a containing array.
class TestStatus {
id: number
name: string
constructor(id, name){
this.id = id;
this.name = name;
}
}
type Statuses = Array<TestStatus>;
var statuses: Statuses = [
new TestStatus(0, "Available"),
new TestStatus(1, "Ready"),
new TestStatus(2, "Started")
]
Maybe you could take a look at JFileChooser, which allow you to use native dialogs in one line of code.
here we console natural number 0 to ......n (next number print in console every 60 sec.) , using setInterval()
var count = 0;
function abc(){
count ++;
console.log(count);
}
setInterval(abc,60*1000);
I also experienced this error.
I add into header Content-Type
: application/json
. Following the change, my submissions succeed!
This happens because Oracle dropped support for Windows XP (which doesn't have RegDeleteKeyExA
used by the installer in its ADVAPI32.DLL
by the way) as described in http://mail.openjdk.java.net/pipermail/openjfx-dev/2013-July/009005.html. Yet while the official support for XP has ended, the Java binaries are still (as of Java 8u20 EA b05 at least) XP-compatible - only the installer isn't...
Because of that, the solution is actually quite easy:
get 7-Zip (or any other good unpacker), unpack the distribution .exe manually, it has one .zip file inside of it (tools.zip
), extract it too,
use unpack200
from JDK8 to unpack all .pack files to .jar files (older unpacks won't work properly); JAVA_HOME
environment variable should be set to your Java unpack root, e.g. "C:\Program Files\Java\jdk8" - you can specify it implicitly by e.g.
SET JAVA_HOME=C:\Program Files\Java\jdk8
Unpack all files with a single command (in batch file):
FOR /R %%f IN (*.pack) DO "%JAVA_HOME%\bin\unpack200.exe" -r -v "%%f" "%%~pf%%~nf.jar"
Unpack all files with a single command (command line from JRE root):
FOR /R %f IN (*.pack) DO "bin\unpack200.exe" -r -v "%f" "%~pf%~nf.jar"
Unpack by manually locating the files and unpacking them one-by-one:
%JAVA_HOME%\bin\unpack200 -r packname.pack packname.jar
where packname
is for example rt
point the tool you want to use (e.g. Netbeans) to the %JAVA_HOME%
and you're good to go.
Note: you probably shouldn't do this just to use Java 8 in your web browser or for any similar reason (installing JRE 8 comes to mind); security flaws in early updates of major Java version releases are (mind me) legendary, and adding to that no real support for neither XP nor Java 8 on XP only makes matters much worse. Not to mention you usually don't need Java in your browser (see e.g. http://nakedsecurity.sophos.com/2013/01/15/disable-java-browsers-homeland-security/ - the topic is already covered on many pages, just Google it if you require further info). In any case, AFAIK the only thing required to apply this procedure to JRE is to change some of the paths specified above from \bin\
to \lib\
(the file placement in installer directory tree is a bit different) - yet I strongly advise against doing it.
See also: How can I get the latest JRE / JDK as a zip file rather than EXE or MSI installer?, JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object
It's also possible to customise your bootstrap build by using:
http://twitter.github.com/bootstrap/customize.html
All the plugins are included by default.
Spring Boot will automatically find and load application.properties and application.yaml files from the following locations when your application starts:
The list is ordered by precedence (with values from lower items overriding earlier ones).
More info you can find here https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-files
You can write one liner using DataRow.Add(params object[] values) instead of four lines.
dt.Rows.Add("Ravi", "500");
As you create new DataTable
object, there seems no need to Clear
DataTable
in very next statement. You can also use DataTable.Columns.AddRange
to add columns with on statement. Complete code would be.
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("Name"), new DataColumn("Marks") });
dt.Rows.Add("Ravi", "500");
I used the following on Mac OSX.
currDate=`date +%Y%m%d`
epochDate=$(date -j -f "%Y%m%d" "${currDate}" "+%s")
Please set this in root vc:
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:YES];
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
-(void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:YES];
self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}
What have you tried, what was the problem?
Creating DataColumns
and add values to a DataTable
is straight forward:
Dim dt = New DataTable()
Dim dcID = New DataColumn("ID", GetType(Int32))
Dim dcName = New DataColumn("Name", GetType(String))
dt.Columns.Add(dcID)
dt.Columns.Add(dcName)
For i = 1 To 1000
dt.Rows.Add(i, "Row #" & i)
Next
Edit:
If you want to read a xml file and load a DataTable from it, you can use DataTable.ReadXml
.
You can use the Grid CSS properties, is the most clear, clean and intuitive way structure your boxes.
#container{_x000D_
display: grid;_x000D_
grid-template-columns: 100px auto;_x000D_
color:white;_x000D_
}_x000D_
#fixed{_x000D_
background: red;_x000D_
grid-column: 1;_x000D_
}_x000D_
#remaining{_x000D_
background: green;_x000D_
grid-column: 2;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="fixed">Fixed</div>_x000D_
<div id="remaining">Remaining</div>_x000D_
</div>
_x000D_
If they're both strings you can just do:
#define STR3 STR1 STR2
This then expands to:
#define STR3 "s" "1"
and in the C language, separating two strings with space as in "s" "1"
is exactly equivalent to having a single string "s1"
.
Assuming your df.index is sorted you can use:
df.loc[df.index.max() + 1] = None
It handles well different indexes and column types.
[EDIT] it works with pd.DatetimeIndex if there is a constant frequency, otherwise we must specify the new index exactly e.g:
df.loc[df.index.max() + pd.Timedelta(milliseconds=1)] = None
long example:
df = pd.DataFrame([[pd.Timestamp(12432423), 23, 'text_field']],
columns=["timestamp", "speed", "text"],
index=pd.DatetimeIndex(start='2111-11-11',freq='ms', periods=1))
df.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 1 entries, 2111-11-11 to 2111-11-11
Freq: L
Data columns (total 3 columns):
timestamp 1 non-null datetime64[ns]
speed 1 non-null int64
text 1 non-null object
dtypes: datetime64[ns](1), int64(1), object(1)
memory usage: 32.0+ bytes
df.loc[df.index.max() + 1] = None
df.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2 entries, 2111-11-11 00:00:00 to 2111-11-11 00:00:00.001000
Data columns (total 3 columns):
timestamp 1 non-null datetime64[ns]
speed 1 non-null float64
text 1 non-null object
dtypes: datetime64[ns](1), float64(1), object(1)
memory usage: 64.0+ bytes
df.head()
timestamp speed text
2111-11-11 00:00:00.000 1970-01-01 00:00:00.012432423 23.0 text_field
2111-11-11 00:00:00.001 NaT NaN NaN
Whoever wants UML deserves Rational Rose :)
If your purpose in truncating the digits is for display reasons, then you just just use an appropriate formatting when you convert the double to a string.
Methods like String.Format()
and Console.WriteLine()
(and others) allow you to limit the number of digits of precision a value is formatted with.
Attempting to "truncate" floating point numbers is ill advised - floating point numbers don't have a precise decimal representation in many cases. Applying an approach like scaling the number up, truncating it, and then scaling it down could easily change the value to something quite different from what you'd expected for the "truncated" value.
If you need precise decimal representations of a number you should be using decimal
rather than double
or float
.
Maybe this could be a little older article. but must of the above answers don´t help me as I need. Then I wrote a little snippet for that.
This accepts any XML that hast at least 3 levels (Like this sample):
<XmlData>
<XmlRow>
<XmlField1>Data 1</XmlField1>
<XmlField2>Data 2</XmlField2>
<XmlField3>Data 3</XmlField3>
.......
</XmlRow>
</XmlData>
public static class XmlParser
{
/// <summary>
/// Converts XML string to DataTable
/// </summary>
/// <param name="Name">DataTable name</param>
/// <param name="XMLString">XML string</param>
/// <returns></returns>
public static DataTable BuildDataTableFromXml(string Name, string XMLString)
{
XmlDocument doc = new XmlDocument();
doc.Load(new StringReader(XMLString));
DataTable Dt = new DataTable(Name);
try
{
XmlNode NodoEstructura = doc.FirstChild.FirstChild;
// Table structure (columns definition)
foreach (XmlNode columna in NodoEstructura.ChildNodes)
{
Dt.Columns.Add(columna.Name, typeof(String));
}
XmlNode Filas = doc.FirstChild;
// Data Rows
foreach (XmlNode Fila in Filas.ChildNodes)
{
List<string> Valores = new List<string>();
foreach (XmlNode Columna in Fila.ChildNodes)
{
Valores.Add(Columna.InnerText);
}
Dt.Rows.Add(Valores.ToArray());
}
} catch(Exception)
{
}
return Dt;
}
}
This solve my problem
EDIT
As pointed out by @Kwame , the below code does validate the url even if the
.com
or.co
etc are not present.also pointed out by @Blaise, URLs like https://www.google is a valid URL and you need to do a DNS check for checking if it resolves or not, separately.
This is simple and works:
So min_attr
contains the basic set of strings that needs to be present to define the validity of a URL,
i.e http://
part and google.com
part.
urlparse.scheme
stores http://
and
urlparse.netloc
store the domain name google.com
from urlparse import urlparse
def url_check(url):
min_attr = ('scheme' , 'netloc')
try:
result = urlparse(url)
if all([result.scheme, result.netloc]):
return True
else:
return False
except:
return False
all()
returns true if all the variables inside it return true.
So if result.scheme
and result.netloc
is present i.e. has some value then the URL is valid and hence returns True
.
This solution kills the process tree in case of shell=True, passes parameters to the process (or not), has a timeout and gets the stdout, stderr and process output of the call back (it uses psutil for the kill_proc_tree). This was based on several solutions posted in SO including jcollado's. Posting in response to comments by Anson and jradice in jcollado's answer. Tested in Windows Srvr 2012 and Ubuntu 14.04. Please note that for Ubuntu you need to change the parent.children(...) call to parent.get_children(...).
def kill_proc_tree(pid, including_parent=True):
parent = psutil.Process(pid)
children = parent.children(recursive=True)
for child in children:
child.kill()
psutil.wait_procs(children, timeout=5)
if including_parent:
parent.kill()
parent.wait(5)
def run_with_timeout(cmd, current_dir, cmd_parms, timeout):
def target():
process = subprocess.Popen(cmd, cwd=current_dir, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
# wait for the process to terminate
if (cmd_parms == ""):
out, err = process.communicate()
else:
out, err = process.communicate(cmd_parms)
errcode = process.returncode
thread = Thread(target=target)
thread.start()
thread.join(timeout)
if thread.is_alive():
me = os.getpid()
kill_proc_tree(me, including_parent=False)
thread.join()
Other than win32, if your company had set up you web outlook, you can also try PYTHON REST API, which is officially made by Microsoft. (https://msdn.microsoft.com/en-us/office/office365/api/mail-rest-operations)
simply use the Out-File cmd but DON'T forget to give an encoding type:
-Encoding UTF8
so use it so:
$log | Out-File -Append C:\as\whatever.csv -Encoding UTF8
-Append is required if you want to write in the file more then once.
I think what you want is something like:
=INDEX(B:B,MATCH(C2,A:A,0))
I should mention that MATCH checks the position at which the value can be found within A:A (given the 0
, or FALSE, parameter, it looks only for an exact match and given its nature, only the first instance found) then INDEX returns the value at that position within B:B.
I assume the question is already answered. If above solution doesn't help in solving the issue then can use below to solve the issue.
The issue occurs if sometimes your maven user settings is not reflecting correct settings.xml file.
To update the settings file go to Windows > Preferences > Maven > User Settings and update the settings.xml to it correct location.
Once this is doen re-build the project, these should solve the issue. Thanks.
$time = date("H:i", strtotime($today . " +5 hours +30 minutes"));
//+5 hours +30 minutes Time Zone +5:30 (Asia/Kolkata)
Use this code, Working properly
CREATE PROCEDURE [dbo].[sp_delete_item]
@ItemId int = 0
@status bit OUT
AS
Begin
DECLARE @cnt int;
DECLARE @status int =0;
SET NOCOUNT OFF
SELECT @cnt =COUNT(Id) from ItemTransaction where ItemId = @ItemId
if(@cnt = 1)
Begin
return @status;
End
else
Begin
SET @status =1;
return @status;
End
END
Execute SP
DECLARE @statuss bit;
EXECUTE [dbo].[sp_delete_item] 6, @statuss output;
PRINT @statuss;
function getStatusCode()
{
$url = 'example.com/test';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpcode;
}
print_r(getStatusCode());
Another example using PowerShell for set permissions (File / Directory) :
Get-Acl "C:\file.txt" | fl *
$acl = Get-Acl "C:\file.txt"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("everyone","FullControl","Allow")
$acl.SetAccessRule($accessRule)
$acl | Set-Acl "C:\file.txt"
Hope this helps
Getters and setters coming from data hiding. Data Hiding means We are hiding data from outsiders or outside person/thing cannot access our data.This is a useful feature in OOP.
As a example:
If you create a public variable, you can access that variable and change value in anywhere(any class). But if you create as private that variable cannot see/access in any class except declared class.
public
andprivate
are access modifiers.
So how can we access that variable outside:
This is the place getters and setters coming from. You can declare variable as private then you can implement getter and setter for that variable.
Example(Java):
private String name;
public String getName(){
return this.name;
}
public void setName(String name){
this.name= name;
}
Advantage:
When anyone want to access or change/set value to balance
variable, he/she must have permision.
//assume we have person1 object
//to give permission to check balance
person1.getName()
//to give permission to set balance
person1.setName()
You can set value in constructor also but when later on when you want to update/change value, you have to implement setter method.
If you need to increase MySQL Connections without MySQL restart do like below, also if you don't know configuration file, below use the mysqlworkbench or phpmyadmin or command prompt to run below queries.
mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 151 |
+-----------------+-------+
1 row in set (0.00 sec)
mysql> SET GLOBAL max_connections = 250;
Query OK, 0 rows affected (0.00 sec)
mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 250 |
+-----------------+-------+
1 row in set (0.00 sec)
These settings will change at MySQL Restart.
For permanent changes add below line in my.cnf and restart MySQL.
max_connections = 151
Thanks Darin, For me, to be able to post to the create method, It only worked after I modified the BindModel code to :
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (!string.IsNullOrEmpty(displayFormat) && value != null)
{
DateTime date;
displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
// use the format specified in the DisplayFormat attribute to parse the date
if (DateTime.TryParse(value.AttemptedValue, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out date))
{
return date;
}
else
{
bindingContext.ModelState.AddModelError(
bindingContext.ModelName,
string.Format("{0} is an invalid date format", value.AttemptedValue)
);
}
}
return base.BindModel(controllerContext, bindingContext);
}
Hope this could help someone else...
In PowerShell v3, have a look at the Invoke-WebRequest and Invoke-RestMethod e.g.:
$msg = Read-Host -Prompt "Enter message"
$encmsg = [System.Web.HttpUtility]::UrlEncode($msg)
Invoke-WebRequest -Uri "http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$encmsg&encoding=windows-1255"
You can make it through echo only and without the other stuff. Don't forget to add "-n" or you will get a linebreak automatically:
echo -n -e "\x5a"
There are a lot of answers here, but I'll add my approach since I found this post while working on the same problem.
Starting with what we know here are the number from 0 to 16.
Number encoded in bits minimum number of bits to encode
0 000000 1
1 000001 1
2 000010 2
3 000011 2
4 000100 3
5 000101 3
6 000110 3
7 000111 3
8 001000 4
9 001001 4
10 001010 4
11 001011 4
12 001100 4
13 001101 4
14 001110 4
15 001111 4
16 010000 5
looking at the breaks, it shows this table
number <= number of bits
1 0
3 2
7 3
15 4
So, now how do we compute the pattern?
Remember that log base 2 (n) = log base 10 (n) / log base 10 (2)
number logb10 (n) logb2 (n) ceil[logb2(n)]
1 0 0 0 (special case)
3 0.477 1.58 2
7 0.845 2.807 3
8 0.903 3 3 (special case)
15 1.176 3.91 4
16 1.204 4 4 (special case)
31 1.491 4.95 5
63 1.799 5.98 6
Now the desired result matching the first table. Notice how also some values are special cases. 0 and any number which is a powers of 2. These values dont change when you apply ceiling so you know you need to add 1 to get the minimum bit field length.
To account for the special cases add one to the input. The resulting code implemented in python is:
from math import log
from math import ceil
def min_num_bits_to_encode_number(a_number):
a_number=a_number+1 # adjust by 1 for special cases
# log of zero is undefined
if 0==a_number:
return 0
num_bits = int(ceil(log(a_number,2))) # logbase2 is available
return (num_bits)
<div class="row-2">
<ul>
<li><a href="index.html" class="active"><p style="margin-top: 10px;">Buy</p></a></li>
</ul>
Play with it
When button is clicked:
loginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent= new Intent(getApplicationContext(), NextActivity.class);
intent.putExtra("data", value); //pass data
startActivity(intent);
}
});
To received the extra data from NextActivity.class
:
Bundle extra = getIntent().getExtras();
if (extra != null){
String str = (String) extra.get("data"); // get a object
}
I have heard good things about SlowCheetah, but was unable to get it to work. I did the following: add am tag to each for a specific configuration.
Ex:
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'UAT|AnyCPU'">
<OutputPath>bin\UAT\</OutputPath>
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AppConfig>App.UAT.config</AppConfig>
</PropertyGroup>
Server:
namespace SocketServer
{
class Program
{
static Socket klient;
static void Main(string[] args)
{
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 8888);
server.Bind(endPoint);
server.Listen(20);
while(true)
{
Console.WriteLine("Waiting...");
klient = server.Accept();
Console.WriteLine("Client connected");
Task t = new Task(ServisClient);
t.Start();
}
}
static void ServisClient()
{
try
{
while (true)
{
byte[] buffer = new byte[64];
Console.WriteLine("Waiting for answer...");
klient.Receive(buffer, 0, buffer.Length, 0);
string message = Encoding.UTF8.GetString(buffer);
Console.WriteLine("Answer: " + message);
string answer = "Actualy date is " + DateTime.Now;
buffer = Encoding.UTF8.GetBytes(answer);
Console.WriteLine("Sending {0}", answer);
klient.Send(buffer);
}
}
catch
{
Console.WriteLine("Disconnected");
}
}
}
}
Maybe I'm too naive but, couldn't you create an event that is raised when GetStringData() is called and attach an EventHandler that calls and awaits the async method?
Something like:
public event EventHandler FireAsync;
public string GetStringData()
{
FireAsync?.Invoke(this, EventArgs.Empty);
return "hello world";
}
public async void HandleFireAsync(object sender, EventArgs e)
{
await MyAsyncMethod();
}
And somewhere in the code attach and detach from the event:
FireAsync += HandleFireAsync;
(...)
FireAsync -= HandleFireAsync;
Not sure if this might be anti-pattern somehow (if it is please let me know), but it catches the Exceptions and returns quickly from GetStringData().
To follow up on malat's response, you can avoid losing changes by creating a patch and reapply it at a later time.
git diff --no-prefix > patch.txt
patch -p0 < patch.txt
Store your patch outside the repository folder for safety.
For Kotlin:
In your adapter, simply call
(context as Your_Activity_Name).yourMethod()
I've added to /etc/sysconfig/jenkins (CentOS):
# Options to pass to java when running Jenkins.
#
JENKINS_JAVA_OPTIONS="-Djava.awt.headless=true -Xmx1024m -XX:MaxPermSize=512m"
For ubuntu the same config should be located in /etc/default
In a build setting set code signing Provision Profile if you have APN Enable certificate then you will definitely get the token id. and remove
Provision Profile : Automatic
and set to
Provision Profile : Your provision profile certificate.
Bit late to the party, but was surprised not to see what I think is the simplest solution here:
import io
import subprocess
proc = subprocess.Popen(["prog", "arg"], stdout=subprocess.PIPE)
for line in io.TextIOWrapper(proc.stdout, encoding="utf-8"): # or another encoding
# do something with line
(This requires Python 3.)
Best approach for Bootstap 3.x -- using CSS flexbox (and requires minimal CSS)..
.equal {
display: flex;
display: -webkit-flex;
flex-wrap: wrap;
}
Bootstrap same height flexbox example
To only apply the same height flexbox at specific breakpoints (responsive), use a media query. For example, here is sm
(768px) and up:
@media (min-width: 768px) {
.row.equal {
display: flex;
flex-wrap: wrap;
}
}
This solution also works well for multiple rows (column wrapping):
https://www.bootply.com/gCEXzPMehZ
Other workarounds
These options will be recommended by others, but are not a good idea for responsive design. These only work for simple single row layouts w/o column wrapping.
1) Using huge negative margins & padding
2) Using display:table-cell (this solution also effects the responsive grid, so a @media query can be used to only apply table
display on wider screens before the columns stack vertically)
Flexbox is now used by default in Bootstrap 4 so there is no need for the extra CSS to make equal height columns: http://www.codeply.com/go/IJYRI4LPwU
Example:
<div class="container">
<div class="row">
<div class="col-md-6"></div>
<div class="col-md-6"></div>
</div>
</div>
Subplot Colorbar
For subplots with scatter, you can trick a colorbar onto your axes by building the "mappable" with the help of a secondary figure and then adding it to your original plot.
As a continuation of the above example:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(10)
y = x
t = x
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, y, c=t, cmap='viridis')
ax2.scatter(x, y, c=t, cmap='viridis_r')
# Build your secondary mirror axes:
fig2, (ax3, ax4) = plt.subplots(1, 2)
# Build maps that parallel the color-coded data
# NOTE 1: imshow requires a 2-D array as input
# NOTE 2: You must use the same cmap tag as above for it match
map1 = ax3.imshow(np.stack([t, t]),cmap='viridis')
map2 = ax4.imshow(np.stack([t, t]),cmap='viridis_r')
# Add your maps onto your original figure/axes
fig.colorbar(map1, ax=ax1)
fig.colorbar(map2, ax=ax2)
plt.show()
Note that you will also output a secondary figure that you can ignore.
If both Column are numeric Then Use This code
Just Cast Column As Varchar(Size)
Example:
Select (Cast(Col1 as Varchar(20)) + '-' + Cast(Col2 as Varchar(20))) As Col3 from Table
you should give permission on your db
grant execute on (packageName or tableName) to user;
The default submit Action is Ext.form.action.Submit, which uses an Ajax request to submit the form's values to a configured URL. To enable normal browser submission of an Ext form, use the standardSubmit config option.
Link: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.form.Basic-cfg-standardSubmit
solution: put standardSubmit :true in your config. Hope that this will help you :)
Everyone already answered but just for the latest updates. If you want to know where all the configuration files reside then run this command in the shell
SELECT name, setting FROM pg_settings WHERE category = 'File Locations';
Put the part from BEGIN....END{}
inside a file and name it like my.awk.
And then execute it like below:
awk -f my.awk life.csv >output.txt
Also I see a field separator as ,
. You can add that in the begin block of the .awk file as FS=","
For Windows 10 I had to put this in my .gitconfig:
[merge]
tool = meld
[mergetool "meld"]
cmd = 'C:/Program Files (x86)/Meld/Meld.exe' $LOCAL $BASE $REMOTE --output=$MERGED
[mergetool]
prompt = false
Everything else you need to know is written in this super answer by mattst further above.
PS: For some reason, this only worked with Meld 3.18.x, Meld 3.20.x gives me an error.
You can use iconSize
like this:
floatingActionButton: FloatingActionButton(
onPressed: () {
// Add your onPressed code here
},
child: IconButton(
icon: isPlaying
? Icon(
Icons.pause_circle_outline,
)
: Icon(
Icons.play_circle_outline,
),
iconSize: 40,
onPressed: () {
setState(() {
isPlaying = !isPlaying;
});
},
),
),
I would suggest Travis for Open source project. It's just simple to configure and use.
Simple steps to setup:
.travis.yml
file in root of your project. Add Travis as service in your repository settings page.Now every time you commit into your repository Travis will build your project. You can follow simple steps to get started with Travis CI.
In Python 3, print
became a function. This means that you need to include parenthesis now like mentioned below:
print("Hello World")
A well-explained answer is already given by @mkobit, but I will add a big picture of the range key and hash key.
In a simple words range + hash key = composite primary key
CoreComponents of Dynamodb
A primary key is consists of a hash key and an optional range key. Hash key is used to select the DynamoDB partition. Partitions are parts of the table data. Range keys are used to sort the items in the partition, if they exist.
So both have a different purpose and together help to do complex query.
In the above example hashkey1 can have multiple n-range.
Another example of range and hashkey is game, userA(hashkey)
can play Ngame(range)
The Music table described in Tables, Items, and Attributes is an example of a table with a composite primary key (Artist and SongTitle). You can access any item in the Music table directly, if you provide the Artist and SongTitle values for that item.
A composite primary key gives you additional flexibility when querying data. For example, if you provide only the value for Artist, DynamoDB retrieves all of the songs by that artist. To retrieve only a subset of songs by a particular artist, you can provide a value for Artist along with a range of values for SongTitle.
https://www.slideshare.net/InfoQ/amazon-dynamodb-design-patterns-best-practices https://www.slideshare.net/AmazonWebServices/awsome-day-2016-module-4-databases-amazon-dynamodb-and-amazon-rds https://ceyhunozgun.blogspot.com/2017/04/implementing-object-persistence-with-dynamodb.html
Try this. hope this will help.
String cls0;
String cls1;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
cls0 = in.nextLine();
System.out.println("Enter a string");
cls1 = in.nextLine();