Well, by IP is faster.
Basically, when you call by server name, it is converted to original IP.
But it would be difficult to memorize an IP, for this reason the domain name was created.
Personally I use http://localhost
instead of http://127.0.0.1
or http://username
.
use this syntax: alter table table_name modify column col_name varchar (10000);
What about:
while range(some_number):
#do something
Add a helper class:
public static class Redirector {
public static void RedirectTo(this Controller ct, string action) {
UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);
ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action));
}
public static void RedirectTo(this Controller ct, string action, string controller) {
UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);
ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action, controller));
}
public static void RedirectTo(this Controller ct, string action, string controller, object routeValues) {
UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);
ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action, controller, routeValues));
}
}
Then call in your action:
this.RedirectTo("Index", "Cement");
Add javascript code to any global javascript included file or layout file to intercept all ajax requests:
<script type="text/javascript">_x000D_
$(function() {_x000D_
$(document).ajaxComplete(function (event, xhr, settings) {_x000D_
var urlHeader = xhr.getResponseHeader('AjaxRedirectURL');_x000D_
_x000D_
if (urlHeader != null && urlHeader !== undefined) {_x000D_
window.location = xhr.getResponseHeader('AjaxRedirectURL');_x000D_
}_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
Your object can also implement the Parcelable interface. Then you can use the Bundle.putParcelable()
method and pass your object between activities within intent.
The Photostream application uses this approach and may be used as a reference.
Instead of using String.valueOf I'd use .toString(); it avoids some of the auto boxing described by @johnathan.holland
The javadoc says that valueOf returns the same thing as Integer.toString().
List<Integer> oldList = ...
List<String> newList = new ArrayList<String>(oldList.size());
for (Integer myInt : oldList) {
newList.add(myInt.toString());
}
The second clause does not need a !variable.nil?
check—if evaluation reaches that point, variable.nil
is guaranteed to be false (because of short-circuiting).
This should be sufficient:
variable = id if variable.nil? || variable.empty?
If you're working with Ruby on Rails, Object.blank?
solves this exact problem:
An object is blank if it’s false, empty, or a whitespace string. For example,
""
," "
,nil
,[]
, and{}
are all blank.
You will have to assign both left
and right
property 0
value for margin: auto
to center the logo.
So in this case:
#logo {
background:red;
height:50px;
position:absolute;
width:50px;
left: 0;
right: 0;
margin: 0 auto;
}
You might also want to set position: relative
for #header
.
This works because, setting left
and right
to zero will horizontally stretch the absolutely positioned element. Now magic happens when margin
is set to auto
. margin
takes up all the extra space(equally on each side) leaving the content to its specified width
. This results in content becoming center aligned.
You want to use intvalue = Color.parseColor("#" + colorobject);
If you use synergy (to share one keyboard for two PCs) and PC(MAC) in which you are using xcode is slave, and master PC is Windows PC
keyboard shortcuts are alt+] for indent and alt+[ for un-indent.
Update:
But from synergy version 1.5 working ?+[ for indent and ?+] for un-indent
There are two tools to look at, depending on how you created the dump file.
Your first source of reference should be the man page pg_dump(1)
as that is what creates the dump itself. It says:
Dumps can be output in script or archive file formats. Script dumps are plain-text files containing the SQL commands required to reconstruct the database to the state it was in at the time it was saved. To restore from such a script, feed it to psql(1). Script files can be used to reconstruct the database even on other machines and other architectures; with some modifications even on other SQL database products.
The alternative archive file formats must be used with pg_restore(1) to rebuild the database. They allow pg_restore to be selective about what is restored, or even to reorder the items prior to being restored. The archive file formats are designed to be portable across architectures.
So depends on the way it was dumped out. You can probably figure it out using the excellent file(1)
command - if it mentions ASCII text and/or SQL, it should be restored with psql
otherwise you should probably use pg_restore
Restoring is pretty easy:
psql -U username -d dbname < filename.sql
-- For Postgres versions 9.0 or earlier
psql -U username -d dbname -1 -f filename.sql
or
pg_restore -U username -d dbname -1 filename.dump
Check out their respective manpages - there's quite a few options that affect how the restore works. You may have to clean out your "live" databases or recreate them from template0 (as pointed out in a comment) before restoring, depending on how the dumps were generated.
This is an issue with the 64 bit version of Kepler and windows7 in my case. I downloaded the 32 bit and it worked immediately.
Change the axis_colour to match the background and if you are modifying the background dynamically you will need to update the axis_colour simultaneously. * The shared picture shows the graph/plot example using mock data ()
### Main Plotting Function ###
plotXY <- function(time, value){
### Plot Style Settings ###
### default bg is white, set it the same as the axis-colour
background <- "white"
### default col.axis is black, set it the same as the background to match
axis_colour <- "white"
plot_title <- "Graph it!"
xlabel <- "Time"
ylabel <- "Value"
label_colour <- "black"
label_scale <- 2
axis_scale <- 2
symbol_scale <- 2
title_scale <- 2
subtitle_scale <- 2
# point style 16 is a black dot
point <- 16
# p - points, l - line, b - both
plot_type <- "b"
plot(time, value, main=plot_title, cex=symbol_scale, cex.lab=label_scale, cex.axis=axis_scale, cex.main=title_scale, cex.sub=subtitle_scale, xlab=xlabel, ylab=ylabel, col.lab=label_colour, col.axis=axis_colour, bg=background, pch=point, type=plot_type)
}
plotXY(time, value)
This could be added to the accepted answer for a 'cross-browser' solution.
Sources:
.your_element{
-ms-word-break: break-all;
word-break: break-all;
/* Non standard for webkit */
word-break: break-word;
-webkit-hyphens: auto;
-moz-hyphens: auto;
-ms-hyphens: auto;
hyphens: auto;
}
document.getElementById(currentInputChoosen).value -= +-100;
Works in my case, if you run into the same problem like me and can't find a solution for that case and find this SO question.
Sorry for little bit off-topic, but as i just found out that this works, i thought it might be worth sharing.
Don't know if it is a dirty workaround, or actually legit.
<Directory /your/directorypath/>
php_admin_value engine Off
</Directory>
There should be a program called dos2unix
that will fix line endings for you. If it's not already on your Linux box, it should be available via the package manager.
To expand upon Martin's excellent answer here is a query that lets you filter based on the parent table and shows you the name of the child table with each parent table so you can see all of the dependent tables/columns based upon the foreign key constraints in the parent table.
select
con.constraint_name,
att2.attname as "child_column",
cl.relname as "parent_table",
att.attname as "parent_column",
con.child_table,
con.child_schema
from
(select
unnest(con1.conkey) as "parent",
unnest(con1.confkey) as "child",
con1.conname as constraint_name,
con1.confrelid,
con1.conrelid,
cl.relname as child_table,
ns.nspname as child_schema
from
pg_class cl
join pg_namespace ns on cl.relnamespace = ns.oid
join pg_constraint con1 on con1.conrelid = cl.oid
where con1.contype = 'f'
) con
join pg_attribute att on
att.attrelid = con.confrelid and att.attnum = con.child
join pg_class cl on
cl.oid = con.confrelid
join pg_attribute att2 on
att2.attrelid = con.conrelid and att2.attnum = con.parent
where cl.relname like '%parent_table%'
You should push the new viewcontroller by using current navigation controller, not present.
self.navigationController.pushViewController(nextViewController, animated: true)
Write bytes and Create the file if not exists:
f = open('./put/your/path/here.png', 'wb')
f.write(data)
f.close()
wb
means open the file in write binary
mode.
If column datatype is text you should use DataLength function like:
select top 1 CR, DataLength(CR)
from tbl
order by DataLength(CR) desc
You almost got it. It should be this:
<input type="radio" name="group1" id="r1" value="1" />_x000D_
<label for="r1"> button one</label>
_x000D_
The value in for
should be the id of the element you are labeling.
You can specify JsonSerializerSettings
for each JsonConvert
, and you can set a global default.
Single JsonConvert
with an overload:
// Option #1.
JsonSerializerSettings config = new JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore };
this.json = JsonConvert.SerializeObject(YourObject, Formatting.Indented, config);
// Option #2 (inline).
JsonConvert.SerializeObject(YourObject, Formatting.Indented,
new JsonSerializerSettings() {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
}
);
Global Setting with code in Application_Start()
in Global.asax.cs:
JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
Formatting = Newtonsoft.Json.Formatting.Indented,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};
Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78
@RSC
for me the critical addition in Xcode Version 6.2 (6C86e) is in override func viewDidLoad()
self.input.delegate = self;
Tried getting it to work with the return key for hours till I found your post, RSC. Thank you!
Also, if you want to hide the keyboard if you touch anywhere else on the screen:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true);
}
In Swift 3.0
You can find the event for the touch/click of the cell of tableview through it delegate method. As well, can find the section and row value of the cell like this.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("section: \(indexPath.section)")
print("row: \(indexPath.row)")
}
If you talk about Activity
, AppcompactActivity
, ActionBarActivity
etc etc..
We need to talk about Base classes which they are extending, First we have to understand the hierarchy of super classes.
All the things are started from Context which is super class for all these classes.
Context is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc
Context
is followed by or extended by ContextWrapper
The ContextWrapper is a class which extend Context class that simply delegates all of its calls to another Context. Can be subclassed to modify behavior without changing the original Context.
Now we Reach to Activity
The Activity is a class which extends ContextThemeWrapper that is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you
Below Classes are restricted to extend but they are extended by their descender internally and provide support for specific Api
The SupportActivity is a class which extends Activity that is a Base class for composing together compatibility functionality
The BaseFragmentActivityApi14 is a class which extends SupportActivity that is a Base class It is restricted class but it is extend by BaseFragmentActivityApi16 to support the functionality of V14
The BaseFragmentActivityApi16 is a class which extends BaseFragmentActivityApi14 that is a Base class for {@code FragmentActivity} to be able to use v16 APIs. But it is also restricted class but it is extend by FragmentActivity to support the functionality of V16.
now FragmentActivty
The FragmentActivity is a class which extends BaseFragmentActivityApi16 and that wants to use the support-based Fragment and Loader APIs.
When using this class as opposed to new platform's built-in fragment and loader support, you must use the getSupportFragmentManager()
and getSupportLoaderManager()
methods respectively to access those features.
ActionBarActivity is part of the Support Library. Support libraries are used to deliver newer features on older platforms. For example the ActionBar was introduced in API 11 and is part of the Activity by default (depending on the theme actually). In contrast there is no ActionBar on the older platforms. So the support library adds a child class of Activity (ActionBarActivity) that provides the ActionBar's functionality and ui
In 2015 ActionBarActivity is deprecated in revision 22.1.0 of the Support Library. AppCompatActivity should be used instead.
The AppcompactActivity is a class which extends FragmentActivity that is Base class for activities that use the support library action bar features.
You can add an ActionBar to your activity when running on API level 7 or higher by extending this class for your activity and setting the activity theme to Theme.AppCompat
or a similar theme
You just need to correct the format of your html
<form>
<li>Number 1: <input type="text" ng-model="one"/> </li>
<li>Number 2: <input type="text" ng-model="two"/> </li>
<li>Total <input type="text" value="{{total()}}"/> </li>
{{total()}}
</form>
The problem is that your code is creating a blank UIViewController, not a SecondViewController. You need to create an instance of your subclass, not a UIViewController,
func transition(Sender: UIButton!) {
let secondViewController:SecondViewController = SecondViewController()
self.presentViewController(secondViewController, animated: true, completion: nil)
}
If you've overridden init(nibName nibName: String!,bundle nibBundle: NSBundle!) in your SecondViewController class, then you need to change the code to,
let sec: SecondViewController = SecondViewController(nibName: nil, bundle: nil)
u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)
Using the path /inout-tracker
without a trailing /
doesn't fetch index.php
. Instead the server will issue a 302
redirect to the version with the trailing /
.
Doing a 302 will typically cause clients to convert a POST to a GET request.
var CommentData= "u_id=" + $(this).attr("u_id") + "&post_id=" + $(this).attr("p_id") + "&comment=" + $(this).val();
You can also try:
if (!Request.QueryString.AllKeys.Contains("aspxerrorpath"))
return;
As an addition to Frank Heiken's answer, if you wish to use INSERT
statements instead of copy from stdin
, then you should specify the --inserts
flag
pg_dump --host localhost --port 5432 --username postgres --format plain --verbose --file "<abstract_file_path>" --table public.tablename --inserts dbname
Notice that I left out the --ignore-version
flag, because it is deprecated.
Try this
spinner.postDelayed(new Runnable() {
@Override
public void run() {
addListeners();
}
}, 1000);.o
It depends on how you validate your XML. If you use XML Schema validation, the correct way of representing null
values is with the xsi:nil
attribute.
[Source]
It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap
object and draw into that using the Graphics.CopyFromScreen
method.
Sample code:
using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0, 0,
bmpScreenCapture.Size,
CopyPixelOperation.SourceCopy);
}
Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.
class foo(object):
mStatic = 12
def __init__(self):
self.x = "OBj"
Considering that foo has no access to x at all (FACT)
the conflict now is in accessing mStatic by an instance or directly by the class .
think of it in the terms of Python's memory management :
12 value is on the memory and the name mStatic (which accessible from the class)
points to it .
c1, c2 = foo(), foo()
this line makes two instances , which includes the name mStatic that points to the value 12 (till now) .
foo.mStatic = 99
this makes mStatic name pointing to a new place in the memory which has the value 99 inside it .
and because the (babies) c1 , c2 are still following (daddy) foo , they has the same name (c1.mStatic & c2.mStatic ) pointing to the same new value .
but once each baby decides to walk alone , things differs :
c1.mStatic ="c1 Control"
c2.mStatic ="c2 Control"
from now and later , each one in that family (c1,c2,foo) has its mStatica pointing to different value .
[Please, try use id() function for all of(c1,c2,foo) in different sates that we talked about , i think it will make things better ]
and this is how our real life goes . sons inherit some beliefs from their father and these beliefs still identical to father's ones until sons decide to change it .
HOPE IT WILL HELP
if you are running and old version of Hadoop (hadoop 1.2) you got an error because http://localhost:50070/dfshealth.html does'nt exit. Check http://localhost:50070/dfshealth.jsp which works !
The default username is root. You can reset the root password if you do not know it: http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html. You should not, however, use the root account from PHP, set up a limited permission user to do that: http://dev.mysql.com/doc/refman/5.1/en/adding-users.html
If MySql is running on the same computer as your webserver, you can just use "localhost" as the host
Here a bit easier:
@echo off
set /p var=Are You Sure?[Y/N]:
if %var%== Y goto ...
if not %var%== Y exit
or
@echo off
echo Are You Sure?[Y/N]
choice /c YN
if %errorlevel%==1 goto yes
if %errorlevel%==2 goto no
:yes
echo yes
goto :EOF
:no
echo no
SELECT id, name, form_id, DATE(updated_at) as date
FROM wp_frm_items
WHERE user_id = 11 && form_id=9
ORDER BY date ASC
"DESC" stands for descending but you need ascending order ("ASC").
Objects are instances of classes. Classes are just the blueprints for objects. So given your class definition -
# Note the added (object) - this is the preferred way of creating new classes
class Student(object):
name = "Unknown name"
age = 0
major = "Unknown major"
You can create a make_student
function by explicitly assigning the attributes to a new instance of Student
-
def make_student(name, age, major):
student = Student()
student.name = name
student.age = age
student.major = major
return student
But it probably makes more sense to do this in a constructor (__init__
) -
class Student(object):
def __init__(self, name="Unknown name", age=0, major="Unknown major"):
self.name = name
self.age = age
self.major = major
The constructor is called when you use Student()
. It will take the arguments defined in the __init__
method. The constructor signature would now essentially be Student(name, age, major)
.
If you use that, then a make_student
function is trivial (and superfluous) -
def make_student(name, age, major):
return Student(name, age, major)
For fun, here is an example of how to create a make_student
function without defining a class. Please do not try this at home.
def make_student(name, age, major):
return type('Student', (object,),
{'name': name, 'age': age, 'major': major})()
NO, you can't do it other way than so.
Featured graphics guidelines:
http://android-developers.blogspot.cz/2011/10/android-market-featured-image.html
List of graphics assets for your application:
http://support.google.com/googleplay/android-developer/bin/answer.py?hl=en&answer=1078870
You could also check our blog post summarizing all graphical assets for both Android and iOS:
http://www.skoumal.net/en/how-to-prepare-graphical-design-for-mobile-app/
MVC provides you with the OnAuthorize method that hangs from your controller classes. Or, you could use a custom action filter to perform authorization. MVC makes it pretty easy to do. I posted a blog post about this here. http://www.bradygaster.com/post/custom-authentication-with-mvc-3.0
To get left and right tabs (now also with sideways) support for Bootstrap 3, bootstrap-vertical-tabs component can be used.
You want to use a JFileChooser
object. It will open and be modal, and block in the thread that opened it until you choose a file.
Open:
JFileChooser fileChooser = new JFileChooser(); if (fileChooser.showOpenDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); // load from file }
Save:
JFileChooser fileChooser = new JFileChooser(); if (fileChooser.showSaveDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); // save to file }
There are more options you can set to set the file name extension filter, or the current directory. See the API for the javax.swing.JFileChooser
for details. There is also a page for "How to Use File Choosers" on Oracle's site:
http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html
There's always a goto
statement, but I would recommend nesting an if
with an inverse of the breaking condition.
PPK ? OpenSSH RSA with PuttyGen & Docker.
Private key:
docker run --rm -v $(pwd):/app zinuzoid/puttygen private.ppk -O private-openssh -o my-openssh-key
Public key:
docker run --rm -v $(pwd):/app zinuzoid/puttygen private.ppk -L -o my-openssh-key.pub
There is a solution even if you don't want to remove your local changes.
Just fix the unmerged files (by git add
or git remove
). Then do git pull
.
You can simply use .toString()
.
var result = require('child_process').execSync('rsync -avAXz --info=progress2 "/src" "/dest"').toString();
console.log(result);
This has been tested on Node v8.5.0
, I'm not sure about previous versions. According to @etov, it doesn't work on v6.3.1
- I'm not sure about in-between.
Edit: Looking back on this, I've realised that it doesn't actually answer the specific question because it doesn't show the output to you 'live' — only once the command has finished running.
However, I'm leaving this answer here because I know quite a few people come across this question just looking for how to print the result of the command after execution.
Java generics uses type erasure. The bit in the angle brackets (<Integer>
and <String>
) gets removed, so you'd end up with two methods that have an identical signature (the add(Set)
you see in the error). That's not allowed because the runtime wouldn't know which to use for each case.
If Java ever gets reified generics, then you could do this, but that's probably unlikely now.
The question is already answered, but you can resolve it like this:
const doSomething = (x) => x
export default doSomething;
import doSomething from "./dependency";
export default (x) => doSomething(x * 2);
jest.mock('../dependency');
import doSomething from "../dependency";
import myModule from "../myModule";
describe('myModule', () => {
it('calls the dependency with double the input', () => {
doSomething.mockImplementation((x) => x * 10)
myModule(2);
expect(doSomething).toHaveBeenCalledWith(4);
console.log(myModule(2)) // 40
});
});
public boolean isAlertPresent()
{
try
{
driver.switchTo().alert();
return true;
} // try
catch (NoAlertPresentException Ex)
{
return false;
} // catch
} // isAlertPresent()
check the link here https://groups.google.com/forum/?fromgroups#!topic/webdriver/1GaSXFK76zY
Just for the purpose of mentioning underscore's find method works in IE with no problem.
git pull
is like running git fetch
then git merge
git pull --rebase
is like git fetch
then git rebase
git pull
is like a git fetch
+ git merge
.
"In its default mode, git pull is shorthand for
git fetch
followed bygit merge
FETCH_HEAD" More precisely,git pull
runsgit fetch
with the given parameters and then callsgit merge
to merge the retrieved branch heads into the current branch"
(Ref: https://git-scm.com/docs/git-pull)
'But what is the difference between git pull
VS git fetch
+ git rebase
'
Again, from same source:
git pull --rebase
"With --rebase, it runs git rebase instead of git merge."
'the difference between merge
and rebase
'
that is answered here too:
https://git-scm.com/book/en/v2/Git-Branching-Rebasing
(the difference between altering the way version history is recorded)
function checkForm(& $fields){
foreach($fields as $field){
if($field['required'] && strlen($_POST[$field['name']]) <= 0){
$fields[$field]['value'] = "Some error";
}
}
return $fields;
}
This is what I would Suggest pass by reference
After asking a similar question I’ve created another package which uses Pygments, and offers quite a few more options than texments
. It’s called minted
and is quite stable and usable.
Just to show it off, here’s a code highlighted with minted:
//String appending
#include <iostream>
using namespace std;
void stringconcat(char *str1, char *str2){
while (*str1 != '\0'){
str1++;
}
while(*str2 != '\0'){
*str1 = *str2;
str1++;
str2++;
}
}
int main() {
char str1[100];
cin.getline(str1, 100);
char str2[100];
cin.getline(str2, 100);
stringconcat(str1, str2);
cout<<str1;
getchar();
return 0;
}
To get the Windows version number, as Jeff notes in his answer, use:
[Environment]::OSVersion
It is worth noting that the result is of type [System.Version]
, so it is possible to check for, say, Windows 7/Windows Server 2008 R2 and later with
[Environment]::OSVersion.Version -ge (new-object 'Version' 6,1)
However this will not tell you if it is client or server Windows, nor the name of the version.
Use WMI's Win32_OperatingSystem
class (always single instance), for example:
(Get-WmiObject -class Win32_OperatingSystem).Caption
will return something like
Microsoft® Windows Server® 2008 Standard
If you've already got underscore or lodash included in your project you can use _.sample
.
// will return one item randomly from the array
_.sample(['January', 'February', 'March']);
If you need to get more than one item randomly, you can pass that as a second argument in underscore:
// will return two items randomly from the array using underscore
_.sample(['January', 'February', 'March'], 2);
or use the _.sampleSize
method in lodash:
// will return two items randomly from the array using lodash
_.sampleSize(['January', 'February', 'March'], 2);
Not tested but you can try something like this :
Declare @count as int
Set @count=1
Declare @inputFile varchar(max)
Declare @Sample Table
(id int,filepath varchar(max) ,Isexists char(3))
while @count<(select max(id) from yourTable)
BEGIN
Set @inputFile =(Select filepath from yourTable where id=@count)
DECLARE @isExists INT
exec master.dbo.xp_fileexist @inputFile ,
@isExists OUTPUT
insert into @Sample
Select @count,@inputFile ,case @isExists
when 1 then 'Yes'
else 'No'
end as isExists
set @count=@count+1
END
Combining matty-j suggestion with the snippet of the question, I ended up with this code focusing on resizing the grid after the data was loaded.
The HTML:
<div ng-grid="gridOptions" class="gridStyle"></div>
The directive:
angular.module('myApp.directives', [])
.directive('resize', function ($window) {
return function (scope, element) {
var w = angular.element($window);
scope.getWindowDimensions = function () {
return { 'h': w.height(), 'w': w.width() };
};
scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
// resize Grid to optimize height
$('.gridStyle').height(newValue.h - 250);
}, true);
w.bind('resize', function () {
scope.$apply();
});
}
});
The controller:
angular.module('myApp').controller('Admin/SurveyCtrl', function ($scope, $routeParams, $location, $window, $timeout, Survey) {
// Retrieve data from the server
$scope.surveys = Survey.query(function(data) {
// Trigger resize event informing elements to resize according to the height of the window.
$timeout(function () {
angular.element($window).resize();
}, 0)
});
// Configure ng-grid.
$scope.gridOptions = {
data: 'surveys',
...
};
}
Correct, when you drag a view controller object onto your storyboard in order to create a new scene, it doesn't automatically make the new class for you, too.
Having added a new view controller scene to your storyboard, you then have to:
Create a UIViewController
subclass. For example, go to your target's folder in the project navigator panel on the left and then control-click and choose "New File...". Choose a "Cocoa Touch Class":
And then select a unique name for the new view controller subclass:
Specify this new subclass as the base class for the scene you just added to the storyboard.
Now hook up any IBOutlet
and IBAction
references for this new scene with the new view controller subclass.
This issue for me was caused by having apowermirror running at the same time, from what I can tell any software that could use a different version of adb could cause these issues as others mention in this thread this can include Genymotion or from other threads unreal studio was the problem.
SCENARIO 1 - wait for async task completion: I agree that WaitHandle/Auto|ManualResetEvent should be used in scenario where a thread is waiting for task on another thread to complete.
SCENARIO 2 - timing while loop: However, as a crude timing mechanism (while+Thread.Sleep) is perfectly fine for 99% of applications which does NOT require knowing exactly when the blocked Thread should "wake up*. The argument that it takes 200k cycles to create the thread is also invalid - the timing loop thread needs be created anyway and 200k cycles is just another big number (tell me how many cycles to open a file/socket/db calls?).
So if while+Thread.Sleep works, why complicate things? Only syntax lawyers would, be practical!
String str = "to";
str.replace("to", "xyz");
Just try it :)
"Not equals" can be expressed with the "not" operator !
and the standard .equals
.
if (a.equals(b)) // a equals b
if (!a.equals(b)) // a not equal to b
In JavaScript you declare variables or functions by using the keywords var, let or function. In TypeScript classes you declare class members or methods without these keywords followed by a colon and the type or interface of that class member.
It’s just syntax sugar, there is no difference between:
var el: HTMLElement = document.getElementById('content');
and:
var el = document.getElementById('content');
On the other hand, because you specify the type you get all the information of your HTMLElement object.
To answer the question as asked (without repeating unduly what appears in other answers)
Lexers and parsers are not very different, as suggested by the accepted answer. Both are based on simple language formalisms: regular languages for lexers and, almost always, context-free (CF) languages for parsers. They both are associated with fairly simple computational models, the finite state automaton and the push-down stack automaton. Regular languages are a special case of context-free languages, so that lexers could be produced with the somewhat more complex CF technology. But it is not a good idea for at least two reasons.
A fundamental point in programming is that a system component should be buit with the most appropriate technology, so that it is easy to produce, to understand and to maintain. The technology should not be overkill (using techniques much more complex and costly than needed), nor should it be at the limit of its power, thus requiring technical contortions to achieve the desired goal.
That is why "It seems fashionable to hate regular expressions". Though they can do a lot, they sometimes require very unreadable coding to achieve it, not to mention the fact that various extensions and restrictions in implementation somewhat reduce their theoretical simplicity. Lexers do not usually do that, and are usually a simple, efficient, and appropriate technology to parse token. Using CF parsers for token would be overkill, though it is possible.
Another reason not to use CF formalism for lexers is that it might then be tempting to use the full CF power. But that might raise sructural problems regarding the reading of programs.
Fundamentally, most of the structure of program text, from which meaning is extracted, is a tree structure. It expresses how the parse sentence (program) is generated from syntax rules. Semantics is derived by compositional techniques (homomorphism for the mathematically oriented) from the way syntax rules are composed to build the parse tree. Hence the tree structure is essential. The fact that tokens are identified with a regular set based lexer does not change the situation, because CF composed with regular still gives CF (I am speaking very loosely about regular transducers, that transform a stream of characters into a stream of token).
However, CF composed with CF (via CF transducers ... sorry for the math), does not necessarily give CF, and might makes things more general, but less tractable in practice. So CF is not the appropriate tool for lexers, even though it can be used.
One of the major differences between regular and CF is that regular languages (and transducers) compose very well with almost any formalism in various ways, while CF languages (and transducers) do not, not even with themselves (with a few exceptions).
(Note that regular transducers may have others uses, such as formalization of some syntax error handling techniques.)
BNF is just a specific syntax for presenting CF grammars.
EBNF is a syntactic sugar for BNF, using the facilities of regular notation to give terser version of BNF grammars. It can always be transformed into an equivalent pure BNF.
However, the regular notation is often used in EBNF only to emphasize these parts of the syntax that correspond to the structure of lexical elements, and should be recognized with the lexer, while the rest with be rather presented in straight BNF. But it is not an absolute rule.
To summarize, the simpler structure of token is better analyzed with the simpler technology of regular languages, while the tree oriented structure of the language (of program syntax) is better handled by CF grammars.
I would suggest also looking at AHR's answer.
But this leaves a question open: Why trees?
Trees are a good basis for specifying syntax because
they give a simple structure to the text
there are very convenient for associating semantics with the text on the basis of that structure, with a mathematically well understood technology (compositionality via homomorphisms), as indicated above. It is a fundamental algebraic tool to define the semantics of mathematical formalisms.
Hence it is a good intermediate representation, as shown by the success of Abstract Syntax Trees (AST). Note that AST are often different from parse tree because the parsing technology used by many professionals (Such as LL or LR) applies only to a subset of CF grammars, thus forcing grammatical distorsions which are later corrected in AST. This can be avoided with more general parsing technology (based on dynamic programming) that accepts any CF grammar.
Statement about the fact that programming languages are context-sensitive (CS) rather than CF are arbitrary and disputable.
The problem is that the separation of syntax and semantics is arbitrary. Checking declarations or type agreement may be seen as either part of syntax, or part of semantics. The same would be true of gender and number agreement in natural languages. But there are natural languages where plural agreement depends on the actual semantic meaning of words, so that it does not fit well with syntax.
Many definitions of programming languages in denotational semantics place declarations and type checking in the semantics. So stating as done by Ira Baxter that CF parsers are being hacked to get a context sensitivity required by syntax is at best an arbitrary view of the situation. It may be organized as a hack in some compilers, but it does not have to be.
Also it is not just that CS parsers (in the sense used in other answers here) are hard to build, and less efficient. They are are also inadequate to express perspicuously the kinf of context-sensitivity that might be needed. And they do not naturally produce a syntactic structure (such as parse-trees) that is convenient to derive the semantics of the program, i.e. to generate the compiled code.
There is another option not mentioned previously:
The simplest way would be to directly subtract the date objects from one another.
For example:
var hours = Math.abs(date1 - date2) / 36e5;
The subtraction returns the difference between the two dates in milliseconds. 36e5
is the scientific notation for 60*60*1000
, dividing by which converts the milliseconds difference into hours.
This is works for me. tyr this
exec(“php asyn.php”.” > /dev/null 2>/dev/null &“);
If you don't have bs-config.json
, you can change the port inside the lite-server module. Go to node_modules/lite-server/lib/config-defaults.js
in your project, then add the port in "modules.export" like this.
module.export {
port :8000, // to any available port
...
}
Then you can restart the server.
As you have said if you want to add 24 hours to the timestamp for right now then simply you can do:
<?php echo strtotime('+1 day'); ?>
Above code will add 1 day or 24 hours to your current timestamp.
in place of +1 day
you can take whatever you want, As php manual says strtotime can Parse about any English textual datetime description into a Unix timestamp.
examples from the manual are as below:
<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
?>
HTML
<input type="text" [(ngModel)]="obj.mobile" name="mobile" id="mobile" class="form-control" placeholder="Mobile/E-mail" />
TS
onClickClear(){
this.obj.mobile= undefined;
}
$computer,$Speed,$Regcheck
will create an array, and run out-file
ones per variable = they get seperate lines. If you construct a single string using the variables first, it will show up a single line. Like this:
"$computer,$Speed,$Regcheck" | out-file -filepath C:\temp\scripts\pshell\dump.txt -append -width 200
IMPORTANT DISCLAIMER: Information provided below is for educational purposes only! Extending a trial period of Visual Studio Community 2017 might be ILLEGAL!
You have the same effect when You remove all files from HKEY_CLASSES_ROOT\Licenses\5C505A59-E312-4B89-9508-E162F8150517. Run "Visual Studio Installer" and chose option "repair". Now You have new 30 days of trial. But You lost all configuration in Your VS.
I had to do some debugging on a Windows Nano docker image and needed to edit the content of a file, who would have guessed it was so difficult.
I used a combination of Get-Content
and Set-Content
and base 64 encoding/decoding to update files. For instance
Editing foo.txt
PS C:\app> Set-Content foo.txt "Hello World"
PS C:\app> Get-Content foo.txt
Hello World
PS C:\app> [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("TXkgbmV3IG11bHRpDQpsaW5lIGRvY3VtZW50DQp3aXRoIGFsbCBraW5kcyBvZiBmdW4gc3R1ZmYNCiFAIyVeJSQmXiYoJiopIUAjIw0KLi4ud29ybGQ=")) | Set-Content foo.txt
PS C:\app> Get-Content foo.txt
My new multi
line document
with all kinds of fun stuff
!@#%^%$&^&(&*)!@##
...world
PS C:\app>
The trick is piping the base 64 decoded string to Set-Content
[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("...")) | Set-Content foo.txt
Its no vim but I can update files, for what its worth.
Use the substring method of the String class :
String removeCurrency=amount.getText().toString().substring(3);
I suppose https://get-ytt.io/ would be an acceptable solution to your problem
Use the following code to destroy the session:
<?php
session_start();
unset($_SESSION['sessionvariable']);
header("Location:index.php");
?>
To add characters such as T and Z in your date
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'")
private Date currentTime;
output
{
"currentTime": "2019-12-11T11:40:49Z"
}
I use the following pattern to make it bulletproof.
Try it out you can't break it without making modifications to the base classes (except if you define an obsolete flag without error flag set to true, but even then you end up with a warning)
public abstract class Base<TSelf, TParameter>
where TSelf : Base<TSelf, TParameter>, new()
{
protected const string FactoryMessage = "Use YourClass.Create(...) instead";
public static TSelf Create(TParameter parameter)
{
var me = new TSelf();
me.Initialize(parameter);
return me;
}
[Obsolete(FactoryMessage, true)]
protected Base()
{
}
protected virtual void Initialize(TParameter parameter)
{
}
}
public abstract class BaseWithConfig<TSelf, TConfig>: Base<TSelf, TConfig>
where TSelf : BaseWithConfig<TSelf, TConfig>, new()
{
public TConfig Config { get; private set; }
[Obsolete(FactoryMessage, true)]
protected BaseWithConfig()
{
}
protected override void Initialize(TConfig parameter)
{
this.Config = parameter;
}
}
public class MyService : BaseWithConfig<MyService, (string UserName, string Password)>
{
[Obsolete(FactoryMessage, true)]
public MyService()
{
}
}
public class Person : Base<Person, (string FirstName, string LastName)>
{
[Obsolete(FactoryMessage,true)]
public Person()
{
}
protected override void Initialize((string FirstName, string LastName) parameter)
{
this.FirstName = parameter.FirstName;
this.LastName = parameter.LastName;
}
public string LastName { get; private set; }
public string FirstName { get; private set; }
}
[Test]
public void FactoryTest()
{
var notInitilaizedPerson = new Person(); // doesn't compile because of the obsolete attribute.
Person max = Person.Create(("Max", "Mustermann"));
Assert.AreEqual("Max",max.FirstName);
var service = MyService.Create(("MyUser", "MyPassword"));
Assert.AreEqual("MyUser", service.Config.UserName);
}
EDIT: And here is an example based on your drawing example that even enforces interface abstraction
public abstract class BaseWithAbstraction<TSelf, TInterface, TParameter>
where TSelf : BaseWithAbstraction<TSelf, TInterface, TParameter>, TInterface, new()
{
[Obsolete(FactoryMessage, true)]
protected BaseWithAbstraction()
{
}
protected const string FactoryMessage = "Use YourClass.Create(...) instead";
public static TInterface Create(TParameter parameter)
{
var me = new TSelf();
me.Initialize(parameter);
return me;
}
protected virtual void Initialize(TParameter parameter)
{
}
}
public abstract class BaseWithParameter<TSelf, TInterface, TParameter> : BaseWithAbstraction<TSelf, TInterface, TParameter>
where TSelf : BaseWithParameter<TSelf, TInterface, TParameter>, TInterface, new()
{
protected TParameter Parameter { get; private set; }
[Obsolete(FactoryMessage, true)]
protected BaseWithParameter()
{
}
protected sealed override void Initialize(TParameter parameter)
{
this.Parameter = parameter;
this.OnAfterInitialize(parameter);
}
protected virtual void OnAfterInitialize(TParameter parameter)
{
}
}
public class GraphicsDeviceManager
{
}
public interface IDrawable
{
void Update();
void Draw();
}
internal abstract class Drawable<TSelf> : BaseWithParameter<TSelf, IDrawable, GraphicsDeviceManager>, IDrawable
where TSelf : Drawable<TSelf>, IDrawable, new()
{
[Obsolete(FactoryMessage, true)]
protected Drawable()
{
}
public abstract void Update();
public abstract void Draw();
}
internal class Rectangle : Drawable<Rectangle>
{
[Obsolete(FactoryMessage, true)]
public Rectangle()
{
}
public override void Update()
{
GraphicsDeviceManager manager = this.Parameter;
// TODo manager
}
public override void Draw()
{
GraphicsDeviceManager manager = this.Parameter;
// TODo manager
}
}
internal class Circle : Drawable<Circle>
{
[Obsolete(FactoryMessage, true)]
public Circle()
{
}
public override void Update()
{
GraphicsDeviceManager manager = this.Parameter;
// TODo manager
}
public override void Draw()
{
GraphicsDeviceManager manager = this.Parameter;
// TODo manager
}
}
[Test]
public void FactoryTest()
{
// doesn't compile because interface abstraction is enforced.
Rectangle rectangle = Rectangle.Create(new GraphicsDeviceManager());
// you get only the IDrawable returned.
IDrawable service = Circle.Create(new GraphicsDeviceManager());
}
You can also use this format:
moment().format('ddd, ll'); // Wed, Jan 4, 2017
You can simply override BaseActivity onActivityResult
on fragment baseActivity.startActivityForResult
.
On BaseActivity add interface and override onActivityResult.
private OnBaseActivityResult baseActivityResult;
public static final int BASE_RESULT_RCODE = 111;
public interface OnBaseActivityResult{
void onBaseActivityResult(int requestCode, int resultCode, Intent data);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(getBaseActivityResult() !=null && requestCode == BASE_RESULT_RCODE){
getBaseActivityResult().onBaseActivityResult(requestCode, resultCode, data);
setBaseActivityResult(null);
}
On Fragment implements OnBaseActivityResult
@Override
public void onBaseActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("RQ","OnBaseActivityResult");
if (data != null) {
Log.d("RQ","OnBaseActivityResult + Data");
Bundle arguments = data.getExtras();
}
}
This workaround will do the trick.
Maybe.
Temporary tables prefixed with one # (#example) are kept on a per session basis. So if your code calls the stored procedure again while another call is running (for example background threads) then the create call will fail because it's already there.
If you're really worried use a table variable instead
DECLARE @MyTempTable TABLE
(
someField int,
someFieldMore nvarchar(50)
)
This will be specific to the "instance" of that stored procedure call.
Combining some answers from this post and also from here, and after some personal research, for NodeJS with typescript I managed to accomplish this by using firebase-admin:
import * as admin from 'firebase-admin';
const getFileNames = (folderName: any) => {
admin.storage().bucket().getFiles(autoPaginate: false).then(([files]: any) => {
const fileNames = files.map((file: any) => file.name);
return fileNames;
})
}
In my case I also needed to get all the files from a specific folder from firebase storage. According to google storage the folders don't exists but are rather a naming conventions. Anyway I managed to to this by adding { prefix: ${folderName}, autoPaginate: false }
the the getFiles
function so:
getFiles({ prefix: `${folderName}`, autoPaginate: false })
I generally URL-encode the fields which can have any commas or any special chars. And then decode it when it is being used/displayed in any visual medium.
(commas becomes %2C)
Every language should have methods to URL-encode and decode strings.
e.g., in java
URLEncoder.encode(myString,"UTF-8"); //to encode
URLDecoder.decode(myEncodedstring, "UTF-8"); //to decode
I know this is a very general solution and it might not be ideal for situation where user wants to view content of csv file, manually.
adding an invisible submit button does the trick
<input type="submit" style="display: none;">
you can use online tool like online Image Map
This might be a bit of a hack, but I avoided the issue and converted the json into PHP's POST array on the server side:
$_POST = json_decode(file_get_contents('php://input'), true);
You actually can't manually "free" memory in C, in the sense that the memory is released from the process back to the OS ... when you call malloc()
, the underlying libc-runtime will request from the OS a memory region. On Linux, this may be done though a relatively "heavy" call like mmap()
. Once this memory region is mapped to your program, there is a linked-list setup called the "free store" that manages this allocated memory region. When you call malloc()
, it quickly looks though the free-store for a free block of memory at the size requested. It then adjusts the linked list to reflect that there has been a chunk of memory taken out of the originally allocated memory pool. When you call free()
the memory block is placed back in the free-store as a linked-list node that indicates its an available chunk of memory.
If you request more memory than what is located in the free-store, the libc-runtime will again request more memory from the OS up to the limit of the OS's ability to allocate memory for running processes. When you free memory though, it's not returned back to the OS ... it's typically recycled back into the free-store where it can be used again by another call to malloc()
. Thus, if you make a lot of calls to malloc()
and free()
with varying memory size requests, it could, in theory, cause a condition called "memory fragmentation", where there is enough space in the free-store to allocate your requested memory block, but not enough contiguous space for the size of the block you've requested. Thus the call to malloc()
fails, and you're effectively "out-of-memory" even though there may be plenty of memory available as a total amount of bytes in the free-store.
None of the solutions work if you just changed the permissions of a file (this is on DOS/Windoze)
Mon 23/11/2015-15:16:34.80 C:\...\work\checkout\slf4j+> git status On branch SLF4J_1.5.3 Changes not staged for commit: (use "git add ..." to update what will be committed) (use "git checkout -- ..." to discard changes in working directory) modified: .gitignore modified: LICENSE.txt modified: TODO.txt modified: codeStyle.xml modified: pom.xml modified: version.pl no changes added to commit (use "git add" and/or "git commit -a") Mon 23/11/2015-15:16:37.87 C:\...\work\checkout\slf4j+> git diff diff --git a/.gitignore b/.gitignore old mode 100644 new mode 100755 diff --git a/LICENSE.txt b/LICENSE.txt old mode 100644 new mode 100755 diff --git a/TODO.txt b/TODO.txt old mode 100644 new mode 100755 diff --git a/codeStyle.xml b/codeStyle.xml old mode 100644 new mode 100755 diff --git a/pom.xml b/pom.xml old mode 100644 new mode 100755 diff --git a/version.pl b/version.pl old mode 100644 new mode 100755 Mon 23/11/2015-15:16:45.22 C:\...\work\checkout\slf4j+> git reset --hard HEAD HEAD is now at 8fa8488 12133-CHIXMISSINGMESSAGES MALCOLMBOEKHOFF 20141223124940 Added .gitignore Mon 23/11/2015-15:16:47.42 C:\...\work\checkout\slf4j+> git clean -f Mon 23/11/2015-15:16:53.49 C:\...\work\checkout\slf4j+> git stash save -u Saved working directory and index state WIP on SLF4J_1.5.3: 8fa8488 12133-CHIXMISSINGMESSAGES MALCOLMBOEKHOFF 20141223124940 Added .gitignore HEAD is now at 8fa8488 12133-CHIXMISSINGMESSAGES MALCOLMBOEKHOFF 20141223124940 Added .gitignore Mon 23/11/2015-15:17:00.40 C:\...\work\checkout\slf4j+> git stash drop Dropped refs/stash@{0} (cb4966e9b1e9c9d8daa79ab94edc0c1442a294dd) Mon 23/11/2015-15:17:06.75 C:\...\work\checkout\slf4j+> git stash drop Dropped refs/stash@{0} (e6c49c470f433ce344e305c5b778e810625d0529) Mon 23/11/2015-15:17:08.90 C:\...\work\checkout\slf4j+> git stash drop No stash found. Mon 23/11/2015-15:17:15.21 C:\...\work\checkout\slf4j+> git checkout -- . Mon 23/11/2015-15:22:00.68 C:\...\work\checkout\slf4j+> git checkout -f -- . Mon 23/11/2015-15:22:04.53 C:\...\work\checkout\slf4j+> git status On branch SLF4J_1.5.3 Changes not staged for commit: (use "git add ..." to update what will be committed) (use "git checkout -- ..." to discard changes in working directory) modified: .gitignore modified: LICENSE.txt modified: TODO.txt modified: codeStyle.xml modified: pom.xml modified: version.pl no changes added to commit (use "git add" and/or "git commit -a") Mon 23/11/2015-15:22:13.06 C:\...\work\checkout\slf4j+> git diff diff --git a/.gitignore b/.gitignore old mode 100644 new mode 100755 diff --git a/LICENSE.txt b/LICENSE.txt old mode 100644 new mode 100755 diff --git a/TODO.txt b/TODO.txt old mode 100644 new mode 100755 diff --git a/codeStyle.xml b/codeStyle.xml old mode 100644 new mode 100755 diff --git a/pom.xml b/pom.xml old mode 100644 new mode 100755 diff --git a/version.pl b/version.pl old mode 100644 new mode 100755
The only way to fix this is to manually reset the permissions on the changed files:
Mon 23/11/2015-15:25:43.79 C:\...\work\checkout\slf4j+> git status -s | egrep "^ M" | cut -c4- | for /f "usebackq tokens=* delims=" %A in (`more`) do chmod 644 %~A Mon 23/11/2015-15:25:55.37 C:\...\work\checkout\slf4j+> git status On branch SLF4J_1.5.3 nothing to commit, working directory clean Mon 23/11/2015-15:25:59.28 C:\...\work\checkout\slf4j+> Mon 23/11/2015-15:26:31.12 C:\...\work\checkout\slf4j+> git diff
I think this will meet your requirements:
For left padding add a string extension like this:
Swift 2.0 +
extension String {
func padLeft (totalWidth: Int, with: String) -> String {
let toPad = totalWidth - self.characters.count
if toPad < 1 { return self }
return "".stringByPaddingToLength(toPad, withString: with, startingAtIndex: 0) + self
}
}
Swift 3.0 +
extension String {
func padLeft (totalWidth: Int, with: String) -> String {
let toPad = totalWidth - self.characters.count
if toPad < 1 { return self }
return "".padding(toLength: toPad, withPad: with, startingAt: 0) + self
}
}
Using this method:
for myInt in 1...3 {
print("\(myInt)".padLeft(totalWidth: 2, with: "0"))
}
You said it worked fine when you were using SQL Express edition. By default express editions create a named instance & run in NT Authority\Network Service.
SQL Server STD by default install a default instance & run in NT Authority\SYSTEM.
Do you have both the full SQL edition & Express edition installed on the same machine?
It could be that somewhere the connection string still refers to the Named instance 'SQLEXPRESS' rather than the default instance created by the full version.
Also where is the connection string defined? In IIS or your code? Make sure that if defined in many places, all point to same SQL instance & database.
Also try looking at the detailed error present in the SQL Server error logs. The error logged in event log are not complete for secuirty reasons. This will also help you to know if the connection was made to the correct SQL Server.
Also make sure that the machine on which SQL is installed is accessible & IIS is trying to access the same machine. In my company sometimes due to wrong name resolution, the query fails since most of our computers have SQL installed & the query lands in the wrong SQL Server.
Make sure that the database exists in the SQL Server. The name displayed under databases in SQL Management Studio should match that in the connection string.
The LDF is the transaction log. It keeps a record of everything done to the database for rollback purposes.
You do not want to delete, but you can shrink it with the dbcc shrinkfile
command. You can also right-click on the database in SQL Server Management Studio and go to Tasks > Shrink.
taken from : Android UI : Fixing skipped frames
Anyone who begins developing android application sees this message on logcat “Choreographer(abc): Skipped xx frames! The application may be doing too much work on its main thread.” So what does it actually means, why should you be concerned and how to solve it.
What this means is that your code is taking long to process and frames are being skipped because of it, It maybe because of some heavy processing that you are doing at the heart of your application or DB access or any other thing which causes the thread to stop for a while.
Here is a more detailed explanation:
Choreographer lets apps to connect themselves to the vsync, and properly time things to improve performance.
Android view animations internally uses Choreographer for the same purpose: to properly time the animations and possibly improve performance.
Since Choreographer is told about every vsync events, I can tell if one of the Runnables passed along by the Choreographer.post* apis doesnt finish in one frame’s time, causing frames to be skipped.
In my understanding Choreographer can only detect the frame skipping. It has no way of telling why this happens.
The message “The application may be doing too much work on its main thread.” could be misleading.
Why you should be concerned
When this message pops up on android emulator and the number of frames skipped are fairly small (<100) then you can take a safe bet of the emulator being slow – which happens almost all the times. But if the number of frames skipped and large and in the order of 300+ then there can be some serious trouble with your code. Android devices come in a vast array of hardware unlike ios and windows devices. The RAM and CPU varies and if you want a reasonable performance and user experience on all the devices then you need to fix this thing. When frames are skipped the UI is slow and laggy, which is not a desirable user experience.
How to fix it
Fixing this requires identifying nodes where there is or possibly can happen long duration of processing. The best way is to do all the processing no matter how small or big in a thread separate from main UI thread. So be it accessing data form SQLite Database or doing some hardcore maths or simply sorting an array – Do it in a different thread
Now there is a catch here, You will create a new Thread for doing these operations and when you run your application, it will crash saying “Only the original thread that created a view hierarchy can touch its views“. You need to know this fact that UI in android can be changed by the main thread or the UI thread only. Any other thread which attempts to do so, fails and crashes with this error. What you need to do is create a new Runnable inside runOnUiThread and inside this runnable you should do all the operations involving the UI. Find an example here.
So we have Thread and Runnable for processing data out of main Thread, what else? There is AsyncTask in android which enables doing long time processes on the UI thread. This is the most useful when you applications are data driven or web api driven or use complex UI’s like those build using Canvas. The power of AsyncTask is that is allows doing things in background and once you are done doing the processing, you can simply do the required actions on UI without causing any lagging effect. This is possible because the AsyncTask derives itself from Activity’s UI thread – all the operations you do on UI via AsyncTask are done is a different thread from the main UI thread, No hindrance to user interaction.
So this is what you need to know for making smooth android applications and as far I know every beginner gets this message on his console.
If you want a relative link to your wiki page on GitHub, use this:
Read here: [Some other wiki page](path/to/some-other-wiki-page)
If you want a link to a file in the repository, let us say, to reference some header file, and the wiki page is at the root of the wiki, use this:
Read here: [myheader.h](../tree/master/path/to/myheader.h)
The rationale for the last is to skip the "/wiki" path with "../", and go to the master branch in the repository tree without specifying the repository name, that may change in the future.
Use this overload (RenderPartialExtensions.RenderPartial
on MSDN):
public static void RenderPartial(
this HtmlHelper htmlHelper,
string partialViewName,
Object model
)
so:
@{Html.RenderPartial(
"FullName",
new { firstName = model.FirstName, lastName = model.LastName});
}
No need for any tweak, you got a native API:
const toNodes = html =>
new DOMParser().parseFromString(html, 'text/html').body.childNodes[0]
Short answer: No.
Slightly longer answer: There is an old, old workaround where you pass a string that you parse for optional arguments:
int f(int arg1, double arg2, char* name, char *opt);
where opt may include "name=value" pair or something, and which you would call like
n = f(2,3.0,"foo","plot=yes save=no");
Obviously this is only occasionally useful. Generally when you want a single interface to a family of functionality.
You still find this approach in particle physics codes that are written by professional programs in c++ (like for instance ROOT). It's main advantage is that it may be extended almost indefinitely while maintaining back compatibility.
To do structural modification on the source of the stream, as Pshemo mentioned in his answer, one solution is to create a new instance of a Collection
like ArrayList
with the items inside your primary list; iterate over the new list, and do the operations on the primary list.
new ArrayList<>(users).stream().forEach(u -> users.remove(u));
I was also facing same issue but able to fix it by putting async: true. I know it is by default true but it works when I write it explicitly
$.ajax({
async: true, // this will solve the problem
type: "POST",
url: "/Page/Method",
contentType: "application/json",
data: JSON.stringify({ ParameterName: paramValue }),
});
Amazon EC2 cannot offer Mac OS X EC2 instances due to Apple's tight licensing to only allow it to legally run on Apple hardware and the current EC2 infrastructure relies upon virtualized hardware.
Apple Mac image on Amazon EC2?
Can you run OS X on an Amazon EC2 instance?
There are other companies that do provide Mac OS X hosting, presumably on Apple hardware. One example is Go Daddy:
Go Daddy Product Catalog (see Mac® Powered Cloud Servers under Web Hosting)
To find more, search for "Mac OS X hosting" and you'll find more options.
New is always used to allocate dynamic memory, which then has to be freed.
By doing the first option, that memory will be automagically freed when scope is lost.
Point p1 = Point(0,0); //This is if you want to be safe and don't want to keep the memory outside this function.
Point* p2 = new Point(0, 0); //This must be freed manually. with...
delete p2;
For me, as I was storing many values within a single print call, the solution was to create a separate variable to store the data as a tuple and then call the print function.
x = (f"{id}", f"{name}", f"{age}")
print(x)
Most of the methods works, but the excel process always stay until close the appliation.
When kill excel process once it can't be executed once again in the same thread - don't know why.
To start a program and then close command prompt without waiting for program to exit:
start /d "path" file.exe
Right click on the web page you want to use as the default page and choose "Set as Start Page" whenever you run the web application from Visual Studio, it will open the selected page.
There have multiple solusions to convert list to a collection
Solution 1
List<Contact> CONTACTS = new ArrayList<String>();
// fill CONTACTS
Collection<Contact> c = CONTACTS;
Solution 2
private static final Collection<String> c = new ArrayList<String>(
Arrays.asList("a", "b", "c"));
Solution 3
private static final Collection<Contact> = new ArrayList<Contact>(
Arrays.asList(new Contact("text1", "name1")
new Contact("text2", "name2")));
Solution 4
List<? extends Contact> col = new ArrayList<Contact>(CONTACTS);
You can use the following code for converting into a one-hot vector:
let x is the normal class vector having a single column with classes 0 to some number:
import numpy as np
np.eye(x.max()+1)[x]
if 0 is not a class; then remove +1.
LinearLayout : A layout that organizes its children into a single horizontal or vertical row. It creates a scrollbar if the length of the window exceeds the length of the screen.It means you can align views one by one (vertically/ horizontally).
RelativeLayout : This enables you to specify the location of child objects relative to each other (child A to the left of child B) or to the parent (aligned to the top of the parent). It is based on relation of views from its parents and other views.
WebView : to load html, static or dynamic pages.
For more information refer this link:http://developer.android.com/guide/topics/ui/layout-objects.html
button.titleLabel.font = <whatever font you want>
For the people wondering why their text isn't showing up, if you do
button.titleLabel.text = @"something";
It won't show up, you need to do:
[button setTitle:@"My title" forState:UIControlStateNormal]; //or whatever you want the control state to be
The Boris Guéry answer's at this post, may help you: Doctrine 2, query inside entities
$idsToFilter = array(1,2,3,4);
$member->getComments()->filter(
function($entry) use ($idsToFilter) {
return in_array($entry->getId(), $idsToFilter);
}
);
This looks to be the fastest way by far...
var el;
while (el = arr.shift()) {
el *= 2;
}
Take into account that this will consume the array, eating it, and leaving nothing left...
At last! I got the answer to this, the size to edit it in photoshop is: 379x674
You are welcome
You can use this lib called cssobj
var result = cssobj({'#my-window': {
position: 'fixed',
zIndex: '102',
display:'none',
top:'50%',
left:'50%'
}})
Any time you can update your rules like this:
result.obj['#my-window'].display = 'block'
result.update()
Then you got the rule changed. jQuery is not the lib doing this.
For only horizontal lines
ax = plt.axes()
ax.yaxis.grid() # horizontal lines
This worked
In swift 4 and autoLayout, you can use sectionInset like this:
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.itemSize = CGSize(width: (view.frame.width-40)/2, height: (view.frame.width40)/2) // item size
layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10) // here you can add space to 4 side of item
collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) // set layout to item
collectionView?.register(ProductCategoryCell.self, forCellWithReuseIdentifier: cellIdentifier) // registerCell
collectionView?.backgroundColor = .white // background color of UICollectionView
view.addSubview(collectionView!) // add UICollectionView to view
@RD /S /Q "D:\PHP_Projects\testproject\Release\testfolder"
Removes (deletes) a directory.
RMDIR [/S] [/Q] [drive:]path RD [/S] [/Q] [drive:]path /S Removes all directories and files in the specified directory in addition to the directory itself. Used to remove a directory tree. /Q Quiet mode, do not ask if ok to remove a directory tree with /S
Kotlin code that works for me:
private fun takePhotoFromCamera() {
val intent = Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent, PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA)
}
And get Result :
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA) {
if (resultCode == Activity.RESULT_OK) {
val photo: Bitmap? = MediaStore.Images.Media.getBitmap(this.contentResolver, Uri.parse( data!!.dataString) )
// Do something here : set image to an ImageView or save it ..
imgV_pic.imageBitmap = photo
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.i(TAG, "Camera , RESULT_CANCELED ")
}
}
}
and don't forget to declare request code:
companion object {
const val PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA = 300
}
A simplistic approach:
[(a[i],a[i+1]) for i in range(0,len(a),2)]
this is useful if your array is a and you want to iterate on it by pairs. To iterate on triplets or more just change the "range" step command, for example:
[(a[i],a[i+1],a[i+2]) for i in range(0,len(a),3)]
(you have to deal with excess values if your array length and the step do not fit)
The java standard answer is often:
For python27 1?Install numpy + mkl(download link:http://www.lfd.uci.edu/~gohlke/pythonlibs/) 2?install scipy (the same site) OK!
Here is my suggestion - it's quite simple as that:
[^-]*
I would recommend 422. It's not part of the main HTTP spec, but it is defined by a public standard (WebDAV) and it should be treated by browsers the same as any other 4xx status code.
From RFC 4918:
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
Omit the parenthesis:
ALTER TABLE User
ADD CONSTRAINT userProperties
FOREIGN KEY(properties)
REFERENCES Properties(ID)
I simply added security.ignored=/**
in the application.properties
,and that did the charm.
RFC2322 states that the subject header "has no length restriction"
but to produce long headers but you need to split it across multiple lines, a process called "folding".
subject is defined as "unstructured" in RFC 5322
here's some quotes ([...] indicate stuff i omitted)
3.6.5. Informational Fields
The informational fields are all optional. The "Subject:" and
"Comments:" fields are unstructured fields as defined in section
2.2.1, [...]
2.2.1. Unstructured Header Field Bodies
Some field bodies in this specification are defined simply as
"unstructured" (which is specified in section 3.2.5 as any printable
US-ASCII characters plus white space characters) with no further
restrictions. These are referred to as unstructured field bodies.
Semantically, unstructured field bodies are simply to be treated as a
single line of characters with no further processing (except for
"folding" and "unfolding" as described in section 2.2.3).
2.2.3 [...] An unfolded header field has no length restriction and
therefore may be indeterminately long.
The selected answer posted here solved one problem, but another is that you'll have to change the app pool to use .Net 2.0.
"SharePoint 2010 uses .NET Framework 3.5, not 4.0. The SharePoint 2010 app pools should be configured as .NET Framework 2.0 using the Integrated Pipeline Mode."
Please (change com.android.support:appcompat-v7:28.0.0-alpha3
) or (com.android.support:appcompat-v7:28.0.0-rc02
) to (com.android.support:appcompat-v7:28.0.0-alpha1
) in build.gradle (Module: App).
Next click File -> Invalidate Caches / Restart
Need internet access.
It works for me Windows 10 and in Ubuntu 18.04.1 LTS
To debug any XHR request:
for a GET request:
for a POST request:
function bookmark(title, url) {
if (window.sidebar) {
// Firefox
window.sidebar.addPanel(title, url, '');
}
else if (window.opera && window.print)
{
// Opera
var elem = document.createElement('a');
elem.setAttribute('href', url);
elem.setAttribute('title', title);
elem.setAttribute('rel', 'sidebar');
elem.click(); //this.title=document.title;
}
else if (document.all)
{
// ie
window.external.AddFavorite(url, title);
}
}
I used this & works great in IE, FF, Netscape. Chrome, Opera and safari do not support it!
I think what you are looking for is:
startDate.setDate(startDate.getDate() + 1);
Also, you can have a look at Moment.js
A javascript date library for parsing, validating, manipulating, and formatting dates.
For Swift 3.0 use the following code:
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "bg.png")?.drawAsPattern(in: self.view.bounds)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: image)
You can convert int
into str
using string function:
user = "mohan"
line = str(50)
print(user + "typed" + line + "lines")
There is no :unchecked pseudo class however if you use the :checked pseudo class and the sibling selector you can differentiate between both states. I believe all of the latest browsers support the :checked pseudo class, you can find more info from this resource: http://www.whatstyle.net/articles/18/pretty_form_controls_with_css
Your going to get better browser support with jquery... you can use a click function to detect when the click happens and if its checked or not, then you can add a class or remove a class as necessary...
One of the subtleties in this question involves the "leading delimiter" question: if you are going to have a combined array of tokens and delimiters you have to know whether it starts with a token or a delimiter. You could of course just assume that a leading delim should be discarded but this seems an unjustified assumption. You might also want to know whether you have a trailing delim or not. This sets two boolean flags accordingly.
Written in Groovy but a Java version should be fairly obvious:
String tokenRegex = /[\p{L}\p{N}]+/ // a String in Groovy, Unicode alphanumeric
def finder = phraseForTokenising =~ tokenRegex
// NB in Groovy the variable 'finder' is then of class java.util.regex.Matcher
def finderIt = finder.iterator() // extra method added to Matcher by Groovy magic
int start = 0
boolean leadingDelim, trailingDelim
def combinedTokensAndDelims = [] // create an array in Groovy
while( finderIt.hasNext() )
{
def token = finderIt.next()
int finderStart = finder.start()
String delim = phraseForTokenising[ start .. finderStart - 1 ]
// Groovy: above gets slice of String/array
if( start == 0 ) leadingDelim = finderStart != 0
if( start > 0 || leadingDelim ) combinedTokensAndDelims << delim
combinedTokensAndDelims << token // add element to end of array
start = finder.end()
}
// start == 0 indicates no tokens found
if( start > 0 ) {
// finish by seeing whether there is a trailing delim
trailingDelim = start < phraseForTokenising.length()
if( trailingDelim ) combinedTokensAndDelims << phraseForTokenising[ start .. -1 ]
println( "leading delim? $leadingDelim, trailing delim? $trailingDelim, combined array:\n $combinedTokensAndDelims" )
}
I found that the easiest way is:
In the Main Form Load function:
Icon = LoadIcon("< the file name of that icon file >");
Rather than provide a theoretical definition, which are beautifully summarized here already, I'll give a simple example:
Assume the run time of f(i)
is O(1)
. Below is a code fragment whose asymptotic runtime is T(n)
. It always calls the function f(...)
n
times. Both the lower and the upper bound is n.
for(int i=0; i<n; i++){
f(i);
}
The second code fragment below has the asymptotic runtime of O(n)
. It calls the function f(...)
at most n
times. The upper bound is n, but the lower bound could be O(1)
or O(log(n))
, depending on what happens inside f2(i)
.
for(int i=0; i<n; i++){
if( f2(i) ) break;
f(i);
}
the function Position
in funprog {base} also does the job. It allows you to pass an arbitrary function, and returns the first or last match.
Position(f, x, right = FALSE, nomatch = NA_integer)
I want to share a code where you can upload a folder full of jars. It's useful when a provider doesn't have a public repository and you need to add lots of libraries manually. I've decided to build a .bat instead of call directly to maven because It could be Out of Memory errors. It was prepared for a windows environment but is easy to adapt it to linux OS:
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
public class CreateMavenRepoApp {
private static final String OCB_PLUGIN_FOLDER = "C://your_folder_with_jars";
public static void main(String[] args) throws IOException {
File directory = new File();
//get all the files from a directory
PrintWriter writer = new PrintWriter("update_repo_maven.bat", "UTF-8");
writer.println("rem "+ new Date());
File[] fList = directory.listFiles();
for (File file : fList){
if (file.isFile()){
String absolutePath = file.getAbsolutePath() ;
Manifest m = new JarFile(absolutePath).getManifest();
Attributes attributes = m.getMainAttributes();
String symbolicName = attributes.getValue("Bundle-SymbolicName");
if(symbolicName!=null &&symbolicName.contains("com.yourCompany.yourProject")) {
String[] parts =symbolicName.split("\\.");
String artifactId = parts[parts.length-1];
String groupId = symbolicName.substring(0,symbolicName.length()-artifactId.length()-1);
String version = attributes.getValue("Bundle-Version");
String mavenLine= "call mvn org.apache.maven.plugins:maven-install-plugin:2.5.1:install-file -Dfile="+ absolutePath+" -DgroupId="+ groupId+" -DartifactId="+ artifactId+" -Dversion="+ version+" -Dpackaging=jar ";
writer.println(mavenLine);
}
}
}
writer.close();
}
}
After run this main from any IDE, run the update_repo_maven.bat.
Try using TempData
:
public ActionResult Create(FormCollection collection) {
...
TempData["notice"] = "Successfully registered";
return RedirectToAction("Index");
...
}
Then, in your Index view, or master page, etc., you can do this:
<% if (TempData["notice"] != null) { %>
<p><%= Html.Encode(TempData["notice"]) %></p>
<% } %>
Or, in a Razor view:
@if (TempData["notice"] != null) {
<p>@TempData["notice"]</p>
}
Quote from MSDN (page no longer exists as of 2014, archived copy here):
An action method can store data in the controller's TempDataDictionary object before it calls the controller's RedirectToAction method to invoke the next action. The TempData property value is stored in session state. Any action method that is called after the TempDataDictionary value is set can get values from the object and then process or display them. The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request.
The solution from Robert MacLean with highest number of votes is 99% correct. But the only addition someone might require, as I did, is whenever you need to open up this jQuery dialog, do not forget to append it to parent. Like below:
var dlg = $('#questionPopup').dialog( 'open');
dlg.parent().appendTo($("form:first"));
I solved this by clearing all the plots in the console and then making sure the plot area was large enough to accommodate what I was creating.
This is not very efficient, but will work if you need glob patterns (as in /var/www/*)
for f in $(cat 1.txt) ; do
rm "$f"
done
If you don't have any patterns and are sure your paths in the file do not contain whitespaces or other weird things, you can use xargs like so:
xargs rm < 1.txt
ERROR: flake8 3.7.9 has requirement pycodestyle<2.6.0,>=2.5.0, but you'll have pycodestyle 2.3.1 which is incompatible.
ERROR: nuscenes-devkit 1.0.8 has requirement motmetrics<=1.1.3, but you'll have motmetrics 1.2.0 which is incompatible.
Installing collected packages: descartes, future, torch, cachetools, torchvision, flake8-import-order, xmltodict, entrypoints, flake8, motmetrics, nuscenes-devkit
Attempting uninstall: torch
Found existing installation: torch 1.0.0
Uninstalling torch-1.0.0:
Successfully uninstalled torch-1.0.0
Attempting uninstall: torchvision
Found existing installation: torchvision 0.2.1
Uninstalling torchvision-0.2.1:
Successfully uninstalled torchvision-0.2.1
Attempting uninstall: entrypoints
Found existing installation: entrypoints 0.2.3
ERROR: Cannot uninstall 'entrypoints'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.
Then I type:
conda uninstall entrypoints
pip install --upgrade pycodestyle
pip install nuscenes-devkit
Done!
With CSS positioning, you can place an element exactly where you want it on your page.
When you are going to use CSS positioning, the first thing you need to do is use the CSS property position to tell the browser if you're going to use absolute or relative positioning.
Both Positions are having different features. In CSS Once you set Position then you can able to use top, right, bottom, left attributes.
Absolute Position
An absolute position element is positioned relative to the first parent element that has a position other than static.
Relative Position
A relative positioned element is positioned relative to its normal position.
To position an element relatively, the property position is set as relative. The difference between absolute and relative positioning is how the position is being calculated.
Summary: If you only want to create a few columns, use df[['new_col1','new_col2']] = df[['data1','data2']].apply( function_of_your_choosing(x), axis=1)
For this solution, the number of new columns you are creating must be equal to the number columns you use as input to the .apply() function. If you want to do something else, have a look at the other answers.
Details Let's say you have two-column dataframe. The first column is a person's height when they are 10; the second is said person's height when they are 20.
Suppose you need to calculate both the mean of each person's heights and sum of each person's heights. That's two values per each row.
You could do this via the following, soon-to-be-applied function:
def mean_and_sum(x):
"""
Calculates the mean and sum of two heights.
Parameters:
:x -- the values in the row this function is applied to. Could also work on a list or a tuple.
"""
sum=x[0]+x[1]
mean=sum/2
return [mean,sum]
You might use this function like so:
df[['height_at_age_10','height_at_age_20']].apply(mean_and_sum(x),axis=1)
(To be clear: this apply function takes in the values from each row in the subsetted dataframe and returns a list.)
However, if you do this:
df['Mean_&_Sum'] = df[['height_at_age_10','height_at_age_20']].apply(mean_and_sum(x),axis=1)
you'll create 1 new column that contains the [mean,sum] lists, which you'd presumably want to avoid, because that would require another Lambda/Apply.
Instead, you want to break out each value into its own column. To do this, you can create two columns at once:
df[['Mean','Sum']] = df[['height_at_age_10','height_at_age_20']]
.apply(mean_and_sum(x),axis=1)
You can use :
const intersection = array1.filter(element => array2.includes(element));
So here's what I found out.
Flush would not work under Apache's mod_gzip or Nginx's gzip because, logically, it is gzipping the content, and to do that it must buffer content to gzip it. Any sort of web server gzipping would affect this. In short, at the server side we need to disable gzip and decrease the fastcgi buffer size. So:
In php.ini:
output_buffering = Off
zlib.output_compression = Off
In nginx.conf:
gzip off;
proxy_buffering off;
Also have these lines at hand, especially if you don't have access to php.ini:
@ini_set('zlib.output_compression',0);
@ini_set('implicit_flush',1);
@ob_end_clean();
set_time_limit(0);
Last, if you have it, comment the code bellow:
ob_start('ob_gzhandler');
ob_flush();
PHP test code:
ob_implicit_flush(1);
for ($i=0; $i<10; $i++) {
echo $i;
// this is to make the buffer achieve the minimum size in order to flush data
echo str_repeat(' ',1024*64);
sleep(1);
}
Option 1 :
org.apache.commons.lang3.LocaleUtils.toLocale("en_US")
Option 2 :
Locale.forLanguageTag("en-US")
Please note Option 1 is "underscore" between language and country , and Option 2 is "dash".
JSON:-
For POST request using json object it can be configured by selecting
Body -> raw -> application/json
Form Data(For Normal content POST):- multipart/form-data
For normal POST request (using multipart/form-data) it can be configured by selecting
Body -> form-data
As amaud576875 said, the \r
escape sequence signifies a carriage-return, similar to pressing the Enter key. However, I'm not sure how you get "o world"; you should (and I do) get "my first hello world" and then a new line. Depending on what operating system you're using (I'm using Mac) you might want to use a \n
instead of a \r
.
Let's assume you want to use core Java, w/o any strategic frameworks. If you can guarantee, that field name of an entity will be equal to the column in database, you can use Reflection API (otherwise create annotation and define mapping name there)
By FieldName
/**
Class<T> clazz - a list of object types you want to be fetched
ResultSet resultSet - pointer to your retrieved results
*/
List<Field> fields = Arrays.asList(clazz.getDeclaredFields());
for(Field field: fields) {
field.setAccessible(true);
}
List<T> list = new ArrayList<>();
while(resultSet.next()) {
T dto = clazz.getConstructor().newInstance();
for(Field field: fields) {
String name = field.getName();
try{
String value = resultSet.getString(name);
field.set(dto, field.getType().getConstructor(String.class).newInstance(value));
} catch (Exception e) {
e.printStackTrace();
}
}
list.add(dto);
}
By annotation
@Retention(RetentionPolicy.RUNTIME)
public @interface Col {
String name();
}
DTO:
class SomeClass {
@Col(name = "column_in_db_name")
private String columnInDbName;
public SomeClass() {}
// ..
}
Same, but
while(resultSet.next()) {
T dto = clazz.getConstructor().newInstance();
for(Field field: fields) {
Col col = field.getAnnotation(Col.class);
if(col!=null) {
String name = col.name();
try{
String value = resultSet.getString(name);
field.set(dto, field.getType().getConstructor(String.class).newInstance(value));
} catch (Exception e) {
e.printStackTrace();
}
}
}
list.add(dto);
}
Thoughts
In fact, iterating over all Fields might seem ineffective, so I would store mapping somewhere, rather than iterating each time. However, if our T
is a DTO with only purpose of transferring data and won't contain loads of unnecessary fields, that's ok. In the end it's much better than using boilerplate methods all the way.
Hope this helps someone.
<input id="name" data-upper type="text"/>
<input id="middle" data-upper type="text"/>
<input id="sur" data-upper type="text"/>
Upper the text on dynamically created element which has attribute upper and when keyup action happens
$(document.body).on('keyup', '[data-upper]', function toUpper() {
this.value = this.value.toUpperCase();
});
There is equally formatDate
const format = 'dd/MM/yyyy';
const myDate = '2019-06-29';
const locale = 'en-US';
const formattedDate = formatDate(myDate, format, locale);
According to the API it takes as param either a date string, a Date object, or a timestamp.
Gotcha: Out of the box, only en-US
is supported.
If you need to add another locale, you need to add it and register it in you app.module, for example for Spanish:
import { registerLocaleData } from '@angular/common';
import localeES from "@angular/common/locales/es";
registerLocaleData(localeES, "es");
Don't forget to add corresponding import:
import { formatDate } from "@angular/common";
You need to define a style in your Word document and use that for source code. I usually have a style called "Code" which has a monospaced font in a small point size, fixed size tabs, single line spacing, no before/after paragraph spacing, etc. You only need to define this style once and then reuse it. You paste in your source code and apply the "Code" style to it.
Note that some editors (e.g. Xcode on the Mac) add RTF as well as text to the clipboard when copying/pasting between applications - Word recognises RTF and helpfully retains the formatting, syntax colouring, etc.
Source code in Xcode:
Copied and pasted to Word:
(Note: it's a good idea to disable spell-checking in your "Code" style in Word.)
You can't use findViewById()
on menu items in onCreate()
because the menu layout isn't inflated yet. You could create a global Menu variable and initialize it in the onCreateOptionsMenu()
and then use it in your onClick()
.
private Menu menu;
In your onCreateOptionsMenu()
this.menu = menu;
In your button's onClick()
method
menu.getItem(0).setIcon(ContextCompat.getDrawable(this, R.drawable.ic_launcher));
When require is given the path of a folder, it'll look for an index.js file in that folder; if there is one, it uses that, and if there isn't, it fails.
It would probably make most sense (if you have control over the folder) to create an index.js file and then assign all the "modules" and then simply require that.
yourfile.js
var routes = require("./routes");
index.js
exports.something = require("./routes/something.js");
exports.others = require("./routes/others.js");
If you don't know the filenames you should write some kind of loader.
Working example of a loader:
var normalizedPath = require("path").join(__dirname, "routes");
require("fs").readdirSync(normalizedPath).forEach(function(file) {
require("./routes/" + file);
});
// Continue application logic here
Unless this is a one-off data conversion, chances are you will benefit from using a calendar table.
Having such a table makes it really easy to filter or aggregate data for non-standard periods in addition to regular ISO weeks. Weeks usually behave a bit differently across companies and the departments within them. As soon as you leave "ISO-land" the built-in date functions can't help you.
create table calender(
day date not null -- Truncated date
,iso_year_week number(6) not null -- ISO Year week (IYYYIW)
,retail_week number(6) not null -- Monday to Sunday (YYYYWW)
,purchase_week number(6) not null -- Sunday to Saturday (YYYYWW)
,primary key(day)
);
You can either create additional tables for "purchase_weeks" or "retail_weeks", or simply aggregate on the fly:
select a.colA
,a.colB
,b.first_day
,b.last_day
from your_table_with_weeks a
join (select iso_year_week
,min(day) as first_day
,max(day) as last_day
from calendar
group
by iso_year_week
) b on(a.iso_year_week = b.iso_year_week)
If you process a large number of records, aggregating on the fly won't make a noticable difference, but if you are performing single-row you would benefit from creating tables for the weeks as well.
Using calendar tables provides a subtle performance benefit in that the optimizer can provide better estimates on static columns than on nested add_months(to_date(to_char()))
function calls.
"In computer science, garbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory used by objects that will never be accessed or mutated again by the application."
All JavaScript engines have their own garbage collectors, and they may differ. Most time you do not have to deal with them because they just do what they supposed to do.
Writing better code mostly depends of how good do you know programming principles, language and particular implementation.
Another example:
for key, igroup in itertools.groupby(xrange(12), lambda x: x // 5):
print key, list(igroup)
results in
0 [0, 1, 2, 3, 4]
1 [5, 6, 7, 8, 9]
2 [10, 11]
Note that igroup is an iterator (a sub-iterator as the documentation calls it).
This is useful for chunking a generator:
def chunker(items, chunk_size):
'''Group items in chunks of chunk_size'''
for _key, group in itertools.groupby(enumerate(items), lambda x: x[0] // chunk_size):
yield (g[1] for g in group)
with open('file.txt') as fobj:
for chunk in chunker(fobj):
process(chunk)
Another example of groupby - when the keys are not sorted. In the following example, items in xx are grouped by values in yy. In this case, one set of zeros is output first, followed by a set of ones, followed again by a set of zeros.
xx = range(10)
yy = [0, 0, 0, 1, 1, 1, 0, 0, 0, 0]
for group in itertools.groupby(iter(xx), lambda x: yy[x]):
print group[0], list(group[1])
Produces:
0 [0, 1, 2]
1 [3, 4, 5]
0 [6, 7, 8, 9]
As M.L. pointed out, JsonSerializer works here. However, if you are formatting database entities, use java.sql.Date to register you serializer. Deserializer is not needed.
Gson gson = new GsonBuilder()
.registerTypeAdapter(java.sql.Date.class, ser).create();
This bug report might be related: http://code.google.com/p/google-gson/issues/detail?id=230. I use version 1.7.2 though.
I've tried using Flexelint (the unix version of PC-Lint) and had somewhat mixed results. This is likely because I'm working on a very large and knotty code base. I recommend carefully examining each file that is reported as unused.
The main worry is false positives. Multiple includes of the same header are reported as an unneeded header. This is bad since Flexelint does not tell you what line the header is included on or where it was included before.
One of the ways automated tools can get this wrong:
In A.hpp:
class A {
// ...
};
In B.hpp:
#include "A.hpp
class B {
public:
A foo;
};
In C.cpp:
#include "C.hpp"
#include "B.hpp" // <-- Unneeded, but lint reports it as needed
#include "A.hpp" // <-- Needed, but lint reports it as unneeded
If you blindly follow the messages from Flexelint you'll muck up your #include dependencies. There are more pathological cases, but basically you're going to need to inspect the headers yourself for best results.
I highly recommend this article on Physical Structure and C++ from the blog Games from within. They recommend a comprehensive approach to cleaning up the #include mess:
Guidelines
Here’s a distilled set of guidelines from Lakos’ book that minimize the number of physical dependencies between files. I’ve been using them for years and I’ve always been really happy with the results.
- Every cpp file includes its own header file first. [snip]
- A header file must include all the header files necessary to parse it. [snip]
- A header file should have the bare minimum number of header files necessary to parse it. [snip]
The problem is that skew
isn't being subsetted in colour=factor(skew)
, so it's the wrong length. Since subset(skew, product == 'p1')
is the same as subset(skew, product == 'p3')
, in this case it doesn't matter which subset is used. So you can solve your problem with:
p1 <- ggplot(df, aes(x=subset(price, product=='p1'),
y=subset(price, product=='p3'),
colour=factor(subset(skew, product == 'p1')))) +
geom_point(size=2, shape=19)
Note that most R users would write this as the more concise:
p1 <- ggplot(df, aes(x=price[product=='p1'],
y=price[product=='p3'],
colour=factor(skew[product == 'p1']))) +
geom_point(size=2, shape=19)
If it's a server socket, you should call listen()
on your socket, and then getsockname()
to find the port number on which it is listening:
struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
perror("getsockname");
else
printf("port number %d\n", ntohs(sin.sin_port));
As for the IP address, if you use INADDR_ANY
then the server socket can accept connections to any of the machine's IP addresses and the server socket itself does not have a specific IP address. For example if your machine has two IP addresses then you might get two incoming connections on this server socket, each with a different local IP address. You can use getsockname()
on the socket for a specific connection (which you get from accept()
) in order to find out which local IP address is being used on that connection.
I don't know about targeting iOS as a whole, but to target iOS Safari specifically:
@supports (-webkit-touch-callout: none) {
/* CSS specific to iOS devices */
}
@supports not (-webkit-touch-callout: none) {
/* CSS for other than iOS devices */
}
Apparently as of iOS 13 -webkit-overflow-scrolling
no longer responds to @supports
, but -webkit-touch-callout
still does. Of course that could change in the future...
This might be an alternative solution. Paste the following code into the new module:
Public Function ModDate()
ModDate =
Format(FileDateTime(ThisWorkbook.FullName), "m/d/yy h:n ampm")
End Function
Before saving your module, make sure to save your Excel file as Excel Macro-Enabled Workbook.
Paste the following code into the cell where you want to display the last modification time:
=ModDate()
I'd also like to recommend an alternative to Excel allowing you to add creation and last modification time easily. Feel free to check on RowShare and this article I wrote: https://www.rowshare.com/blog/en/2018/01/10/Displaying-Last-Modification-Time-in-Excel
Each directive's pre-link
function is called whenever a new related element is instantiated.
As seen previously in the compilation order section, pre-link
functions are called parent-then-child, whereas post-link
functions are called child-then-parent
.
The pre-link
function is rarely used, but can be useful in special scenarios; for example, when a child controller registers itself with the parent controller, but the registration has to be in a parent-then-child
fashion (ngModelController
does things this way).
Actually they are the same. LEFT OUTER JOIN
is same as LEFT JOIN
and RIGHT OUTER JOIN
is same as RIGHT JOIN
. It is more informative way to compare from INNER Join
.
See this Wikipedia article for details.
<p>
<img style="float: right; margin: 0px 15px 15px 0px;" src="files/styles/large_hero_desktop_1x/public/headers/Kids%20on%20iPad%20 %202400x880.jpg?itok=PFa-MXyQ" width="100" />
Nunc pulvinar lacus id purus ultrices id sagittis neque convallis. Nunc vel libero orci.
<br style="clear: both;" />
</p>
Since JDK 1.7, the canonical way to have an application be notified of changes to a file is using the WatchService API. The WatchService is event-driven. The official tutorial provides an example:
/*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
import static java.nio.file.LinkOption.*;
import java.nio.file.attribute.*;
import java.io.*;
import java.util.*;
/**
* Example to watch a directory (or tree) for changes to files.
*/
public class WatchDir {
private final WatchService watcher;
private final Map<WatchKey,Path> keys;
private final boolean recursive;
private boolean trace = false;
@SuppressWarnings("unchecked")
static <T> WatchEvent<T> cast(WatchEvent<?> event) {
return (WatchEvent<T>)event;
}
/**
* Register the given directory with the WatchService
*/
private void register(Path dir) throws IOException {
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
if (trace) {
Path prev = keys.get(key);
if (prev == null) {
System.out.format("register: %s\n", dir);
} else {
if (!dir.equals(prev)) {
System.out.format("update: %s -> %s\n", prev, dir);
}
}
}
keys.put(key, dir);
}
/**
* Register the given directory, and all its sub-directories, with the
* WatchService.
*/
private void registerAll(final Path start) throws IOException {
// register directory and sub-directories
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException
{
register(dir);
return FileVisitResult.CONTINUE;
}
});
}
/**
* Creates a WatchService and registers the given directory
*/
WatchDir(Path dir, boolean recursive) throws IOException {
this.watcher = FileSystems.getDefault().newWatchService();
this.keys = new HashMap<WatchKey,Path>();
this.recursive = recursive;
if (recursive) {
System.out.format("Scanning %s ...\n", dir);
registerAll(dir);
System.out.println("Done.");
} else {
register(dir);
}
// enable trace after initial registration
this.trace = true;
}
/**
* Process all events for keys queued to the watcher
*/
void processEvents() {
for (;;) {
// wait for key to be signalled
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}
Path dir = keys.get(key);
if (dir == null) {
System.err.println("WatchKey not recognized!!");
continue;
}
for (WatchEvent<?> event: key.pollEvents()) {
WatchEvent.Kind kind = event.kind();
// TBD - provide example of how OVERFLOW event is handled
if (kind == OVERFLOW) {
continue;
}
// Context for directory entry event is the file name of entry
WatchEvent<Path> ev = cast(event);
Path name = ev.context();
Path child = dir.resolve(name);
// print out event
System.out.format("%s: %s\n", event.kind().name(), child);
// if directory is created, and watching recursively, then
// register it and its sub-directories
if (recursive && (kind == ENTRY_CREATE)) {
try {
if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
registerAll(child);
}
} catch (IOException x) {
// ignore to keep sample readbale
}
}
}
// reset key and remove from set if directory no longer accessible
boolean valid = key.reset();
if (!valid) {
keys.remove(key);
// all directories are inaccessible
if (keys.isEmpty()) {
break;
}
}
}
}
static void usage() {
System.err.println("usage: java WatchDir [-r] dir");
System.exit(-1);
}
public static void main(String[] args) throws IOException {
// parse arguments
if (args.length == 0 || args.length > 2)
usage();
boolean recursive = false;
int dirArg = 0;
if (args[0].equals("-r")) {
if (args.length < 2)
usage();
recursive = true;
dirArg++;
}
// register directory and process its events
Path dir = Paths.get(args[dirArg]);
new WatchDir(dir, recursive).processEvents();
}
}
For individual files, various solutions exist, such as:
Note that Apache VFS uses a polling algorithm, although it may offer greater functionality. Also note that the API does not offer a way to determine whether a file has been closed.
The minimum requirements are based on the Express edition you're attempting to install:
Express for Web (Web sites and HTML5 applications) - Windows 7 SP1 (With IE 10)
Express for Windows (Windows 8 Apps) - Windows 8.1
Express for Windows Desktop (Windows Programs) - Windows 7 SP1 (With IE 10)
Express for Windows Phone (Windows Phone Apps) - Windows 8
It sounds like you're trying to install the "Express 2013 for Windows" edition, which is for developing Windows 8 "Modern UI" apps, or the Windows Phone edition.
The similarly named version that is compatible with Windows 7 SP1 is "Express 2013 for Windows Desktop"
you can use the below command to see the complete characteristics of DB
db2look -d <DB NAme>-u walid -e -o
you can use the below command to see the complete characteristics of Schema
db2look -d <DB NAme> -u walid -z <Schema Name> -e -o
you can use the below command to see the complete characteristics of table
db2look -d <DB NAme> -u walid -z <Schema Name> -t <Table Name>-e -o
you can also visit the below link for more details. https://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=%2Fcom.ibm.db2.udb.admin.doc%2Fdoc%2Fr0002051.htm
Drop the 's' off of the package name.
You want sudo apt-get install build-essential
You may also need to run sudo apt-get update
to make sure that your package index is up to date.
For anyone wondering why this package may be needed as part of another install, it contains the essential tools for building most other packages from source (C/C++ compiler, libc, and make).
npm install font-awesome --save
add ~/ before path
@import "~/font-awesome/scss/font-awesome.scss";
Strings.xml
<string name="my_text"><Data><![CDATA[<b>Your text</b>]]></Data></string>
To set
textView.setText(Html.fromHtml(getString(R.string.activity_completed_text)));
The main difference between Web server and application server is that web server is meant to serve static pages e.g. HTML and CSS, while Application Server is responsible for generating dynamic content by executing server side code e.g. JSP, Servlet or EJB.
Which one should i use?
Once you know the difference between web and application server and web containers, it's easy to figure out when to use them.
You need a web server
like Apache HTTPD if you are serving static web pages. If you have a Java application with just JSP and Servlet to generate dynamic content then you need web containers
like Tomcat or Jetty. While, if you have Java EE application using EJB, distributed transaction, messaging and other fancy features than you need a full fledged application server
like JBoss, WebSphere or Oracle's WebLogic.
Web container is a part of Web Server and the Web Server is a part of Application Server.
Web Server is composed of web container, while Application Server is composed of web container as well as EJB container.
You've not shown how you're creating the string 2016-01-12T23:00:00.000Z
, but I assume via .format()
.
Anyway, .set()
is using your local time zone, but the Z
in the time string indicates zero time, otherwise known as UTC.
https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators
So I assume your local timezone is 23 hours from UTC?
saikumar's answer showed how to load the time in as UTC, but the other option is to use a .format()
call that outputs using your local timezone, rather than UTC.
http://momentjs.com/docs/#/get-set/
http://momentjs.com/docs/#/displaying/format/
Do this steps :-
Go to Run - Edit Configuration -> Application (on the left of the panel ) -> select the scala application that u want to run -> program argument
You can do it via RegEx replacement. Here is an example:
-- Citations Per Year - Cited Publications main query. Includes list of unique associated core project numbers, ordered by core project number.
SELECT ptc.pmid AS pmid, ptc.pmc_id, ptc.pub_title AS pubtitle, ptc.author_list AS authorlist,
ptc.pub_date AS pubdate,
REGEXP_REPLACE( LISTAGG ( ppcc.admin_phs_org_code ||
TO_CHAR(ppcc.serial_num,'FM000000'), ',') WITHIN GROUP (ORDER BY ppcc.admin_phs_org_code ||
TO_CHAR(ppcc.serial_num,'FM000000')),
'(^|,)(.+)(,\2)+', '\1\2')
AS projectNum
FROM publication_total_citations ptc
JOIN proj_paper_citation_counts ppcc
ON ptc.pmid = ppcc.pmid
AND ppcc.citation_year = 2013
JOIN user_appls ua
ON ppcc.admin_phs_org_code = ua.admin_phs_org_code
AND ppcc.serial_num = ua.serial_num
AND ua.login_id = 'EVANSF'
GROUP BY ptc.pmid, ptc.pmc_id, ptc.pub_title, ptc.author_list, ptc.pub_date
ORDER BY pmid;
Also posted here: Oracle - unique Listagg values
An API is ready-made source code library.
In Java for example APIs are a set of related classes and interfaces that come in packages. This picture illustrates the libraries included in the Java Standard Edition API. Packages are denoted by their color.
If you`re not using jQuery then please make sure:
var json_upload = "json_name=" + JSON.stringify({name:"John Rambo", time:"2pm"});
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", "/file.php");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(json_upload);
And for the php receiving end:
$_POST['json_name']
If you're going to use the preprocessor anyway, as per the other answers, then you can make the compiler determine the value of NUM_TYPES
automagically:
#define NUM_TYPES (sizeof types / sizeof types[0])
static int types[] = {
1,
2,
3,
4 };
You can use Phonegap (Cordova) to develop iOS Apps without a Mac, but yout would still need a Mac to submit your application to the App Store. We developed a cloud application which also can publish your app without a Mac https://www.wenz.io/ApplicationLoader. Currently we are in beta and you can use the service for free.
Best regards, Steffen Wenz
(I'm the creator of the site)
The character set is part of the locale, which is determined by the value of NLS_LANG
. As the documentation makes clear this is an operating system variable:
NLS_LANG
is set as an environment variable on UNIX platforms.NLS_LANG
is set in the registry on Windows platforms.
Now we can use ALTER SESSION
to change the values for a couple of locale elements, NLS_LANGUAGE and NLS_TERRITORY. But not, alas, the character set. The reason for this discrepancy is - I think - that the language and territory simply effect how Oracle interprets the stored data, e.g. whether to display a comma or a period when displaying a large number. Wheareas the character set is concerned with how the client application renders the displayed data. This information is picked up by the client application at startup time, and cannot be changed from within.
Use the after
method on the Tk
object:
from tkinter import *
root = Tk()
def task():
print("hello")
root.after(2000, task) # reschedule event in 2 seconds
root.after(2000, task)
root.mainloop()
Here's the declaration and documentation for the after
method:
def after(self, ms, func=None, *args):
"""Call function once after given time.
MS specifies the time in milliseconds. FUNC gives the
function which shall be called. Additional parameters
are given as parameters to the function call. Return
identifier to cancel scheduling with after_cancel."""
JSONArray successObject=new JSONArray();
JSONObject dataObject=new JSONObject();
successObject.put(dataObject.toString());
This works for me.
To read binary ASCII characters with great speed using only your head:
Letters start with leading bits 01. Bit 3 is on (1) for lower case, off (0) for capitals. Scan the following bits 4–8 for the first that is on, and select the starting letter from the same index in this string: “PHDBA” (think P.H.D., Bachelors in Arts). E.g. 1xxxx = P, 01xxx = H, etc. Then convert the remaining bits to an integer value (e.g. 010 = 2), and count that many letters up from your starting letter. E.g. 01001010 => H+2 = J.
In insert()
public void insert(String tableImg, Object object,
ContentValues dataToInsert) {
db.insert(tablename, null, dataToInsert);
}
Hope it helps you.
openssl s_client -connect 127.0.0.1:6379 -state
CONNECTED(00000003)
SSL_connect:before SSL initialization
SSL_connect:SSLv3/TLS write client hello
Building upon your existing Student class, this is how I usually do it, especially if I need more than one comparator.
public class Student implements Comparable<Student> {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return name + ":" + age;
}
@Override
public int compareTo(Student o) {
return Comparators.NAME.compare(this, o);
}
public static class Comparators {
public static Comparator<Student> NAME = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.name.compareTo(o2.name);
}
};
public static Comparator<Student> AGE = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.age - o2.age;
}
};
public static Comparator<Student> NAMEANDAGE = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int i = o1.name.compareTo(o2.name);
if (i == 0) {
i = o1.age - o2.age;
}
return i;
}
};
}
}
Usage:
List<Student> studentList = new LinkedList<>();
Collections.sort(studentList, Student.Comparators.AGE);
EDIT
Since the release of Java 8 the inner class Comparators
may be greatly simplified using lambdas. Java 8 also introduces a new method for the Comparator
object thenComparing
, which removes the need for doing manual checking of each comparator when nesting them. Below is the Java 8 implementation of the Student.Comparators
class with these changes taken into account.
public static class Comparators {
public static final Comparator<Student> NAME = (Student o1, Student o2) -> o1.name.compareTo(o2.name);
public static final Comparator<Student> AGE = (Student o1, Student o2) -> Integer.compare(o1.age, o2.age);
public static final Comparator<Student> NAMEANDAGE = (Student o1, Student o2) -> NAME.thenComparing(AGE).compare(o1, o2);
}
I know this question was asked over 2 years ago but no one has mentioned this yet.
The best method is to use a http header
Adding the meta tag to the head doesn't always work because IE might have determined the mode before it's read. The best way to make sure IE always uses standards mode is to use a custom http header.
Header:
name: X-UA-Compatible
value: IE=edge
For example in a .NET application you could put this in the web.config file.
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="X-UA-Compatible" value="IE=edge" />
</customHeaders>
</httpProtocol>
</system.webServer>