You can also take a look at PDFMiner (or for older versions of Python see PDFMiner and PDFMiner).
A particular feature of interest in PDFMiner is that you can control how it regroups text parts when extracting them. You do this by specifying the space between lines, words, characters, etc. So, maybe by tweaking this you can achieve what you want (that depends of the variability of your documents). PDFMiner can also give you the location of the text in the page, it can extract data by Object ID and other stuff. So dig in PDFMiner and be creative!
But your problem is really not an easy one to solve because, in a PDF, the text is not continuous, but made from a lot of small groups of characters positioned absolutely in the page. The focus of PDF is to keep the layout intact. It's not content oriented but presentation oriented.
Its not that hard to replicate in javascript :-) , though it will only work for width and height the best but you can expand it as per your expectations :-)
function calcShim(element,property,expression){
var calculated = 0;
var freed_expression = expression.replace(/ /gi,'').replace("(","").replace(")","");
// Remove all the ( ) and spaces
// Now find the parts
var parts = freed_expression.split(/[\*+-\/]/gi);
var units = {
'px':function(quantity){
var part = 0;
part = parseFloat(quantity,10);
return part;
},
'%':function(quantity){
var part = 0,
parentQuantity = parseFloat(element.parent().css(property));
part = parentQuantity * ((parseFloat(quantity,10))/100);
return part;
} // you can always add more units here.
}
for( var i = 0; i < parts.length; i++ ){
for( var unit in units ){
if( parts[i].indexOf(unit) != -1 ){
// replace the expression by calculated part.
expression = expression.replace(parts[i],units[unit](parts[i]));
break;
}
}
}
// And now compute it. though eval is evil but in some cases its a good friend.
// Though i wish there was math. calc
element.css(property,eval(expression));
}
If you want to set it to LF as default, you can go to File->Preferences->Settings and under user settings you can paste this line in below your other user settings.
"files.eol": "\n"
For example.
"git.confirmSync": false,
"window.zoomLevel": -1,
"workbench.activityBar.visible": true,
"editor.wordWrap": true,
"workbench.iconTheme": "vscode-icons",
"window.menuBarVisibility": "default",
"vsicons.projectDetection.autoReload": true,
"files.eol": "\n"
I thought I had this configured but it turns out I set the URL in the wrong place. I followed the URL provided in the Google error page and added my URL here. Stupid mistake from my part, but easily done. Hope this helps
The most compatible way of doing this is using tput
to discover the right sequences to send to the terminal:
bold=$(tput bold)
normal=$(tput sgr0)
then you can use the variables $bold
and $normal
to format things:
echo "this is ${bold}bold${normal} but this isn't"
gives
this is bold but this isn't
You can use a cursor and temp table approach so you aren't doing full table scan each time. What this would be doing is populating the temp table with all of your keywords, and then with each string in the @letters XML
, it would remove any records from the temp table. At the end, you only have records in your temp table that have each of your desired strings in it.
declare @letters xml
SET @letters = '<letters>
<letter>a</letter>
<letter>b</letter>
</letters>'
-- SELECTING LETTERS FROM THE XML
SELECT Letters.l.value('.', 'nvarchar(50)') AS letter
FROM @letters.nodes('/letters/letter') AS Letters(l)
-- CREATE A TEMP TABLE WE CAN DELETE FROM IF A RECORD DOESN'T HAVE THE LETTER
CREATE TABLE #TempResults (keywordID int not null, keyWord nvarchar(50) not null)
INSERT INTO #TempResults (keywordID, keyWord)
SELECT employeeID, firstName FROM Employee
-- CREATE A CURSOR, SO WE CAN LOOP THROUGH OUR LETTERS AND REMOVE KEYWORDS THAT DON'T MATCH
DECLARE Cursor_Letters CURSOR READ_ONLY
FOR
SELECT Letters.l.value('.', 'nvarchar(50)') AS letter
FROM @letters.nodes('/letters/letter') AS Letters(l)
DECLARE @letter varchar(50)
OPEN Cursor_Letters
FETCH NEXT FROM Cursor_Letters INTO @letter
WHILE (@@fetch_status <> -1)
BEGIN
IF (@@fetch_status <> -2)
BEGIN
DELETE FROM #TempResults
WHERE keywordID NOT IN
(SELECT keywordID FROM #TempResults WHERE keyWord LIKE '%' + @letter + '%')
END
FETCH NEXT FROM Cursor_Letters INTO @letter
END
CLOSE Cursor_Letters
DEALLOCATE Cursor_Letters
SELECT * FROM #TempResults
DROP Table #TempResults
GO
Define "necessary".
It is necessary if you want the browser to know what the type of the file is. PHP automatically sets the Content-Type
header to text/html
if you don't override it so your browser is treating it as an HTML file that doesn't contain any HTML. If your output contained any HTML you'd see very different outcomes. If you were to send:
<b><i>test</i></b>
a Content-Type: text/html
would output:
test
whereas Content-Type: text/plain
would output:
<b><i>test</i></b>
TLDR Version: If you really are only outputing text then it doesn't really matter, but it IS wrong.
Using the time.h library, try something like this:
long start_time, end_time, elapsed;
start_time = clock();
// Do something
end_time = clock();
elapsed = (end_time - start_time) / CLOCKS_PER_SEC * 1000;
You only have to add group = 1
into the ggplot or geom_line aes().
For line graphs, the data points must be grouped so that it knows which points to connect. In this case, it is simple -- all points should be connected, so group=1. When more variables are used and multiple lines are drawn, the grouping for lines is usually done by variable.
Reference: Cookbook for R, Chapter: Graphs Bar_and_line_graphs_(ggplot2), Line graphs.
Try this:
plot5 <- ggplot(df, aes(year, pollution, group = 1)) +
geom_point() +
geom_line() +
labs(x = "Year", y = "Particulate matter emissions (tons)",
title = "Motor vehicle emissions in Baltimore")
I was tripped up by the fact that our web.config file has multiple system.web sections: it worked when I added < httpRuntime maxRequestLength="1048576" /> to the system.web section that at the configuration level.
In a node.js server console.log
outputs to the terminal window, not to the browser's console window.
How are you running your server? You should see the output directly after you start it.
Here lies your problem:
private void fillTextView (int id, String text) {
TextView tv = (TextView) findViewById(id);
tv.setText(text); // tv is null
}
--> (TextView) findViewById(id); // returns null But from your code, I can't find why this method returns null. Try to track down, what id you give as a parameter and if this view with the specified id exists.
The error message is very clear and even tells you at what method. From the documentation:
public final View findViewById (int id)
Look for a child view with the given id. If this view has the given id, return this view.
Parameters
id The id to search for.
Returns
The view that has the given id in the hierarchy or null
http://developer.android.com/reference/android/view/View.html#findViewById%28int%29
In other words: You have no view with the id you give as a parameter.
I am not sure if this is the case but this problem seems to occur a number of times when migrating wordpress sites or migrating dynamic sites in general. If this is the case make sure the hosting you are migrating to uses the same PHP version your old site uses.
If you are not migrating your site and this is just a problem that has come up try updating to PHP 5. This takes care of some of these problems. Might seem like a silly solution but did the trick for me.
As far as i know there is no built in way of casting strings to booleans,
but if your strings only consist of 'true'
and 'false'
you could shorten your method to the following:
def to_boolean(str)
str == 'true'
end
What I use to get the desired outcome is:
toggle_cell.py
in the same directory as of your notebookfrom IPython.core.display import display, HTML
toggle_code_str = '''
<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Show Sloution"></form>
'''
toggle_code_prepare_str = '''
<script>
function code_toggle() {
if ($('div.cell.code_cell.rendered.selected div.input').css('display')!='none'){
$('div.cell.code_cell.rendered.selected div.input').hide();
} else {
$('div.cell.code_cell.rendered.selected div.input').show();
}
}
</script>
'''
display(HTML(toggle_code_prepare_str + toggle_code_str))
def hide_sloution():
display(HTML(toggle_code_str))
from toggle_cell import toggle_code as hide_sloution
hide_sloution()
add ng-model="$ctrl.formName"
attribute to your form, and then in the controller you can access the form as an object inside your controller by this.formName
In my case, this was because the partition hosting the ibdata1 file was full.
Add this in your module gradle file. Its not there in default project. Then u will surely find the APK in /build/outputs/apk/
buildTypes {
debug {
applicationIdSuffix ".debug"
}
}
You should try. When you clear your Graphics you must choose color. SystemColors.Control is native color of form
Graphics g = pB.CreateGraphics();
g.Clear(SystemColors.Control);
Yes You can either set [disabled]= "true" or if it is an radio button or checkbox then you can simply use disable
For radio button:
<md-radio-button disabled>Select color</md-radio-button>
For dropdown:
<ng-select (selected)="someFunction($event)" [disabled]="true"></ng-select>
Be sure to supply the exact same path as when you set it, i.e.
Setting:
$.cookie('foo','bar', {path: '/'});
Removing:
$.cookie('foo', null, {path: '/'});
Note that
$.cookie('foo', null);
will NOT work, since it is actually not the same cookie.
Hope that helps. The same goes for the other options in the hash
Try
let a = document.createElement('a');
a.href = "data:application/octet-stream,"+encodeURIComponent("My DATA");
a.download = 'abc.txt';
a.click();
_x000D_
If you want to download binary data look here
2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop works (reason: sandbox security restrictions) - but JSFiddle version works - here
n_values = data.income.value_counts()
First unique value count
n_at_most_50k = n_values[0]
Second unique value count
n_greater_50k = n_values[1]
n_values
Output:
<=50K 34014
>50K 11208
Name: income, dtype: int64
Output:
n_greater_50k,n_at_most_50k:-
(11208, 34014)
In addition to Oleiade, see the spec on zero values:
When memory is allocated to store a value, either through a declaration or a call of make or new, and no explicit initialization is provided, the memory is given a default initialization. Each element of such a value is set to the zero value for its type: false for booleans, 0 for integers, 0.0 for floats, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps. This initialization is done recursively, so for instance each element of an array of structs will have its fields zeroed if no value is specified.
As you can see, nil
is not the zero value for every type but only for pointers, functions, interfaces, slices, channels and maps. This is the reason why config == nil
is an error and
&config == nil
is not.
To check whether your struct is uninitialized you'd have to check every member for its
respective zero value (e.g. host == ""
, port == 0
, etc.) or have a private field which
is set by an internal initialization method. Example:
type Config struct {
Host string
Port float64
setup bool
}
func NewConfig(host string, port float64) *Config {
return &Config{host, port, true}
}
func (c *Config) Initialized() bool { return c != nil && c.setup }
Correct Answer here
Create class with name MyApp like below:
public class MyApp implements Application.ActivityLifecycleCallbacks, ComponentCallbacks2 {
private Context context;
public void setContext(Context context)
{
this.context = context;
}
private boolean isInBackground = false;
@Override
public void onTrimMemory(final int level) {
if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
isInBackground = true;
Log.d("status = ","we are out");
}
}
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
if(isInBackground){
isInBackground = false;
Log.d("status = ","we are in");
}
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
@Override
public void onConfigurationChanged(Configuration configuration) {
}
@Override
public void onLowMemory() {
}
}
Then, everywhere you want (better first activity launched in app), add the code below:
MyApp myApp = new MyApp();
registerComponentCallbacks(myApp);
getApplication().registerActivityLifecycleCallbacks(myApp);
Done! Now when the app is in the background, we get log status : we are out
and when we go in app, we get log status : we are out
To prevent the browser validation message from appearing in your document, with jQuery:
$('input, select, textarea').on("invalid", function(e) {
e.preventDefault();
});
For enable PHP Extension intl , follow the Steps..
kindly remove the starting semicolon ( ; )
Like :
;extension=php_intl.dll
to
extension=php_intl.dll
Save the xampp/php/php.ini file.
Hope its work..Cheers..
Oracle 11G Express Edition is now available to install on 64-bit versions of Windows.
The whole point of using Maps is direct access. If you know for sure that the value in a map will never be Groovy-false
, then you can do this:
def mymap = [name:"Gromit", likes:"cheese", id:1234]
def key = "likes"
if(mymap[key]) {
println mymap[key]
}
However, if the value could potentially be Groovy-false
, you should use:
if(mymap.containsKey(key)) {
println mymap[key]
}
The easiest solution, though, if you know the value isn't going to be Groovy-false
(or you can ignore that), and want a default value, is like this:
def value = mymap[key] ?: "default"
All three of these solutions are significantly faster than your examples, because they don't scan the entire map for keys. They take advantage of the HashMap
(or LinkedHashMap
) design that makes direct key access nearly instantaneous.
please use setInterval like below:
setInterval(()=>{this.checkOrder()},2000);
I came up with a different solution. The idea is to fill the drawable first with the color that you like the line to be and then fill the whole area again with the background color while using left or right padding. Obviously this only works for a vertical line in the far left or right of your drawable.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@color/divider_color" />
<item android:left="6dp" android:drawable="@color/background_color" />
</layer-list>
For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:
"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets>
<sheet name="MySheet1" sheetId="1" r:id="rId1" />
<sheet name="MySheet2" sheetId="2" r:id="rId2" />
</sheets>
</workbook>
The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" ?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData>
<row r="1">
<c r="A1">
<v>100</v>
</c>
</row>
</sheetData>
</worksheet>
"
Detection of cell encodings:
one way i have found:
try to insert this field into your generated form code:
<input type='hidden' name='rm' value='2'>
rm means return method;
2 means (post)
Than after user purchases and returns to your site url, then that url gets the POST parameters as well
p.s. if using php, try to insert var_dump($_POST);
in your return url(script),then make a test purchase and when you return back to your site you will see what variables are got on your url.
If you are generating a heap of commands to be run, then call that script from a terminal, you can try the following.
sftp login@host < /path/to/command/list
You will then be asked to enter your password (as per normal) however all the commands in the script run after that.
This is clearly not a completely automated option that can be used in a cron
job, but it can be used from a terminal.
When you are creating an object of intent, you can take advantage of following two methods for passing objects between two activities.
You can have your class implement either Parcelable or Serializable. Then you can pass around your custom classes across activities. I have found this very useful.
Here is a small snippet of code I am using
CustomListing currentListing = new CustomListing();
Intent i = new Intent();
Bundle b = new Bundle();
b.putParcelable(Constants.CUSTOM_LISTING, currentListing);
i.putExtras(b);
i.setClass(this, SearchDetailsActivity.class);
startActivity(i);
And in newly started activity code will be something like this...
Bundle b = this.getIntent().getExtras();
if (b != null)
mCurrentListing = b.getParcelable(Constants.CUSTOM_LISTING);
you can also do a hard code like this, where you are checking each and every case possible, it's easy to understand for beginners
SELECT DISTINCT CITY
FROM STATION
WHERE CITY LIKE 'A%A' OR CITY LIKE 'E%E' OR CITY LIKE 'I%I' OR CITY LIKE 'O%O' OR
CITY LIKE 'U%U' OR CITY LIKE 'A%E' OR CITY LIKE 'A%I' OR CITY LIKE 'A%O' OR
CITY LIKE 'A%U' OR CITY LIKE 'E%A' OR CITY LIKE 'E%I' OR CITY LIKE 'E%O' OR
CITY LIKE 'E%U' OR CITY LIKE 'I%A' OR CITY LIKE 'I%E' OR CITY LIKE 'I%O' OR
CITY LIKE 'I%U' OR CITY LIKE 'O%A' OR CITY LIKE 'O%E' OR CITY LIKE 'O%I' OR
CITY LIKE 'O%U' OR CITY LIKE 'U%A' OR CITY LIKE 'U%E' OR CITY LIKE 'U%I' OR
CITY LIKE 'U%O'
You can delete all breakpoints using
del <start_breakpoint_num> - <end_breakpoint_num>
To view the start_breakpoint_num and end_breakpoint_num use:
info break
You don't have jdk1.7.0_17 in your PATH - check again. There is only JRE which may not contain 'javac' compiler.
Besides it is best to set JAVA_HOME variable, and then include it in PATH.
I think I found it. All you have to do is type in "`n" (WITH THE QUOTATION MARKS!)
Thanks!
Use the dos2unix command in linux to convert the saved file. example :
dos2unix file_name
It is late for this question. Here is my 2 cents. I made a rake task for stopping the server when I don't have access to it. I only tested on Mac though.
With this you can simply add it to your project then run the rake command.
Here you go:
Gist link: -latest version will be here. https://gist.github.com/houmanka/289184ca5d8d92de0499#file-server-rake
Some code in here:
# Make a file under: `project_root/lib/tasks/server.rake`
# Then paste the following code
namespace :server do
desc "Stop the running server by killing the PID"
task :kill do
STDOUT.puts "Enter port number: "
post_number = STDIN.gets.strip
system "pid=$(lsof -i:#{post_number.to_i} -t); kill -TERM $pid || kill -KILL $pid"
end
end
# Then to use it in the terminal: `rake server:kill`
I suggest use the common way of import.
First I will explain the way it called "relative import" maybe this way cause of some error
Second I will explain the common way of import.
FIRST:
In go version >= 1.12 there is some new tips about import file and somethings changed.
1- You should put your file in another folder for example I create a file in "model" folder and the file's name is "example.go"
2- You have to use uppercase when you want to import a file!
3- Use Uppercase for variables, structures and functions that you want to import in another files
Notice: There is no way to import the main.go in another file.
file directory is:
root
|_____main.go
|_____model
|_____example.go
this is a example.go:
package model
import (
"time"
)
var StartTime = time.Now()
and this is main.go you should use uppercase when you want to import a file. "Mod" started with uppercase
package main
import (
Mod "./model"
"fmt"
)
func main() {
fmt.Println(Mod.StartTime)
}
NOTE!!!
NOTE: I don't recommend this this type of import!
SECOND:
(normal import)
the better way import file is:
your structure should be like this:
root
|_____github.com
|_________Your-account-name-in-github
| |__________Your-project-name
| |________main.go
| |________handlers
| |________models
|
|_________gorilla
|__________sessions
and this is a example:
package main
import (
"github.com/gorilla/sessions"
)
func main(){
//you can use sessions here
}
so you can import "github.com/gorilla/sessions" in every where that you want...just import it.
Always use :::
. There are two reasons: efficiency and type safety.
Efficiency
x ::: y ::: z
is faster than x ++ y ++ z
, because :::
is right associative. x ::: y ::: z
is parsed as x ::: (y ::: z)
, which is algorithmically faster than (x ::: y) ::: z
(the latter requires O(|x|) more steps).
Type safety
With :::
you can only concatenate two List
s. With ++
you can append any collection to List
, which is terrible:
scala> List(1, 2, 3) ++ "ab"
res0: List[AnyVal] = List(1, 2, 3, a, b)
++
is also easy to mix up with +
:
scala> List(1, 2, 3) + "ab"
res1: String = List(1, 2, 3)ab
this was happening for me for a different reason altogether.
net::ERR_INCOMPLETE_CHUNKED_ENCODING 200
when i inspect the page and go to newtork tab, i see that the vendor.js page has failed to load. Upon checking it seems that the size of the js file is big ~ 6.5 mb.Thats when i realised that i needed to compress the js. I checked that I was using ng build
command to build. Instead when i used ng build --prod --aot --vendor-chunk --common-chunk --delete-output-path --buildOptimizer
it worked for me.see https://github.com/angular/angular-cli/issues/9016
Tested in Kafka 0.8.2, for the quick-start example: First, Add one line to server.properties file under config folder:
delete.topic.enable=true
then, you can run this command:
bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic test
null
is a special value meaning "no value". null
is a special object because typeof null
returns 'object'.
On the other hand, undefined
means that the variable has not been declared, or has not been given a value.
Separate the increments with a comma too.
for(int a = 0, b = 1; a<cards.length-1; b=a+1, a++)
Here is another answer. No extra packages required.
datetime.date(year + int(month/12), month%12+1, 1)-datetime.timedelta(days=1)
Get the first day of the next month and subtract a day from it.
You can try use this function to find any object in nested nested array of arrays of kings.
Example
function findTByKeyValue (element, target){
var found = true;
for(var key in target) {
if (!element.hasOwnProperty(key) || element[key] !== target[key]) {
found = false;
break;
}
}
if(found) {
return element;
}
if(typeof(element) !== "object") {
return false;
}
for(var index in element) {
var result = findTByKeyValue(element[index],target);
if(result) {
return result;
}
}
};
findTByKeyValue(problems,{"name":"somethingElse","strength":"500 mg"}) =====> result equal to object associatedDrug#2
I know it is not Dictionary<TKey, TValue>
class, however you can avoid KeyNotFoundException
while incrementing a value like:
dictionary[key]++; // throws `KeyNotFoundException` if there is no such key
by using ConcurrentDictionary<TKey, TValue> and its really nice method AddOrUpdate()..
Let me show an example:
var str = "Hellooo!!!";
var characters = new ConcurrentDictionary<char, int>();
foreach (var ch in str)
characters.AddOrUpdate(ch, 1, (k, v) => v + 1);
Simple. In the print, do:
print(foobar.__dict__)
as long as the constructor is
__init__
I added this and it worked fine for me.
web.api
config.EnableCors();
Then you will call the model using cors:
In a controller you will add at the top for global scope or on each class. It's up to you.
[EnableCorsAttribute("http://localhost:51003/", "*", "*")]
Also, when your pushing this data to Angular it wants to see the .cshtml file being called as well, or it will push the data but not populate your view.
(function () {
"use strict";
angular.module('common.services',
['ngResource'])
.constant('appSettings',
{
serverPath: "http://localhost:51003/About"
});
}());
//Replace URL with the appropriate path from production server.
I hope this helps anyone out, it took me a while to understand Entity Framework, and why CORS is so useful.
If you are using Java 8 and you want the last segment in a file path you can do.
Path path = Paths.get("example/path/to/file");
String lastSegment = path.getFileName().toString();
If you have a url such as http://base_path/some_segment/id
you can do.
final Path urlPath = Paths.get("http://base_path/some_segment/id");
final Path lastSegment = urlPath.getName(urlPath.getNameCount() - 1);
The answer to your problem is easy: replace the current Fragment
with the new Fragment
and push transaction onto the backstack. This preserves back button behaviour...
Creating a new Activity
really defeats the whole purpose to use fragments anyway...very counter productive.
@Override
public void onClick(View v) {
// Create new fragment and transaction
Fragment newFragment = new chartsFragment();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
http://developer.android.com/guide/components/fragments.html#Transactions
In some environments, NSLog() will be unresponsive. But there are other ways to get output...
NSString* url = @"someurlstring";
printf("%s", [url UTF8String]);
By using printf
with the appropriate parameters, we can display things this way. This is the only way I have found to work on online Objective-C sandbox environments.
In Oracle, This work for me
SELECT name, min(date), min(time)
FROM table_name
GROUP BY name
Create a base class for your ViewModels
with the following constructor code which will apply the DefaultValueAttributes
when any inheriting model is created.
public abstract class BaseViewModel
{
protected BaseViewModel()
{
// apply any DefaultValueAttribute settings to their properties
var propertyInfos = this.GetType().GetProperties();
foreach (var propertyInfo in propertyInfos)
{
var attributes = propertyInfo.GetCustomAttributes(typeof(DefaultValueAttribute), true);
if (attributes.Any())
{
var attribute = (DefaultValueAttribute) attributes[0];
propertyInfo.SetValue(this, attribute.Value, null);
}
}
}
}
And inherit from this in your ViewModels:
public class SearchModel : BaseViewModel
{
[DefaultValue(true)]
public bool IsMale { get; set; }
[DefaultValue(true)]
public bool IsFemale { get; set; }
}
TL;DR
To store "abc"
into $foo
:
echo "abc" | read foo
But, because pipes create forks, you have to use $foo
before the pipe ends, so...
echo "abc" | ( read foo; date +"I received $foo on %D"; )
Sure, all these other answers show ways to not do what the OP asked, but that really screws up the rest of us who searched for the OP's question.
read
command.# I would usually do this on one line, but for readability...
series | of | commands \
| \
(
read string;
mystic_command --opt "$string" /path/to/file
) \
| \
handle_mystified_file
Let's pretend that the series | of | commands
is a very complicated series of piped commands.
mystic_command
can accept the content of a file as stdin in lieu of a file path, but not the --opt
arg therefore it must come in as a variable. The command outputs the modified content and would commonly be redirected into a file or piped to another command. (E.g. sed
, awk
, perl
, etc.)
read
takes stdin and places it into the variable $string
Putting the read
and the mystic_command
into a "sub shell" via parenthesis is not necessary but makes it flow like a continuous pipe as if the 2 commands where in a separate script file.
There is always an alternative, and in this case the alternative is ugly and unreadable compared to my example above.
# my example above as a oneliner
series | of | commands | (read string; mystic_command --opt "$string" /path/to/file) | handle_mystified_file
# ugly and unreadable alternative
mystic_command --opt "$(series | of | commands)" /path/to/file | handle_mystified_file
My way is entirely chronological and logical. The alternative starts with the 4th command and shoves commands 1, 2, and 3 into command substitution.
I have a real world example of this in this script but I didn't use it as the example above because it has some other crazy/confusing/distracting bash magic going on also.
I wanted to replicate Unix/Linux's cp -r
as closely as possible. I came up with the following:
xcopy /e /k /h /i srcdir destdir
Flag explanation:
/e
Copies directories and subdirectories, including empty ones.
/k
Copies attributes. Normal Xcopy will reset read-only attributes.
/h
Copies hidden and system files also.
/i
If destination does not exist and copying more than one file, assume destination is a directory.
I made the following into a batch file (cpr.bat
) so that I didn't have to remember the flags:
xcopy /e /k /h /i %*
Usage: cpr srcdir destdir
You might also want to use the following flags, but I didn't:
/q
Quiet. Do not display file names while copying.
/b
Copies the Symbolic Link itself versus the target of the link. (requires UAC admin)
/o
Copies directory and file ACLs. (requires UAC admin)
Maybe something like this:
SELECT count(*) FROM user_tab_columns WHERE table_name = 'FOO'
this will count number of columns in a the table FOO
You can also just
select count(*) from all_tab_columns where owner='BAR' and table_name='FOO';
where the owner is schema and note that Table Names are upper case
The question is relatively old, but I hope this post still might be relevant for others.
TL;DR: use AlarmManager to schedule a task, use IntentService, see the sample code here;
Simple helloworld app, which sends you notification every 2 hours. Clicking on notification - opens secondary Activity in the app; deleting notification tracks.
Once you need to run some task on a scheduled basis. My own case: once a day, I want to fetch new content from server, compose a notification based on the content I got and show it to user.
First, let's create 2 activities: MainActivity, which starts notification-service and NotificationActivity, which will be started by clicking notification:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<Button
android:id="@+id/sendNotifications"
android:onClick="onSendNotificationsButtonClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Sending Notifications Every 2 Hours!" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onSendNotificationsButtonClick(View view) {
NotificationEventReceiver.setupAlarm(getApplicationContext());
}
}
and NotificationActivity is any random activity you can come up with. NB! Don't forget to add both activities into AndroidManifest.
Then let's create WakefulBroadcastReceiver
broadcast receiver, I called NotificationEventReceiver in code above.
Here, we'll set up AlarmManager
to fire PendingIntent
every 2 hours (or with any other frequency), and specify the handled actions for this intent in onReceive()
method. In our case - wakefully start IntentService
, which we'll specify in the later steps. This IntentService
would generate notifications for us.
Also, this receiver would contain some helper-methods like creating PendintIntents, which we'll use later
NB1! As I'm using WakefulBroadcastReceiver
, I need to add extra-permission into my manifest: <uses-permission android:name="android.permission.WAKE_LOCK" />
NB2! I use it wakeful version of broadcast receiver, as I want to ensure, that the device does not go back to sleep during my IntentService
's operation. In the hello-world it's not that important (we have no long-running operation in our service, but imagine, if you have to fetch some relatively huge files from server during this operation). Read more about Device Awake here.
NotificationEventReceiver.java
public class NotificationEventReceiver extends WakefulBroadcastReceiver {
private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";
private static final int NOTIFICATIONS_INTERVAL_IN_HOURS = 2;
public static void setupAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent = getStartPendingIntent(context);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
getTriggerAt(new Date()),
NOTIFICATIONS_INTERVAL_IN_HOURS * AlarmManager.INTERVAL_HOUR,
alarmIntent);
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Intent serviceIntent = null;
if (ACTION_START_NOTIFICATION_SERVICE.equals(action)) {
Log.i(getClass().getSimpleName(), "onReceive from alarm, starting notification service");
serviceIntent = NotificationIntentService.createIntentStartNotificationService(context);
} else if (ACTION_DELETE_NOTIFICATION.equals(action)) {
Log.i(getClass().getSimpleName(), "onReceive delete notification action, starting notification service to handle delete");
serviceIntent = NotificationIntentService.createIntentDeleteNotification(context);
}
if (serviceIntent != null) {
startWakefulService(context, serviceIntent);
}
}
private static long getTriggerAt(Date now) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
//calendar.add(Calendar.HOUR, NOTIFICATIONS_INTERVAL_IN_HOURS);
return calendar.getTimeInMillis();
}
private static PendingIntent getStartPendingIntent(Context context) {
Intent intent = new Intent(context, NotificationEventReceiver.class);
intent.setAction(ACTION_START_NOTIFICATION_SERVICE);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
public static PendingIntent getDeleteIntent(Context context) {
Intent intent = new Intent(context, NotificationEventReceiver.class);
intent.setAction(ACTION_DELETE_NOTIFICATION);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
Now let's create an IntentService
to actually create notifications.
There, we specify onHandleIntent()
which is responses on NotificationEventReceiver's intent we passed in startWakefulService
method.
If it's Delete action - we can log it to our analytics, for example. If it's Start notification intent - then by using NotificationCompat.Builder
we're composing new notification and showing it by NotificationManager.notify
. While composing notification, we are also setting pending intents for click and remove actions. Fairly Easy.
NotificationIntentService.java
public class NotificationIntentService extends IntentService {
private static final int NOTIFICATION_ID = 1;
private static final String ACTION_START = "ACTION_START";
private static final String ACTION_DELETE = "ACTION_DELETE";
public NotificationIntentService() {
super(NotificationIntentService.class.getSimpleName());
}
public static Intent createIntentStartNotificationService(Context context) {
Intent intent = new Intent(context, NotificationIntentService.class);
intent.setAction(ACTION_START);
return intent;
}
public static Intent createIntentDeleteNotification(Context context) {
Intent intent = new Intent(context, NotificationIntentService.class);
intent.setAction(ACTION_DELETE);
return intent;
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(getClass().getSimpleName(), "onHandleIntent, started handling a notification event");
try {
String action = intent.getAction();
if (ACTION_START.equals(action)) {
processStartNotification();
}
if (ACTION_DELETE.equals(action)) {
processDeleteNotification(intent);
}
} finally {
WakefulBroadcastReceiver.completeWakefulIntent(intent);
}
}
private void processDeleteNotification(Intent intent) {
// Log something?
}
private void processStartNotification() {
// Do something. For example, fetch fresh data from backend to create a rich notification?
final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle("Scheduled Notification")
.setAutoCancel(true)
.setColor(getResources().getColor(R.color.colorAccent))
.setContentText("This notification has been triggered by Notification Service")
.setSmallIcon(R.drawable.notification_icon);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
NOTIFICATION_ID,
new Intent(this, NotificationActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
builder.setDeleteIntent(NotificationEventReceiver.getDeleteIntent(this));
final NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(NOTIFICATION_ID, builder.build());
}
}
Almost done. Now I also add broadcast receiver for BOOT_COMPLETED, TIMEZONE_CHANGED, and TIME_SET events to re-setup my AlarmManager, once device has been rebooted or timezone has changed (For example, user flown from USA to Europe and you don't want notification to pop up in the middle of the night, but was sticky to the local time :-) ).
NotificationServiceStarterReceiver.java
public final class NotificationServiceStarterReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationEventReceiver.setupAlarm(context);
}
}
We need to also register all our services, broadcast receivers in AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="klogi.com.notificationbyschedule">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".notifications.NotificationIntentService"
android:enabled="true"
android:exported="false" />
<receiver android:name=".broadcast_receivers.NotificationEventReceiver" />
<receiver android:name=".broadcast_receivers.NotificationServiceStarterReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
<action android:name="android.intent.action.TIME_SET" />
</intent-filter>
</receiver>
<activity
android:name=".NotificationActivity"
android:label="@string/title_activity_notification"
android:theme="@style/AppTheme.NoActionBar"/>
</application>
</manifest>
The source code for this project you can find here. I hope, you will find this post helpful.
I'm using spring-boot-1.3.5.RELEASE
and I had the same issue. None of above solutions are not worked for me. But finally adding following property to application.properties
was fixed the problem.
multipart.max-file-size=10MB
It seems that you have a bunch of describe
s that never have end
s keywords, starting with describe "when email format is invalid" do
until describe "when email address is already taken" do
Put an end on those guys and you're probably done =)
For this you just need to add content
attribute and font-family
attribute to the required element via :before or :after wherever applicable.
For example: I wanted to attach an attachment icon after all the a
element inside my post. So, first I need to search if such icon exists in fontawesome. Like in the case I found it here, i.e. fa fa-paperclip
. Then I would right click the icon there, and go the ::before
pseudo property to fetch out the content
tag it is using, which in my case I found to be \f0c6
. Then I would use that in my css like this:
.post a:after {
font-family: FontAwesome,
content: " \f0c6" /* I added a space before \ for better UI */
}
Your mistake is looking for range
, which gives you the range
of a vector, for example:
range(c(10, -5, 100))
gives
-5 100
Instead, look at the :
operator to give sequences (with a step size of one):
1:100
or you can use the seq
function to have a bit more control. For example,
##Step size of 2
seq(1, 100, by=2)
or
##length.out: desired length of the sequence
seq(1, 100, length.out=5)
First of all there are functions for this. But if you prefer vars then your task can be done like this:
$ cmd=ls
$ $cmd # works
file file2 test
$ cmd='ls | grep file'
$ $cmd # not works
ls: cannot access '|': No such file or directory
ls: cannot access 'grep': No such file or directory
file
$ bash -c $cmd # works
file file2 test
$ bash -c "$cmd" # also works
file
file2
$ bash <<< $cmd
file
file2
$ bash <<< "$cmd"
file
file2
Or via tmp file
$ tmp=$(mktemp)
$ echo "$cmd" > "$tmp"
$ chmod +x "$tmp"
$ "$tmp"
file
file2
$ rm "$tmp"
SELECT Call.ID, Call.date, Call.phone_number
FROM Call
LEFT OUTER JOIN Phone_Book
ON (Call.phone_number=Phone_book.phone_number)
WHERE Phone_book.phone_number IS NULL
Should remove the subquery, allowing the query optimiser to work its magic.
Also, avoid "SELECT *" because it can break your code if someone alters the underlying tables or views (and it's inefficient).
Quite straight. This can be a good starting point
int makeDir(char *fullpath, mode_t permissions){
int i=0;
char *arrDirs[20];
char aggrpaz[255];
arrDirs[i] = strtok(fullpath,"/");
strcpy(aggrpaz, "/");
while(arrDirs[i]!=NULL)
{
arrDirs[++i] = strtok(NULL,"/");
strcat(aggrpaz, arrDirs[i-1]);
mkdir(aggrpaz,permissions);
strcat(aggrpaz, "/");
}
i=0;
return 0;
}
You parse this function a full path plus the permissions you want, i.e S_IRUSR, for a full list of modes go here https://techoverflow.net/2013/04/05/how-to-use-mkdir-from-sysstat-h/
The fullpath string will be split by the "/" character and individual dirs will be appended to the aggrpaz string one at a time. Each loop iteration calls the mkdir function, passing it the aggregate path so far plus the permissions. This example can be improved, I am not checking the mkdir function output and this function only works with absolute paths.
float: left
… Below are the most common ways to achieve two elements side-by-side…
Some basic css styles for parent
and child
elements in these examples:
.parent {
background: mediumpurple;
padding: 1rem;
}
.child {
border: 1px solid indigo;
padding: 1rem;
}
Using the float
solution my have unintended affect on other elements. (Hint: You may need to use a clearfix.)
html
<div class='parent'>
<div class='child float-left-child'>A</div>
<div class='child float-left-child'>B</div>
</div>
css
.float-left-child {
float: left;
}
html
<div class='parent'>
<div class='child inline-block-child'>A</div>
<div class='child inline-block-child'>B</div>
</div>
css
.inline-block-child {
display: inline-block;
}
Note: the space between these two child elements can be removed, by removing the space between the div tags:
html
<div class='parent'>
<div class='child inline-block-child'>A</div><div class='child inline-block-child'>B</div>
</div>
css
.inline-block-child {
display: inline-block;
}
html
<div class='parent flex-parent'>
<div class='child flex-child'>A</div>
<div class='child flex-child'>B</div>
</div>
css
.flex-parent {
display: flex;
}
.flex-child {
flex: 1;
}
html
<div class='parent inline-flex-parent'>
<div class='child'>A</div>
<div class='child'>B</div>
</div>
css
.inline-flex-parent {
display: inline-flex;
}
html
<div class='parent grid-parent'>
<div class='child'>A</div>
<div class='child'>B</div>
</div>
css
.grid-parent {
display: grid;
grid-template-columns: 1fr 1fr
}
You use a compound key (a key with more than one attribute) whenever you want to ensure the uniqueness of a combination of several attributes. A single attribute key would not achieve the same thing.
The terms resource and endpoint are often used synonymously. But in fact they do not mean the same thing.
The term endpoint is focused on the URL that is used to make a request.
The term resource is focused on the data set that is returned by a request.
Now, the same resource can often be accessed by multiple different endpoints.
Also the same endpoint can return different resources, depending on a query string.
Let us see some examples:
Have a look at the following examples of different endpoints:
/api/companies/5/employees/3
/api/v2/companies/5/employees/3
/api/employees/3
They obviously could all access the very same resource in a given API.
Also an existing API could be changed completely. This could lead to new endpoints that would access the same old resources using totally new and different URLs:
/api/employees/3
/new_api/staff/3
If your endpoint returns a collection, you could implement searching/filtering/sorting using query strings. As a result the following URLs all use the same endpoint (/api/companies
), but they can return different resources (or resource collections, which by definition are resources in themselves):
/api/companies
/api/companies?sort=name_asc
/api/companies?location=germany
/api/companies?search=siemens
You could use a Regexp.
var result = /^(\d{2})-(\d{2})-(\d{4})$/.exec($("#datepicker").val());
if (result) {
from = new Date(
parseInt(result[3], 10),
parseInt(result[2], 10) - 1,
parseInt(result[1], 10)
);
}
I modified Sanoj Dushmantha's answer to use sessionStorage instead of localStorage. However, despite the documentation, browsers will still store this data even after the browser is closed. To fix this issue, I am removing the scroll position after it is reset.
<script>
document.addEventListener("DOMContentLoaded", function (event) {
var scrollpos = sessionStorage.getItem('scrollpos');
if (scrollpos) {
window.scrollTo(0, scrollpos);
sessionStorage.removeItem('scrollpos');
}
});
window.addEventListener("beforeunload", function (e) {
sessionStorage.setItem('scrollpos', window.scrollY);
});
</script>
For Windows Vista and Windows 7 you need to get the Remote Server Administration Tools (RSAT) - the Active Directory Users & Computers Snap-In is included in that pack. Download link: Remote Server Administration Tools for Windows 7.
The accepted answer doesn't work for UILocalNotification. For some reason, %%%%
(4 percent signs) or the unicode character '\uFF05
' only work for this.
So to recap, when formatting your string you may use %%
. However, if your string is part of a UILocalNotification, use %%%%
or \uFF05
.
Use try block in your code like
try
{
// Your code...
// Could also be before try if you know the exception occurs in SaveChanges
context.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
You can check the details here as well
I tried many thing to get DELETE method work (I was getting 405 method not allowed web api) , and finally I added [Route("api/scan/{id}")] to my controller and was work fine. hope this post help some one.
// DELETE api/Scan/5
[Route("api/scan/{id}")]
[ResponseType(typeof(Scan))]
public IHttpActionResult DeleteScan(int id)
{
Scan scan = db.Scans.Find(id);
if (scan == null)
{
return NotFound();
}
db.Scans.Remove(scan);
db.SaveChanges();
return Ok(scan);
}
http://www.w3schools.com/tags/tag_ul.asp
ul {
display: block;
list-style-type: disc;
margin-top: 1em;
margin-bottom: 1em;
margin-left: 0;
margin-right: 0;
padding-left: 40px;
}
Use scipy:
import scipy;
a=[1,2,4];
print(scipy.mean(a));
To check if Zookeeper is accessible. One method is to simply telnet to the proper port and execute the stats command.
root@host:~# telnet localhost 2181
Trying 127.0.0.1...
Connected to myhost.
Escape character is '^]'.
stats
Zookeeper version: 3.4.3-cdh4.0.1--1, built on 06/28/2012 23:59 GMT
Clients:
Latency min/avg/max: 0/0/677
Received: 4684478
Sent: 4687034
Outstanding: 0
Zxid: 0xb00187dd0
Mode: leader
Node count: 127182
Connection closed by foreign host.
If you want to find all commits where commit message contains given word, use
$ git log --grep=word
If you want to find all commits where "word" was added or removed in the file contents (to be more exact: where number of occurences of "word" changed), i.e. search the commit contents, use so called 'pickaxe' search with
$ git log -Sword
In modern git there is also
$ git log -Gword
to look for differences whose added or removed line matches "word" (also commit contents).
Note that -G
by default accepts a regex, while -S
accepts a string, but can be modified to accept regexes using the --pickaxe-regex
.
To illustrate the difference between
-S<regex> --pickaxe-regex
and-G<regex>
, consider a commit with the following diff in the same file:+ return !regexec(regexp, two->ptr, 1, ®match, 0); ... - hit = !regexec(regexp, mf2.ptr, 1, ®match, 0);
While
git log -G"regexec\(regexp"
will show this commit,git log -S"regexec\(regexp" --pickaxe-regex
will not (because the number of occurrences of that string did not change).
With Git 2.25.1 (Feb. 2020), the documentation is clarified around those regexes.
See commit 9299f84 (06 Feb 2020) by Martin Ågren (``).
(Merged by Junio C Hamano -- gitster
-- in commit 0d11410, 12 Feb 2020)
diff-options.txt
: avoid "regex" overload in exampleReported-by: Adam Dinwoodie
Signed-off-by: Martin Ågren
Reviewed-by: Taylor BlauWhen we exemplify the difference between
-G
and-S
(using--pickaxe-regex
), we do so using an example diff andgit diff
invocation involving "regexec", "regexp", "regmatch", ...The example is correct, but we can make it easier to untangle by avoiding writing "regex.*" unless it's really needed to make our point.
Use some made-up, non-regexy words instead.
The git diff
documentation now includes:
To illustrate the difference between
-S<regex> --pickaxe-regex
and-G<regex>
, consider a commit with the following diff in the same file:+ return frotz(nitfol, two->ptr, 1, 0); ... - hit = frotz(nitfol, mf2.ptr, 1, 0);
While
git log -G"frotz\(nitfol"
will show this commit,git log -S"frotz\(nitfol" --pickaxe-regex
will not (because the number of occurrences of that string did not change).
<div (mouseenter)="changeText=true" (mouseout)="changeText=false">
<span *ngIf="!changeText">Hide</span>
<span *ngIf="changeText">Show</span>
</div>
and if you want to use in *ngFor then assign the object value of hover data and then check its id and show hover info/icon or anything like that:-
<div (mouseenter)="hoverCard(d)" (mouseleave)="hoverCard(null)" *ngFor="let d of data" class="col-lg-3 col-md-4 col-sm-6 mt-4">
<a *ngIf="hoverData && hoverData.id == d.id" class="text-right"><i class="fas fa-edit"></i>Hover Text</a>
Normal Text
</div>
in TS File
hoverData!:Data|null;
hoverCard(d: Data|null){
this.hoverData = sCatg;
}
Netbeans allows you to do a simple filecopy. As you know, Eclipse doesn't work like that. You must explicitly "import" files and projects.
If you do import, and if there are no problems, then they should show up.
I'd consider:
a) making a backup of your existing workspace
b) deleting and reinstalling Eclipse
c) Trying another "test import"
I think you could do:
$('#google_translate_element').find('*').each(function(){
$(this).unbind('click');
});
but it would cause a lot of overhead
It doesn't compile because T could be anything, and not everything will have the myvar
field.
You could make myvar
a property on ITest
:
public ITest
{
string myvar{get;}
}
and implement it on the classes as a property:
public class MyClass1 : ITest
{
public string myvar{ get { return "hello 1"; } }
}
and then put a generic constraint on your method:
public void PrintGeneric<T>(T test) where T : ITest
{
Console.WriteLine("Generic : " + test.myvar);
}
but in that case to be honest you are better off just passing in an ITest:
public void PrintGeneric(ITest test)
{
Console.WriteLine("Generic : " + test.myvar);
}
Set style= "display:none;"
. By setting visible=false
, it will not render button in the browser. Thus,client side script wont execute.
<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" style="display:none" />
html markup should be
<button id="btnsave" onclick="fncsave()">Save</button>
Change javascript to
<script type="text/javascript">
function fncsave()
{
document.getElementById('<%= savebtn.ClientID %>').click();
}
</script>
This section of the boto3 documentation is helpful.
Here's what worked for me:
session = boto3.Session(profile_name='dev')
client = session.client('cloudfront')
The UN maintains a list of countries and "states" / regions for economic trade. That DB is available here: http://www.unece.org/cefact/locode/welcome.html
If the OPENROWSET is causing you issues, there is another way from 2012 onwards; make use of sys.dm_exec_describe_first_result_set_for_object, as mentioned here: Retrieve column names and types of a stored procedure?
First, create this stored procedure to generate the SQL for the temporary table:
CREATE PROCEDURE dbo.usp_GetStoredProcTableDefinition(
@ProcedureName nvarchar(128),
@TableName nvarchar(128),
@SQL nvarchar(max) OUTPUT
)
AS
SET @SQL = 'CREATE TABLE ' + @tableName + ' ('
SELECT @SQL = @SQL + '['+name +'] '+ system_type_name +'' + ','
FROM sys.dm_exec_describe_first_result_set_for_object
(
OBJECT_ID(@ProcedureName),
NULL
);
--Remove trailing comma
SET @SQL = SUBSTRING(@SQL,0,LEN(@SQL))
SET @SQL = @SQL +')'
To use the procedure, call it in the following way:
DECLARE @SQL NVARCHAR(MAX)
exec dbo.usp_GetStoredProcTableDefinition
@ProcedureName='dbo.usp_YourProcedure',
@TableName='##YourGlobalTempTable',@SQL = @SQL OUTPUT
INSERT INTO ##YourGlobalTempTable
EXEC [dbo].usp_YourProcedure
select * from ##YourGlobalTempTable
Note that I'm using a global temporary table. That's because using EXEC to run the dynamic SQL creates its own session, so an ordinary temporary table would be out of scope to any subsequent code. If a global temporary table is a problem, you can use an ordinary temporary table, but any subsequent SQL would need to be dynamic, that is, also executed by the EXEC statement.
I recently face the same problem, I am using mac os and ios simulator. flutter devices
command shows No devices detected
.
Then i run the flutter doctor
command and it says my xcode installation is incomplete,
But its not true(i verify it by building native ios app and it runs well)!
I didn't reinstall/download xcode again, just run that two commands according to their suggestions
sudo xcode-select --switch /Applications/Xcode.app/Contacts/Developer
sudo xcodebuild -runFirstLaunch
And it solves my problem. Here is the final flutter doctor
command output.
Hope this will be helpful for someone.
$name=array();
while($result=mysql_fetch_array($res)) {
$name[]=array('Id'=>$result['id']);
// here you want to fetch all
// records from table like this.
// then you should get the array
// from all rows into one array
}
Use
Comparator<File> comparator = Comparator.comparing(File::lastModified);
Collections.sort(list, comparator.reversed());
Then
.forEach(item -> item.delete());
SQL Error: ORA-30926: unable to get a stable set of rows in the source tables
30926. 00000 - "unable to get a stable set of rows in the source tables"
*Cause: A stable set of rows could not be got because of large dml
activity or a non-deterministic where clause.
*Action: Remove any non-deterministic where clauses and reissue the dml.
This Error occurred for me because of duplicate records(16K)
I tried with unique it worked .
but again when I tried merge without unique same proble occurred Second time it was due to commit
after merge if commit is not done same Error will be shown.
Without unique, Query will work if commit is given after each merge operation.
For an incoming request like /v1/location/1234
, as you can imagine it would be difficult for Web API to automatically figure out if the value of the segment corresponding to '1234' is related to appid
and not to deviceid
.
I think you should change your route template to be like
[Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")]
and then parse the deiveOrAppid
to figure out the type of id.
Also you need to make the segments in the route template itself optional otherwise the segments are considered as required. Note the ?
character in this case.
For example:
[Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")]
From what i understand, you can just manage windows using microsoft. hold control and select multiple windows in the taskbar, then right click it and tile whatever way you want. what i've been looking for is a way to actually split a physical monitor into two. so you can run not just windowed prgrams (explorer, firefox, whatever) but full screen programs like games or movies or whatever else you want. this is super useful to fix bugs in full screen programs. im tired of these "windows mangagers" its easier just to click and drag it where you want. and im not OCD about it lining up just right. i just want to split a monitor into two. is that so hard to ask?
This is what the Python documentation has got to say about None
:
The sole value of types.NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function.
Changed in version 2.4: Assignments to None are illegal and raise a SyntaxError.
Note The names None and debug cannot be reassigned (assignments to them, even as an attribute name, raise SyntaxError), so they can be considered “true” constants.
Let's confirm the type of None
first
print type(None)
print None.__class__
Output
<type 'NoneType'>
<type 'NoneType'>
Basically, NoneType
is a data type just like int
, float
, etc. You can check out the list of default types available in Python in 8.15. types — Names for built-in types.
And, None
is an instance of NoneType
class. So we might want to create instances of None
ourselves. Let's try that
print types.IntType()
print types.NoneType()
Output
0
TypeError: cannot create 'NoneType' instances
So clearly, cannot create NoneType
instances. We don't have to worry about the uniqueness of the value None
.
Let's check how we have implemented None
internally.
print dir(None)
Output
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__',
'__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
Except __setattr__
, all others are read-only attributes. So, there is no way we can alter the attributes of None
.
Let's try and add new attributes to None
setattr(types.NoneType, 'somefield', 'somevalue')
setattr(None, 'somefield', 'somevalue')
None.somefield = 'somevalue'
Output
TypeError: can't set attributes of built-in/extension type 'NoneType'
AttributeError: 'NoneType' object has no attribute 'somefield'
AttributeError: 'NoneType' object has no attribute 'somefield'
The above seen statements produce these error messages, respectively. It means that, we cannot create attributes dynamically on a None
instance.
Let us check what happens when we assign something None
. As per the documentation, it should throw a SyntaxError
. It means, if we assign something to None
, the program will not be executed at all.
None = 1
Output
SyntaxError: cannot assign to None
We have established that
None
is an instance of NoneType
None
cannot have new attributesNone
cannot be changed.NoneType
None
by assigning values to it.So, as mentioned in the documentation, None
can really be considered as a true constant
.
Happy knowing None
:)
One way to give preference to specific rows is to add a large number to their priority. You can do this with a CASE
statement:
select id, name, priority
from mytable
order by priority + CASE WHEN name='core' THEN 1000 ELSE 0 END desc
As of Swift 3 / 4 / 5, this is done as follows.
To add a new element to the end of an Array.
anArray.append("This String")
To append a different Array to the end of your Array.
anArray += ["Moar", "Strings"]
anArray.append(contentsOf: ["Moar", "Strings"])
To insert a new element into your Array.
anArray.insert("This String", at: 0)
To insert the contents of a different Array into your Array.
anArray.insert(contentsOf: ["Moar", "Strings"], at: 0)
More information can be found in the "Collection Types" chapter of "The Swift Programming Language", starting on page 110.
this will make the powershell window to wait until you press any key:
pause
Update One
Thanks to Stein. it is the Enter key not any key.
KeyedCollection works like dictionary and is serializable.
First create a class containing key and value:
/// <summary>
/// simple class
/// </summary>
/// <remarks></remarks>
[Serializable()]
public class cCulture
{
/// <summary>
/// culture
/// </summary>
public string culture;
/// <summary>
/// word list
/// </summary>
public List<string> list;
/// <summary>
/// status
/// </summary>
public string status;
}
then create a class of type KeyedCollection, and define a property of your class as key.
/// <summary>
/// keyed collection.
/// </summary>
/// <remarks></remarks>
[Serializable()]
public class cCultures : System.Collections.ObjectModel.KeyedCollection<string, cCulture>
{
protected override string GetKeyForItem(cCulture item)
{
return item.culture;
}
}
Usefull to serialize such type of datas.
/* Microsoft Edge Browser 12-18 (All versions before Chromium) - one-liner method */
_:-ms-lang(x), _:-webkit-full-screen, .selector { property:value; }
That works great!
// for instance:
_:-ms-lang(x), _:-webkit-full-screen, .headerClass
{
border: 1px solid brown;
}
https://jeffclayton.wordpress.com/2015/04/07/css-hacks-for-windows-10-and-spartan-browser-preview/
See the wiki article:
In point-to-point situations confidentiality and data integrity can also be enforced on Web services through the use of Transport Layer Security (TLS), for example, by sending messages over https.
WS-Security however addresses the wider problem of maintaining integrity and confidentiality of messages until after a message was sent from the originating node, providing so called end to end security.
That is:
I had a similar problem.
I would also look at this answer: Is there a high resolution (microsecond, nanosecond) DateTime object available for the CLR?.
About half-way down is an answer by "Robert P" with some extension functions I found useful.
Try this , if you are using PHP 5.3+, in php
$query_date = '2010-02-04';
$date = new DateTime($query_date);
//First day of month
$date->modify('first day of this month');
$firstday= $date->format('Y-m-d');
//Last day of month
$date->modify('last day of this month');
$lastday= $date->format('Y-m-d');
For finding next month last date, modify as follows,
$date->modify('last day of 1 month');
echo $date->format('Y-m-d');
and so on..
This part has problems:
Card* cardArray;
void Deck() {
cardArray = new Card[NUM_TOTAL_CARDS];
int cardCount = 0;
for (int i = 0; i > NUM_SUITS; i++) { //Error
for (int j = 0; j > NUM_RANKS; j++) { //Error
cardArray[cardCount] = Card(Card::Rank(i), Card::Suit(j) );
cardCount++;
}
}
}
cardArray
is a dynamic array, but not a member of Card
class. It is strange if you would like to initialize a dynamic array which is not member of the classvoid Deck()
is not constructor of class Deck since you missed the
scope resolution operator. You may be confused with defining the constructor and the function with name Deck
and return type void
.<
not >
otherwise, loop will never
be executed.I know this will not work for everyone, but I thought it interesting that just adding a Divider solves for this.
struct DividerTest: View {
var body: some View {
VStack(alignment: .leading) {
Text("Foo")
Text("Bar")
Divider()
}.background(Color.red)
}
}
I know this is an old question but anyway it might help someone.
I tend to use PHP_EOL
for this purposes (due to cross-platform compatibility).
echo "line 1".PHP_EOL."line 2".PHP_EOL;
If you're planning to show the result in a browser then you have to use "<br>"
.
EDIT: since your exact question is about emails, things are a bit different. For pure text emails see Brendan Bullen's accepted answer. For HTML emails you simply use HTML formatting.
The HTML5 spec says that the type
attribute is purely advisory and explains in detail how browsers should act if it's omitted (too much to quote here). It doesn't explicitly say that an omitted type attribute is either valid or invalid, but you can safely omit it knowing that browsers will still react as you expect.
Line from above answer:
HtmlDocument doc = new HtmlDocument();
This doesn't work in VS 2015 C#. You cannot construct an HtmlDocument
any more.
Another MS "feature" that makes things more difficult to use. Try HtmlAgilityPack.HtmlWeb
and check out this link for some sample code.
Your string looks like a JSON string without the curly braces.
This should work then:
obj = eval('({' + str + '})');
I'm also facing the problem that exceeding the stars than specified no of stars. For this, we don't want worry about whatever the layout type either relative or linear layout. Simply use the width as follows:
ratingBar.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
Please avoid using match_parent and fill_parent for ratingbar.
Hope the things would be helpful.
My "DerivedData" with Xcode 10.2 and Mojave was here:
MacHD/Users/[MyUser]/Library/Developer/Xcode
I like answer of arnefm but he made a small mistake (see comments) which I will try to correct:
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
/**
* ImageView that keeps aspect ratio when scaled
*/
public class ScaleImageView extends ImageView {
public ScaleImageView(Context context) {
super(context);
}
public ScaleImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ScaleImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
try {
Drawable drawable = getDrawable();
if (drawable == null) {
setMeasuredDimension(0, 0);
} else {
int measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
int measuredHeight = MeasureSpec.getSize(heightMeasureSpec);
if (measuredHeight == 0 && measuredWidth == 0) { //Height and width set to wrap_content
setMeasuredDimension(measuredWidth, measuredHeight);
} else if (measuredHeight == 0) { //Height set to wrap_content
int width = measuredWidth;
int height = width * drawable.getIntrinsicHeight() / drawable.getIntrinsicWidth();
setMeasuredDimension(width, height);
} else if (measuredWidth == 0){ //Width set to wrap_content
int height = measuredHeight;
int width = height * drawable.getIntrinsicWidth() / drawable.getIntrinsicHeight();
setMeasuredDimension(width, height);
} else { //Width and height are explicitly set (either to match_parent or to exact value)
setMeasuredDimension(measuredWidth, measuredHeight);
}
}
} catch (Exception e) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
Thus your ImageView
will be scaled properly and will have no dimension problems if (for instance) put inside of ScrollView
WARNING: Not for git newbies.
This comes up enough in my workflow that I've almost tried to write a new git command for it. The usual git stash
flow is the way to go but is a little awkward. I usually make a new commit first since if I have been looking at the changes, all the information is fresh in my mind and it's better to just start git commit
-ing what I found (usually a bugfix belonging on master that I discover while working on a feature branch) right away.
It is also helpful—if you run into situations like this a lot—to have another working directory alongside your current one that always have the
master
branch checked out.
So how I achieve this goes like this:
git commit
the changes right away with a good commit message.git reset HEAD~1
to undo the commit from current branch.Sometimes later (asynchronously), or immediately in another terminal window:
cd my-project-master
which is another WD sharing the same .git
git reflog
to find the bugfix I've just made.git cherry-pick SHA1
of the commit.Optionally (still asynchronous) you can then rebase (or merge) your feature branch to get the bugfix, usually when you are about to submit a PR and have cleaned your feature branch and WD already:
cd my-project
which is the main WD I'm working on.git rebase master
to get the bugfixes.This way I can keep working on the feature uninterrupted and not have to worry about git stash
-ing anything or having to clean my WD before a git checkout
(and then having the check the feature branch backout again.) and still have all my bugfixes goes to master
instead of hidden in my feature branch.
IMO git stash
and git checkout
is a real PIA when you are in the middle of working on some big feature.
You will need to make sure about timeouts between you and the file. In this case PHP and Curl.
To tell Curl to never timeout when a transfer is still active, you need to set CURLOPT_TIMEOUT
to 0
, instead of 1000
.
curl_setopt($ch, CURLOPT_TIMEOUT, 0);
In PHP, again, you must remove time limits or PHP it self (after 30 seconds by default) will kill the script along Curl's request. This alone should fix your issue.
In addition, if you require data integrity, you could add a layer of security by using ignore_user_abort
:
# The maximum execution time, in seconds. If set to zero, no time limit is imposed.
set_time_limit(0);
# Make sure to keep alive the script when a client disconnect.
ignore_user_abort(true);
A client disconnection will interrupt the execution of the script and possibly damaging data,
eg. non-transitional database query, building a config file, ecc., while in your case it would download a partial file... and you might, or not, care about this.
Answering this old question because this thread is at the top on engine searches for CURL_TIMEOUT
.
You can simulate a readonly select box using the CSS pointer-events property:
select[readonly]
{
pointer-events: none;
}
The HTML tabindex property will also prevent it from being selected by keyboard tabbing:
<select tabindex="-1">
select[readonly]_x000D_
{_x000D_
pointer-events: none;_x000D_
}_x000D_
_x000D_
_x000D_
/* irrelevent styling */_x000D_
_x000D_
*_x000D_
{_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
*[readonly]_x000D_
{_x000D_
background: #fafafa;_x000D_
border: 1px solid #ccc;_x000D_
color: #555;_x000D_
}_x000D_
_x000D_
input, select_x000D_
{_x000D_
display:block;_x000D_
width: 20rem;_x000D_
padding: 0.5rem;_x000D_
margin-bottom: 1rem;_x000D_
}
_x000D_
<form>_x000D_
<input type="text" value="this is a normal text box">_x000D_
<input type="text" readonly value="this is a readonly text box">_x000D_
<select readonly tabindex="-1">_x000D_
<option>This is a readonly select box</option>_x000D_
<option>Option 2</option>_x000D_
</select>_x000D_
<select>_x000D_
<option>This is a normal select box</option>_x000D_
<option>Option 2</option>_x000D_
</select>_x000D_
</form>
_x000D_
You can put content with `` around it, like
var hi = `I am here,
hello,
`
From an answer of @NimChimpsky in similar question:
Resource resource = new ClassPathResource("storedProcedures.sql");
InputStream resourceInputStream = resource.getInputStream();
Using ClassPathResource and interface Resource. And make sure you are adding the resources directory correctly (adding /src/main/resources/
into the classpath).
Note that Resource have a method to get a java.io.File
so you can also use:
Resource resource = new ClassPathResource("storedProcedures.sql");
FileReader fr = new FileReader(resource.getFile());
Here is a very simple way to do this (using SQL 2012 or later)
datefromparts(year(getdate()),month(getdate()),1)
you can also easily get the last day of the month using
eomonth(getdate())
One use: test some code that should raise an exception.
try:
this_should_raise_TypeError()
except TypeError:
pass
except:
assert False, "Raised the wrong exception type"
else:
assert False, "Didn't raise any exception"
(This code should be abstracted into a more generic test in practice.)
In case you're working with a regular old System.Collections.IEnumerable
instead of IEnumerable<T>
you can use enumerable.Cast<object>().ToList()
The use of cron on OS X is discouraged. launchd
is used instead. Try man launchctl
to get started. You have to create special XML files that define your jobs and put them in a special place with certain permissions.
You'll usually just need to figure out launchctl load
http://nb.nathanamy.org/2012/07/schedule-jobs-using-launchd/
Edit
If you really do want to use cron on OS X, check out this answer: https://superuser.com/a/243944/2449
For the example given, I prefer the ternary or condition operator (?
) for a specific reason: I can clearly see that assigning a
is not optional. With a simple example, it's not too hard to scan the if-else block to see that a
is assigned in each clause, but imagine several assignments in each clause:
if (i == 0)
{
a = 10;
b = 6;
c = 3;
}
else
{
a = 5;
b = 4;
d = 1;
}
a = (i == 0) ? 10 : 5;
b = (i == 0) ? 6 : 4;
c = (i == 0) ? 3 : 9;
d = (i == 0) ? 12 : 1;
I prefer the latter so that you know you haven't missed an assignment.
I don’t think you can select the parent in CSS only.
But as you already seem to have an .active
class, it would be easier to move that class to the li
(instead of the a
). That way you can access both the li
and the a
via CSS only.
You can export the private key with the command-line tool from GPG. It works on the Windows-shell. Use the following command:
gpg --export-secret-keys
A normal export with --export
will not include any private keys, therefore you have to use --export-secret-keys
.
Edit:
To sum up the information given in my comments, this is the command that allows you to export a specific key with the ID 1234ABCD to the file secret.asc:
gpg --export-secret-keys --armor 1234ABCD > secret.asc
You can find the ID that you need using the following command. The ID is the second part of the second column:
gpg --list-keys
To Export just 1 specific secret key instead of all of them:
gpg --export-secret-keys keyIDNumber > exportedKeyFilename.asc
keyIDNumber is the number of the key id for the desired key you are trying to export.
Programmatic options for controlling services:
StartService
method. This is good for cases where you need to be able to perform other processing (e.g. to select which service).Start-Service
via RunspaceInvoke
or by creating your own Runspace
and using its CreatePipeline
method to execute. This is good for cases where you need to be able to perform other processing (e.g. to select which service) with a much easier coding model than WMI, but depends on PSH being installed.ServiceController
@RestController
was provided since Spring 4.0.1. These controllers indicate that here @RequestMapping methods assume @ResponseBody semantics by default.
In earlier versions the similar functionality could be achieved by using below:
@RequestMapping
coupled with @ResponseBody
like @RequestMapping(value = "/abc", method = RequestMethod.GET, produces ="application/xml")
public @ResponseBody MyBean fetch(){
return new MyBean("hi")
}
<mvc:annotation-driven/>
may be used as one of the ways for using JSON with Jackson or xml.
@XmlRootElement(name = "MyBean")
@XmlType(propOrder = {"field2", "field1"})
public class MyBean{
field1
field2 ..
//getter, setter
}
@ResponseBody
is treated as the view here among MVC and it is dispatched directly instead being dispatched from Dispatcher Servlet and the respective converters convert the response in the related format like text/html, application/xml, application/json .However, the Restcontroller is already coupled with ResponseBody and the respective converters. Secondly, here, since instead of converting the responsebody, it is automatically converted to http response.
Here's an example of how to do it using Boost's transform_iterator
#include <iostream>
#include <map>
#include <iterator>
#include "boost/iterator/transform_iterator.hpp"
using std::map;
typedef std::string Key;
typedef std::string Val;
map<Key,Val>::key_type get_key(map<Key,Val>::value_type aPair) {
return aPair.first;
}
typedef map<Key,Val>::key_type (*get_key_t)(map<Key,Val>::value_type);
typedef map<Key,Val>::iterator map_iterator;
typedef boost::transform_iterator<get_key_t, map_iterator> mapkey_iterator;
int main() {
map<Key,Val> m;
m["a"]="A";
m["b"]="B";
m["c"]="C";
// iterate over the map's (key,val) pairs as usual
for(map_iterator i = m.begin(); i != m.end(); i++) {
std::cout << i->first << " " << i->second << std::endl;
}
// iterate over the keys using the transformed iterators
mapkey_iterator keybegin(m.begin(), get_key);
mapkey_iterator keyend(m.end(), get_key);
for(mapkey_iterator i = keybegin; i != keyend; i++) {
std::cout << *i << std::endl;
}
}
C++ "one-liner":
#include <iostream>
#include <iterator>
#include <numeric>
using namespace std;
int main() {
cout << accumulate(istream_iterator<int>(cin), istream_iterator<int>(), 0) << endl;
}
Add this two file in res/anim folder.
R.anim.slide_out_bottom
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate
android:duration="@integer/time_duration_max"
android:fromXDelta="0%"
android:fromYDelta="100%"
android:toXDelta="0%"
android:toYDelta="0%" />
</set>
R.anim.slide_in_bottom
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate
android:duration="@integer/time_duration_max"
android:fromXDelta="0%"
android:fromYDelta="0%"
android:toXDelta="0%"
android:toYDelta="100%" />
</set>
And write the below line of code in your view click listener.
startActivity(new Intent(MainActivity.this, NameOfTargetActivity.class));
overridePendingTransition(R.anim.slide_out_bottom, R.anim.slide_in_bottom);
It would be good to share, For DB2 use:
INSERT(someColumn, 1, 4, '')
Stuff
is not supported in DB2
Many problems here
I've set up a fiddle that works for you: http://jsfiddle.net/w9kSU/
$('.majorpointslegend').click(function(){
if($(this).text()=='Expand'){
$('#mylist').show();
$(this).text('Colapse');
}else{
$('#mylist').hide();
$(this).text('Expand');
}
});
I built this little function to automatically format anything into a nice currency format.
function formatDollars($dollars)
{
return "$".number_format(sprintf('%0.2f', preg_replace("/[^0-9.]/", "", $dollars)),2);
}
Edit
It was pointed out that this does not show negative values. I broke it into two lines so it's easier to edit the formatting. Wrap it in parenthesis if it's a negative value:
function formatDollars($dollars)
{
$formatted = "$" . number_format(sprintf('%0.2f', preg_replace("/[^0-9.]/", "", $dollars)), 2);
return $dollars < 0 ? "({$formatted})" : "{$formatted}";
}
use java decompiler and decompile all the .class files and save all files as project structure .
then use meld diff viewer and compare as folders ..
The proper test is:
if (capital != null && capital.length < 1) {
This ensures that capital
is always non null, when you perform the length check.
Also, as the comments suggest, capital
is null
because you never initialize it.
You're using the dequeueReusableCellWithIdentifier:forIndexPath:
method. The documentation for that method says this:
Important: You must register a class or nib file using the
registerNib:forCellReuseIdentifier:
orregisterClass:forCellReuseIdentifier:
method before calling this method.
You didn't register a nib or a class for the reuse identifier "Cell"
.
Looking at your code, you seem to expect the dequeue method to return nil
if it doesn't have a cell to give you. You need to use the dequeueReusableCellWithIdentifier:
for that behavior:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Notice that dequeueReusableCellWithIdentifier:
and dequeueReusableCellWithIdentifier:forIndexPath:
are different methods. See doc for the former and the latter.
If you want to understand why you'd want to ever use dequeueReusableCellWithIdentifier:forIndexPath:
, check out this Q&A.
simple and best way to use date function
example
SELECT * FROM
data
WHERE date(datetime) = '2009-10-20'
OR
SELECT * FROM
data
WHERE date(datetime ) >= '2009-10-20' && date(datetime ) <= '2009-10-20'
I write this answer because I was looking for a way to plot together the histograms of different groups. What follows is not very smart, but it works fine for me. I use Numpy to compute the histogram and Bokeh for plotting. I think it is self-explanatory, but feel free to ask for clarifications and I'll be happy to add details (and write it better).
figures = {
'Transit': figure(title='Transit', x_axis_label='speed [km/h]', y_axis_label='frequency'),
'Driving': figure(title='Driving', x_axis_label='speed [km/h]', y_axis_label='frequency')
}
cols = {'Vienna': 'red', 'Turin': 'blue', 'Rome': 'Orange'}
for gr in df_trips.groupby(['locality', 'means']):
locality = gr[0][0]
means = gr[0][1]
fig = figures[means]
h, b = np.histogram(pd.DataFrame(gr[1]).speed.values)
fig.vbar(x=b[1:], top=h, width=(b[1]-b[0]), legend_label=locality, fill_color=cols[locality], alpha=0.5)
show(gridplot([
[figures['Transit']],
[figures['Driving']],
]))
They are normal symbols as 'a' or '?' or any other. Just (invisible) entries in a string. \r moves cursor to the beginning of the line. \n goes one line down.
As for your replacement, you haven't specified what language you're using, so here's the sketch:
someString.replace("\r\n", "\n").replace("\r", "\n")
I like ndjango. It is very easy to use and very flexible. You can easily extend view functionality with custom tags and filters. I think that "greatly tied to F#" is rather advantage than disadvantage.
A third variant:
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readValue("{\"k1\":\"v1\"}", JsonNode.class);
SwiftUI
RoundedRectangle(cornerRadius: 50)
.frame(height: 40)
.colorInvert() // sets the background white
.padding()
.shadow(radius: 12) // adds shadow to the rectangle
.overlay(
HStack(spacing: 20){
Image(systemName: "person")
.resizable()
.aspectRatio(contentMode: .fit)
TextField("Username ", text: $username)
.font(Font.custom("Arial", size: 25))
.font(.title)
}
.padding()
.padding()
)
A very basic and easy approach for a weighted choice is the following:
np.random.choice(['A', 'B', 'C'], p=[0.3, 0.4, 0.3])
Using this method it is also possible to perform mass configuration changes, such as changing the all sessions font.
Extracted from here: http://www.sysadmit.com/2015/11/putty-exportar-configuracion.html
From some where I found below :-
In fact, you can.
Using reflections API you can access any class so far. At least I was able to :)
Class fooClass = Class.forName("FooBar");
Method fooMethod =
fooClass.getMethod("fooMethod", new Class[] { String.class });
String fooReturned =
(String) fooMethod.invoke(fooClass.newInstance(), "I did it");
Most browsers will simply ignore any NON-hex values in your color string, substituting non-hex digits with zeros.
ChuCknorris
translates to c00c0000000
. At this point, the browser will divide the string into three equal sections, indicating Red, Green and Blue values: c00c 0000 0000
. Extra bits in each section will be ignored, which makes the final result #c00000
which is a reddish color.
Note, this does not apply to CSS color parsing, which follow the CSS standard.
<p><font color='chucknorris'>Redish</font></p>_x000D_
<p><font color='#c00000'>Same as above</font></p>_x000D_
<p><span style="color: chucknorris">Black</span></p>
_x000D_
The easiest solution to workaround this is to create 'temporary' input with type submit and trigger click:
var submitInput = $("<input type='submit' />");
$("#aspnetForm").append(submitInput);
submitInput.trigger("click");
In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:
CSS solution:
HTML4's scrolling="no"
is kind of an alias of the CSS's overflow: hidden
, to do so it is important to set size attributes width/height:
iframe.noScrolling{
width: 250px; /*or any other size*/
height: 300px; /*or any other size*/
overflow: hidden;
}
Add this class to your iframe and you're done:
<iframe src="http://www.example.com/" class="noScrolling"></iframe>
! IMPORTANT NOTE ! : overflow: hidden
for <iframe>
is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no"
and overflow:hidden
at the same time :)
UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors
Set in RecyclerView
initialization
recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
Strictly stated you must check all of the following: defined, not empty AND not None.
For "normal" variables it makes a difference if defined and set or not set. See foo
and bar
in the example below. Both are defined but only foo
is set.
On the other side registered variables are set to the result of the running command and vary from module to module. They are mostly json structures. You probably must check the subelement you're interested in. See xyz
and xyz.msg
in the example below:
cat > test.yml <<EOF
- hosts: 127.0.0.1
vars:
foo: "" # foo is defined and foo == '' and foo != None
bar: # bar is defined and bar != '' and bar == None
tasks:
- debug:
msg : ""
register: xyz # xyz is defined and xyz != '' and xyz != None
# xyz.msg is defined and xyz.msg == '' and xyz.msg != None
- debug:
msg: "foo is defined and foo == '' and foo != None"
when: foo is defined and foo == '' and foo != None
- debug:
msg: "bar is defined and bar != '' and bar == None"
when: bar is defined and bar != '' and bar == None
- debug:
msg: "xyz is defined and xyz != '' and xyz != None"
when: xyz is defined and xyz != '' and xyz != None
- debug:
msg: "{{ xyz }}"
- debug:
msg: "xyz.msg is defined and xyz.msg == '' and xyz.msg != None"
when: xyz.msg is defined and xyz.msg == '' and xyz.msg != None
- debug:
msg: "{{ xyz.msg }}"
EOF
ansible-playbook -v test.yml
Using map
:
def caesar(text, key):
return ''.join(map(lambda c:
chr((ord(c.lower()) - ord('a') + key) % 26 + ord('a')) if c.isalpha() else ''
, text))
A little addition to what's written up there:
First, make sure your destructor is also pure virtual
Second, you may want to inherit virtually (rather than normally) when you do implement, just for good measures.
I was having the same issue with mysql datasource using spring data that would work outside but gave me this error when deployed on tomcat.
The error went away when I added the driver jar mysql-connector-java-8.0.16.jar to the jres lib/ext folder
However I did not want to do this in production for fear of interfering with other applications. Explicity defining the driver class solved this issue for me
spring.datasource.driver-class-name: com.mysql.cj.jdbc.Driver
Use this code:
HttpContext.Current.Server.MapPath("~")
Detailed Reference:
Server.MapPath
specifies the relative or virtual path to map to a physical directory.
Server.MapPath(".")
returns the current physical directory of the
file (e.g. aspx) being executedServer.MapPath("..")
returns the parent directoryServer.MapPath("~")
returns the physical path to the root of the
applicationServer.MapPath("/")
returns the physical path to the root of the
domain name (is not necessarily the same as the root of the
application)An example:
Let's say you pointed a web site application (http://www.example.com/) to
C:\Inetpub\wwwroot
and installed your shop application (sub web as virtual directory in IIS, marked as application) in
D:\WebApps\shop
For example, if you call Server.MapPath
in following request:
http://www.example.com/shop/products/GetProduct.aspx?id=2342
then:
Server.MapPath(".") returns D:\WebApps\shop\products
Server.MapPath("..") returns D:\WebApps\shop
Server.MapPath("~") returns D:\WebApps\shop
Server.MapPath("/") returns C:\Inetpub\wwwroot
Server.MapPath("/shop") returns D:\WebApps\shop
If Path starts with either a forward (/) or backward slash (), the MapPath
method returns a path as if Path were a full, virtual path.
If Path doesn't start with a slash, the MapPath
method returns a path relative to the directory of the request being processed.
Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.
Footnotes
Server.MapPath(null)
and Server.MapPath("")
will produce this effect too.
[list[y], list[x]] = [list[x], list[y]];
No temporary variable required!
I was thinking about simply calling list.reverse()
.
But then I realised it would work as swap only when list.length = x + y + 1
.
I have looked into various modern Javascript constructions to this effect, including Map and map, but sadly none has resulted in a code that was more compact or faster than this old-fashioned, loop-based construction:
function multiswap(arr,i0,i1) {/* argument immutable if string */
if (arr.split) return multiswap(arr.split(""), i0, i1).join("");
var diff = [];
for (let i in i0) diff[i0[i]] = arr[i1[i]];
return Object.assign(arr,diff);
}
Example:
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var [x,y,z] = [14,6,15];
var output = document.getElementsByTagName("code");
output[0].innerHTML = alphabet;
output[1].innerHTML = multiswap(alphabet, [0,25], [25,0]);
output[2].innerHTML = multiswap(alphabet, [0,25,z,1,y,x], [25,0,x,y,z,3]);
_x000D_
<table>
<tr><td>Input:</td> <td><code></code></td></tr>
<tr><td>Swap two elements:</td> <td><code></code></td></tr>
<tr><td>Swap multiple elements: </td> <td><code></code></td></tr>
</table>
_x000D_
Here's how you can mock your FileConnection
Mock<IFileConnection> fileConnection = new Mock<IFileConnection>(
MockBehavior.Strict);
fileConnection.Setup(item => item.Get(It.IsAny<string>,It.IsAny<string>))
.Throws(new IOException());
Then instantiate your Transfer class and use the mock in your method call
Transfer transfer = new Transfer();
transfer.GetFile(fileConnection.Object, someRemoteFilename, someLocalFileName);
Update:
First of all you have to mock your dependencies only, not the class you are testing(Transfer class in this case). Stating those dependencies in your constructor make it easy to see what services your class needs to work. It also makes it possible to replace them with fakes when you are writing your unit tests. At the moment it's impossible to replace those properties with fakes.
Since you are setting those properties using another dependency, I would write it like this:
public class Transfer
{
public Transfer(IInternalConfig internalConfig)
{
source = internalConfig.GetFileConnection("source");
destination = internalConfig.GetFileConnection("destination");
}
//you should consider making these private or protected fields
public virtual IFileConnection source { get; set; }
public virtual IFileConnection destination { get; set; }
public virtual void GetFile(IFileConnection connection,
string remoteFilename, string localFilename)
{
connection.Get(remoteFilename, localFilename);
}
public virtual void PutFile(IFileConnection connection,
string localFilename, string remoteFilename)
{
connection.Get(remoteFilename, localFilename);
}
public virtual void TransferFiles(string sourceName, string destName)
{
var tempName = Path.GetTempFileName();
GetFile(source, sourceName, tempName);
PutFile(destination, tempName, destName);
}
}
This way you can mock internalConfig and make it return IFileConnection mocks that does what you want.
Microsoft announced the intention to ship .NET Framework 4 on 29 September 2008. The Public Beta was released on 20 May 2009.
After the release of the .NET Framework 4, Microsoft released a set of enhancements, named Windows Server AppFabric, for application server capabilities in the form of AppFabric Hosting and in-memory distributed caching support.
.NET Framework 4.5 was released on 15 August 2012., a set of new or improved features were added into this version. The .NET Framework 4.5 is only supported on Windows Vista or later. The .NET Framework 4.5 uses Common Language Runtime 4.0, with some additional runtime features.
Metro-style apps are designed for specific form factors and leverage the power of the Windows operating system. A subset of the .NET Framework is available for building Metro style apps for Windows 8 using C# or Visual Basic. This subset is called .NET APIs for apps. The version of .NET Framework, runtime and libraries, used for Metro style apps is a part of the new Windows Runtime, which is the new platform and application model for Metro style apps. It is an ecosystem that houses many platforms and languages, including .NET Framework, C++ and HTML5/JavaScript.
In the .NET Framework 4.5, new asynchronous features were added to the C# and Visual Basic languages. These features add a task-based model for performing asynchronous operations.
In the .NET Framework 4.5, the following features have been added to make it simpler to write and maintain Windows Communication Foundation (WCF) applications:
For more information and access to reference links, please visit:
===========.Net 4.5 Poster=========
May be it's too late. Your code is correct so please check again your url in filebrowserUploadUrl
CKEDITOR.replace( 'editor1', {
filebrowserUploadUrl: "upload/upload.php"
} );
And the Upload.php file
if (file_exists("images/" . $_FILES["upload"]["name"]))
{
echo $_FILES["upload"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["upload"]["tmp_name"],
"images/" . $_FILES["upload"]["name"]);
echo "Stored in: " . "images/" . $_FILES["upload"]["name"];
}
My windows laptop has both the clients 32 & 64 bit I started facing all of sudden then I reordered the path variable like below
Before:
C:\app\oracle64\product\12.1.0\client_1\bin;
C:\app\oracle32\product\12.1.0\client_1\bin;
After:
C:\app\oracle32\product\12.1.0\client_1\bin;
C:\app\oracle64\product\12.1.0\client_1\bin;
started working... Hope this helps everyone.
Your code is throwing on com.example.tabwithslidingdrawer.MainActivity.onCreate(MainActivity.java:95)
:
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
The problem is pretty simple- your Activity
is inheriting from the new android.support.v7.app.ActionBarActivity
. You should be using a call to getSupportActionBar()
instead of getActionBar()
.
If you look above around line 65 of your code you'll see that you're already doing that:
actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
// TODO: Remove the redundant calls to getSupportActionBar()
// and use variable actionBar instead
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
And then lower down around line 87 it looks like you figured out the same:
getSupportActionBar().setTitle(
Html.fromHtml("<font color=\"black\">" + mTitle + " - "
+ menutitles[0] + "</font>"));
// getActionBar().setTitle(mTitle +menutitles[0]);
Notice how you commented out getActionBar()
.
In Boost.Test there is the --auto_start_dbg
parameter for breaking into the debugger when a test fails (on an exception or on an assertion failure). For some reason it doesn't work for me.
For this reason I have created my custom test_observer that will break into the debugger when there is an assertion failure or an exception. This is enabled on debug builds when we are running under a debugger.
In one of the source files of my unit test EXE file I have added this code:
#ifdef _DEBUG
#include <boost/test/framework.hpp>
#include <boost/test/test_observer.hpp>
struct BoostUnitTestCrtBreakpointInDebug: boost::unit_test::test_observer
{
BoostUnitTestCrtBreakpointInDebug()
{
boost::unit_test::framework::register_observer(*this);
}
virtual ~BoostUnitTestCrtBreakpointInDebug()
{
boost::unit_test::framework::deregister_observer(*this);
}
virtual void assertion_result( bool passed /* passed */ )
{
if (!passed)
BreakIfInDebugger();
}
virtual void exception_caught( boost::execution_exception const& )
{
BreakIfInDebugger();
}
void BreakIfInDebugger()
{
if (IsDebuggerPresent())
{
/**
* Hello, I know you are here staring at the debugger :)
*
* If you got here then there is an exception in your unit
* test code. Walk the call stack to find the actual cause.
*/
_CrtDbgBreak();
}
}
};
BOOST_GLOBAL_FIXTURE(BoostUnitTestCrtBreakpointInDebug);
#endif
You may find this version usefull.
-- Test DATA
select @@datefirst
create table #test (datum datetime)
insert #test values ('2013-01-01')
insert #test values ('2013-01-02')
insert #test values ('2013-01-03')
insert #test values ('2013-01-04')
insert #test values ('2013-01-05')
insert #test values ('2013-01-06')
insert #test values ('2013-01-07')
insert #test values ('2013-01-08')
-- Test DATA
select Substring('Sun,Mon,Tue,Wed,Thu,Fri,Sat,Sun,Mon,Tue,Wed,Thu,Fri,Sat',
(DATEPART(WEEKDAY,datum)+@@datefirst-1)*4+1,3),Datum
from #test
The short answer is: No. The only way to post images is through the mobile app.
From the Instagram API documentation: http://instagram.com/developer/endpoints/media/
At this time, uploading via the API is not possible. We made a conscious choice not to add this for the following reasons:
- Instagram is about your life on the go – we hope to encourage photos from within the app. However, in the future we may give whitelist access to individual apps on a case by case basis.
- We want to fight spam & low quality photos. Once we allow uploading from other sources, it's harder to control what comes into the Instagram ecosystem.
All this being said, we're working on ways to ensure users have a consistent and high-quality experience on our platform.
If all you want is the POST request body, you could use a method like this:
static String extractPostRequestBody(HttpServletRequest request) throws IOException {
if ("POST".equalsIgnoreCase(request.getMethod())) {
Scanner s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
return "";
}
Credit to: https://stackoverflow.com/a/5445161/1389219
I think the easiest is to simply open the file in write mode and then close it. For example, if your file myfile.dat
contains:
"This is the original content"
Then you can simply write:
f = open('myfile.dat', 'w')
f.close()
This would erase all the content. Then you can write the new content to the file:
f = open('myfile.dat', 'w')
f.write('This is the new content!')
f.close()
With Spring Boot JPA, use the below code in your application.properties file and obviously you can modify timezone to your choice
spring.jpa.properties.hibernate.jdbc.time_zone = UTC
Then in your Entity class file,
@Column
private LocalDateTime created;
Change your code to:
System.out.println("AM or PM?");
Scanner TimeOfDayQ = new Scanner(System.in);
TimeOfDayStringQ = TimeOfDayQ.next();
if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) { // <--
System.out.println("Sorry, incorrect input.");
System.exit(1);
}
...
if(Hours == 13){
if (TimeOfDayStringQ.equals("AM")) {
TimeOfDayStringQ = "PM"; // <--
} else {
TimeOfDayStringQ = "AM"; // <--
}
Hours = 1;
}
}
Please use this simple one liner:
Invoke-Expression "C:\'Program Files (x86)\Microsoft Office\root\Office16'\EXCEL.EXE"
PHP 7.0 $_SERVER varibales have changed. var_dump it and see how it fits your reqs.
some of them giving remote details are, REMOTE_ADDR HTTP_X_FORWARDED_FOR HTTP_CF_CONNECTING_IP HTTP_CF_IPCOUNTRY
UPDATE totals
SET total = total + 1
WHERE name = 'bill';
If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:
UPDATE totals
SET total = total + 1
WHERE name = 'bill'
AND total = 203;
You can cheat! Say your div is 20px high, place the div at the top of the next container and set
position: absolute;
top: -20px;
It may not be semantically clean but does scale with responsive designs
An addition to the other answers concerning object comparison:
== compares objects using the name of the object and their values. If two objects are of the same type and have the same member values, $a == $b
yields true.
=== compares the internal object id of the objects. Even if the members are equal, $a !== $b
if they are not exactly the same object.
class TestClassA {
public $a;
}
class TestClassB {
public $a;
}
$a1 = new TestClassA();
$a2 = new TestClassA();
$b = new TestClassB();
$a1->a = 10;
$a2->a = 10;
$b->a = 10;
$a1 == $a1;
$a1 == $a2; // Same members
$a1 != $b; // Different classes
$a1 === $a1;
$a1 !== $a2; // Not the same object
try below code
Directory.GetFiles(txtFolderPath.Text, "*ProfileHandler.cs",SearchOption.AllDirectories)
SELECT *
FROM Customer
WHERE (I.IsClose=@ISClose OR @ISClose is NULL)
AND (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )
AND (isnull(@Value,1) <> 2
OR I.RecurringCharge = @Total
OR @Total is NULL )
AND (isnull(@Value,2) <> 3
OR I.RecurringCharge like '%'+cast(@Total as varchar(50))+'%'
OR @Total is NULL )
Basically, your condition was
if (@Value=2)
TEST FOR => (I.RecurringCharge=@Total or @Total is NULL )
flipped around,
AND (isnull(@Value,1) <> 2 -- A
OR I.RecurringCharge = @Total -- B
OR @Total is NULL ) -- C
When (A) is true, i.e. @Value is not 2, [A or B or C] will become TRUE regardless of B and C results. B and C are in reality only checked when @Value = 2
, which is the original intention.
I was puzzled by this also... didn't like the parentheses that windows puts in when you rename in bulk. In my research I decided to write a script with PowerShell instead. Super easy and worked like a charm. Now I can use it whenever I need to batch process file renaming... which is frequent. I take hundreds of photos and the camera names them IMG1234.JPG etc...
Here is the script I wrote:
# filename: bulk_file_rename.ps1
# by: subcan
# PowerShell script to rename multiple files within a folder to a
# name that increments without (#)
# create counter
$int = 1
# ask user for what they want
$regex = Read-Host "Regex for files you are looking for? ex. IMG*.JPG "
$file_name = Read-Host "What is new file name, without extension? ex. New Image "
$extension = Read-Host "What extension do you want? ex. .JPG "
# get a total count of the files that meet regex
$total = Get-ChildItem -Filter $regex | measure
# while loop to rename all files with new name
while ($int -le $total.Count)
{
# diplay where in loop you are
Write-Host "within while loop" $int
# create variable for concatinated new name -
# $int.ToString(000) ensures 3 digit number 001, 010, etc
$new_name = $file_name + $int.ToString(000)+$extension
# get the first occurance and rename
Get-ChildItem -Filter $regex | select -First 1 | Rename-Item -NewName $new_name
# display renamed file name
Write-Host "Renamed to" $new_name
# increment counter
$int++
}
I hope that this is helpful to someone out there.
subcan
I had the same issue and solved just add a piece of code, If you are getting this issue means you had already completed all the steps that need to use Firebase. You just need to create a class that extends the Application (public class Application_CrashReport extends Application ) and add this class in mainifest file and In that class just override the below method
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
}
and add MultiDex.install(this); in that method means
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
Note :- Don't forget to follow above steps
Right click on the spring boot project -> debug as -> spring boot App
. Put a debugger point and invoke the app from a client like postman
Here is my solution (derived from SaraubhM
's answer)
**Jump To**: [Hotkeys & Markers](#hotkeys-markers) / [Radii](#radii) / [Route Wizard 2.0](#route-wizard-2-0)
Which gives you:
Jump To: Hotkeys & Markers / Radii / Route Wizard 2.0
Note the changes from and
.
to -
and also the loss of the &
in the links.
From the other answers, the problem is that you're templating a typedef. The only "way" to do this is to use a templated class; ie, basic template metaprogramming.
template<class T> class vector_Typedefs {
/*typedef*/ struct array { //The typedef isn't necessary
size_t x;
T *ary;
};
//Any other templated typedefs you need. Think of the templated class like something
// between a function and namespace.
}
//An advantage is:
template<> class vector_Typedefs<bool>
{
struct array {
//Special behavior for the binary array
}
}
You should have to use DateTime.TryParseExact
.
var newDate = DateTime.ParseExact("20111120",
"yyyyMMdd",
CultureInfo.InvariantCulture);
OR
string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;
if (DateTime.TryParseExact(str,
format,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date))
{
//valid
}
@marknadal's solution wasn't grabbing hyphenated properties for me (e.g. max-width
), but changing the first for
loop in css2json()
made it work, and I suspect performs fewer iterations:
for (var i = 0; i < css.length; i += 1) {
s[css[i]] = css.getPropertyValue(css[i]);
}
Loops via length
rather than in,
retrieves via getPropertyValue()
rather than toLowerCase().
Further modification from JC_VA, take what he has, and replace the MyModelConverter with...
public class MyModelConverter : JsonConverter
{
//objectType is the type as specified for List<myModel> (i.e. myModel)
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.Load(reader); //json from myModelList > model
var list = Activator.CreateInstance(objectType) as System.Collections.IList; // new list to return
var itemType = objectType.GenericTypeArguments[0]; // type of the list (myModel)
if (token.Type.ToString() == "Object") //Object
{
var child = token.Children();
var newObject = Activator.CreateInstance(itemType);
serializer.Populate(token.CreateReader(), newObject);
list.Add(newObject);
}
else //Array
{
foreach (var child in token.Children())
{
var newObject = Activator.CreateInstance(itemType);
serializer.Populate(child.CreateReader(), newObject);
list.Add(newObject);
}
}
return list;
}
public override bool CanConvert(Type objectType)
{
return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
}
This should work for json that is either
myModelList{
model: [{ ... object ... }]
}
or
myModelList{
model: { ... object ... }
}
they will both end up being parsed as if they were
myModelList{
model: [{ ... object ... }]
}
quick answer
#include<stdio.h>
#include<time.h>
int main()
{
clock_t t1, t2;
t1 = clock();
int i;
for(i = 0; i < 1000000; i++)
{
int x = 90;
}
t2 = clock();
float diff = ((float)(t2 - t1) / 1000000.0F ) * 1000;
printf("%f",diff);
return 0;
}
If you want to get a constraint by the column or table names, or you want to get all the constraints in the database, look to other answers. However, if you're just looking for exactly what the question asks, namely, to "test if a given default constraint exists ... by the name of the constraint", then there's a much easier way.
Here's a future-proof answer that doesn't use the sysobjects
or other sys
tables at all:
IF object_id('DF_CONSTRAINT_NAME', 'D') IS NOT NULL BEGIN
-- constraint exists, work with it.
END
In C++ (without error checking):
std::string blob = ...; // assume blob is in the string
std::string query = "INSERT INTO foo (blob_column) VALUES (?);";
sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, query, query.size(), &stmt, nullptr);
sqlite3_bind_blob(stmt, 1, blob.data(), blob.size(),
SQLITE_TRANSIENT);
That can be SQLITE_STATIC
if the query will be executed before blob
gets destructed.
Just had to do something incredible similar to this. My code:
public T IsNull<T>(this object value, T nullAlterative)
{
if(value != DBNull.Value)
{
Type type = typeof(T);
if (type.IsGenericType &&
type.GetGenericTypeDefinition() == typeof(Nullable<>).GetGenericTypeDefinition())
{
type = Nullable.GetUnderlyingType(type);
}
return (T)(type.IsEnum ? Enum.ToObject(type, Convert.ToInt32(value)) :
Convert.ChangeType(value, type));
}
else
return nullAlternative;
}
Migration files must match the pattern *_*.php
, or else they won't be found. Since users.php
does not match this pattern (it has no underscore), this file will not be found by the migrator.
Ideally, you should be creating your migration files using artisan:
php artisan make:migration create_users_table
This will create the file with the appropriate name, which you can then edit to flesh out your migration. The name will also include the timestamp, to help the migrator determine the order of migrations.
You can also use the --create
or --table
switches to add a little bit more boilerplate to help get you started:
php artisan make:migration create_users_table --create=users
The documentation on migrations can be found here.
Try this
Replace
<Directory /usr/share/phpMyAdmin/>
<IfModule mod_authz_core.c>
# Apache 2.4
<RequireAny>
Require ip 127.0.0.1
Require ip ::1
</RequireAny>
</IfModule>
<IfModule !mod_authz_core.c>
# Apache 2.2
Order Deny,Allow
Deny from All
Allow from 127.0.0.1
Allow from ::1
</IfModule>
</Directory>
With this:
<Directory "/usr/share/phpMyAdmin/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Allow,Deny
Allow from all
</Directory>
Add the following line for ease of access:
Alias /phpmyadmin /usr/share/phpMyAdmin
Step 1: Create a class AppStatus in your project(you can give any other name also). Then please paste the given below lines into your code:
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
public class AppStatus {
private static AppStatus instance = new AppStatus();
static Context context;
ConnectivityManager connectivityManager;
NetworkInfo wifiInfo, mobileInfo;
boolean connected = false;
public static AppStatus getInstance(Context ctx) {
context = ctx.getApplicationContext();
return instance;
}
public boolean isOnline() {
try {
connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
connected = networkInfo != null && networkInfo.isAvailable() &&
networkInfo.isConnected();
return connected;
} catch (Exception e) {
System.out.println("CheckConnectivity Exception: " + e.getMessage());
Log.v("connectivity", e.toString());
}
return connected;
}
}
Step 2: Now to check if the your device has network connectivity then just add this code snippet where ever you want to check ...
if (AppStatus.getInstance(this).isOnline()) {
Toast.makeText(this,"You are online!!!!",8000).show();
} else {
Toast.makeText(this,"You are not online!!!!",8000).show();
Log.v("Home", "############################You are not online!!!!");
}
As per Jenkins Documentation,
BUILD_NUMBER
is used. This number is identify how many times jenkins run this build process
$BUILD_NUMBER
is general syntax for it.
Call $watch
with true
as the third argument:
$scope.$watch('form', function(newVal, oldVal){
console.log('changed');
}, true);
By default when comparing two complex objects in JavaScript, they will be checked for "reference" equality, which asks if the two objects refer to the same thing, rather than "value" equality, which checks if the values of all the properties of those objects are equal.
Per the Angular documentation, the third parameter is for objectEquality
:
When
objectEquality == true
, inequality of the watchExpression is determined according to theangular.equals
function. To save the value of the object for later comparison, theangular.copy
function is used. This therefore means that watching complex objects will have adverse memory and performance implications.
Why not:
onItemClick: function (event) {
event.currentTarget.style.backgroundColor = '#ccc';
},
render: function() {
return (
<div>
<ul>
<li onClick={this.onItemClick}>Component 1</li>
</ul>
</div>
);
}
And if you want to be more React-ive about it, you might want to set the selected item as state of its containing React component, then reference that state to determine the item's color within render
:
onItemClick: function (event) {
this.setState({ selectedItem: event.currentTarget.dataset.id });
//where 'id' = whatever suffix you give the data-* li attribute
},
render: function() {
return (
<div>
<ul>
<li onClick={this.onItemClick} data-id="1" className={this.state.selectedItem == 1 ? "on" : "off"}>Component 1</li>
<li onClick={this.onItemClick} data-id="2" className={this.state.selectedItem == 2 ? "on" : "off"}>Component 2</li>
<li onClick={this.onItemClick} data-id="3" className={this.state.selectedItem == 3 ? "on" : "off"}>Component 3</li>
</ul>
</div>
);
},
You'd want to put those <li>
s into a loop, and you need to make the li.on
and li.off
styles set your background-color
.
No need to add a containing div.
The default for the css "align-items" property is "stretch" which is what is causing your images to be stretched to its full original height. Setting the css "align-items" property to "flex-start" fixes your issue.
.slider {
display: flex;
align-items: flex-start; /* ADD THIS! */
}
I got similar problem
1: I tried to resolve with the answer which is marked correct above But I was not able to get the system setting which was quit amazing (On MacBook).
Most of the time such errors & issues comes because of replacing your grade file with other grade file ,due which gradel does not sync properly and while building the project issue comes . The issue is bascially related to non syncing for platform tools
Solution a: Go to File and then to Your project strucutre -modules -app-Properties -build tool version -click on options which is required for your project (if required build tool version not there chose any other). This will sync the grade file and now you can go to gradel and change target version and build tool version as per your requirement .you will prompted to download the required platform tool to sync it , now click on install tool version and let project to build
Solution b: Try Anuja Ans if you can get option of system setting and install platform tool.
Store Unique characters in list
Method 1:
uniue_char = list(set('aaabcabccd'))
#['a', 'b', 'c', 'd']
Method 2: By Loop ( Complex )
uniue_char = []
for c in 'aaabcabccd':
if not c in uniue_char:
uniue_char.append(c)
print(uniue_char)
#['a', 'b', 'c', 'd']
I like this light weight http request client called `unirest'
gem install unirest
usage:
response = Unirest.post "http://httpbin.org/post",
headers:{ "Accept" => "application/json" },
parameters:{ :age => 23, :foo => "bar" }
response.code # Status code
response.headers # Response headers
response.body # Parsed body
response.raw_body # Unparsed body