I ended up coming up with an alternative solution that solved the problem.
I've upvoted the other two answers that provided valid yet ugly solutions for an uglier question:)
Have you tried this?:
$string = '';
while($row = mysql_fetch_array($result))
{
//this will combine all the results into one string
$string .= '<img src="'.$row['name'].'" />
<div>'.$row['name'].'</div>
<div>'.$row['title'].'</div>
<div>'.$row['description'].'</div>
<div>'.$row['link'].'</div><br />';
//or this will add the individual result in an array
/*
$yourHtml[] = $row;
*/
}
then you echo the $tring to the place you want it to be
<div id="place_here">
<?php echo $string; ?>
<?php
//or
/*
echo '<img src="'.$yourHtml[0]['name'].'" />;//change the index, or you just foreach loop it
*/
?>
</div>
I create a div at the end of the body like that:
<div v-if="isPopup" class="outside" v-on:click="away()"></div>
Where .outside is :
.outside {
width: 100vw;
height: 100vh;
position: fixed;
top: 0px;
left: 0px;
}
And away() is a method in Vue instance :
away() {
this.isPopup = false;
}
Easy, works well.
if you want a nav bar do
ul{ list-style-type: none; } li{text-decoration: none;
with the < a > tag:
a:link {text-decoration: none}
You can do it this way:
=IF(E9>21,"Text 1",IF(AND(E9>=5,E9<=21),"Test 2","Text 3"))
Note I assume you meant >=
and <=
here since your description skipped the values 5
and 21
, but you can adjust these inequalities as needed.
Or you can do it this way:
=IF(E9>21,"Text 1",IF(E9<5,"Text 3","Text 2"))
Starting with version 3.5.0 of Mockito and using the InlineMockMaker
, you can now mock object constructions:
try (MockedConstruction mocked = mockConstruction(A.class)) {
A a = new A();
when(a.check()).thenReturn("bar");
}
Inside the try-with-resources
construct all object constructions are returning a mock.
To come full circle and include all versions of Visual Studio, @Myster originally stated that;
Pre Visual Studio 2015 the paths to applicationhost.config were:
%userprofile%\documents\iisexpress\config\applicationhost.config
%userprofile%\my documents\iisexpress\config\applicationhost.config
Visual Studio 2015/2017 path can be found at: (credit: @Talon)
$(solutionDir)\.vs\config\applicationhost.config
Visual Studio 2019 path can be found at: (credit: @Talon)
$(solutionDir)\.vs\config\$(ProjectName)\applicationhost.config
But the part that might get some people is that the project settings in the .sln file can repopulate the applicationhost.config for Visual Studio 2015+. (credit: @Lex Li)
So, if you make a change in the applicationhost.config you also have to make sure your changes match here:
$(solutionDir)\ProjectName.sln
The two important settings should look like:
Project("{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}") = "ProjectName", "ProjectPath\", "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"
and
VWDPort = "Port#"
What is important here is that the two settings in the .sln must match the name and bindingInformation respectively in the applicationhost.config file if you plan on making changes. There may be more places that link these two files and I will update as I find more links either by comments or more experience.
This worked for me...
double num = 10025000;
new DecimalFormat("#,###.##");
DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(Locale.GERMAN);
System.out.println(df.format(num));
[request setValue:@"application/zip" forHTTPHeaderField:@"Content-Type"];
List list1 = new ArrayList();
list1.add("one");
list1.add("three");
list1.add("four");
List list2 = new ArrayList();
list2.add("one");
list2.add("two");
list2.add("three");
list2.add("four");
list2.add("five");
list2.stream().filter( x -> !list1.contains(x) ).forEach(x -> System.out.println(x));
The output is:
two
five
Here's an alternative to the HeberLZ's answer, using npm scripts.
My package.json
:
"scripts": {
"watch": "nodemon -e ts -w ./src -x npm run watch:serve",
"watch:serve": "ts-node --inspect src/index.ts"
},
-e
flag sets the extenstions to look for,-w
sets the watched directory,-x
executes the script.--inspect
in the watch:serve
script is actually a node.js flag, it just enables debugging protocol.
To add my 2 cents, I got this same issue when I m accidentally sending null
as the ID. Below code depicts my scenario (and anyway OP didn't mention any specific scenario).
Employee emp = new Employee();
emp.setDept(new Dept(deptId)); // -----> when deptId PKID is null, same error will be thrown
// calls to other setters...
em.persist(emp);
Here I m setting the existing department id to a new employee instance without actually getting the department entity first, as I don't want to another select query to fire.
In some scenarios, deptId
PKID is coming as null
from calling method and I m getting the same error.
So, watch for null
values for PK ID
Same answer given here
In my case where the last component was non latin characters I did the following in Swift 2.2
:
extension String {
func encodeUTF8() -> String? {
//If I can create an NSURL out of the string nothing is wrong with it
if let _ = NSURL(string: self) {
return self
}
//Get the last component from the string this will return subSequence
let optionalLastComponent = self.characters.split { $0 == "/" }.last
if let lastComponent = optionalLastComponent {
//Get the string from the sub sequence by mapping the characters to [String] then reduce the array to String
let lastComponentAsString = lastComponent.map { String($0) }.reduce("", combine: +)
//Get the range of the last component
if let rangeOfLastComponent = self.rangeOfString(lastComponentAsString) {
//Get the string without its last component
let stringWithoutLastComponent = self.substringToIndex(rangeOfLastComponent.startIndex)
//Encode the last component
if let lastComponentEncoded = lastComponentAsString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet()) {
//Finally append the original string (without its last component) to the encoded part (encoded last component)
let encodedString = stringWithoutLastComponent + lastComponentEncoded
//Return the string (original string/encoded string)
return encodedString
}
}
}
return nil;
}
}
select count(distinct(column_name)) AS columndatacount from table_name where somecondition=true
You can use this query, to count different/distinct data. Thanks
OMG, I tried to find a simple solution to this for hours. I knew the code was simple but no one provided me what I wanted. So finally got to work on some example code and made something simple that anyone can use no JQuery required. Simple javascript and css and html. In order for the animation to work you have to set the height and width or the animation wont work. Found that out the hard way.
<script>
function dostuff() {
if (document.getElementById('MyBox').style.height == "0px") {
document.getElementById('MyBox').setAttribute("style", "background-color: #45CEE0; height: 200px; width: 200px; transition: all 2s ease;");
}
else {
document.getElementById('MyBox').setAttribute("style", "background-color: #45CEE0; height: 0px; width: 0px; transition: all 2s ease;");
}
}
</script>
<div id="MyBox" style="height: 0px; width: 0px;">
</div>
<input type="button" id="buttontest" onclick="dostuff()" value="Click Me">
Please make sure that you don't do any network access on UI Thread, instead do it in Async Task
The reason why your application crashes on Android versions 3.0 and above, but works fine on Android 2.x is because since HoneyComb are much stricter about abuse against the UI Thread. For example, when an Android device running HoneyComb or above detects a network access on the UI thread, a NetworkOnMainThreadException will be thrown.
See this
SO what i have decided to do finally is here and its working fine on all mobile browsers including iPhones and Androids.
$(document).ready(function(){_x000D_
_x000D_
$('input[type="date"]').each(function(e) {_x000D_
var $el = $(this), _x000D_
$this_placeholder = $(this).closest('label').find('.custom-placeholder');_x000D_
$el.on('change',function(){_x000D_
if($el.val()){_x000D_
$this_placeholder.text('');_x000D_
}else {_x000D_
$this_placeholder.text($el.attr('placeholder'));_x000D_
}_x000D_
});_x000D_
});_x000D_
_x000D_
});
_x000D_
label {_x000D_
position: relative; _x000D_
}_x000D_
.custom-placeholder {_x000D_
#font > .proxima-nova-light(26px,40px);_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
z-index: 10;_x000D_
color: #999;_x000D_
}
_x000D_
<label>_x000D_
<input type="date" placeholder="Date">_x000D_
<span class="custom-placeholder">Date</span>_x000D_
</label>
_x000D_
Date
Every time you are creating plots you might get this error - "Error in plot.new() : figure margins too large
". To avoid such errors you can first check par("mar")
output. You should be getting:
[1] 5.1 4.1 4.1 2.1
To change that write:
par(mar=c(1,1,1,1))
This should rectify the error. Or else you can change the values accordingly.
Hope this works for you.
Consider the following example,
import import { AfterViewInit, ViewChild } from '@angular/core';
import { Component } from '@angular/core';
import { CountdownTimerComponent } from './countdown-timer.component';
@Component({
selector: 'app-countdown-parent-vc',
templateUrl: 'app-countdown-parent-vc.html',
styleUrl: [app-countdown-parent-vc.css]
export class CreateCategoryComponent implements OnInit {
@ViewChild(CountdownTimerComponent, {static: false})
private timerComponent: CountdownTimerComponent;
ngAfterViewInit() {
this.timerComponent.startTimer();
}
submitNewCategory(){
this.ngAfterViewInit();
}
Read more about @ViewChild here.
We are used to
class ClassTypeA implements InterfaceTypeA {}
class ClassTypeB extends ClassTypeA {}
and any slight deviation from these rules greatly confuses us.
The syntax of a type bound is defined as
TypeBound:
extends TypeVariable
extends ClassOrInterfaceType {AdditionalBound}
(JLS 12 > 4.4. Type Variables > TypeBound
)
If we were to change it, we would surely add the implements
case
TypeBound:
extends TypeVariable
extends ClassType {AdditionalBound}
implements InterfaceType {AdditionalBound}
and end up with two identically processed clauses
ClassOrInterfaceType:
ClassType
InterfaceType
(JLS 12 > 4.3. Reference Types and Values > ClassOrInterfaceType
)
except we would also need to take care of implements
, which would complicate things further.
I believe it's the main reason why extends ClassOrInterfaceType
is used instead of extends ClassType
and implements InterfaceType
- to keep things simple within the complicated concept. The problem is we don't have the right word to cover both extends
and implements
and we definitely don't want to introduce one.
<T is ClassTypeA>
<T is InterfaceTypeA>
Although extends
brings some mess when it goes along with an interface, it's a broader term and it can be used to describe both cases. Try to tune your mind to the concept of extending a type (not extending a class, not implementing an interface). You restrict a type parameter by another type and it doesn't matter what that type actually is. It only matters that it's its upper bound and it's its supertype.
(trunc(random() * 10) % 10) + 1
CSS:
.topmenu ul li.active a, .topmenu ul li a:hover {
text-decoration:none;
color:#fff;
background:url(../images/menu_a.jpg) no-repeat center top;
}
JavaScript:
<script src="JavaScript/jquery-1.10.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
// this will get the full URL at the address bar
var url = window.location.href;
// passes on every "a" tag
$(".topmenu a").each(function() {
// checks if its the same on the address bar
if (url == (this.href)) {
$(this).closest("li").addClass("active");
//for making parent of submenu active
$(this).closest("li").parent().parent().addClass("active");
}
});
});
</script>
Html Code:
<div class="topmenu">
<ul>
<li><a href="Default.aspx">Home</a></li>
<li><a href="NewsLetter.aspx">Newsletter</a></li>
<li><a href="#">Forms</a></li>
<li><a href="#">Mail</a></li>
<li><a href="#">Service</a></li>
<li style="border:none;"><a href="#">HSE</a></li>
<li><a href="#">MainMenu2</a>
<ul>
<li>submenu1</li>
<li>submenu2</li>
<li>submenu3</li>
</ul>
</li>
</ul>
</div>
wrap a <span>
around those words and style with the appropriate color
now is the time for <span style='color:orange'>all good men</span> to come to the
A submodule may be marked as dirty if filemode settings is enabled and you changed file permissions in submodule subtree.
To disable filemode in a submodule, you can edit /.git/modules/path/to/your/submodule/config and add
[core]
filemode = false
If you want to ignore all dirty states, you can either set ignore = dirty
property in /.gitmodules file, but I think it's better to only disable filemode.
In the OnStart
method, do the following.
protected override void OnStart(string[] args)
{
try
{
RequestAdditionalTime(600000);
System.Diagnostics.Debugger.Launch(); // Put breakpoint here.
.... Your code
}
catch (Exception ex)
{
.... Your exception code
}
}
Then run a command prompt as administrator and put in the following:
c:\> sc create test-xyzService binPath= <ProjectPath>\bin\debug\service.exe type= own start= demand
The above line will create test-xyzService in the service list.
To start the service, this will prompt you to attach to debut in Visual Studio or not.
c:\> sc start text-xyzService
To stop the service:
c:\> sc stop test-xyzService
To delete or uninstall:
c:\> sc delete text-xyzService
git clone https://github.com/ORGANIZATION/repository.git
(clone the repository)
cd repository (navigate to the repository)
git fetch origin 2600f4f928773d79164964137d514b85400b09b2
git checkout FETCH_HEAD
If you're more used to using ax
objects to do your plotting, you might find the ax.xaxis.label.set_size()
easier to remember, or at least easier to find using tab in an ipython terminal. It seems to need a redraw operation after to see the effect. For example:
import matplotlib.pyplot as plt
# set up a plot with dummy data
fig, ax = plt.subplots()
x = [0, 1, 2]
y = [0, 3, 9]
ax.plot(x,y)
# title and labels, setting initial sizes
fig.suptitle('test title', fontsize=12)
ax.set_xlabel('xlabel', fontsize=10)
ax.set_ylabel('ylabel', fontsize='medium') # relative to plt.rcParams['font.size']
# setting label sizes after creation
ax.xaxis.label.set_size(20)
plt.draw()
I don't know of a similar way to set the suptitle size after it's created.
For having a trasition effect like a highlighter just to highlight the text and fade off the bg color, we used the following:
.field-error {_x000D_
color: #f44336;_x000D_
padding: 2px 5px;_x000D_
position: absolute;_x000D_
font-size: small;_x000D_
background-color: white;_x000D_
}_x000D_
_x000D_
.highlighter {_x000D_
animation: fadeoutBg 3s; /***Transition delay 3s fadeout is class***/_x000D_
-moz-animation: fadeoutBg 3s; /* Firefox */_x000D_
-webkit-animation: fadeoutBg 3s; /* Safari and Chrome */_x000D_
-o-animation: fadeoutBg 3s; /* Opera */_x000D_
}_x000D_
_x000D_
@keyframes fadeoutBg {_x000D_
from { background-color: lightgreen; } /** from color **/_x000D_
to { background-color: white; } /** to color **/_x000D_
}_x000D_
_x000D_
@-moz-keyframes fadeoutBg { /* Firefox */_x000D_
from { background-color: lightgreen; }_x000D_
to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeoutBg { /* Safari and Chrome */_x000D_
from { background-color: lightgreen; }_x000D_
to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-o-keyframes fadeoutBg { /* Opera */_x000D_
from { background-color: lightgreen; }_x000D_
to { background-color: white; }_x000D_
}
_x000D_
<div class="field-error highlighter">File name already exists.</div>
_x000D_
I had a similar error after php update. PHP fixed a security bug where o
had rw
permission to the socket file.
/etc/php5/fpm/pool.d/www.conf
or /etc/php/7.0/fpm/pool.d/www.conf
, depending on your version. Uncomment all permission lines, like:
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
Restart fpm - sudo service php5-fpm restart
or sudo service php7.0-fpm restart
Note: if your webserver runs as user other than www-data, you will need to update the www.conf
file accordingly
This would work just fine, set the height to desired pixel
#inner-right{
height: 100px;
overflow:auto;
}
char * bufSecs = new char[32];
char * bufMs = new char[32];
sprintf(bufSecs, "%d", timeStart.elapsed()/1000);
sprintf(bufMs, "%d", timeStart.elapsed()%1000);
I think this is the most comprehensive answer on the PostgreSQL wiki itself: https://wiki.postgresql.org/wiki/BinaryFilesInDB
Read the part with the title 'What is the best way to store the files in the Database?'
ALTER won't do it because column order does not matter for storage or querying
If SQL Server, you'd have to use the SSMS Table Designer to arrange your columns, which can then generate a script which drops and recreates the table
Edit Jun 2013
Cross link to my answer here: Performance / Space implications when ordering SQL Server columns?
You can also try react-native-extended-stylesheet that supports percentage for single-orientation apps:
import EStyleSheet from 'react-native-extended-stylesheet';
const styles = EStyleSheet.create({
column: {
width: '80%',
height: '50%',
marginLeft: '10%'
}
});
This OTN-thread contains several ways to do string aggregation, including a performance comparison: http://forums.oracle.com/forums/message.jspa?messageID=1819487#1819487
My .zip file was formatted correctly (I think) but it wasn't working. Even unchecking "Group items by category" didn't work
To install it I did so:
At this point Eclipse read the plugin correctly, I went ahead, accepted the conditions and then asked me to restart the IDE.
Try to configure the setting of your projects, it is usually due to x86/x64 architecture problems:
Go and set your choice as shown:
First you need to find a row with id == 2 then change the name so:
foreach(DataRow dr in table.Rows) // search whole table
{
if(dr["Product_id"] == 2) // if id==2
{
dr["Product_name"] = "cde"; //change the name
//break; break or not depending on you
}
}
You could also try these solutions:
table.Rows[1]["Product_name"] = "cde" // not recommended as it selects 2nd row as I know that it has id 2
Or:
DataRow dr = table.Select("Product_id=2").FirstOrDefault(); // finds all rows with id==2 and selects first or null if haven't found any
if(dr != null)
{
dr["Product_name"] = "cde"; //changes the Product_name
}
Now you can use nameof
:
public static void Output<T>(IEnumerable<T> dataSource) where T : class
{
string dataSourceName = typeof(T).Name;
switch (dataSourceName)
{
case nameof(CustomerDetails):
var t = 123;
break;
default:
Console.WriteLine("Test");
}
}
nameof(CustomerDetails)
is basically identical to the string literal "CustomerDetails"
, but with a compile-time check that it refers to some symbol (to prevent a typo).
nameof
appeared in C# 6.0, so after this question was asked.
This is because keypress
events are fired before the new character is added to the value
of the element (so the first keypress
event is fired before the first character is added, while the value
is still empty). You should use keyup
instead, which is fired after the character has been added.
Note that, if your element #dSuggest
is the same as input:text[name=dSuggest]
you can simplify this code considerably (and if it isn't, having an element with a name that is the same as the id
of another element is not a good idea).
$('#dSuggest').keypress(function() {
var dInput = this.value;
console.log(dInput);
$(".dDimension:contains('" + dInput + "')").css("display","block");
});
The .htaccess is either in the root-directory of your webpage or in the directory you want to protect.
Make sure to make them visible in your filesystem, because AFAIK (I'm no unix expert either) files starting with a period are invisible by default on unix-systems.
Try with:
$row = mysqli_fetch_assoc($result);
echo "my result <a href='data/" . htmlentities($row['classtype'], ENT_QUOTES, 'UTF-8') . ".php'>My account</a>";
If using AngularJS 1.2 you can use 'track by' to tell Angular how to compare objects.
<select
ng-model="Choice.SelectedOption"
ng-options="choice.Name for choice in Choice.Options track by choice.ID">
</select>
Updated fiddle http://jsfiddle.net/gFCzV/34/
you just make a list of lists like so:
List<List<string>> results = new List<List<string>>();
and then it's just a matter of using the functionality you want
results.Add(new List<string>()); //adds a new list to your list of lists
results[0].Add("this is a string"); //adds a string to the first list
results[0][0]; //gets the first string in your first list
It sounds to me as if you actually mean "linux guests" and not "linux hosts".
But in any case, I suspect you did not install the VMWare Tools: doubleclick on that icon on the Desktop that can be seen on your screenshot. It will install some drivers that communicate with VMWare that, among other things, allow to adjust the screen resolution dynamically.
When the installation process is finished, you'll most likely have to reboot the VM.
This is how I would do it, in order to get in the var4 restriction:
dfr<-data.frame(var1=rnorm(100), var2=rnorm(100), var3=rnorm(100, 160, 10), var4=rnorm(100, 27, 6))
plot( subset( dfr, var3 < 155 & var4 > 27, select = c( var1, var2 ) ) )
Rgds, Rainer
Please select the same in the outer select. You can't access the alias name in the same query.
SELECT *, (CASE
WHEN articleNumber < 2 THEN 'Ama'
WHEN articleNumber < 5 THEN 'SemiAma'
WHEN articleNumber < 7 THEN 'Good'
WHEN articleNumber < 9 THEN 'Better'
WHEN articleNumber < 12 THEN 'Best'
ELSE 'Outstanding'
END) AS ranking
FROM(
SELECT registrationDate, (SELECT COUNT(*) FROM Articles WHERE Articles.userId = Users.userId) as articleNumber,
hobbies, etc...
FROM USERS
)x
The END
comes from the pager used to display the log (your are at that moment still inside it). Type q to exit it.
Swift 3 & 4/5
self.navigationController!.viewControllers.removeAll()
self.navigationController?.viewControllers.remove(at: "insert here a number")
Swift 2.1
remove all:
self.navigationController!.viewControllers.removeAll()
remove at index
self.navigationController?.viewControllers.removeAtIndex("insert here a number")
There a bunch of more possible actions like removeFirst,range etc.
For those using python 3+
import requests
import logging
import http.client
http.client.HTTPConnection.debuglevel = 1
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
Based on @EdChum's answer, you can try the following solution:
df[df.columns[pd.Series(df.columns).str.contains("foo")]]
This will be really helpful in case not all the columns you want to select start with foo
. This method selects all the columns that contain the substring foo
and it could be placed in at any point of a column's name.
In essence, I replaced .startswith()
with .contains()
.
I have JSONObject like this: {"status":[{"Response":"success"}]}
.
If I want to convert the JSONObject value, which is a JSONArray into JSONObject automatically without using any static value, here is the code for that.
JSONArray array=new JSONArray();
JSONObject obj2=new JSONObject();
obj2.put("Response", "success");
array.put(obj2);
JSONObject obj=new JSONObject();
obj.put("status",array);
Converting the JSONArray to JSON Object:
Iterator<String> it=obj.keys();
while(it.hasNext()){
String keys=it.next();
JSONObject innerJson=new JSONObject(obj.toString());
JSONArray innerArray=innerJson.getJSONArray(keys);
for(int i=0;i<innerArray.length();i++){
JSONObject innInnerObj=innerArray.getJSONObject(i);
Iterator<String> InnerIterator=innInnerObj.keys();
while(InnerIterator.hasNext()){
System.out.println("InnInnerObject value is :"+innInnerObj.get(InnerIterator.next()));
}
}
In your doSomething()
function, pass in the event e
and use e.preventDefault()
.
doSomething = function (e) {
alert('it works!');
e.preventDefault();
}
If the text is a simple markup and has existing anchors, stage the existing anchor tags first, swap out the urls, then replace the staged markers.
$text = '
Lorem Ipsum is simply dummy text found by searching http://google.com/?q=lorem in your <a href=https://www.mozilla.org/en-US/firefox/>Firefox</a>,
<a href="https://www.apple.com/safari/">Safari</a>, or https://www.google.com/chrome/ browser.
Link replacements will first stage existing anchor tags, replace each with a marker, then swap out the remaining links.
Links should be properly encoded. If links are not separated from surrounding content like a trailing "." period then they it will be included in the link.
Links that are not encoded properly may create a problem, so best to use this when you know the text you are processing is not mixed HTML.
Example: http://google.com/i,m,complicate--d/index.html
Example: https://www.google.com/chrome/?123&t=123
Example: http://google.com/?q='. urlencode('<a href="http://google.com">http://google.com</a>') .'
';
// Replace existing links with a marker
$linkStore = array();
$text = preg_replace_callback('/(<a.*?a>)/', function($match) use (&$linkStore){ $key = '__linkStore'.count($linkStore).'__'; $linkStore[$key] = $match[0]; return $key; }, $text);
// Replace remaining URLs with an anchor tag
$text = preg_replace_callback("/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/", function($match) use (&$linkStore){ return '<a href="'. $match[0] .'">'. $match[0] .'</a>'; }, $text);
// Replace link markers with original
$text = str_replace(array_keys($linkStore), array_values($linkStore), $text);
echo '<pre>'.$text;
I use the following:
Function GetProgramOutput([string]$exe, [string]$arguments)
{
$process = New-Object -TypeName System.Diagnostics.Process
$process.StartInfo.FileName = $exe
$process.StartInfo.Arguments = $arguments
$process.StartInfo.UseShellExecute = $false
$process.StartInfo.RedirectStandardOutput = $true
$process.StartInfo.RedirectStandardError = $true
$process.Start()
$output = $process.StandardOutput.ReadToEnd()
$err = $process.StandardError.ReadToEnd()
$process.WaitForExit()
$output
$err
}
$exe = "C:\Program Files\7-Zip\7z.exe"
$arguments = "i"
$runResult = (GetProgramOutput $exe $arguments)
$stdout = $runResult[-2]
$stderr = $runResult[-1]
[System.Console]::WriteLine("Standard out: " + $stdout)
[System.Console]::WriteLine("Standard error: " + $stderr)
To expand on the above and make a quick reference:
ALTER USER username WITH SUPERUSER;
ALTER USER username WITH NOSUPERUSER;
ALTER USER username CREATEDB;
You can also use CREATEROLE
and CREATEUSER
to allow a user privileges without making them a superuser.
A shorter alternative to the previously mentioned stash approach would be:
Temporarily move the changes to a stash.
git stash
Create and switch to a new branch and then pop the stash to it in just one step.
git stash branch new_branch_name
Then just add
and commit
the changes to this new branch.
As for front-end developer many time we are dealing with the forms in which we have to handle the dropdowns and we have to use the value of selected dropdown to perform some action or the send the value on the Server, it's very simple you have to write the simple dropdown in HTML just put the one onChange method for the selection in the dropdown whenever user change the value of dropdown set that value to state so you can easily access it in AvFeaturedPlayList 1 remember you will always get the result as option value and not the dropdown text which is displayed on the screen
import React, { Component } from "react";
import { Server } from "net";
class InlineStyle extends Component {
constructor(props) {
super(props);
this.state = {
selectValue: ""
};
this.handleDropdownChange = this.handleDropdownChange.bind(this);
}
handleDropdownChange(e) {
this.setState({ selectValue: e.target.value });
}
render() {
return (
<div>
<div>
<div>
<select id="dropdown" onChange={this.handleDropdownChange}>
<option value="N/A">N/A</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<div>Selected value is : {this.state.selectValue}</div>
</div>
</div>
);
}
}
export default InlineStyle;
Another option is to delete all the classes and rebuild. Having build file is an ideal solution to control whole process like compilation, packaging and deployment. You can also specify source/target versions
Use the mapfile
command:
mapfile -t myArray < file.txt
The error is using for
-- the idiomatic way to loop over lines of a file is:
while IFS= read -r line; do echo ">>$line<<"; done < file.txt
See BashFAQ/005 for more details.
issue resolved in my case by changing delete
to truncate
issue- query:
delete from Survey1.sr_survey_generic_details
mycursor.execute(query)
fix- query:
truncate table Survey1.sr_survey_generic_details
mycursor.execute(query)
Suppose you wanted to cast a String
to a File
(yes it does not make any sense), you cannot cast it directly because the File
class is not a child and not a parent of the String
class (and the compiler complains).
But you could cast your String
to Object
, because a String
is an Object
(Object
is parent). Then you could cast this object to a File
, because a File is an Object
.
So all you operations are 'legal' from a typing point of view at compile time, but it does not mean that it will work at runtime !
File f = (File)(Object) "Stupid cast";
The compiler will allow this even if it does not make sense, but it will crash at runtime with this exception:
Exception in thread "main" java.lang.ClassCastException:
java.lang.String cannot be cast to java.io.File
This reads a line of text from standard input and prints out the characters in the line and their ASCII codes:
#include <stdio.h>
void printChars(void)
{
unsigned char line[80+1];
int i;
// Read a text line
if (fgets(line, 80, stdin) == NULL)
return;
// Print the line chars
for (i = 0; line[i] != '\n'; i++)
{
int ch;
ch = line[i];
printf("'%c' %3d 0x%02X\n", ch, ch, (unsigned)ch);
}
}
//"Comment" Filter datagrid without changing dataset,Perfectly works.
(dg.ItemsSource as ListCollectionView).Filter = (d) =>
{
DataRow myRow = ((System.Data.DataRowView)(d)).Row;
if (myRow["FName"].ToString().ToUpper().Contains(searchText.ToString().ToUpper()) || myRow["LName"].ToString().ToUpper().Contains(searchText.ToString().ToUpper()))
return true; //if want to show in grid
return false; //if don't want to show in grid
};
The other answers are all good. For Xilinx FPGA designs, it is best not to use global reset lines, and use initial
blocks for reset conditions for most logic. Here is the white paper from Ken Chapman (Xilinx FPGA guru)
http://japan.xilinx.com/support/documentation/white_papers/wp272.pdf
Even more useful, if you have multiple parameters you can access any/all of them with:
_mock.Setup(x => x.DoSomething(It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>())
.Returns((string a, string b, string c) => string.Concat(a,b,c));
You always need to reference all the arguments, to match the method's signature, even if you're only going to use one of them.
git log
's pickaxe will find commits with changes including "word" with git log -Sword
I haven't fully explored the TPL but they might have something that fits your needs, or at the very least, some Reflector fodder to snag some inspiration from.
Hope that helps.
I used Joe's way to solve this issue :)
decimal argument = 123.456m;
int count = BitConverter.GetBytes(decimal.GetBits(argument)[3])[2];
Here is a much faster version, which doesn't use regular expressions, nor encodeURIComponent():
function byteLength(str) {
// returns the byte length of an utf8 string
var s = str.length;
for (var i=str.length-1; i>=0; i--) {
var code = str.charCodeAt(i);
if (code > 0x7f && code <= 0x7ff) s++;
else if (code > 0x7ff && code <= 0xffff) s+=2;
if (code >= 0xDC00 && code <= 0xDFFF) i--; //trail surrogate
}
return s;
}
Here is a performance comparison.
It just computes the length in UTF8 of each unicode codepoints returned by charCodeAt() (based on wikipedia's descriptions of UTF8, and UTF16 surrogate characters).
It follows RFC3629 (where UTF-8 characters are at most 4-bytes long).
In terms of the optimizer, it shouldn't make a difference whether you define your join clauses with ON or WHERE.
However, IMHO, I think it's much clearer to use the ON clause when performing joins. That way you have a specific section of you query that dictates how the join is handled versus intermixed with the rest of the WHERE clauses.
Seems you need to use JToggleButton
:
JToggleButton tb = new JToggleButton("push me");
tb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JToggleButton btn = (JToggleButton) e.getSource();
btn.setText(btn.isSelected() ? "pushed" : "push me");
}
});
this
is a reference for the DOM element for which the event is being handled (the current target). event.target
refers to the element which initiated the event. They were the same in this case, and can often be, but they aren't necessarily always so.
You can get a good sense of this by reviewing the jQuery event docs, but in summary:
event.currentTarget
The current DOM element within the event bubbling phase.
event.delegateTarget
The element where the currently-called jQuery event handler was attached.
event.relatedTarget
The other DOM element involved in the event, if any.
event.target
The DOM element that initiated the event.
To get the desired functionality using jQuery, you must wrap it in a jQuery object using either: $(this)
or $(evt.target)
.
The .attr()
method only works on a jQuery object, not on a DOM element. $(evt.target).attr('href')
or simply evt.target.href
will give you what you want.
Making Changes to the answer by danh32 since the display.getWidth(); is now deprecated.
private int getScale(){
Point p = new Point();
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
display.getSize(p);
int width = p.x;
Double val = new Double(width)/new Double(PIC_WIDTH);
val = val * 100d;
return val.intValue();
}
Then use
WebView web = new WebView(this);
web.setPadding(0, 0, 0, 0);
web.setInitialScale(getScale());
You can include your header function wherever you like, as long as NO html and/or text has been printed to standard out.
For more information and usage: http://php.net/manual/en/function.header.php
I see in your code that you echo()
out some text in case of error or success. Don't do that: you can't. You can only redirect OR show the text. If you show the text you'll then fail to redirect.
Basically, no difference. The only consistent trend is that Python seems to be getting slower with every version... :(
%%timeit
x = []
for i in range(100000000): # xrange on Python 2.7
x.append('a')
x = ''.join(x)
Python 2.7
1 loop, best of 3: 7.34 s per loop
Python 3.4
1 loop, best of 3: 7.99 s per loop
Python 3.5
1 loop, best of 3: 8.48 s per loop
Python 3.6
1 loop, best of 3: 9.93 s per loop
%%timeit
x = ''
for i in range(100000000): # xrange on Python 2.7
x += 'a'
Python 2.7:
1 loop, best of 3: 7.41 s per loop
Python 3.4
1 loop, best of 3: 9.08 s per loop
Python 3.5
1 loop, best of 3: 8.82 s per loop
Python 3.6
1 loop, best of 3: 9.24 s per loop
Specify POST method in form
<form name="registrationform" action="register.php" method="post">
your form code
</form>
You can use res.json() to jsonify any object. lean() will remove all the empty fields in the mongoose query.
UserModel.find().lean().exec(function (err, users) {
return res.json(users);
}
you cannot set this in javascript, you have to do this with html/css:
<style type="text/css" media="print">
@page { size: landscape; }
</style>
EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?
Right click on the particular element (e.g. div
, table
, td
) and select the copy as html.
If you're not using the storyboard. You can initialize your main view controller programmatically.
Swift 4
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let rootViewController = MainViewController()
let navigationController = UINavigationController(rootViewController: rootViewController)
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
return true
}
class MainViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .green
}
}
And also remove Main
from Deployment Info.
You can also have a look at the method findText(const QString & text) from QComboBox; it returns the index of the element which contains the given text, (-1 if not found). The advantage of using this method is that you don't need to set the second parameter when you add an item.
Here is a little example :
/* Create the comboBox */
QComboBox *_comboBox = new QComboBox;
/* Create the ComboBox elements list (here we use QString) */
QList<QString> stringsList;
stringsList.append("Text1");
stringsList.append("Text3");
stringsList.append("Text4");
stringsList.append("Text2");
stringsList.append("Text5");
/* Populate the comboBox */
_comboBox->addItems(stringsList);
/* Create the label */
QLabel *label = new QLabel;
/* Search for "Text2" text */
int index = _comboBox->findText("Text2");
if( index == -1 )
label->setText("Text2 not found !");
else
label->setText(QString("Text2's index is ")
.append(QString::number(_comboBox->findText("Text2"))));
/* setup layout */
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(_comboBox);
layout->addWidget(label);
All we want is parent above child. This is how you do it.
You put img
into span
, set z-index & position
for both elements, and extra display
for span. Add hover to span
so you can test it and you got it!
HTML:
<span><img src="/images/"></span>
CSS
span img {
position:relative;
z-index:-1;
}
span {
position:relative;
z-index:initial;
display:inline-block;
}
span:hover {
background-color:#000;
}
I couldnt find a simple working example anywhere (as of Jan 19), so here is an updated version. I have chrome version 71.0.3578.98.
C# Websocket server :
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
namespace WebSocketServer
{
class Program
{
static Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
static void Main(string[] args)
{
serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));
serverSocket.Listen(1); //just one socket
serverSocket.BeginAccept(null, 0, OnAccept, null);
Console.Read();
}
private static void OnAccept(IAsyncResult result)
{
byte[] buffer = new byte[1024];
try
{
Socket client = null;
string headerResponse = "";
if (serverSocket != null && serverSocket.IsBound)
{
client = serverSocket.EndAccept(result);
var i = client.Receive(buffer);
headerResponse = (System.Text.Encoding.UTF8.GetString(buffer)).Substring(0, i);
// write received data to the console
Console.WriteLine(headerResponse);
Console.WriteLine("=====================");
}
if (client != null)
{
/* Handshaking and managing ClientSocket */
var key = headerResponse.Replace("ey:", "`")
.Split('`')[1] // dGhlIHNhbXBsZSBub25jZQ== \r\n .......
.Replace("\r", "").Split('\n')[0] // dGhlIHNhbXBsZSBub25jZQ==
.Trim();
// key should now equal dGhlIHNhbXBsZSBub25jZQ==
var test1 = AcceptKey(ref key);
var newLine = "\r\n";
var response = "HTTP/1.1 101 Switching Protocols" + newLine
+ "Upgrade: websocket" + newLine
+ "Connection: Upgrade" + newLine
+ "Sec-WebSocket-Accept: " + test1 + newLine + newLine
//+ "Sec-WebSocket-Protocol: chat, superchat" + newLine
//+ "Sec-WebSocket-Version: 13" + newLine
;
client.Send(System.Text.Encoding.UTF8.GetBytes(response));
var i = client.Receive(buffer); // wait for client to send a message
string browserSent = GetDecodedData(buffer, i);
Console.WriteLine("BrowserSent: " + browserSent);
Console.WriteLine("=====================");
//now send message to client
client.Send(GetFrameFromString("This is message from server to client."));
System.Threading.Thread.Sleep(10000);//wait for message to be sent
}
}
catch (SocketException exception)
{
throw exception;
}
finally
{
if (serverSocket != null && serverSocket.IsBound)
{
serverSocket.BeginAccept(null, 0, OnAccept, null);
}
}
}
public static T[] SubArray<T>(T[] data, int index, int length)
{
T[] result = new T[length];
Array.Copy(data, index, result, 0, length);
return result;
}
private static string AcceptKey(ref string key)
{
string longKey = key + guid;
byte[] hashBytes = ComputeHash(longKey);
return Convert.ToBase64String(hashBytes);
}
static SHA1 sha1 = SHA1CryptoServiceProvider.Create();
private static byte[] ComputeHash(string str)
{
return sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str));
}
//Needed to decode frame
public static string GetDecodedData(byte[] buffer, int length)
{
byte b = buffer[1];
int dataLength = 0;
int totalLength = 0;
int keyIndex = 0;
if (b - 128 <= 125)
{
dataLength = b - 128;
keyIndex = 2;
totalLength = dataLength + 6;
}
if (b - 128 == 126)
{
dataLength = BitConverter.ToInt16(new byte[] { buffer[3], buffer[2] }, 0);
keyIndex = 4;
totalLength = dataLength + 8;
}
if (b - 128 == 127)
{
dataLength = (int)BitConverter.ToInt64(new byte[] { buffer[9], buffer[8], buffer[7], buffer[6], buffer[5], buffer[4], buffer[3], buffer[2] }, 0);
keyIndex = 10;
totalLength = dataLength + 14;
}
if (totalLength > length)
throw new Exception("The buffer length is small than the data length");
byte[] key = new byte[] { buffer[keyIndex], buffer[keyIndex + 1], buffer[keyIndex + 2], buffer[keyIndex + 3] };
int dataIndex = keyIndex + 4;
int count = 0;
for (int i = dataIndex; i < totalLength; i++)
{
buffer[i] = (byte)(buffer[i] ^ key[count % 4]);
count++;
}
return Encoding.ASCII.GetString(buffer, dataIndex, dataLength);
}
//function to create frames to send to client
/// <summary>
/// Enum for opcode types
/// </summary>
public enum EOpcodeType
{
/* Denotes a continuation code */
Fragment = 0,
/* Denotes a text code */
Text = 1,
/* Denotes a binary code */
Binary = 2,
/* Denotes a closed connection */
ClosedConnection = 8,
/* Denotes a ping*/
Ping = 9,
/* Denotes a pong */
Pong = 10
}
/// <summary>Gets an encoded websocket frame to send to a client from a string</summary>
/// <param name="Message">The message to encode into the frame</param>
/// <param name="Opcode">The opcode of the frame</param>
/// <returns>Byte array in form of a websocket frame</returns>
public static byte[] GetFrameFromString(string Message, EOpcodeType Opcode = EOpcodeType.Text)
{
byte[] response;
byte[] bytesRaw = Encoding.Default.GetBytes(Message);
byte[] frame = new byte[10];
int indexStartRawData = -1;
int length = bytesRaw.Length;
frame[0] = (byte)(128 + (int)Opcode);
if (length <= 125)
{
frame[1] = (byte)length;
indexStartRawData = 2;
}
else if (length >= 126 && length <= 65535)
{
frame[1] = (byte)126;
frame[2] = (byte)((length >> 8) & 255);
frame[3] = (byte)(length & 255);
indexStartRawData = 4;
}
else
{
frame[1] = (byte)127;
frame[2] = (byte)((length >> 56) & 255);
frame[3] = (byte)((length >> 48) & 255);
frame[4] = (byte)((length >> 40) & 255);
frame[5] = (byte)((length >> 32) & 255);
frame[6] = (byte)((length >> 24) & 255);
frame[7] = (byte)((length >> 16) & 255);
frame[8] = (byte)((length >> 8) & 255);
frame[9] = (byte)(length & 255);
indexStartRawData = 10;
}
response = new byte[indexStartRawData + length];
int i, reponseIdx = 0;
//Add the frame bytes to the reponse
for (i = 0; i < indexStartRawData; i++)
{
response[reponseIdx] = frame[i];
reponseIdx++;
}
//Add the data bytes to the response
for (i = 0; i < length; i++)
{
response[reponseIdx] = bytesRaw[i];
reponseIdx++;
}
return response;
}
}
}
Client html and javascript:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"_x000D_
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<script type="text/javascript">_x000D_
var socket = new WebSocket('ws://localhost:8080/websession');_x000D_
socket.onopen = function() {_x000D_
// alert('handshake successfully established. May send data now...');_x000D_
socket.send("Hi there from browser.");_x000D_
};_x000D_
socket.onmessage = function (evt) {_x000D_
//alert("About to receive data");_x000D_
var received_msg = evt.data;_x000D_
alert("Message received = "+received_msg);_x000D_
};_x000D_
socket.onclose = function() {_x000D_
alert('connection closed');_x000D_
};_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
</body>_x000D_
</html>
_x000D_
Use this SQL code
copy table_name(atribute1,attribute2,attribute3...)
from 'E:\test.csv' delimiter ',' csv header
the header keyword lets the DBMS know that the csv file have a header with attributes
for more visit http://www.postgresqltutorial.com/import-csv-file-into-posgresql-table/
For Bootstrap v.5
document.querySelectorAll('.form-file-input')
.forEach(el => el.addEventListener('change', e => e.target.parentElement.querySelector('.form-file-text').innerText = e.target.files[0].name));
Affect all file input element. No need to specify elements id.
Thanks RBarry. I'm putting together an IP block allocation system and storing as binary is the only way to go.
I'm storing the CIDR representation (ex: 192.168.1.0/24) of the IP block in a varchar field, and using 2 calculated fields to hold the binary form of the start and end of the block. From there, I can run fast queries to see if a given block as already been allocated or is free to assign.
I modified your function to calculate the ending IP Address like so:
CREATE FUNCTION dbo.fnDisplayIPv4End(@block AS VARCHAR(18)) RETURNS BINARY(4)
AS
BEGIN
DECLARE @bin AS BINARY(4)
DECLARE @ip AS VARCHAR(15)
DECLARE @size AS INT
SELECT @ip = Left(@block, Len(@block)-3)
SELECT @size = Right(@block, 2)
SELECT @bin = CAST( CAST( PARSENAME( @ip, 4 ) AS INTEGER) AS BINARY(1))
+ CAST( CAST( PARSENAME( @ip, 3 ) AS INTEGER) AS BINARY(1))
+ CAST( CAST( PARSENAME( @ip, 2 ) AS INTEGER) AS BINARY(1))
+ CAST( CAST( PARSENAME( @ip, 1 ) AS INTEGER) AS BINARY(1))
SELECT @bin = CAST(@bin + POWER(2, 32-@size) AS BINARY(4))
RETURN @bin
END;
go
I had to enable HTTP Activation
in .NET Framework 4.5 Advanced Services
> WCF Services
Chrome Extensions don't allow you to have inline JavaScript (documentation).
The same goes for Firefox WebExtensions (documentation).
You are going to have to do something similar to this:
Assign an ID to the link (<a onClick=hellYeah("xxx")>
becomes <a id="link">
), and use addEventListener
to bind the event. Put the following in your popup.js
file:
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('link');
// onClick's logic below:
link.addEventListener('click', function() {
hellYeah('xxx');
});
});
popup.js
should be loaded as a separate script file:
<script src="popup.js"></script>
After hours of struggling, I solved it by including the following within app/build.gradle:
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
Found these docu on the google docu pages:
In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns
edit
Using the example on the docu:
// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);
The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G
So you come to the range: C2:G8
It was not clear to me in the question if ts.tax_status_code is a primary or alternate key or not. Same thing with recipient_code. This would be useful to know.
You can deal with the possibility of your bind variable being null using an OR as follows. You would bind the same thing to the first two bind variables.
If you are concerned about performance, you would be better to check if the values you intend to bind are null or not and then issue different SQL statement to avoid the OR.
insert into account_type_standard
(account_type_Standard_id, tax_status_id, recipient_id)
(
select
account_type_standard_seq.nextval,
ts.tax_status_id,
r.recipient_id
from tax_status ts, recipient r
where (ts.tax_status_code = ? OR (ts.tax_status_code IS NULL and ? IS NULL))
and (r.recipient_code = ? OR (r.recipient_code IS NULL and ? IS NULL))
I unistalled the original version of python (2.6.6) and install 2.7(with option make && make altinstall
) but when I tried install something with yum didn't work.
So I solved this issue as follow:
# ln -s /usr/local/bin/python /usr/bin/python
rpm -Uvh python-2.6.6-36.el6.i686.rpm
Done
I've created my own dark color scheme (based on Oblivion from gedit), which I think is very nice to work with.
Preview & details at: http://www.rogerdudler.com/?p=362
We're happy to announce the beta of eclipsecolorthemes.org, a new website to download, create and maintain Eclipse color themes / schemes. The theme editor allows you to copy an existing theme and edit the colors with a live preview of your changes on specific editors. The downloadable themes support a lot of editors (PHP, Java, SQL, Ant, text, HTML, CSS, and more to follow)
There's a growing list of themes already available on the site:
You can read more about the launch here.
You are writing to the file prior to closing your filestream:
using(FileStream fs=new FileStream(path,FileMode.OpenOrCreate))
using (StreamWriter str=new StreamWriter(fs))
{
str.BaseStream.Seek(0,SeekOrigin.End);
str.Write("mytext.txt.........................");
str.WriteLine(DateTime.Now.ToLongTimeString()+" "+DateTime.Now.ToLongDateString());
string addtext="this line is added"+Environment.NewLine;
str.Flush();
}
File.AppendAllText(path,addtext); //Exception occurrs ??????????
string readtext=File.ReadAllText(path);
Console.WriteLine(readtext);
The above code should work, using the methods you are currently using. You should also look into the using
statement and wrap your streams in a using block.
What about 1.1E10, +1, -0, etc? Parsing all possible numbers is trickier than many people think. If you want to include as many numbers are possible you should use the to_number function in a PL/SQL function. From http://www.oracle-developer.net/content/utilities/is_number.sql:
CREATE OR REPLACE FUNCTION is_number (str_in IN VARCHAR2) RETURN NUMBER IS
n NUMBER;
BEGIN
n := TO_NUMBER(str_in);
RETURN 1;
EXCEPTION
WHEN VALUE_ERROR THEN
RETURN 0;
END;
/
If you are in a network of users, then the username will be different:
Environment.UserName
- Will Display format : 'Username'
rather than
System.Security.Principal.WindowsIdentity.GetCurrent().Name
- Will Display format : 'NetworkName\Username'
Choose the format you want.
IMHO, one point that is missing in this discussion is that whatever variable you use, it is guaranteed to always point at the appropriate folder. This becomes critical in the rare cases where Windows is installed on a drive other than C:\
If the comment message includes non-English characters, using method provided by user456814, those characters will be replaced by question marks. (tested under sourcetree Ver2.5.5.0)
So I have to use the following method.
CAUTION: if the commit has been pulled by other members, changes below might cause chaos for them.
Step1: In the sourcetree main window, locate your repo tab, and click the "terminal" button to open the git command console.
Step2:
[Situation A]: target commit is the latest one.
1) In the git command console, input
git commit --amend -m "new comment message"
2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input
git push --force
[Situation B]: target commit is not the latest one.
1) In the git command console, input
git rebase -i HEAD~n
It is to squash the latest n commits. e.g. if you want to edit the message before the last one, n is 2.
This command will open a vi window, the first word of each line is "pick", and you change the "pick" to "reword" for the line you want to edit. Then, input :wq
to save&quit that vi window. Now, a new vi window will be open, in this window you input your new message. Also use :wq
to save&quit.
2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input
git push --force
Finally: In the sourcetree main window, Press F5
to refresh.
$(function() {
$("#upload").bind("click", function() {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.xlsx)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof(FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function(e) {
var customers = new Array();
var rows = e.target.result.split("\r\n");
for (var i = 0; i < rows.length - 1; i++) {
var cells = rows[i].split(",");
if (cells[0] == "" || cells[0] == undefined) {
var s = customers[customers.length - 1];
s.Ord.push(cells[2]);
} else {
var dt = customers.find(x => x.Number === cells[0]);
if (dt == undefined) {
if (cells.length > 1) {
var customer = {};
customer.Number = cells[0];
customer.Name = cells[1];
customer.Ord = new Array();
customer.Ord.push(cells[2]);
customer.Point_ID = cells[3];
customer.Point_Name = cells[4];
customer.Point_Type = cells[5];
customer.Set_ORD = cells[6];
customers.push(customer);
}
} else {
var dtt = dt;
dtt.Ord.push(cells[2]);
}
}
}
Surely have a mutex-wrapped variable initialised to false
, that the thread sets to true
as the last thing it does before exiting. Is that atomic enough for your needs?
If you don't remember your password, then run this command in the Shell:
mysqladmin.exe -u root password NewPassword
where 'NewPassword' is your new password.
<?php
// do something here
header("Location: http://example.com/thankyou.php");
?>
func convertDateFormatter(date: String) -> String
{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date = dateFormatter.dateFromString(date)
dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"///this is what you want to convert format
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let timeStamp = dateFormatter.stringFromDate(date!)
return timeStamp
}
Updated for Swift 3.
func convertDateFormatter(date: String) -> String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let date = dateFormatter.date(from: date)
dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"///this is what you want to convert format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let timeStamp = dateFormatter.string(from: date!)
return timeStamp
}
This is handy if you want to erase all the history, including the fact that you erased all the history!
rm .bash_history;export HISTFILE=/dev/null;exit
If you can catch this in time and you don't have the ability to ROLLBACK
or use the transaction log, you can take a backup immediately and use a tool like Redgate's SQL Data Compare to generate a script to "restore" the affected data. This worked like a charm for me. :)
If you don't have access to sysjobs table (someone elses server etc) you might be have or be allowed access to sysjobs_view
SELECT *
from msdb..sysjobs_view s
left join master.sys.syslogins l on s.owner_sid = l.sid
or
SELECT *, SUSER_SNAME(s.owner_sid) AS owner
from msdb..sysjobs_view s
For some non-activity classes, like Worker, you're already given a Context object in the public constructor.
Worker(Context context, WorkerParameters workerParams)
You can just use that, e.g., save it to a private Context variable in the class (say, mContext
), and then, for example
mContext.getSystenService(Context.ACTIVITY_SERVICE)
The above options were not working for me because unlike creating a directory or file in the terminal, when the CLI generates a component, it adds the path src/app by default to the path you enter.
If I generate the component from my main app folder like so (WRONG WAY)
ng g c ./src/app/child/grandchild
the component that was generated was this:
src/app/src/app/child/grandchild.component.ts
so I only had to type
ng g c child/grandchild
Hopefully this helps someone
You can try this: git add * && git reset main/dontcheckmein.txt
Here is the code to check whether value is present or not.
If Trim(textbox1.text) <> "" Then
'Your code goes here
Else
'Nothing
End If
I think this will help.
jQuery has very limited array functions since JavaScript has most of them itself. But here are the ones they have: Utilities - jQuery API.
Try this:
git commit --amend
Then copy and paste the Change-Id: I55862204ef71f69bc88c79fe2259f7cb8365699a
at the end of the file.
Save it and push it again!
Truncate table
is faster than delete * from XXX
. Delete
is slow because it works one row at a time. There are a few situations where truncate doesn't work, which you can read about on MSDN.
If, having imagemagick installed on your maschine is an option, I recommend im4java. It is a very thin abstraction layer upon the command line interface, but does its job very well.
There is no real limit -- everything is named with a 160-bit name. The size of the file must be representable in a 64 bit number so no real limit there either.
There is a practical limit, though. I have a repository that's ~8GB with >880,000 files and git gc takes a while. The working tree is rather large so operations that inspect the entire working directory take quite a while. This repo is only used for data storage, though, so it's just a bunch of automated tools that handle it. Pulling changes from the repo is much, much faster than rsyncing the same data.
%find . -type f | wc -l
791887
%time git add .
git add . 6.48s user 13.53s system 55% cpu 36.121 total
%time git status
# On branch master
nothing to commit (working directory clean)
git status 0.00s user 0.01s system 0% cpu 47.169 total
%du -sh .
29G .
%cd .git
%du -sh .
7.9G .
I agree, it's more like an 'elif not [condition(s) raising break]'.
I know this is an old thread, but I am looking into the same question right now, and I'm not sure anyone has captured the answer to this question in the way I understand it.
For me, there are three ways of "reading" the else
in For... else
or While... else
statements, all of which are equivalent, are:
else
==
if the loop completes normally (without a break or error)
else
==
if the loop does not encounter a break
else
==
else not (condition raising break)
(presumably there is such a condition, or you wouldn't have a loop)So, essentially, the "else" in a loop is really an "elif ..." where '...' is (1) no break, which is equivalent to (2) NOT [condition(s) raising break].
I think the key is that the else
is pointless without the 'break', so a for...else
includes:
for:
do stuff
conditional break # implied by else
else not break:
do more stuff
So, essential elements of a for...else
loop are as follows, and you would read them in plainer English as:
for:
do stuff
condition:
break
else: # read as "else not break" or "else not condition"
do more stuff
As the other posters have said, a break is generally raised when you are able to locate what your loop is looking for, so the else:
becomes "what to do if target item not located".
Example
You can also use exception handling, breaks, and for loops all together.
for x in range(0,3):
print("x: {}".format(x))
if x == 2:
try:
raise AssertionError("ASSERTION ERROR: x is {}".format(x))
except:
print(AssertionError("ASSERTION ERROR: x is {}".format(x)))
break
else:
print("X loop complete without error")
Result
x: 0
x: 1
x: 2
ASSERTION ERROR: x is 2
----------
# loop not completed (hit break), so else didn't run
Example
Simple example with a break being hit.
for y in range(0,3):
print("y: {}".format(y))
if y == 2: # will be executed
print("BREAK: y is {}\n----------".format(y))
break
else: # not executed because break is hit
print("y_loop completed without break----------\n")
Result
y: 0
y: 1
y: 2
BREAK: y is 2
----------
# loop not completed (hit break), so else didn't run
Example
Simple example where there no break, no condition raising a break, and no error are encountered.
for z in range(0,3):
print("z: {}".format(z))
if z == 4: # will not be executed
print("BREAK: z is {}\n".format(y))
break
if z == 4: # will not be executed
raise AssertionError("ASSERTION ERROR: x is {}".format(x))
else:
print("z_loop complete without break or error\n----------\n")
Result
z: 0
z: 1
z: 2
z_loop complete without break or error
----------
Late to the question, here, but: I maintain a class at this address: http://lacinato.com/cm/software/emailrelated/emailaddress
It is based on Les Hazlewood's class, but has numerous improvements and fixes a few bugs. Apache license.
I believe it is the most capable email parser in Java, and I have yet to see one more capable in any language, though there may be one out there. It's not a lexer-style parser, but uses some complicated java regex, and thus is not as efficient as it could be, but my company has parsed well over 10 billion real-world addresses with it: it's certainly usable in a high-performance situation. Maybe once a year it'll hit an address that causes a regex stack overflow (appropriately), but these are spam addresses which are hundreds or thousands of characters long with many many quotes and parenthesis and the like.
RFC 2822 and the related specs are really quite permissive in terms of email addresses, so a class like this is overkill for most uses. For example, the following is a legitimate address, according to spec, spaces and all:
"<bob \" (here) " < (hi there) "bob(the man)smith" (hi) @ (there) example.com (hello) > (again)
No mail server would allow that, but this class can parse it (and rewrite it to a usable form).
We found the existing Java email parser options to be insufficiently durable (meaning, all of them could not parse some valid addresses), so we created this class.
The code is well-documented and has a lot of easy-to-change options to allow or disallow certain email forms. It also provides a lot of methods to access certain parts of the address (left-hand side, right-hand side, personal names, comments, etc), to parse/validate mailbox-list headers, to parse/validate the return-path (which is unique among the headers), and so forth.
The code as written has a javamail dependency, but it's easy to remove if you don't want the minor functionality it provides.
to validate the email string you will need to write a regular expression to check it is in the correct form. there are plenty out on the web but be carefull as some can exclude what are actually legal addresses.
essentially it will look something like this
^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$
Actually checking if the email exists and doesn't bounce would mean sending an email and seeing what the result was. i.e. it bounced or it didn't. However it might not bounce for several hours or not at all and still not be a "real" email address. There are a number of services out there which purport to do this for you and would probably be paid for by you and quite frankly why bother to see if it is real?
It is good to check the user has not misspelt their email else they could enter it incorrectly, not realise it and then get hacked of with you for not replying. However if someone wants to add a bum email address there would be nothing to stop them creating it on hotmail or yahoo (or many other places) to gain the same end.
So do the regular expression and validate the structure but forget about validating against a service.
I had same problem, but solved.
I removed the following line in .bashrc
alias do="docker.exe" # this line caused the problem
I use WSL(windows subsystem for linux)
On newer versions of Android (post Android 4.2 (Jelly Bean) at least), the setAlpha(int value) method is depreciated. Instead, use the setAlpha(float value)
method that takes a float between 0 and 1 where 0 is complete transparency and 1 is no transparency.
I just tried SMTPop and it worked.
smtpop.dll
reference to my C# .NET projectWrote the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmtPop;
namespace SMT_POP3 {
class Program {
static void Main(string[] args) {
SmtPop.POP3Client pop = new SmtPop.POP3Client();
pop.Open("<hostURL>", 110, "<username>", "<password>");
// Get message list from POP server
SmtPop.POPMessageId[] messages = pop.GetMailList();
if (messages != null) {
// Walk attachment list
foreach(SmtPop.POPMessageId id in messages) {
SmtPop.POPReader reader= pop.GetMailReader(id);
SmtPop.MimeMessage msg = new SmtPop.MimeMessage();
// Read message
msg.Read(reader);
if (msg.AddressFrom != null) {
String from= msg.AddressFrom[0].Name;
Console.WriteLine("from: " + from);
}
if (msg.Subject != null) {
String subject = msg.Subject;
Console.WriteLine("subject: "+ subject);
}
if (msg.Body != null) {
String body = msg.Body;
Console.WriteLine("body: " + body);
}
if (msg.Attachments != null && false) {
// Do something with first attachment
SmtPop.MimeAttachment attach = msg.Attachments[0];
if (attach.Filename == "data") {
// Read data from attachment
Byte[] b = Convert.FromBase64String(attach.Body);
System.IO.MemoryStream mem = new System.IO.MemoryStream(b, false);
//BinaryFormatter f = new BinaryFormatter();
// DataClass data= (DataClass)f.Deserialize(mem);
mem.Close();
}
// Delete message
// pop.Dele(id.Id);
}
}
}
pop.Quit();
}
}
}
Well, the above answer is correct, auto_now_add and auto_now would do it, but it would be better to make an abstract class and use it in any model where you require created_at
and updated_at
fields.
class TimeStampMixin(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
Now anywhere you want to use it you can do a simple inherit and you can use timestamp in any model you make like.
class Posts(TimeStampMixin):
name = models.CharField(max_length=50)
...
...
In this way, you can leverage object-oriented reusability, in Django DRY(don't repeat yourself)
The concept of static constructors was introduced in Java after they learned from the problems in C++. So we have no direct equivalent.
The best solution is to use POD types that can be initialised explicitly.
Or make your static members a specific type that has its own constructor that will initialize it correctly.
//header
class A
{
// Make sure this is private so that nobody can missues the fact that
// you are overriding std::vector. Just doing it here as a quicky example
// don't take it as a recomendation for deriving from vector.
class MyInitedVar: public std::vector<char>
{
public:
MyInitedVar()
{
// Pre-Initialize the vector.
for(char c = 'a';c <= 'z';++c)
{
push_back(c);
}
}
};
static int count;
static MyInitedVar var1;
};
//source
int A::count = 0;
A::MyInitedVar A::var1;
We needed to serialise an arbitrary object hierarchy, where the root or any of the nested properties in the hierarchy could be instances of Error.
Our solution was to use the replacer
param of JSON.stringify()
, e.g.:
function jsonFriendlyErrorReplacer(key, value) {_x000D_
if (value instanceof Error) {_x000D_
return {_x000D_
// Pull all enumerable properties, supporting properties on custom Errors_x000D_
...value,_x000D_
// Explicitly pull Error's non-enumerable properties_x000D_
name: value.name,_x000D_
message: value.message,_x000D_
stack: value.stack,_x000D_
}_x000D_
}_x000D_
_x000D_
return value_x000D_
}_x000D_
_x000D_
let obj = {_x000D_
error: new Error('nested error message')_x000D_
}_x000D_
_x000D_
console.log('Result WITHOUT custom replacer:', JSON.stringify(obj))_x000D_
console.log('Result WITH custom replacer:', JSON.stringify(obj, jsonFriendlyErrorReplacer))
_x000D_
You can replace the values "null" from the original file & field/column.
Refer Here
With Android Studio, you may use Android file explorer like: Click View > Tool Windows > Device File Explorer or click the Device File Explorer
To give a URL to an image tag which locates images/
directory in the root like
`logo.png`
you should give src
URL starting with /
as follows:
<img src="/images/logo.png"/>
This code works in any directories without any troubles even if you are in branches/europe/about.php
still the logo can be seen right there.
Profile pictures are scaled down to 125x125 on the facebook sever when they're uploaded, so as far as I know you can't get pictures bigger than that. How big is the picture you're getting?
I just had to solve a similar problem where I added a Sequence number (so that items as grouped by a parent ID, have a Sequence that I can order by (and presumably the user can change the sequence number to change the ordering).
In my case, it's insurance for a Patient, and the user gets to set the order they are assigned, so just going by the primary key isn't useful for long-term, but is useful for setting a default.
The problem with all the other solutions is that certain aggregate functions aren't allowed outside of a SELECT
This SELECT gets you the new Sequence number:
select PatientID,
PatientInsuranceID,
Sequence,
Row_Number() over(partition by PatientID order by PatientInsuranceID) as RowNum
from PatientInsurance
order by PatientID, PatientInsuranceID
This update command, would be simple, but isn't allowed:
update PatientInsurance
set Sequence = Row_Number() over(partition by PatientID order by PatientInsuranceID)
The solution that worked (I just did it), and is similar to eKek0's solution:
UPDATE PatientInsurance
SET PatientInsurance.Sequence = q.RowNum
FROM (select PatientInsuranceID,
Row_Number() over(partition by PatientID order by PatientInsuranceID) as RowNum
from PatientInsurance
) as q
WHERE PatientInsurance.PatientInsuranceID=q.PatientInsuranceID
this lets me select the ID I need to match things up to, and the value I need to set for that ID. Other solutions would have been fine IF I wasn't using Row_Number() which won't work outside of a SELECT.
Given that this is a 1 time operation, it's coding is still simple, and run-speed is fast enough for 4000+ rows
How about something like this...
Dim rs As RecordSet
Set rs = Currentdb.OpenRecordSet("SELECT PictureLocation, ID FROM MyAccessTable;")
Do While Not rs.EOF
Debug.Print rs("PictureLocation") & " - " & rs("ID")
rs.MoveNext
Loop
According to Oracle's Java Documentation:
private static final Pattern NUMBER_PATTERN = Pattern.compile(
"[\\x00-\\x20]*[+-]?(NaN|Infinity|((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)" +
"([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|" +
"(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))" +
"[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*");
boolean isNumber(String s){
return NUMBER_PATTERN.matcher(s).matches()
}
The two syntaxes for stubbing are roughly equivalent. However, you can always use doReturn/when
for stubbing; but there are cases where you can't use when/thenReturn
. Stubbing void methods is one such. Others include use with Mockito spies, and stubbing the same method more than once.
One thing that when/thenReturn
gives you, that doReturn/when
doesn't, is type-checking of the value that you're returning, at compile time. However, I believe this is of almost no value - if you've got the type wrong, you'll find out as soon as you run your test.
I strongly recommend only using doReturn/when
. There is no point in learning two syntaxes when one will do.
You may wish to refer to my answer at Forming Mockito "grammars" - a more detailed answer to a very closely related question.
NOTE: This one is just an alternative for the previous provided .NET framework 3.5 and above
You can send it as raw xml
<test>or like this</test>
If you declare the paramater2 as XElement data type
Simply add static
in the declaration of these two methods and the compile time error will disappear!
By default in C# methods are instance methods, and they receive the implicit "self" argument. By making them static, no such argument is needed (nor available), and the method must then of course refrain from accessing any instance (non-static) objects or methods of the class.
More info on static methods
Provided the class and the method's access modifiers (public vs. private) are ok, a static method can then be called from anywhere without having to previously instantiate a instance of the class. In other words static methods are used with the following syntax:
className.classMethod(arguments)
rather than
someInstanceVariable.classMethod(arguments)
A classical example of static methods are found in the System.Math class, whereby we can call a bunch of these methods like
Math.Sqrt(2)
Math.Cos(Math.PI)
without ever instantiating a "Math" class (in fact I don't even know if such an instance is possible)
def fruitBag = ["orange","banana","coconut"]
def fruit = fruitBag.collect{item -> item.contains('n')}
I did it like this so it works if someone is looking for it.
You must enable php! Check the folder mods-enabled
in the Apache directory (default: /etc/apache2/
) to see if you find a file named php
. I don't remember the extension but I think it's .so
.
Also check in /var/log/apache2/error.log
to see if you have any other errors.
You have to parse the string as JSON (data[0] == "["
is an indication that data
is actually a string, not an object):
data = $.parseJSON(data);
$.each(data, function(i, item) {
alert(item);
});
I know this is an older post, but I found what worked for me to fix this error was using the IP address of my server instead of using the domain name within my fetch request. So for example:
#(original) var request = new Request('https://davidwalsh.name/demo/arsenal.json');
#use IP instead
var request = new Request('https://0.0.0.0/demo/arsenal.json');
fetch(request).then(function(response) {
// Convert to JSON
return response.json();
}).then(function(j) {
// Yay, `j` is a JavaScript object
console.log(JSON.stringify(j));
}).catch(function(error) {
console.log('Request failed', error)
});
As a good practice you can use an Ant Script (Eclipse comes with it) to generate your JAR file. Inside this JAR you can have all dependent libs.
You can even set the MANIFEST's Class-path header to point to files in your filesystem, it's not a good practice though.
Ant build.xml script example:
<project name="jar with libs" default="compile and build" basedir=".">
<!-- this is used at compile time -->
<path id="example-classpath">
<pathelement location="${root-dir}" />
<fileset dir="D:/LIC/xalan-j_2_7_1" includes="*.jar" />
</path>
<target name="compile and build">
<!-- deletes previously created jar -->
<delete file="test.jar" />
<!-- compile your code and drop .class into "bin" directory -->
<javac srcdir="${basedir}" destdir="bin" debug="true" deprecation="on">
<!-- this is telling the compiler where are the dependencies -->
<classpath refid="example-classpath" />
</javac>
<!-- copy the JARs that you need to "bin" directory -->
<copy todir="bin">
<fileset dir="D:/LIC/xalan-j_2_7_1" includes="*.jar" />
</copy>
<!-- creates your jar with the contents inside "bin" (now with your .class and .jar dependencies) -->
<jar destfile="test.jar" basedir="bin" duplicate="preserve">
<manifest>
<!-- Who is building this jar? -->
<attribute name="Built-By" value="${user.name}" />
<!-- Information about the program itself -->
<attribute name="Implementation-Vendor" value="ACME inc." />
<attribute name="Implementation-Title" value="GreatProduct" />
<attribute name="Implementation-Version" value="1.0.0beta2" />
<!-- this tells which class should run when executing your jar -->
<attribute name="Main-class" value="ApplyXPath" />
</manifest>
</jar>
</target>
Here's a Boolean thing:
if (not suffix == "flac" ) or (not suffix == "cue" ): # WRONG! FAILS
print filename + ' is not a flac or cue file'
but
if not (suffix == "flac" or suffix == "cue" ): # CORRECT!
print filename + ' is not a flac or cue file'
(not a) or (not b) == not ( a and b )
,
is false only if a and b are both true
not (a or b)
is true only if a and be are both false.
maybe problem with margin?
width:auto;
padding: 0px;
margin: 0px
I did it by the following way. number and name are two arraylist. I have to sort name .If any change happen to name arralist order then the number arraylist also change its order.
public void sortval(){
String tempname="",tempnum="";
if (name.size()>1) // check if the number of orders is larger than 1
{
for (int x=0; x<name.size(); x++) // bubble sort outer loop
{
for (int i=0; i < name.size()-x-1; i++) {
if (name.get(i).compareTo(name.get(i+1)) > 0)
{
tempname = name.get(i);
tempnum=number.get(i);
name.set(i,name.get(i+1) );
name.set(i+1, tempname);
number.set(i,number.get(i+1) );
number.set(i+1, tempnum);
}
}
}
}
}
In case you are running it on a Google Bucket, the simple solution to this is to consider 'index.html' for Error (404 not found) Page.
To do so:
Have you tried:
ifconfig 10:35978f0 down
As the physical interface is 10
and the virtual aspect is after the colon :
.
See also https://www.cyberciti.biz/faq/linux-command-to-remove-virtual-interfaces-or-network-aliases/
Look at the Inner Exception and find out what object might have caused the problem, you might have changed its name.
Because 1
is numeric, but not integer (i.e. it's a floating point number), and 1:6000
is numeric and integer.
> print(class(1))
[1] "numeric"
> print(class(1:60000))
[1] "integer"
60000 squared is 3.6 billion, which is NOT representable in signed 32-bit integer, hence you get an overflow error:
> as.integer(60000)*as.integer(60000)
[1] NA
Warning message:
In as.integer(60000) * as.integer(60000) : NAs produced by integer overflow
3.6 billion is easily representable in floating point, however:
> as.single(60000)*as.single(60000)
[1] 3.6e+09
To fix your for
code, convert to a floating point representation:
function (N)
{
for(i in as.single(1:N)) {
y <- i*i
}
}
That single last line worked perfectly @GSerg.
The other function was what I had been working on but I don't like having to resort to UDF's unless absolutely necessary.
I had been trying a combination of excel and vba and had got this to work - but its clunky compared with your answer.
strArea = Sheets("Oper St Report CC").Range("cc_rev").CurrentRegion.Address
cc_rev_rows = "=ROWS(" & strArea & ")"
Range("cc_rev_count").Formula = cc_rev_rows
Using simple html,
<div>
<object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
</object>
</div>
Or jquery,
<script>
$("#mydiv")
.html('<object data="http://your-website-domain"/>');
</script>
public class MyException extends Exception {
// special exception code goes here
}
Throw it as:
throw new MyException ("Something happened")
Catch as:
catch (MyException e)
{
// something
}
Just the same way as you would do in normal Java code.
for (Map.Entry<String, String> entry : countries.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// ...
}
However, scriptlets (raw Java code in JSP files, those <% %>
things) are considered a poor practice. I recommend to install JSTL (just drop the JAR file in /WEB-INF/lib
and declare the needed taglibs in top of JSP). It has a <c:forEach>
tag which can iterate over among others Map
s. Every iteration will give you a Map.Entry
back which in turn has getKey()
and getValue()
methods.
Here's a basic example:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach items="${map}" var="entry">
Key = ${entry.key}, value = ${entry.value}<br>
</c:forEach>
Thus your particular issue can be solved as follows:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<select name="country">
<c:forEach items="${countries}" var="country">
<option value="${country.key}">${country.value}</option>
</c:forEach>
</select>
You need a Servlet
or a ServletContextListener
to place the ${countries}
in the desired scope. If this list is supposed to be request-based, then use the Servlet
's doGet()
:
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
Map<String, String> countries = MainUtils.getCountries();
request.setAttribute("countries", countries);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
}
Or if this list is supposed to be an application-wide constant, then use ServletContextListener
's contextInitialized()
so that it will be loaded only once and kept in memory:
public void contextInitialized(ServletContextEvent event) {
Map<String, String> countries = MainUtils.getCountries();
event.getServletContext().setAttribute("countries", countries);
}
In both cases the countries
will be available in EL by ${countries}
.
Hope this helps.
For python2 you can also do this
'%(author)s in %(publication)s'%{'author':unicode(self.author),
'publication':unicode(self.publication)}
which is handy if you have a lot of arguments to substitute (particularly if you are doing internationalisation)
Python2.6 onwards supports .format()
'{author} in {publication}'.format(author=self.author,
publication=self.publication)
Of the 4 shells that I've tested, ABC -eq XYZ
evaluates to true in the test
builtin for zsh
and ksh
. The expression evaluates to false under /usr/bin/test
and the builtins for dash
and bash
. In ksh
and zsh
, the strings are converted to numerical values and are equal since they are both 0. IMO, the behavior of the builtins for ksh
and zsh
is incorrect, but the spec for test
is ambiguous on this.
You have to do this to echo it:
echo $row['note'];
(The data is coming as an array)
Efficiency isn't going to matter for something like this in 99.999999% of situations. Do whatever is easier to read and or maintain.
In my apps I usually rely on classes to provide hiding and showing, for example .addClass('isHidden')/.removeClass('isHidden')
which would allow me to animate things with CSS3 if I wanted to. It provides more flexibility.
You can limit the number of files uploaded by changing in dropezone.js
Dropzone.prototype.defaultOptions = { maxFiles: 10, }
I also needed a button to navigate left on a PageViewController, one that should do exactly what you would expect from the swipe motion.
Since I had a few rules already in place inside "pageViewController:viewControllerBeforeViewController" for dealing with the natural swipe navigation, I wanted the button to re-use all that code, and simply could not afford to use specific indexes to reach pages as the previous answers did. So, I had to take an alternate solution.
Please note that the following code is for a Page View Controller that is a property inside my custom ViewController, and has its spine set to mid.
Here is the code I wrote for my Navigate Left button:
- (IBAction)btnNavigateLeft_Click:(id)sender {
// Calling the PageViewController to obtain the current left page
UIViewController *currentLeftPage = [_pageController.viewControllers objectAtIndex:0];
// Creating future pages to be displayed
NSArray *newDisplayedPages = nil;
UIViewController *newRightPage = nil;
UIViewController *newLeftPage = nil;
// Calling the delegate to obtain previous pages
// My "pageViewController:viewControllerBeforeViewController" method returns nil if there is no such page (first page of the book).
newRightPage = [self pageViewController:_pageController viewControllerBeforeViewController:currentLeftPage];
if (newRightPage) {
newLeftPage = [self pageViewController:_pageController viewControllerBeforeViewController:newRightPage];
}
if (newLeftPage) {
newDisplayedPages = [[NSArray alloc] initWithObjects:newLeftPage, newRightPage, nil];
}
// If there are two new pages to display, show them with animation.
if (newDisplayedPages) {
[_pageController setViewControllers:newDisplayedPages direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:nil];
}
}
You can do something very similar to make a right navigation button from here.
In Java multiple inheritance is not permitted. It was excluded from the language as a design decision, primarily to avoid circular dependencies.
Scenario1: As you have learned the following is not possible in Java:
public class Dog extends Animal, Canine{
}
Scenario 2: However the following is possible:
public class Canine extends Animal{
}
public class Dog extends Canine{
}
The difference in these two approaches is that in the second approach there is a clearly defined parent or super
class, while in the first approach the super
class is ambiguous.
Consider if both Animal
and Canine
had a method drink()
. Under the first scenario which parent method would be called if we called Dog.drink()
? Under the second scenario, we know calling Dog.drink()
would call the Canine
classes drink
method as long as Dog
had not overridden it.
Uninstall mysql using yum remove mysql*
Recursively delete /usr/bin/mysql
and /var/lib/mysql
Delete the file /etc/my.cnf.rmp
Use ps -e
to check the processes to make sure mysql isn't still running.
Reboot server with reboot
Run yum install mysql-server
. This also seems to install the mysql client as a dependency.
Give mysql ownership and group priveleges with:
chown -R mysql /var/lib/mysql
chgrp -R mysql /var/lib/mysql
Use service mysqld start
to start MySQL Daemon.
a->b
means (*a).b
.
If a
is a pointer, a->b
is the member b
of which a
points to.
a
can also be a pointer like object (like a vector<bool>
's stub) override the operators.
(if you don't know what a pointer is, you have another question)
You must attach the event after insert elements, like that you don't attach a global event on your document
but a specific event on the inserted elements.
e.g.
document.getElementById('form').addEventListener('submit', function(e) {_x000D_
e.preventDefault();_x000D_
var name = document.getElementById('txtName').value;_x000D_
var idElement = 'btnPrepend';_x000D_
var html = `_x000D_
<ul>_x000D_
<li>${name}</li>_x000D_
</ul>_x000D_
<input type="button" value="prepend" id="${idElement}" />_x000D_
`;_x000D_
/* Insert the html into your DOM */_x000D_
insertHTML('form', html);_x000D_
/* Add an event listener after insert html */_x000D_
addEvent(idElement);_x000D_
});_x000D_
_x000D_
const insertHTML = (tag = 'form', html, position = 'afterend', index = 0) => {_x000D_
document.getElementsByTagName(tag)[index].insertAdjacentHTML(position, html);_x000D_
}_x000D_
const addEvent = (id, event = 'click') => {_x000D_
document.getElementById(id).addEventListener(event, function() {_x000D_
insertHTML('ul', '<li>Prepending data</li>', 'afterbegin')_x000D_
});_x000D_
}
_x000D_
<form id="form">_x000D_
<div>_x000D_
<label for="txtName">Name</label>_x000D_
<input id="txtName" name="txtName" type="text" />_x000D_
</div>_x000D_
<input type="submit" value="submit" />_x000D_
</form>
_x000D_
You can't, you'll have to do something like
<script type="text/javascript">
var php_var = "<?php echo $php_var; ?>";
</script>
You can also load it with AJAX
rhino is right, the snippet lacks of a type for the sake of brevity.
Also, note that if $php_var
has quotes, it will break your script. You shall use addslashes, htmlentities or a custom function.
Or, if you are doing a split - join:
GROUP_CONCAT(split(thing, " "), '----') AS thing_name,
You may want to inclue WITHIN RECORD
, like this:
GROUP_CONCAT(split(thing, " "), '----') WITHIN RECORD AS thing_name,
from BigQuery API page
for color in ['r', 'b', 'g', 'k', 'm']:
plot(x, y, color=color)
For the kotlin users out there here is a kotlin extension method that has worked for my use cases:
fun View.hideKeyboard() {
val imm = this.context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
}
put it in a file called ViewExtensions (or what have you) and call it on your views just like a normal method.
All the three syntax work very well.
Another way is to first write
path = r'C:\user\...................' (whatever is the path for you)
and then passing it to os.chdir(path)
those are miliseconds, just divide them by 1000, since gmtime expects seconds ...
time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807/1000.0))
As @TomMcKenzie says in a comment to another answer, date -r 123456789
is arguably a more common (i.e. more widely implemented) simple solution for times given as seconds since the Unix Epoch, but unfortunately there's no universal guaranteed portable solution.
The -d
option on many types of systems means something entirely different than GNU Date's --date
extension. Sadly GNU Date doesn't interpret -r
the same as these other implementations. So unfortunately you have to know which version of date
you're using, and many older Unix date
commands don't support either option.
Even worse, POSIX date
recognizes neither -d
nor -r
and provides no standard way in any command at all (that I know of) to format a Unix time from the command line (since POSIX Awk also lacks strftime()
). (You can't use touch -t
and ls
because the former does not accept a time given as seconds since the Unix Epoch.)
Note though The One True Awk available direct from Brian Kernighan does now have the strftime()
function built-in as well as a systime()
function to return the current time in seconds since the Unix Epoch), so perhaps the Awk solution is the most portable.
Refactoring:
new WindowsMediaPlayer() { URL = "MyMusic.mp3" }.controls.play();
In my case, the static content was already being served:
app.use('/*', express.static(path.join(__dirname, '../pub/index.html')));
...and everything in the app seemed to rely on that in some way. (path
dep is require('path')
)
So, a) yes, it can be a file; and b) you can make a redirect!
app.get('/', function (req, res) { res.redirect('/index.html') });
Now anyone hitting /
gets /index.html
which is served statically from ../pub/index.html
.
Hope this helps someone else.
What you could do is, a validation of the values, for example:
if the value of the input of fullanme is greater than some value length and if the value of the input of address is greater than some value length then redirect to a new page, otherwise shows an error for the input.
// We access to the inputs by their id's
let fullname = document.getElementById("fullname");
let address = document.getElementById("address");
// Error messages
let errorElement = document.getElementById("name_error");
let errorElementAddress = document.getElementById("address_error");
// Form
let contactForm = document.getElementById("form");
// Event listener
contactForm.addEventListener("submit", function (e) {
let messageName = [];
let messageAddress = [];
if (fullname.value === "" || fullname.value === null) {
messageName.push("* This field is required");
}
if (address.value === "" || address.value === null) {
messageAddress.push("* This field is required");
}
// Statement to shows the errors
if (messageName.length || messageAddress.length > 0) {
e.preventDefault();
errorElement.innerText = messageName;
errorElementAddress.innerText = messageAddress;
}
// if the values length is filled and it's greater than 2 then redirect to this page
if (
(fullname.value.length > 2,
address.value.length > 2)
) {
e.preventDefault();
window.location.assign("https://www.google.com");
}
});
_x000D_
.error {
color: #000;
}
.input-container {
display: flex;
flex-direction: column;
margin: 1rem auto;
}
_x000D_
<html>
<body>
<form id="form" method="POST">
<div class="input-container">
<label>Full name:</label>
<input type="text" id="fullname" name="fullname">
<div class="error" id="name_error"></div>
</div>
<div class="input-container">
<label>Address:</label>
<input type="text" id="address" name="address">
<div class="error" id="address_error"></div>
</div>
<button type="submit" id="submit_button" value="Submit request" >Submit</button>
</form>
</body>
</html>
_x000D_
To Remove Special character
String t2 = "!@#$%^&*()-';,./?><+abdd";
t2 = t2.replaceAll("\\W+","");
Output will be : abdd.
This works perfectly.
You must write that function body outside the ready();
because ready is used to call a function or to bind a function with binding id like this.
$(document).ready(function() {
$("Some id/class name").click(function(){
alert("i'm in");
});
});
but you can't do this if you are calling "showAmount" function onchange/onclick event
$(document).ready(function() {
function showAmount(value){
alert(value);
}
});
You have to write "showAmount" outside the ready();
function showAmount(value){
alert(value);//will be called on event it is bind with
}
$(document).ready(function() {
alert("will display on page load")
});
The caller-saved / callee-saved terminology is based on a pretty braindead inefficient model of programming where callers actually do save/restore all the call-clobbered registers (instead of keeping long-term-useful values elsewhere), and callees actually do save/restore all the call-preserved registers (instead of just not using some or any of them).
Or you have to understand that "caller-saved" means "saved somehow if you want the value later".
In reality, efficient code lets values get destroyed when they're no longer needed. Compilers typically make functions that save a few call-preserved registers at the start of a function (and restore them at the end). Inside the function, they use those regs for values that need to survive across function calls.
I prefer "call-preserved" vs. "call-clobbered", which are unambiguous and self-describing once you've heard of the basic concept, and don't require any serious mental gymnastics to think about from the caller's perspective or the callee's perspective. (Both terms are from the same perspective).
Plus, these terms differ by more than one letter.
The terms volatile / non-volatile are pretty good, by analogy with storage which loses its value on power-loss or not, (like DRAM vs. Flash). But the C volatile
keyword has a totally different technical meaning, so that's a downside to "(non)-volatile" when describing C calling conventions.
From the callee's perspective, your function can freely overwrite (aka clobber) these registers without saving/restoring.
From a caller's perspective, call foo
destroys (aka clobbers) all the call-clobbered registers, or at least you have to assume it does.
You can write private helper functions that have a custom calling convention, e.g. you know they don't modify a certain register. But if all you know (or want to assume or depend on) is that the target function follows the normal calling convention, then you have to treat a function call as if it does destroy all the call-clobbered registers. That's literally what the name come from: a call clobbers those registers.
Some compilers that do inter-procedural optimization can also create internal-use-only definitions of functions that don't follow the ABI, using a custom calling convention.
From a callee's perspective, these registers can't be modified unless you save the original value somewhere so you can restore it before returning. Or for registers like the stack pointer (which is almost always call-preserved), you can subtract a known offset and add it back again before returning, instead of actually saving the old value anywhere. i.e. you can restore it by dead reckoning, unless you allocate a runtime-variable amount of stack space. Then typically you restore the stack pointer from another register.
A function that can benefit from using a lot of registers can save/restore some call-preserved registers just so it can use them as more temporaries, even if it doesn't make any function calls. Normally you'd only do this after running out of call-clobbered registers to use, because save/restore typically costs a push/pop at the start/end of the function. (Or if your function has multiple exit paths, a pop
in each of them.)
The name "caller-saved" is misleading: you don't have to specially save/restore them. Normally you arrange your code to have values that need to survive a function call in call-preserved registers, or somewhere on the stack, or somewhere else that you can reload from. It's normal to let a call
destroy temporary values.
See for example What registers are preserved through a linux x86-64 function call for the x86-64 System V ABI.
Also, arg-passing registers are always call-clobbered in all function-calling conventions I'm aware of. See Are rdi and rsi caller saved or callee saved registers?
But system-call calling conventions typically make all the registers except the return value call-preserved. (Usually including even condition-codes / flags.) See What are the calling conventions for UNIX & Linux system calls on i386 and x86-64
Use the other answers if you don't mind losing local changes. This method can still wreck your remote if you choose the wrong commit hash to go back to.
If you just want to make the remote match a commit that's anywhere in your local repo:
git log
to find the commit you want to the remote to be at. git log -p
to see changes, or git log --graph --all --oneline --decorate
to see a compact tree.Run a command like:
git push --force <remote> <commit-ish>:<the remote branch>
e.g.
git push --force origin 606fdfaa33af1844c86f4267a136d4666e576cdc:master
or
git push --force staging v2.4.0b2:releases
I use convenient alias (git go
) for viewing history as in step 2, which can be added like so:
git config --global alias.go 'log --graph --all --decorate --oneline'`
I found that it's easy to write an app that can open another app.
Let's assume that we have two apps called FirstApp
and SecondApp
. When we open the FirstApp, we want to be able to open the SecondApp by clicking a button. The solution to do this is:
In SecondApp
Go to the plist file of SecondApp and you need to add a URL Schemes with a string iOSDevTips(of course you can write another string.it's up to you).
2 . In FirstApp
Create a button with the below action:
- (void)buttonPressed:(UIButton *)button
{
NSString *customURL = @"iOSDevTips://";
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:customURL]])
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:customURL]];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"URL error"
message:[NSString stringWithFormat:@"No custom URL defined for %@", customURL]
delegate:self cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alert show];
}
}
That's it. Now when you can click the button in the FirstApp it should open the SecondApp.
From MSDN:
Use of two sequential underscore characters ( __ ) at the beginning of an identifier, or a single leading underscore followed by a capital letter, is reserved for C++ implementations in all scopes. You should avoid using one leading underscore followed by a lowercase letter for names with file scope because of possible conflicts with current or future reserved identifiers.
This means that you can use a single underscore as a member variable prefix, as long as it's followed by a lower-case letter.
This is apparently taken from section 17.4.3.1.2 of the C++ standard, but I can't find an original source for the full standard online.
See also this question.
I just found TryParse()
has an issue that it accounts for thousands seperator. Example in En-US, 10,36.00 is ok. I had a specific scenario where the thousands seperator should not be considered and hence regex \d(\.\d)
turned out to be the best bet. Of course had to keep the decimal char variable for different locales.
Starting with Spring 4.1, We can directly set the property in application.yml using the @TestPropertySource annotation.
@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(properties = {"yoursection.yourparameter=your_value"})
public MyIntTest
{
//your test methods
}
Just convert your yaml parameters into complete property structure. For example: If content of application.yml is like below
yoursection:
yourparameter:your_value
Then value to go inside the @TestPropertySource will be,
yoursection.yourparameter=your_value
Try
new Date().toLocaleTimeString().replace("/.*(\d{2}:\d{2}:\d{2}).*/", "$1");
Or
new Date().toTimeString().split(" ")[0];
Please try the below code:
<script>
const games = {
"Fifa": "232",
"Minecraft": "476",
"Call of Duty": "182"
};
Object.keys(games).forEach((item, index, array) => {
var msg = item+' '+games[item];
console.log(msg);
});
It seems that your problem is more in determining the new file name rather than the rename itself (for which you could use the os.rename method).
It is not clear from your question what the pattern is that you want to be renaming. There is nothing wrong with string manipulation. A regular expression may be what you need here.
When working with buckets that have 1000+ objects its necessary to implement a solution that uses the NextContinuationToken
on sequential sets of, at most, 1000 keys. This solution first compiles a list of objects then iteratively creates the specified directories and downloads the existing objects.
import boto3
import os
s3_client = boto3.client('s3')
def download_dir(prefix, local, bucket, client=s3_client):
"""
params:
- prefix: pattern to match in s3
- local: local path to folder in which to place files
- bucket: s3 bucket with target contents
- client: initialized s3 client object
"""
keys = []
dirs = []
next_token = ''
base_kwargs = {
'Bucket':bucket,
'Prefix':prefix,
}
while next_token is not None:
kwargs = base_kwargs.copy()
if next_token != '':
kwargs.update({'ContinuationToken': next_token})
results = client.list_objects_v2(**kwargs)
contents = results.get('Contents')
for i in contents:
k = i.get('Key')
if k[-1] != '/':
keys.append(k)
else:
dirs.append(k)
next_token = results.get('NextContinuationToken')
for d in dirs:
dest_pathname = os.path.join(local, d)
if not os.path.exists(os.path.dirname(dest_pathname)):
os.makedirs(os.path.dirname(dest_pathname))
for k in keys:
dest_pathname = os.path.join(local, k)
if not os.path.exists(os.path.dirname(dest_pathname)):
os.makedirs(os.path.dirname(dest_pathname))
client.download_file(bucket, k, dest_pathname)
yes, static block is used for initialize the code and it will load at the time JVM start for execution.
static block is used in previous versions of java but in latest version it doesn't work.
Get the querystring collection, parse it into a (name=value pair
) string, excluding the one you want to REMOVE, and name it newQueryString
Then call Response.Redirect(known_path?newqueryString)
;
You should check for ''
(empty string) before pushing into your array. Your array has elements that are empty strings. Then your album_text.length === 0
will work just fine.
Note: As the original asker implied, if you are setting up two databases on the same machine you probably want to make two schemas instead - in that case you don't need anything special to query across them.
postgres_fdw
Use postgres_fdw
(foreign data wrapper) to connect to tables in any Postgres database - local or remote.
Note that there are foreign data wrappers for other popular data sources. At this time, only postgres_fdw
and file_fdw
are part of the official Postgres distribution.
Versions this old are no longer supported, but if you need to do this in a pre-2013 Postgres installation, there is a function called dblink
.
I've never used it, but it is maintained and distributed with the rest of PostgreSQL. If you're using the version of PostgreSQL that came with your Linux distro, you might need to install a package called postgresql-contrib.
Managed code is a differentiation coined by Microsoft to identify computer program code that requires and will only execute under the "management" of a Common Language Runtime virtual machine (resulting in Bytecode).
If you are using the newest version of Android Studio, you can let it assist you in this.
Note: I have tested this in Android Studio 3.0 only.
The procedure is as follows:
In the project view (this comes along with captures and structure on the left side of screen), select Project instead of Android.
The name of your project will be the top of the tree (alongside external libraries).
Select your project then go to Refactor -> Copy...
.
Android Studio will ask you the new name and where you want to copy the project. Provide the same.
After the copying is done, open your new project in Android Studio.
Packages will still be under the old project name.
That is the Java classes packages, application ID and everything else that was generated using the old package name.
We need to change that.
In the project view, select Android.
Open the java sub-directory and select the main package.
Then right click on it and go to Refactor
then Rename
.
Android Studio will give you a warning saying that multiple directories correspond to the package you are about to refactor.
Click on Rename package
and not Rename directory
.
After this step, your project is now completely under the new name.
Build -> Clean project
then Build -> Rebuild project
.Here's the script I use:
#!/bin/bash
IFS=$'\n\t'
set -euox pipefail
CNAME="$1"
FILE_PATH="$2"
TMPFILE="$(mktemp)"
docker exec "$CNAME" cat "$FILE_PATH" > "$TMPFILE"
$EDITOR "$TMPFILE"
cat "$TMPFILE" | docker exec -i "$CNAME" sh -c 'cat > '"$FILE_PATH"
rm "$TMPFILE"
and the gist for when I fix it but forget to update this answer: https://gist.github.com/dmohs/b50ea4302b62ebfc4f308a20d3de4213
I think the solution is actually very simple.
use
break
to only do first iteration of the for loop, there must be a more elegant way.
for root, dirs, files in os.walk(dir_name):
for f in files:
...
...
break
...
The first time you call os.walk, it returns tulips for the current directory, then on next loop the contents of the next directory.
Take original script and just add a break.
def _dir_list(self, dir_name, whitelist):
outputList = []
for root, dirs, files in os.walk(dir_name):
for f in files:
if os.path.splitext(f)[1] in whitelist:
outputList.append(os.path.join(root, f))
else:
self._email_to_("ignore")
break
return outputList
Undoing a merge with git is so easy you shouldn't even worry about the dry run:
$ git pull $REMOTE $BRANCH
# uh oh, that wasn't right
$ git reset --hard ORIG_HEAD
# all is right with the world
EDIT: As noted in the comments below, if you have changes in your working directory or staging area you'll probably want to stash them before doing the above (otherwise they will disappear following the git reset
above)
Make a connection and open it.
con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=<database_name>)));User Id =<userid>; Password =<password>");
con.Open();
Write the select query:
string sql = "select * from Pending_Tasks";
Create a command object:
OracleCommand cmd = new OracleCommand(sql, con);
Execute the command and put the result in a object to read it.
OracleDataReader r = cmd.ExecuteReader();
now start reading from it.
while (read.Read())
{
CustID.Text = (read["Customer_ID"].ToString());
CustName.Text = (read["Customer_Name"].ToString());
Add1.Text = (read["Address_1"].ToString());
Add2.Text = (read["Address_2"].ToString());
PostBox.Text = (read["Postcode"].ToString());
PassBox.Text = (read["Password"].ToString());
DatBox.Text = (read["Data_Important"].ToString());
LanNumb.Text = (read["Landline"].ToString());
MobNumber.Text = (read["Mobile"].ToString());
FaultRep.Text = (read["Fault_Report"].ToString());
}
read.Close();
Add this too using Oracle.ManagedDataAccess.Client;
There seems also to be a relation to the environment:
I had that "invalid argument supplied foreach()" error only in the dev environment, but not in prod (I am working on the server, not localhost).
Despite the error a var_dump indicated that the array was well there (in both cases app and dev).
The if (is_array($array))
around the foreach ($array as $subarray)
solved the problem.
Sorry, that I cannot explain the cause, but as it took me a while to figure a solution I thought of better sharing this as an observation.
There is an open issue to only print this warning if there was actually something sanitized: https://github.com/angular/angular/pull/10272
I didn't read in detail when this warning is printed when nothing was sanitized.
For an iPhone 7/7 Plus or newer, use these three Haptic feedback APIs.
let generator = UINotificationFeedbackGenerator()
generator.notificationOccured(style: .error)
Available styles are .error
, .success
, and .warning
. Each has its own distinctive feel.
From the docs:
A concrete
UIFeedbackGenerator
subclass that creates haptics to communicate successes, failures, and warnings.
let generator = UIImpactFeedbackGenerator(style: .medium)
generator.impactOccured()
Available styles are .heavy
, .medium
, and .light
. These are simple vibrations with varying degrees of "hardness".
From the docs:
A concrete
UIFeedbackGenerator
subclass that creates haptics to simulate physical impacts
let generator = UISelectionFeedbackGenerator()
generator.selectionChanged()
This is the least noticeable of all the haptics, and so is the most suitable for when haptics should not be taking over the app experience.
From the docs:
A concrete
UIFeedbackGenerator
subclass that creates haptics to indicate a change in selection.
There are a couple of things worth remembering when using these APIs.
You do not actually create the haptic. You request the system generate a haptic. The system will decide based on the below:
Therefore, the system will silently ignore your request for a haptic if it is not possible. If this is due to an unsupported device, you could try this:
func haptic() {
// Get whether the device can generate haptics or not
// If feedbackSupportLevel is nil, will assign 0
let feedbackSupportLevel = UIDevice.current.value(forKey: "_feedbackSupportLevel") as? Int ?? 0
switch feedbackSupportLevel {
case 2:
// 2 means the device has a Taptic Engine
// Put Taptic Engine code here, using the APIs explained above
case 1:
// 1 means no Taptic Engine, but will support AudioToolbox
// AudioToolbox code from the myriad of other answers!
default: // 0
// No haptic support
// Do something else, like a beeping noise or LED flash instead of haptics
}
Substitute the comments in the switch
-case
statements, and this haptic generation code will be portable to other iOS devices. It will generate the highest level of haptic possible.
prepare()
method, to put it in a state of readiness. Using your Game Over example: You may know that the game is about to end, by the user having very low HP, or a dangerous monster being near them.
In this case, preparing the Taptic Engine would create a higher-quality, more responsive experience.
For example, let's say your app uses a pan gesture recogniser to change the portion of the world visible. You want a haptic to generate when the user 'looks' round 360 degrees. Here is how you could use prepare()
:
@IBAction func userChangedViewablePortionOfWorld(_ gesture: UIPanGestureRecogniser!) {
haptic = UIImpactFeedbackGenerator(style: .heavy)
switch gesture.state {
case .began:
// The user started dragging the screen.
haptic.prepare()
case .changed:
// The user trying to 'look' in another direction
// Code to change viewable portion of the virtual world
if virtualWorldViewpointDegreeMiddle = 360.0 {
haptic.impactOccured()
}
default:
break
}
You can try this
click Help>Install New Software on the menu bar