Since Xcode 11.4, overriding the preferredStatusBarStyle
property in a UINavigationController extension no longer works since it will not be called.
Setting the barStyle
of navigationBar
to .black
works indeed but this will add unwanted side effects if you add subviews to the navigationBar which may have different appearances for light and dark mode. Because by setting the barStyle
to black, the userInterfaceStyle
of a view thats embedded in the navigationBar will then always have userInterfaceStyle.dark
regardless of the userInterfaceStyle
of the app.
The proper solution I come up with is by adding a subclass of UINavigationController
and override preferredStatusBarStyle
there. If you then use this custom UINavigationController for all your views you will be on the save side.
This will fix it for a UITableViewController (without any magic numbers). The only thing I couldn't get it to fix is if you are on a phone call, in which case the top of the tableView is pushed down too much. If anyone knows how to solve that, please let us know.
class MyTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
configureTableViewTop()
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
coordinator.animateAlongsideTransition({ (context) -> Void in
}, completion: { (context) -> Void in
self.configureTableViewTop()
})
}
func configureTableViewTop() {
tableView.contentInset.top = UIApplication.sharedApplication().statusBarFrame.height
}
}
In Plist, add this:
UIStatusBarStyleLightContent
NO
If you still unable to change the status bar style base on the method
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
You may try using this method:
override viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.barStyle = .black
}
This version always returns the number of seconds difference as a positive number (same result as @freedeveloper's solution):
var seconds = System.Math.Abs((date1 - date2).TotalSeconds);
I have the same problem as @KTCheek in that I need it to execute sequentially. However I figured I would try using IAsyncEnumerable (introduced in .NET Core 3) and await foreach (introduced in C# 8). Here's what I have come up with:
public static class IEnumerableExtensions {
public static async IAsyncEnumerable<TResult> SelectAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> selector) {
foreach (var item in source) {
yield return await selector(item);
}
}
}
public static class IAsyncEnumerableExtensions {
public static async Task<List<TSource>> ToListAsync<TSource>(this IAsyncEnumerable<TSource> source) {
var list = new List<TSource>();
await foreach (var item in source) {
list.Add(item);
}
return list;
}
}
This can be consumed by saying:
var inputs = await events.SelectAsync(ev => ProcessEventAsync(ev)).ToListAsync();
Update: Alternatively you can add a reference to "System.Linq.Async" and then you can say:
var inputs = await events
.ToAsyncEnumerable()
.SelectAwait(async ev => await ProcessEventAsync(ev))
.ToListAsync();
Additionally, this will only work if Value is of type bool. Normally this is used with predicates. Any predicate would be generally used find whether there is any element satisfying a given condition. Here you're just doing a map from your element i to a bool property. It will search for an "i" whose Value property is true. Once done, the method will return true.
Assuming the image data is already in the format you want, you don't need image ImageIO
at all - you just need to write the data to the file:
// Note preferred way of declaring an array variable
byte[] data = Base64.decodeBase64(crntImage);
try (OutputStream stream = new FileOutputStream("c:/decode/abc.bmp")) {
stream.write(data);
}
(I'm assuming you're using Java 7 here - if not, you'll need to write a manual try/finally statement to close the stream.)
If the image data isn't in the format you want, you'll need to give more details.
I found this here: https://port135.com/schannel-the-internal-error-state-is-10013-solved/
"Correct file permissions Correct the permissions on the c:\ProgramData\Microsoft\Crypto\RSA\MachineKeys folder:
Everyone Access: Special Applies to 'This folder only' Network Service Access: Read & Execute Applies to 'This folder, subfolders and files' Administrators Access: Full Control Applies to 'This folder, subfolder and files' System Access: Full control Applies to 'This folder, subfolder and Files' IUSR Access: Full Control Applies to 'This folder, subfolder and files' The internal error state is 10013 After these changes, restart the server. The 10013 errors should disappear."
Try it:
if (Objects.equals(gender, "Male")) {
salutation ="Mr.";
} else if (Objects.equals(gender, "Female")) {
salutation ="Ms.";
}
Make the exception happen like this:
when(obj.someMethod()).thenThrow(new AnException());
Verify it has happened either by asserting that your test will throw such an exception:
@Test(expected = AnException.class)
Or by normal mock verification:
verify(obj).someMethod();
The latter option is required if your test is designed to prove intermediate code handles the exception (i.e. the exception won't be thrown from your test method).
final File open = new File("PicDic.exe");
if (open.exists() == true) {
if (Desktop.isDesktopSupported()) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Desktop.getDesktop().open(open);
} catch (IOException ex) {
return;
}
}
});
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
//DocumentEditorView.this.getFrame().dispose();
System.exit(0);
}
});
} else {
JOptionPane.showMessageDialog(this.getFrame(), "Desktop is not support to open editor\n You should try manualy");
}
} else {
JOptionPane.showMessageDialog(this.getFrame(), "PicDic.exe is not found");
}
//you can start another apps by using it and can slit your whole project in many apps. it will work lot
Generally, you could create a channel and receive a stop signal in the goroutine.
There two way to create channel in this example.
channel
context. In the example I will demo context.WithCancel
The first demo, use channel
:
package main
import "fmt"
import "time"
func do_stuff() int {
return 1
}
func main() {
ch := make(chan int, 100)
done := make(chan struct{})
go func() {
for {
select {
case ch <- do_stuff():
case <-done:
close(ch)
return
}
time.Sleep(100 * time.Millisecond)
}
}()
go func() {
time.Sleep(3 * time.Second)
done <- struct{}{}
}()
for i := range ch {
fmt.Println("receive value: ", i)
}
fmt.Println("finish")
}
The second demo, use context
:
package main
import (
"context"
"fmt"
"time"
)
func main() {
forever := make(chan struct{})
ctx, cancel := context.WithCancel(context.Background())
go func(ctx context.Context) {
for {
select {
case <-ctx.Done(): // if cancel() execute
forever <- struct{}{}
return
default:
fmt.Println("for loop")
}
time.Sleep(500 * time.Millisecond)
}
}(ctx)
go func() {
time.Sleep(3 * time.Second)
cancel()
}()
<-forever
fmt.Println("finish")
}
You can use +
if you know all the values are strings. Jinja also provides the ~
operator, which will ensure all values are converted to string first.
{% set my_string = my_string ~ stuff ~ ', '%}
TRY
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings
EnableAutoProxyResultCache = dword: 0
PerformSelector:WithObject always takes an object, so in order to pass arguments like int/double/float etc..... You can use something like this.
//NSNumber is an object..
[self performSelector:@selector(setUserAlphaNumber:) withObject: [NSNumber numberWithFloat: 1.0f]
afterDelay:1.5];
-(void) setUserAlphaNumber: (NSNumber*) number{
[txtUsername setAlpha: [number floatValue] ];
}
Same way you can use [NSNumber numberWithInt:] etc.... and in the receiving method you can convert the number into your format as [number int] or [number double].
The following code works for me.
//escape the double quotes in json string
String payload="{\"jsonrpc\":\"2.0\",\"method\":\"changeDetail\",\"params\":[{\"id\":11376}],\"id\":2}";
String requestUrl="https://git.eclipse.org/r/gerrit/rpc/ChangeDetailService";
sendPostRequest(requestUrl, payload);
method implementation:
public static String sendPostRequest(String requestUrl, String payload) {
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer jsonString = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
return jsonString.toString();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
This can be done in one line.
{{corretor.isAdministrador && 'YES' || 'NÂO'}}
Usage in a td
tag:
<td class="text-center">{{corretor.isAdministrador && 'Sim' || 'Não'}}</td>
If you place anything in src/main/resources
directory, then by default it will end up in your final *.jar
. If you are referencing it from some other project and it cannot be found on a classpath, then you did one of those two mistakes:
*.jar
is not correctly loaded (maybe typo in the path?)/src/main/resources/conf/settings.properties
is seen on classpath as classpath:conf/settings.properties
I'm surprised this method hasn't been mentioned: "Some string".split(' ').shift()
To answer the question directly:
let firstWords = []
let str = "Hello m|sss sss|mmm ss";
const codeLines = str.split("|");
for (var i = 0; i < codeLines.length; i++) {
const first = codeLines[i].split(' ').shift()
firstWords.push(first)
}
Don’t overthink what a Namespace is.
Namespace is basically just a Class prefix (like directory in Operating System) to ensure the Class path uniqueness.
Also just to make things clear, the use statement is not doing anything only aliasing your Namespaces so you can use shortcuts or include Classes with the same name but different Namespace in the same file.
E.g:
// You can do this at the top of your Class
use Symfony\Component\Debug\Debug;
if ($_SERVER['APP_DEBUG']) {
// So you can utilize the Debug class it in an elegant way
Debug::enable();
// Instead of this ugly one
// \Symfony\Component\Debug\Debug::enable();
}
If you want to know how PHP Namespaces and autoloading (the old way as well as the new way with Composer) works, you can read the blog post I just wrote on this topic: https://enterprise-level-php.com/2017/12/25/the-magic-behind-autoloading-php-files-using-composer.html
For Grammarly you can use:
<textarea data-gramm="false" />
Use package osext
It's providing function ExecutableFolder()
that returns an absolute path to folder where the currently running program executable reside (useful for cron jobs). It's cross platform.
package main
import (
"github.com/kardianos/osext"
"fmt"
"log"
)
func main() {
folderPath, err := osext.ExecutableFolder()
if err != nil {
log.Fatal(err)
}
fmt.Println(folderPath)
}
I'm using Ubuntu. I spent a whole morning fixing this, tried all different solutions, when I type go version, it's still there, really annoying... Finally this worked for me, hope this will help!
sudo apt-get remove golang-go
sudo apt-get remove --auto-remove golang-go
BigInteger n = new BigInteger(byteArray);
String hexa = n.toString(16));
The fundamental difference, which no other answer seems to have mentioned, is that XML is a markup language (as it actually says in its name), whereas JSON is a way of representing objects (as also noted in its name).
A markup language is a way of adding extra information to free-flowing plain text, e.g
Here is some text.
With XML (using a certain element vocabulary) you can put:
<Document>
<Paragraph Align="Center">
Here <Bold>is</Bold> some text.
</Paragraph>
</Document>
This is what makes markup languages so useful for representing documents.
An object notation like JSON is not as flexible. But this is usually a good thing. When you're representing objects, you simply don't need the extra flexibility. To represent the above example in JSON, you'd actually have to solve some problems manually that XML solves for you.
{
"Paragraphs": [
{
"align": "center",
"content": [
"Here ", {
"style" : "bold",
"content": [ "is" ]
},
" some text."
]
}
]
}
It's not as nice as the XML, and the reason is that we're trying to do markup with an object notation. So we have to invent a way to scatter snippets of plain text around our objects, using "content" arrays that can hold a mixture of strings and nested objects.
On the other hand, if you have typical a hierarchy of objects and you want to represent them in a stream, JSON is better suited to this task than HTML.
{
"firstName": "Homer",
"lastName": "Simpson",
"relatives": [ "Grandpa", "Marge", "The Boy", "Lisa", "I think that's all of them" ]
}
Here's the logically equivalent XML:
<Person>
<FirstName>Homer</FirstName>
<LastName>Simpsons</LastName>
<Relatives>
<Relative>Grandpa</Relative>
<Relative>Marge</Relative>
<Relative>The Boy</Relative>
<Relative>Lisa</Relative>
<Relative>I think that's all of them</Relative>
</Relatives>
</Person>
JSON looks more like the data structures we declare in programming languages. Also it has less redundant repetition of names.
But most importantly of all, it has a defined way of distinguishing between a "record" (items unordered, identified by names) and a "list" (items ordered, identified by position). An object notation is practically useless without such a distinction. And XML has no such distinction! In my XML example <Person>
is a record and <Relatives>
is a list, but they are not identified as such by the syntax.
Instead, XML has "elements" versus "attributes". This looks like the same kind of distinction, but it's not, because attributes can only have string values. They cannot be nested objects. So I couldn't have applied this idea to <Person>
, because I shouldn't have to turn <Relatives>
into a single string.
By using an external schema, or extra user-defined attributes, you can formalise a distinction between lists and records in XML. The advantage of JSON is that the low-level syntax has that distinction built into it, so it's very succinct and universal. This means that JSON is more "self describing" by default, which is an important goal of both formats.
So JSON should be the first choice for object notation, where XML's sweet spot is document markup.
Unfortunately for XML, we already have HTML as the world's number one rich text markup language. An attempt was made to reformulate HTML in terms of XML, but there isn't much advantage in this.
So XML should (in my opinion) have been a pretty limited niche technology, best suited only for inventing your own rich text markup languages if you don't want to use HTML for some reason. The problem was that in 1998 there was still a lot of hype about the Web, and XML became popular due to its superficial resemblance to HTML. It was a strange design choice to try to apply to hierarchical data a syntax actually designed for convenient markup.
you can use this trick to run tomcat using cmd and directly by tomcat bin folder.
1. set the path of jdk.
2.
To set path. go to Desktop and right click on computer icon. Click the Properties
go to Advance System Settings.
then Click Advance to Environment variables.
Click new and set path AS,
in the column Variable name=JAVA_HOME
Variable Value=C:\Program Files\Java\jdk1.6.0_19
Click ok ok.
now path is stetted.
3.
Go to tomcat folder where you installed the tomcat. go to bin folder. there are two window batch files.
1.Startup
2.Shutdown.
By using cmd if you installed the tomcate in D Drive
type on cmd screen
D:
Cd tomcat\bin then type Startup.
4. By clicking them you can start and stop the tomcat.
5.
Final step.
if you start and want to check it.
open a Browser in URL bar type.
**HTTP://localhost:8080/**
public class GetUsers extends AsyncTask {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public String connect()
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpPost htopost = new HttpPost("URL");
htopost.setHeader(new BasicHeader("Authorization","Basic Og=="));
try {
JSONObject param = new JSONObject();
param.put("PageSize",100);
param.put("Userid",userId);
param.put("CurrentPage",1);
htopost.setEntity(new StringEntity(param.toString()));
// Execute the request
HttpResponse response;
response = httpclient.execute(htopost);
// Examine the response status
// Get hold of the response entity
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
// A Simple JSONObject Creation
json = new JSONArray(result);
// Closing the input stream will trigger connection release
instream.close();
return ""+response.getStatusLine().getStatusCode();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected String doInBackground(String... urls) {
return connect();
}
@Override
protected void onPostExecute(String status){
try {
if(status.equals("200"))
{
Global.defaultMoemntLsit.clear();
for (int i = 0; i < json.length(); i++) {
JSONObject ojb = json.getJSONObject(i);
UserMomentModel u = new UserMomentModel();
u.setId(ojb.getString("Name"));
u.setUserId(ojb.getString("ID"));
Global.defaultMoemntLsit.add(u);
}
userAdapter = new UserAdapter(getActivity(), Global.defaultMoemntLsit);
recycleView.setAdapter(userMomentAdapter);
recycleView.setLayoutManager(mLayoutManager);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
If you want to plot lines instead of points, see this example, modified here to plot good/bad points representing a function as a black/red as appropriate:
def plot(xx, yy, good):
"""Plot data
Good parts are plotted as black, bad parts as red.
Parameters
----------
xx, yy : 1D arrays
Data to plot.
good : `numpy.ndarray`, boolean
Boolean array indicating if point is good.
"""
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
from matplotlib.colors import from_levels_and_colors
from matplotlib.collections import LineCollection
cmap, norm = from_levels_and_colors([0.0, 0.5, 1.5], ['red', 'black'])
points = np.array([xx, yy]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lines = LineCollection(segments, cmap=cmap, norm=norm)
lines.set_array(good.astype(int))
ax.add_collection(lines)
plt.show()
I think natually do it is straightforward, whether Intellij IDEA or Android Studio, I always click new Java class menu, and then typing the class name, press Enter to create. after that, I manually typing "extends Activity" in the class file, and then import the class by shortcut key. finally, I also manually override the onCreate() method and invoke the setContentView() method.
"Run-time error '3061'. Too few parameters. Expected 1."
I believe this happens when the field name(s) in your sql query do not match the table field name(s), i.e. a field name in the query is wrong or perhaps the table is missing the field altogether.
I guess I'm unclear about what the OP was really asking for... Do you want to pass the whole array/list and operate on it inside the function? Or do you want the same thing done on every value/item in the array/list. If the latter is what you wish I have found a method which works well.
I'm more familiar with programming languages such as Fortran and C, in which you can define elemental functions which operate on each element inside an array. I finally tracked down the python equivalent to this and thought I would repost the solution here. The key is to 'vectorize' the function. Here is an example:
def myfunc(a,b):
if (a>b): return a
else: return b
vecfunc = np.vectorize(myfunc)
result=vecfunc([[1,2,3],[5,6,9]],[7,4,5])
print(result)
Output:
[[7 4 5]
[7 6 9]]
I usually do like this to remove most of the noise:
void LogException(Exception error) {
Exception realerror = error;
while (realerror.InnerException != null)
realerror = realerror.InnerException;
Console.WriteLine(realerror.ToString())
}
Edit: I forgot about this answer and is surprised no one pointed out that you can just do
void LogException(Exception error) {
Console.WriteLine(error.GetBaseException().ToString())
}
json = " { \"success\" : false, \"errors\": { \"text\" : \"??????!\" } }";
return new MemoryStream(Encoding.UTF8.GetBytes(json));
Npm and Bower are both dependency management tools. But the main difference between both is npm is used for installing Node js modules but bower js is used for managing front end components like html, css, js etc.
A fact that makes this more confusing is that npm provides some packages which can be used in front-end development as well, like grunt
and jshint
.
These lines add more meaning
Bower, unlike npm, can have multiple files (e.g. .js, .css, .html, .png, .ttf) which are considered the main file(s). Bower semantically considers these main files, when packaged together, a component.
Edit: Grunt is quite different from Npm and Bower. Grunt is a javascript task runner tool. You can do a lot of things using grunt which you had to do manually otherwise. Highlighting some of the uses of Grunt:
There are grunt plugins for sass compilation, uglifying your javascript, copy files/folders, minifying javascript etc.
Please Note that grunt plugin is also an npm package.
Question-1
When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json
It really depends where does this package belong to. If it is a node module(like grunt,request) then it will go in package.json otherwise into bower json.
Question-2
When should I ever install packages explicitly like that without adding them to the file that manages dependencies
It does not matter whether you are installing packages explicitly or mentioning the dependency in .json file. Suppose you are in the middle of working on a node project and you need another project, say request
, then you have two options:
OR
npm install --save request
--save
options adds the dependency to package.json file as well. If you don't specify --save
option, it will only download the package but the json file will be unaffected.
You can do this either way, there will not be a substantial difference.
Web.Config file:
<configuration>
<system.net>
<mailSettings>
<smtp from="[email protected]">
<network host="smtp.gmail.com"
port="587"
userName="[email protected]"
password="yourpassword"
enableSsl="true"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
var getDirectories = (rootdir , cb) => {
fs.readdir(rootdir, (err, files) => {
if(err) throw err ;
var dirs = files.map(filename => path.join(rootdir,filename)).filter( pathname => fs.statSync(pathname).isDirectory());
return cb(dirs);
})
}
getDirectories( myDirectories => console.log(myDirectories));``
And as suggested above by Siu Ching Pong -Asuka Kenji with the function which in my opinion makes more sense and leaves you with the convenience of the map type without the function wrapper around:
// romanNumeralDict returns map[int]string dictionary, since the return
// value is always the same it gives the pseudo-constant output, which
// can be referred to in the same map-alike fashion.
var romanNumeralDict = func() map[int]string { return map[int]string {
1000: "M",
900: "CM",
500: "D",
400: "CD",
100: "C",
90: "XC",
50: "L",
40: "XL",
10: "X",
9: "IX",
5: "V",
4: "IV",
1: "I",
}
}
func printRoman(key int) {
fmt.Println(romanNumeralDict()[key])
}
func printKeyN(key, n int) {
fmt.Println(strings.Repeat(romanNumeralDict()[key], n))
}
func main() {
printRoman(1000)
printRoman(50)
printKeyN(10, 3)
}
Use Simple HTML
<frameset cols="25%,*">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
</frameset>
Git add .
Git status //Check file that being modified
// git reset HEAD --- replace to which file you want to ignore
git reset HEAD .idea/ <-- Those who wanted to exclude .idea from before commit // git check status and the idea file will be gone, and you're ready to go!
git commit -m ''
git push
there are 600 million ticks per minute. ticksperminute
improving @josh answer for all fields:
class Person(models.Model):
name = models.CharField()
def __init__(self, *args, **kwargs):
super(Person, self).__init__(*args, **kwargs)
self._original_fields = dict([(field.attname, getattr(self, field.attname))
for field in self._meta.local_fields if not isinstance(field, models.ForeignKey)])
def save(self, *args, **kwargs):
if self.id:
for field in self._meta.local_fields:
if not isinstance(field, models.ForeignKey) and\
self._original_fields[field.name] != getattr(self, field.name):
# Do Something
super(Person, self).save(*args, **kwargs)
just to clarify, the getattr works to get fields like person.name
with strings (i.e. getattr(person, "name")
The following code implements a default context menu known from Windows
with copy, cut, paste, select all, undo and redo functions. It also works on Linux
and Mac OS X
:
import javax.swing.*;
import javax.swing.text.JTextComponent;
import javax.swing.undo.UndoManager;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class DefaultContextMenu extends JPopupMenu
{
private Clipboard clipboard;
private UndoManager undoManager;
private JMenuItem undo;
private JMenuItem redo;
private JMenuItem cut;
private JMenuItem copy;
private JMenuItem paste;
private JMenuItem delete;
private JMenuItem selectAll;
private JTextComponent textComponent;
public DefaultContextMenu()
{
undoManager = new UndoManager();
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
addPopupMenuItems();
}
private void addPopupMenuItems()
{
undo = new JMenuItem("Undo");
undo.setEnabled(false);
undo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
undo.addActionListener(event -> undoManager.undo());
add(undo);
redo = new JMenuItem("Redo");
redo.setEnabled(false);
redo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
redo.addActionListener(event -> undoManager.redo());
add(redo);
add(new JSeparator());
cut = new JMenuItem("Cut");
cut.setEnabled(false);
cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
cut.addActionListener(event -> textComponent.cut());
add(cut);
copy = new JMenuItem("Copy");
copy.setEnabled(false);
copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
copy.addActionListener(event -> textComponent.copy());
add(copy);
paste = new JMenuItem("Paste");
paste.setEnabled(false);
paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
paste.addActionListener(event -> textComponent.paste());
add(paste);
delete = new JMenuItem("Delete");
delete.setEnabled(false);
delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
delete.addActionListener(event -> textComponent.replaceSelection(""));
add(delete);
add(new JSeparator());
selectAll = new JMenuItem("Select All");
selectAll.setEnabled(false);
selectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
selectAll.addActionListener(event -> textComponent.selectAll());
add(selectAll);
}
private void addTo(JTextComponent textComponent)
{
textComponent.addKeyListener(new KeyAdapter()
{
@Override
public void keyPressed(KeyEvent pressedEvent)
{
if ((pressedEvent.getKeyCode() == KeyEvent.VK_Z)
&& ((pressedEvent.getModifiersEx() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0))
{
if (undoManager.canUndo())
{
undoManager.undo();
}
}
if ((pressedEvent.getKeyCode() == KeyEvent.VK_Y)
&& ((pressedEvent.getModifiersEx() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0))
{
if (undoManager.canRedo())
{
undoManager.redo();
}
}
}
});
textComponent.addMouseListener(new MouseAdapter()
{
@Override
public void mousePressed(MouseEvent releasedEvent)
{
handleContextMenu(releasedEvent);
}
@Override
public void mouseReleased(MouseEvent releasedEvent)
{
handleContextMenu(releasedEvent);
}
});
textComponent.getDocument().addUndoableEditListener(event -> undoManager.addEdit(event.getEdit()));
}
private void handleContextMenu(MouseEvent releasedEvent)
{
if (releasedEvent.getButton() == MouseEvent.BUTTON3)
{
processClick(releasedEvent);
}
}
private void processClick(MouseEvent event)
{
textComponent = (JTextComponent) event.getSource();
textComponent.requestFocus();
boolean enableUndo = undoManager.canUndo();
boolean enableRedo = undoManager.canRedo();
boolean enableCut = false;
boolean enableCopy = false;
boolean enablePaste = false;
boolean enableDelete = false;
boolean enableSelectAll = false;
String selectedText = textComponent.getSelectedText();
String text = textComponent.getText();
if (text != null)
{
if (text.length() > 0)
{
enableSelectAll = true;
}
}
if (selectedText != null)
{
if (selectedText.length() > 0)
{
enableCut = true;
enableCopy = true;
enableDelete = true;
}
}
if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor) && textComponent.isEnabled())
{
enablePaste = true;
}
undo.setEnabled(enableUndo);
redo.setEnabled(enableRedo);
cut.setEnabled(enableCut);
copy.setEnabled(enableCopy);
paste.setEnabled(enablePaste);
delete.setEnabled(enableDelete);
selectAll.setEnabled(enableSelectAll);
// Shows the popup menu
show(textComponent, event.getX(), event.getY());
}
public static void addDefaultContextMenu(JTextComponent component)
{
DefaultContextMenu defaultContextMenu = new DefaultContextMenu();
defaultContextMenu.addTo(component);
}
}
Usage:
JTextArea textArea = new JTextArea();
DefaultContextMenu.addDefaultContextMenu(textArea);
Now the textArea
will have a context menu when it is right-clicked on.
Google has ended support for eclipse plugin. If you prefer to use eclipse still you can download Eclipse Android Development Tool from
If you are looking for range like function which works for float type, then here is a very good article.
def frange(start, stop, step=1.0):
''' "range()" like function which accept float type'''
i = start
while i < stop:
yield i
i += step
# Generate one element at a time.
# Preferred when you don't need all generated elements at the same time.
# This will save memory.
for i in frange(1.0, 2.0, 0.5):
print i # Use generated element.
# Generate all elements at once.
# Preferred when generated list ought to be small.
print list(frange(1.0, 10.0, 0.5))
Output:
1.0
1.5
[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5]
Read : 101 LINQ Samples in that LINQ - Grouping Operators from Microsoft MSDN site
var x = from t in types group t by t.Type
into grp
select new { type = grp.key, count = grp.Count() };
forsingle object make use of stringbuilder and append it that will do or convert this in form of dictionary
// fordictionary
var x = (from t in types group t by t.Type
into grp
select new { type = grp.key, count = grp.Count() })
.ToDictionary( t => t.type, t => t.count);
//for stringbuilder not sure for this
var x = from t in types group t by t.Type
into grp
select new { type = grp.key, count = grp.Count() };
StringBuilder MyStringBuilder = new StringBuilder();
foreach (var res in x)
{
//: is separator between to object
MyStringBuilder.Append(result.Type +" , "+ result.Count + " : ");
}
Console.WriteLine(MyStringBuilder.ToString());
hi just to come back at the question. If you want to sort the List of this sequence "1" "10" "100" "200" "2" "20" "3" "30" "300" and get the sorted items in this form 1;2;3;10;20;30;100;200;300 you can use this:
public class OrderingAscending : IComparer<String>
{
public int Compare(String x, String y)
{
Int32.TryParse(x, out var xtmp);
Int32.TryParse(y, out var ytmp);
int comparedItem = xtmp.CompareTo(ytmp);
return comparedItem;
}
}
and you can use it in code behind in this form:
IComparer<String> comparerHandle = new OrderingAscending();
yourList.Sort(comparerHandle);
For a pointer, we could just use
*pointervariable.foo
But the .
operator has greater precedence than the *
operator, so .
is evaluated first. So we need to force this with parenthesis:
(*pointervariable).foo
But typing the ()'s all the time is hard, so they developed ->
as a shortcut to say the same thing. If you are accessing a property of an object or object reference, use .
If you are accessing a property of an object through a pointer, use ->
It's worth noting that today, the use of floated elements for layout is getting more and more discouraged with the use of better alternatives.
display: inline-block
- BetterFlexbox is supported from Firefox 18, Chrome 21, Opera 12.10, and Internet Explorer 10, Safari 6.1 (including Mobile Safari) and Android's default browser 4.4.
For a detailed browser list see: https://caniuse.com/flexbox.
(Perhaps once its position is established completely, it may be the absolutely recommended way of laying out elements.)
A clearfix is a way for an element to automatically clear its child elements, so that you don't need to add additional markup. It's generally used in float layouts where elements are floated to be stacked horizontally.
The clearfix is a way to combat the zero-height container problem for floated elements
A clearfix is performed as follows:
.clearfix:after {
content: " "; /* Older browser do not support empty content */
visibility: hidden;
display: block;
height: 0;
clear: both;
}
Or, if you don't require IE<8 support, the following is fine too:
.clearfix:after {
content: "";
display: table;
clear: both;
}
Normally you would need to do something as follows:
<div>
<div style="float: left;">Sidebar</div>
<div style="clear: both;"></div> <!-- Clear the float -->
</div>
With clearfix, you only need the following:
<div class="clearfix">
<div style="float: left;" class="clearfix">Sidebar</div>
<!-- No Clearing div! -->
</div>
Read about it in this article - by Chris Coyer @ CSS-Tricks
One alternative method is convert your List
to array
, iterate them and remove them directly from the List
based on your logic.
List<String> myList = new ArrayList<String>(); // You can use either list or set
myList.add("abc");
myList.add("abcd");
myList.add("abcde");
myList.add("abcdef");
myList.add("abcdefg");
Object[] obj = myList.toArray();
for(Object o:obj) {
if(condition)
myList.remove(o.toString());
}
For anyone completely new to Qt Creator like me, you can modify your project's .pro file from within Qt Creator:
Just double-click on "your project name".pro in the Projects window and add the include path at the bottom of the .pro file like I've done.
This is for vmware workstation 6.5
It is pretty far down.
select Create new virtual machine ->
select custom ->
on compatibility page take defaults ->
check I will install os later
-> click through several pages choosing other for OS, give it a name, make sure it IS NOT in the same folder as the VMDK file. Choose bridged network.
You will now see a screen asking to select disk, select existing virual disk. then browse and select the VMDK file
Your syntax is incorrect. The var
keyword in your for
loop must be followed by a variable name, in this case its propName
var propValue;
for(var propName in nyc) {
propValue = nyc[propName]
console.log(propName,propValue);
}
I suggest you have a look here for some basics:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
**The simplest way to drop and recreate a stored proc in T-Sql is **
Use DatabaseName
go
If Object_Id('schema.storedprocname') is not null
begin
drop procedure schema.storedprocname
end
go
create procedure schema.storedprocname
as
begin
end
I added substr to the test of https://stackoverflow.com/a/25472778/2386943 and that's the fastet way I could test (CentOS PHP 5.3.3, Ubuntu PHP 5.5.9) both with an i5.
$classNameWithNamespace=get_class($this);
return substr($classNameWithNamespace, strrpos($classNameWithNamespace, '\\')+1);
Results
Reflection: 0.068084406852722 s ClassA
Basename: 0.12301609516144 s ClassA
Explode: 0.14073524475098 s ClassA
Substring: 0.059865570068359 s ClassA
Code
namespace foo\bar\baz;
class ClassA{
public function getClassExplode(){
$c = array_pop(explode('\\', get_class($this)));
return $c;
}
public function getClassReflection(){
$c = (new \ReflectionClass($this))->getShortName();
return $c;
}
public function getClassBasename(){
$c = basename(str_replace('\\', '/', get_class($this)));
return $c;
}
public function getClassSubstring(){
$classNameWithNamespace = get_class($this);
return substr($classNameWithNamespace, strrpos($classNameWithNamespace, '\\')+1);
}
}
$a = new ClassA();
$num = 100000;
$rounds = 10;
$res = array(
"Reflection" => array(),
"Basename" => array(),
"Explode" => array(),
"Substring" => array()
);
for($r = 0; $r < $rounds; $r++){
$start = microtime(true);
for($i = 0; $i < $num; $i++){
$a->getClassReflection();
}
$end = microtime(true);
$res["Reflection"][] = ($end-$start);
$start = microtime(true);
for($i = 0; $i < $num; $i++){
$a->getClassBasename();
}
$end = microtime(true);
$res["Basename"][] = ($end-$start);
$start = microtime(true);
for($i = 0; $i < $num; $i++){
$a->getClassExplode();
}
$end = microtime(true);
$res["Explode"][] = ($end-$start);
$start = microtime(true);
for($i = 0; $i < $num; $i++){
$a->getClassSubstring();
}
$end = microtime(true);
$res["Substring"][] = ($end-$start);
}
echo "Reflection: ".array_sum($res["Reflection"])/count($res["Reflection"])." s ".$a->getClassReflection()."\n";
echo "Basename: ".array_sum($res["Basename"])/count($res["Basename"])." s ".$a->getClassBasename()."\n";
echo "Explode: ".array_sum($res["Explode"])/count($res["Explode"])." s ".$a->getClassExplode()."\n";
echo "Substring: ".array_sum($res["Substring"])/count($res["Substring"])." s ".$a->getClassSubstring()."\n";
==UPDATE==
As mentioned in the comments by @MrBandersnatch there is even a faster way to do this:
return substr(strrchr(get_class($this), '\\'), 1);
Here are the updated test results with "SubstringStrChr" (saves up to about 0.001 s):
Reflection: 0.073065280914307 s ClassA
Basename: 0.12585079669952 s ClassA
Explode: 0.14593172073364 s ClassA
Substring: 0.060415267944336 s ClassA
SubstringStrChr: 0.059880912303925 s ClassA
I did this as follows, but its relevet only if your goal is to close / open the keyboad.
close example: (checking if keyboard already closed, if not - closing)
imm.showSoftInput(etSearch, InputMethodManager.HIDE_IMPLICIT_ONLY, new ResultReceiver(null) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode != InputMethodManager.RESULT_UNCHANGED_HIDDEN)
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
});
Take a look at the equation you can find that binary cross entropy not only punish those label = 1, predicted =0, but also label = 0, predicted = 1.
However categorical cross entropy only punish those label = 1 but predicted = 1.That's why we make assumption that there is only ONE label positive.
Just try this in razor
@{
var selectList = new SelectList(
new List<SelectListItem>
{
new SelectListItem {Text = "Google", Value = "Google"},
new SelectListItem {Text = "Other", Value = "Other"},
}, "Value", "Text");
}
and then
@Html.DropDownListFor(m => m.YourFieldName, selectList, "Default label", new { @class = "css-class" })
or
@Html.DropDownList("ddlDropDownList", selectList, "Default label", new { @class = "css-class" })
The /g
modifier is used to perform a global match (find all matches rather than stopping after the first)
You can use \d
for digit, as it is shorter than [0-9]
.
JavaScript:
var s = "04.07.2012";
echo(s.replace(/\d/g, "X"));
Output:
XX.XX.XXXX
And you can't use valueOf()?
Edit: Btw, there is nothing stopping you from using static { } in an enum.
select age(timestamp_A, timestamp_B)
Answering to Igor's comment:
select age('2013-02-28 11:01:28'::timestamp, '2011-12-31 11:00'::timestamp);
age
-------------------------------
1 year 1 mon 28 days 00:01:28
It has discussed many times in SO. In short, "%z" is not supported because platform not support it. My solution is a new one, just skip the time zone.:
datetime.datetime.strptime(re.sub(r"[+-]([0-9])+", "", "Tue May 08 15:14:45 +0800 2012"),"%a %b %d %H:%M:%S %Y")
This turned out to be a stupid error. My log4j wasn't configured to capture my error output. I was throwing configuration errors in the background and once I fixed those I was good to go and my request mappings worked fine.
The rest of these answers are out of date and/or over the top complicated for something that should be simple IMO (how long has gzip been around for now? longer than Java...) From the docs:
In application.properties 1.3+
# ???
server.compression.enabled=true
# opt in to content types
server.compression.mime-types=application/json,application/xml,text/html,text/xml,text/plain,application/javascript,text/css
# not worth the CPU cycles at some point, probably
server.compression.min-response-size=10240
In application.properties 1.2.2 - <1.3
server.tomcat.compression=on
server.tomcat.compressableMimeTypes=application/json,application/xml,text/html,text/xml,text/plain,application/javascript,text/css
Older than 1.2.2:
@Component
public class TomcatCustomizer implements TomcatConnectorCustomizer {
@Override
public void customize(Connector connector) {
connector.setProperty("compression", "on");
// Add json and xml mime types, as they're not in the mimetype list by default
connector.setProperty("compressableMimeType", "text/html,text/xml,text/plain,application/json,application/xml");
}
}
If you plan to deploy to a non embedded tomcat you will have to enable it in server.xml http://tomcat.apache.org/tomcat-9.0-doc/config/http.html#Standard_Implementation
Also to avoid all of this consider using a proxy/load balancer setup in front of Tomcat with nginx and/or haproxy or similar since it will handle static assets and gzip MUCH more efficiently and easily than Java/Tomcat's threading model.
You don't want to throw 'cat in the bath because it's busy compressing stuff instead of serving up requests (or more likely spinning up threads/eating CPU/heap sitting around waiting for database IO to occur while running up your AWS bill which is why traditional Java/Tomcat might not be a good idea to begin with depending on what you are doing but I digress...)
Found it at http://www.linuxquestions.org/questions/suse-novell-60/howto-kill-defunct-processes-574612/
2) Here a great tip from another user (Thxs Bill Dandreta): Sometimes
kill -9 <pid>
will not kill a process. Run
ps -xal
the 4th field is the parent process, kill all of a zombie's parents and the zombie dies!
Example
4 0 18581 31706 17 0 2664 1236 wait S ? 0:00 sh -c /usr/bin/gcc -fomit-frame-pointer -O -mfpmat
4 0 18582 18581 17 0 2064 828 wait S ? 0:00 /usr/i686-pc-linux-gnu/gcc-bin/3.3.6/gcc -fomit-fr
4 0 18583 18582 21 0 6684 3100 - R ? 0:00 /usr/lib/gcc-lib/i686-pc-linux-gnu/3.3.6/cc1 -quie
18581
, 18582
, 18583
are zombies -
kill -9 18581 18582 18583
has no effect.
kill -9 31706
removes the zombies.
You can try FileUtils#forceMkdir
FileUtils.forceMkdir("/path/directory");
This library have a lot of useful functions.
I solved this problem by doing the "subselect" like it:
string newQuery = "select * from (" + query + ") as temp";
When do it on mysql, all collunms properties (unique, non-null ...) will be cleared.
Your .mobile
div has the following styles on it:
.mobile {
display: none !important;
visibility: hidden !important;
}
Therefore you need to override the visibility
property with visible
in addition to overriding the display
property with block
. Like so:
.visible-sm {
display: block !important;
visibility: visible !important;
}
Postgres allows the use of any existing database on the server as a template when creating a new database. I'm not sure whether pgAdmin gives you the option on the create database dialog but you should be able to execute the following in a query window if it doesn't:
CREATE DATABASE newdb WITH TEMPLATE originaldb OWNER dbuser;
Still, you may get:
ERROR: source database "originaldb" is being accessed by other users
To disconnect all other users from the database, you can use this query:
SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity
WHERE pg_stat_activity.datname = 'originaldb' AND pid <> pg_backend_pid();
For me the problem was that right after making the request, my main activity launched another activity. That superseded the dialog so it was never seen.
.getBoundingClientRect() returns the size of an element and its position relative to the viewport.We can easily get following
Example :
var element = d3.select('.elementClassName').node();
element.getBoundingClientRect().width;
Wow...there is a lot of low-level security code in this thread -- most of which did not work for me, either -- although I learned a lot in the process. One thing that I learned is that most of this code is not geared to applications seeking per user access rights -- it is for Administrators wanting to alter rights programmatically, which -- as has been pointed out -- is not a good thing. As a developer, I cannot use the "easy way out" -- by running as Administrator -- which -- I am not one on the machine that runs the code, nor are my users -- so, as clever as these solutions are -- they are not for my situation, and probably not for most rank and file developers, either.
Like most posters of this type of question -- I initially felt it was "hackey", too -- I have since decided that it is perfectly alright to try it and let the possible exception tell you exactly what the user's rights are -- because the information I got did not tell me what the rights actually were. The code below -- did.
Private Function CheckUserAccessLevel(folder As String) As Boolean
Try
Dim newDir As String = String.Format("{0}{1}{2}",
folder,
If(folder.EndsWith("\"),
"",
"\"),
"LookWhatICanDo")
Dim lookWhatICanDo = Directory.CreateDirectory(newDir)
Directory.Delete(newDir)
Return True
Catch ex As Exception
Return False
End Try
End Function
Try this
$(this).datepicker("destroy").datepicker({
changeMonth: false, changeYear: false,defaultDate:new Date(), dateFormat: "dd-mm-yy", showOn: "focus", yearRange: "-5:+10"
}).focus();
System.out.println(first.substring(0,1).toUpperCase());
System.out.println(last.substring(0,1).toUpperCase());
for API level 21 or higher just use
android:progressBackgroundTint="@color/yourBackgroundColor"
android:progressTint="@color/yourColor"
Simply add
android:keepScreenOn="true"
or call
setKeepScreenOn(true)
on parent view.
I came hear looking for this answer but also wanted to pipe it to another command. The given answer is correct but if anyone wants to pipe it, you need to pipe it before the multi-line string like this
echo | tee /tmp/pipetest << EndOfMessage
This is line 1.
This is line 2.
Line 3.
EndOfMessage
This will allow you to have a multi line string but also put it in the stdin of a subsequent command.
You can delay your code using setTimeout
to execute after click
function changeLink(){
setTimeout(function() {
var link = document.getElementById("mylink");
link.setAttribute('href', "http://facebook.com");
document.getElementById("mylink").innerHTML = "facebook";
}, 100);
}
The fastest way I was able to find (and using ) is with convert().
from Doc. CONVERT() with USING is used to convert data between different character sets.
Example:
convert(string USING ascii)
In your case the right character set will be self defined
NOTE from Doc. The USING form of CONVERT()
is available as of 4.1.0.
Follow These Steps and it Will Work For You :
msfconsole
db_connect user:pass@host:port.../database
sorry I don't remember it but it's like this one then replace the user and the password and the host and the database with the information included in the database.yml
in the emplacement: /usr/share/metasploit-framework/config
msfconsole: msf>db_status
you will see that it's connected.# or even faster copy paste answer if you have sudo on the host
sudo su - postgres -c "psql template1 -c 'CREATE EXTENSION IF NOT EXISTS \"dblink\";'"
Try this solution
<activity android:name=".SplashActivity"
android:label="@string/app_name"
android:icon="@drawable/ic_launcher">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity-alias android:label="ShortCut"
android:icon="@drawable/ic_short_cut"
android:name=".SplashActivityAlias"
android:enabled="false"
android:targetActivity=".SplashActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
Add the following code when you want to change your app icon
PackageManager pm = getPackageManager();
pm.setComponentEnabledSetting(
new ComponentName(YourActivity.this,
"your_package_name.SplashActivity"),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
pm.setComponentEnabledSetting(
new ComponentName(YourActivity.this,
"your_package_name.SplashActivityAlias"),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
To have the dynamic cell height as the text of Label increases, you first need to calculate height,that the text gonna use in -heightForRowAtIndexPath
delegate method and return it with the added heights of other lables,images (max height of text+height of other static componenets) and use same height in cell creation.
#define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 300.0f
#define CELL_CONTENT_MARGIN 10.0f
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
if (indexPath.row == 2) { // the cell you want to be dynamic
NSString *text = dynamic text for your label;
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = MAX(size.height, 44.0f);
return height + (CELL_CONTENT_MARGIN * 2);
}
else {
return 44; // return normal cell height
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UILabel *label;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] ;
}
label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 280, 34)];
[label setNumberOfLines:2];
label.backgroundColor = [UIColor clearColor];
[label setFont:[UIFont systemFontOfSize:FONT_SIZE]];
label.adjustsFontSizeToFitWidth = NO;
[[cell contentView] addSubview:label];
NSString *text = dynamic text fro your label;
[label setText:text];
if (indexPath.row == 2) {// the cell which needs to be dynamic
[label setNumberOfLines:0];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
[label setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];
}
return cell;
}
I recommend to read Microsoft guide for use Relationships, Navigation Properties and Foreign Keys in EF Code First, like this picture.
Guide link below:
https://docs.microsoft.com/en-gb/ef/ef6/fundamentals/relationships?redirectedfrom=MSDN
$sb = [scriptblock]::create($command)
I found a solution:
print("My message here");
I had to create a timer for teachers grading students' work. Here's one I used which is entirely based on elapsed time since the grading begun by storing the system time at the point that the page is loaded, and then comparing it every half second to the system time at that point:
var startTime = Math.floor(Date.now() / 1000); //Get the starting time (right now) in seconds
localStorage.setItem("startTime", startTime); // Store it if I want to restart the timer on the next page
function startTimeCounter() {
var now = Math.floor(Date.now() / 1000); // get the time now
var diff = now - startTime; // diff in seconds between now and start
var m = Math.floor(diff / 60); // get minutes value (quotient of diff)
var s = Math.floor(diff % 60); // get seconds value (remainder of diff)
m = checkTime(m); // add a leading zero if it's single digit
s = checkTime(s); // add a leading zero if it's single digit
document.getElementById("idName").innerHTML = m + ":" + s; // update the element where the timer will appear
var t = setTimeout(startTimeCounter, 500); // set a timeout to update the timer
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
startTimeCounter();
This way, it really doesn't matter if the 'setTimeout' is subject to execution delays, the elapsed time is always relative the system time when it first began, and the system time at the time of update.
You could use the following code, it does a recursive call into the function in order to properly wait for the desired time.
function exportar(page,miliseconds,totalpages)
{
if (page <= totalpages)
{
nextpage = page + 1;
console.log('fnExcelReport('+ page +'); nextpage = '+ nextpage + '; miliseconds = '+ miliseconds + '; totalpages = '+ totalpages );
fnExcelReport(page);
setTimeout(function(){
exportar(nextpage,miliseconds,totalpages);
},miliseconds);
};
}
I have recently not used VS 2010.
Does your application really build correctly?
To get more control in VS 2010 C++ Express
, you can check menu item "Expert Settings
" under Tools>Settings
to get a Build' menu
.
After clicking Build->Build Solution
(or Rebuild
), you may verify in Output
window (View->Outout
), if your application is compiling and linking correctly.
Sources :
Hope it helps.
Here is an extension to the Prototype widget that Jeremy posted on June 4th:
It stops the user from entering more characters if you're using limits in textareas. It checks if there are characters left. If the user copies text into the textarea, the text is cut off at the max. length:
/**
* Prototype Widget: Textarea
* Automatically resizes a textarea and displays the number of remaining chars
*
* From: http://stackoverflow.com/questions/7477/autosizing-textarea
* Inspired by: http://github.com/jaz303/jquery-grab-bag/blob/63d7e445b09698272b2923cb081878fd145b5e3d/javascripts/jquery.autogrow-textarea.js
*/
if (window.Widget == undefined) window.Widget = {};
Widget.Textarea = Class.create({
initialize: function(textarea, options){
this.textarea = $(textarea);
this.options = $H({
'min_height' : 30,
'max_length' : 400
}).update(options);
this.textarea.observe('keyup', this.refresh.bind(this));
this._shadow = new Element('div').setStyle({
lineHeight : this.textarea.getStyle('lineHeight'),
fontSize : this.textarea.getStyle('fontSize'),
fontFamily : this.textarea.getStyle('fontFamily'),
position : 'absolute',
top: '-10000px',
left: '-10000px',
width: this.textarea.getWidth() + 'px'
});
this.textarea.insert({ after: this._shadow });
this._remainingCharacters = new Element('p').addClassName('remainingCharacters');
this.textarea.insert({after: this._remainingCharacters});
this.refresh();
},
refresh: function(){
this._shadow.update($F(this.textarea).replace(/\n/g, '<br/>'));
this.textarea.setStyle({
height: Math.max(parseInt(this._shadow.getHeight()) + parseInt(this.textarea.getStyle('lineHeight').replace('px', '')), this.options.get('min_height')) + 'px'
});
// Keep the text/character count inside the limits:
if($F(this.textarea).length > this.options.get('max_length')){
text = $F(this.textarea).substring(0, this.options.get('max_length'));
this.textarea.value = text;
return false;
}
var remaining = this.options.get('max_length') - $F(this.textarea).length;
this._remainingCharacters.update(Math.abs(remaining) + ' characters remaining'));
}
});
Try
cordova platform version
It will give you the following output
Installed platforms: android 3.5.1, ios 3.5.0
Available platforms: amazon-fireos, blackberry10, browser, firefoxos
Also to know the version of cordodva cli try
cordova -v
I know this post is a bit old, but thought I would add the functions I use that take into account any filters and any <![CDATA[some stuff]]>
content you want to safely exclude.
Simply add to your functions.php file and use anywhere you would like, such as:
content(53);
or
excerpt(27);
Enjoy!
//limit excerpt
function excerpt($limit) {
$excerpt = explode(' ', get_the_excerpt(), $limit);
if (count($excerpt)>=$limit) {
array_pop($excerpt);
$excerpt = implode(" ",$excerpt).'...';
} else {
$excerpt = implode(" ",$excerpt);
}
$excerpt = preg_replace('`\[[^\]]*\]`','',$excerpt);
return $excerpt;
}
//limit content
function content($limit) {
$content = explode(' ', get_the_content(), $limit);
if (count($content)>=$limit) {
array_pop($content);
$content = implode(" ",$content).'...';
} else {
$content = implode(" ",$content);
}
$content = preg_replace('/\[.+\]/','', $content);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
return $content;
}
I guess that what you want to do is an UNION
of both tables.
If both tables have the same columns then you can just do
SELECT category_id, col1, col2, col3
FROM items_a
UNION
SELECT category_id, col1, col2, col3
FROM items_b
Else, you might have to do something like
SELECT category_id, col1, col2, col3
FROM items_a
UNION
SELECT category_id, col_1 as col1, col_2 as col2, col_3 as col3
FROM items_b
Use:
public static class StringExtensions
{
/// <summary>
/// Cut End. "12".SubstringFromEnd(1) -> "1"
/// </summary>
public static string SubstringFromEnd(this string value, int startindex)
{
if (string.IsNullOrEmpty(value)) return value;
return value.Substring(0, value.Length - startindex);
}
}
I prefer an extension method here for two reasons:
Example: f1.Substring(directorypathLength).SubstringFromEnd(1)
This one also works for nullable bools.
[ValueConversion(typeof(bool?), typeof(bool))]
public class InverseBooleanConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (targetType != typeof(bool?))
{
throw new InvalidOperationException("The target must be a nullable boolean");
}
bool? b = (bool?)value;
return b.HasValue && !b.Value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return !(value as bool?);
}
#endregion
}
one-to-many has parent class contains n number of childrens so it is a collection mapping.
many-to-one has n number of childrens contains one parent so it is a object mapping
<script type="text/javascript">
/***********************************************
* Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
function disableSelection(target){
if (typeof target.onselectstart!="undefined") //IE route
target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
target.style.MozUserSelect="none"
else //All other route (ie: Opera)
target.onmousedown=function(){return false}
target.style.cursor = "default"
}
//Sample usages
//disableSelection(document.body) //Disable text selection on entire body
//disableSelection(document.getElementById("mydiv")) //Disable text selection on element with id="mydiv"
</script>
EDIT
Code apparently comes from http://www.dynamicdrive.com
@echo off
set source="C:\test case"
set target="C:\Users\Alexander\Desktop\random folder"
FOR /F "delims=" %%I IN ('DIR %source%\*.* /A:-D /O:-D /B') DO COPY %source%\"%%I" %target% & echo %%I & GOTO :END
:END
TIMEOUT 4
My attempt to copy the newest file from a folder
just set your source and target folders and it should work
This one ignores folders, concern itself only with files
Recommed that you choose filetype in the DIR path changing *.*
to *.zip
for example
TIMEOUT wont work on winXP I think
try with screen -d -r
or screen -D -RR
generally, as a File object:
File getCwd() {
return new File("").getAbsoluteFile();
}
you may want to have full qualified string like "D:/a/b/c" doing:
getCwd().getAbsolutePath()
for a in range(1):
for b in range(3):
a = b*2
print(a)
As per your question, you want to iterate the outer loop with help of the inner loop.
In the inner loop, we are iterating the 3 digits which are in the multiple of 2, starting from 0.
Output:
0
2
4
You can do injection on Directives, and it looks just like it does everywhere else.
app.directive('changeIt', ['myData', function(myData){
return {
restrict: 'C',
link: function (scope, element, attrs) {
scope.name = myData.name;
}
}
}]);
<script type="text/javascript">
$(document).ready(function() {
showWarning('@ViewBag.Message');
});
</script>
You can use ViewBag.PropertyName in javascript like this.
Just right click in your project go Manage NuGet Packages search for Microsoft.AspNet.WebApi.Client install it and you will have access to the extension method.
Just do this:
import pandas as pd
import pyodbc
cnxn = pyodbc.connect("Driver={SQL Server}\
;Server=SERVER_NAME\
;Database=DATABASE_NAME\
;Trusted_Connection=yes")
df = pd.read_sql("SELECT * FROM myTableName", cnxn)
df.head()
Extending the top voted comment.
Note that you should pass request as a parameter to your delete function in your views. An example would be like:
from django.shortcuts import redirect
def delete(request, id):
YourModelName.objects.filter(id=id).delete()
return redirect('url_name')
The marked answer has the problem that the available packages on the machine that is doing the downloads might be different from the target machine, and thus the package set might be incomplete.
To avoid this and get all dependencies, use the following:
apt-get download $(apt-rdepends <package>|grep -v "^ ")
Some packages returned from apt-rdepends
don't exist with the exact name for apt-get download
to download (for example, libc-dev
). In those cases, filter out those exact names (be sure to use ^<NAME>$
so that other related names, for example libc-dev-bin
, that do exist are not skipped).
apt-get download $(apt-rdepends <package>|grep -v "^ " |grep -v "^libc-dev$")
Once downloaded, you can move the .deb
files to a machine without Internet and install them:
sudo dpkg -i *.deb
Came here looking for an answer to the same problem, but I'm using WCF for NET Core. If you're in the same boat, use:
client.ClientCredentials.ServiceCertificate.SslCertificateAuthentication =
new X509ServiceCertificateAuthentication()
{
CertificateValidationMode = X509CertificateValidationMode.None,
RevocationMode = X509RevocationMode.NoCheck
};
Since expression is boolean:
return expression;
sn -T <assembly>
in Visual Studio command line.
If an assembly is installed in the global assembly cache, it's easier to go to C:\Windows\assembly
and find it in the list of GAC assemblies.
On your specific case, you might be mixing type full name with assembly reference, you might want to take a look at MSDN.
As I think, It's not best way to using UIGestureRecognizer-based cells.
First, you'll not have any options to use CoreGraphics.
Perfect solution, will UIResponder or one UIGestureRecognizer
for whole table view. Not for every UITableViewCell
. It will make you app stuck.
using System;
using System.IO.Ports;
using System.Threading;
namespace SerialReadTest
{
class SerialRead
{
static void Main(string[] args)
{
Console.WriteLine("Serial read init");
SerialPort port = new SerialPort("COM6", 115200, Parity.None, 8, StopBits.One);
port.Open();
while(true){
Console.WriteLine(port.ReadLine());
}
}
}
}
It's easier with the enumitem package:
\documentclass{article}
\usepackage{enumitem}
\begin{document}
Less space:
\begin{itemize}[noitemsep]
\item foo
\item bar
\item baz
\end{itemize}
Even more compact:
\begin{itemize}[noitemsep,nolistsep]
\item foo
\item bar
\item baz
\end{itemize}
\end{document}
The enumitem package provides a lot of features to customize bullets, numbering and lengths.
The paralist package provides very compact lists: compactitem, compactenum and even lists within paragraphs like inparaenum and inparaitem.
If the table has an index on a NOT NULL column the COUNT(*) will use that. Otherwise it is executes a full table scan. Note that the index doesn't have to be UNIQUE it just has to be NOT NULL.
Here is a table...
SQL> desc big23
Name Null? Type
----------------------------------------- -------- ---------------------------
PK_COL NOT NULL NUMBER
COL_1 VARCHAR2(30)
COL_2 VARCHAR2(30)
COL_3 NUMBER
COL_4 DATE
COL_5 NUMBER
NAME VARCHAR2(10)
SQL>
First we'll do a count with no indexes ....
SQL> explain plan for
2 select count(*) from big23
3 /
Explained.
SQL> select * from table(dbms_xplan.display)
2 /
select * from table)dbms_xplan.display)
PLAN_TABLE_OUTPUT
--------------------------------------------------------------------
Plan hash value: 983596667
--------------------------------------------------------------------
| Id | Operation | Name | Rows | Cost (%CPU)| Time |
--------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 1618 (1)| 00:00:20 |
| 1 | SORT AGGREGATE | | 1 | | |
| 2 | TABLE ACCESS FULL| BIG23 | 472K| 1618 (1)| 00:00:20 |
--------------------------------------------------------------------
Note
PLAN_TABLE_OUTPUT
--------------------------------------------------------------------
- dynamic sampling used for this statement
13 rows selected.
SQL>
No we create an index on a column which can contain NULL entries ...
SQL> create index i23 on big23(col_5)
2 /
Index created.
SQL> delete from plan_table
2 /
3 rows deleted.
SQL> explain plan for
2 select count(*) from big23
3 /
Explained.
SQL> select * from table(dbms_xplan.display)
2 /
PLAN_TABLE_OUTPUT
--------------------------------------------------------------------
Plan hash value: 983596667
--------------------------------------------------------------------
| Id | Operation | Name | Rows | Cost (%CPU)| Time |
--------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 1618 (1)| 00:00:20 |
| 1 | SORT AGGREGATE | | 1 | | |
| 2 | TABLE ACCESS FULL| BIG23 | 472K| 1618 (1)| 00:00:20 |
--------------------------------------------------------------------
Note
PLAN_TABLE_OUTPUT
--------------------------------------------------------------------
- dynamic sampling used for this statement
13 rows selected.
SQL>
Finally let's build the index on the NOT NULL column ....
SQL> drop index i23
2 /
Index dropped.
SQL> create index i23 on big23(pk_col)
2 /
Index created.
SQL> delete from plan_table
2 /
3 rows deleted.
SQL> explain plan for
2 select count(*) from big23
3 /
Explained.
SQL> select * from table(dbms_xplan.display)
2 /
PLAN_TABLE_OUTPUT
---------------------------------------------------------------------
Plan hash value: 1352920814
----------------------------------------------------------------------
| Id | Operation | Name | Rows | Cost (%CPU)| Time |
----------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 326 (1)| 00:00:04 |
| 1 | SORT AGGREGATE | | 1 | | |
| 2 | INDEX FAST FULL SCAN| I23 | 472K| 326 (1)| 00:00:04 |
----------------------------------------------------------------------
Note
PLAN_TABLE_OUTPUT
----------------------------------------------------------------------
- dynamic sampling used for this statement
13 rows selected.
SQL>
There are a few characters which can indicate a new line. The usual ones are these two: '\n' or '0x0A' (10 in decimal) -> This character is called "Line Feed" (LF). '\r' or '0x0D' (13 in decimal) -> This one is called "Carriage return" (CR).
Different Operating Systems handle newlines in a different way. Here is a short list of the most common ones:
DOS and Windows
They expect a newline to be the combination of two characters, namely '\r\n' (or 13 followed by 10).
Unix (and hence Linux as well)
Unix uses a single '\n' to indicate a new line.
Mac
Macs use a single '\r'.
Build a Python list and convert that to a Numpy array. That takes amortized O(1) time per append + O(n) for the conversion to array, for a total of O(n).
a = []
for x in y:
a.append(x)
a = np.array(a)
Alternatively, you can just use,
<li v-for="catalog, key in catalogs">this is index {{++key}}</li>
This is working just fine.
You can use /bin/sh
to call or execute another script (via your actual script):
# cat showdate.sh
#!/bin/bash
echo "Date is: `date`"
# cat mainscript.sh
#!/bin/bash
echo "You are login as: `whoami`"
echo "`/bin/sh ./showdate.sh`" # exact path for the script file
The output would be:
# ./mainscript.sh
You are login as: root
Date is: Thu Oct 17 02:56:36 EDT 2013
I think an example of the case that has caught me by surprise is relevant:
var myObject = { name: "Cody", status: "Surprised" };
for (var propertyName in myObject) {
document.writeln( propertyName + " : " + myObject[propertyName] );
}
But to my surprise, the output is
name : Cody
status : Surprised
forEach : function (obj, callback) {
for (prop in obj) {
if (obj.hasOwnProperty(prop) && typeof obj[prop] !== "function") {
callback(prop);
}
}
}
Why? Another script on the page has extended the Object prototype:
Object.prototype.forEach = function (obj, callback) {
for ( prop in obj ) {
if ( obj.hasOwnProperty( prop ) && typeof obj[prop] !== "function" ) {
callback( prop );
}
}
};
You can also use the join command (dplyr).
For example:
new_dataset <- dataset1 %>% right_join(dataset2, by=c("column1","column2"))
you can turn the ":" to space, and do the split.eg
>>> f=open("/proc/net/dev")
>>> for line in f:
... line=line.replace(":"," ").split()
... print len(line)
no regex needed (for this case)
For me it was important to delete the "php.executablePath" path from the VS code settings and leave only the path to PHP in the Path variable.
When I had the Path variable together with php.executablePath, an irritating error still occurred (despite the fact that the path to php was correct).
It's always pass by value, but for objects the value of the variable is a reference. Because of this, when you pass an object and change its members, those changes persist outside of the function. This makes it look like pass by reference. But if you actually change the value of the object variable you will see that the change does not persist, proving it's really pass by value.
Example:
function changeObject(x) {_x000D_
x = { member: "bar" };_x000D_
console.log("in changeObject: " + x.member);_x000D_
}_x000D_
_x000D_
function changeMember(x) {_x000D_
x.member = "bar";_x000D_
console.log("in changeMember: " + x.member);_x000D_
}_x000D_
_x000D_
var x = { member: "foo" };_x000D_
_x000D_
console.log("before changeObject: " + x.member);_x000D_
changeObject(x);_x000D_
console.log("after changeObject: " + x.member); /* change did not persist */_x000D_
_x000D_
console.log("before changeMember: " + x.member);_x000D_
changeMember(x);_x000D_
console.log("after changeMember: " + x.member); /* change persists */
_x000D_
Output:
before changeObject: foo
in changeObject: bar
after changeObject: foo
before changeMember: foo
in changeMember: bar
after changeMember: bar
Use malloc()
when you don't know the amount of memory needed during compile time. In case if you have read-only strings then you can use const char* str = "something";
. Note that the string is most probably be stored in a read-only memory location and you'll not be able to modify it. On the other hand if you know the string during compiler time then you can do something like: char str[10]; strcpy(str, "Something");
Here the memory is allocated from stack and you will be able to modify the str. Third case is allocating using malloc. Lets say you don'r know the length of the string during compile time. Then you can do char* str = malloc(requiredMem); strcpy(str, "Something"); free(str);
try
git reflog
this gives you a history of how your HEAD and branch pointers where moved in the past.
e.g. :
88ea06b HEAD@{0}: checkout: moving from DEVELOPMENT to remotes/origin/SomeNiceFeature e47bf80 HEAD@{1}: pull origin DEVELOPMENT: Fast-forward
the top of this list is one reasone one might encounter a DETACHED HEAD state ... checking out a remote tracking branch.
To change the text in of a button simply execute the following line of jQuery for
<input type='button' value='XYZ' id='btnAddProfile'>
use
$("#btnAddProfile").val('Save');
while for
<button id='btnAddProfile'>XYZ</button>
use this
$("#btnAddProfile").html('Save');
If what you want is to have the print operation automatically change floats to only show 2 decimal places, consider writing a function to replace 'print'. For instance:
def fp(*args): # fp means 'floating print'
tmps = []
for arg in args:
if type(arg) is float: arg = round(arg, 2) # transform only floats
tmps.append(str(arg))
print(" ".join(tmps)
Use fp() in place of print ...
fp("PI is", 3.14159)
... instead of ... print "PI is", 3.14159
I used this configurations and still have the problem of pixelization :
Bitmap bmpOriginal = BitmapFactory.decodeResource(this.getResources(), R.drawable.map_pin);
Bitmap targetBitmap = Bitmap.createBitmap((bmpOriginal.getWidth()),
(bmpOriginal.getHeight()),
Bitmap.Config.ARGB_8888);
Paint p = new Paint();
p.setAntiAlias(true);
Matrix matrix = new Matrix();
matrix.setRotate((float) lock.getDirection(),(float) (bmpOriginal.getWidth()/2),
(float)(bmpOriginal.getHeight()/2));
RectF rectF = new RectF(0, 0, bmpOriginal.getWidth(), bmpOriginal.getHeight());
matrix.mapRect(rectF);
targetBitmap = Bitmap.createBitmap((int)rectF.width(), (int)rectF.height(), Bitmap.Config.ARGB_8888);
Canvas tempCanvas = new Canvas(targetBitmap);
tempCanvas.drawBitmap(bmpOriginal, matrix, p);
This following code should extract face in images and save faces on disk
def detect(image):
image_faces = []
bitmap = cv.fromarray(image)
faces = cv.HaarDetectObjects(bitmap, cascade, cv.CreateMemStorage(0))
if faces:
for (x,y,w,h),n in faces:
image_faces.append(image[y:(y+h), x:(x+w)])
#cv2.rectangle(image,(x,y),(x+w,y+h),(255,255,255),3)
return image_faces
if __name__ == "__main__":
cam = cv2.VideoCapture(0)
while 1:
_,frame =cam.read()
image_faces = []
image_faces = detect(frame)
for i, face in enumerate(image_faces):
cv2.imwrite("face-" + str(i) + ".jpg", face)
#cv2.imshow("features", frame)
if cv2.waitKey(1) == 0x1b: # ESC
print 'ESC pressed. Exiting ...'
break
Use hsh.delete_if. In your specific case, something like: hsh.delete_if { |k, v| v.empty? }
you can use simple line:
dt2.ToString("d MMM yyyy") ?? ""
this answer helped me out a lot and pointed me in the right direction but what worked for me, and hopefully others, is:
menuApp.controller("dynamicMenuController", function($scope, $http) {
$scope.appetizers= [];
$http.get('config/menu.json').success(function(data) {
console.log("success!");
$scope.appetizers = data.appetizers;
console.log(data.appetizers);
});
});
Complete java converter code for all primitive types to/from arrays http://www.daniweb.com/code/snippet216874.html
You could either do:
public class Data {
private int[] data;
public Data() {
data = new int[]{0, 0, 0};
}
}
Which initializes data
in the constructor, or:
public class Data {
private int[] data = new int[]{0, 0, 0};
public Data() {
// data already initialised
}
}
Which initializes data
before the code in the constructor is executed.
The problem is that an isin does not identify the exchange, only an issuer.
Let's say your isin is US4592001014
(IBM), one way to do it would be:
get the ticker (in A1):
=BDP("US4592001014 ISIN", "TICKER") => IBM
get a proper symbol (in A2)
=BDP("US4592001014 ISIN", "PARSEKYABLE_DES") => IBM XX Equity
where XX
depends on your terminal settings, which you can check on CNDF <Go>
.
get the main exchange composite ticker, or whatever suits your need (in A3):
=BDP(A2,"EQY_PRIM_SECURITY_COMP_EXCH") => US
and finally:
=BDP(A1&" "&A3&" Equity", "LAST_PRICE") => the last price of IBM US Equity
"." | "!" | "~" | "*" | "'" | "(" | ")"
are also acceptable [RFC2396]. Really, anything can be in a GET parameter if it is properly encoded.
not nearly as concise as the link you provided: but the following chapter 14 - 24 may help :) hehe
Use This code
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main(){
char a[10];
clrscr();
gets(a);
int i,length=0;
for(i=0;a[i]!='\0';i++)
length+=1;
for(i=0;i<length;i++){
a[i]=a[i]^32;
}
printf("%s",&a);
getch();
}
There's no method in the JDK for this that I'm aware of. Apache Commons Lang has various overloaded join()
methods in the StringUtils
class that do what you want.
Best alternative:
public static readonly byte[] ZeroHash = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
from
a directory_of_modules
, you can import
a specific_module.py
specific_module.py
, can contain a Class
with some_methods()
or just functions()
specific_module.py
, you can instantiate a Class
or call functions()
Class
, you can execute some_method()
Example:
#!/usr/bin/python3
from directory_of_modules import specific_module
instance = specific_module.DbConnect("username","password")
instance.login()
Excerpts from PEP 8 - Style Guide for Python Code:
Modules should have short and all-lowercase names.
Notice: Underscores can be used in the module name if it improves readability.
A Python module is simply a source file(*.py), which can expose:
Class: names using the "CapWords" convention.
Function: names in lowercase, words separated by underscores.
Global Variables: the conventions are about the same as those for Functions.
oh, that's a tough one. What you have here, basically, is two values for each item. Then you are trying to call them with a number as the key. Unfortunately, one of your values is already set as the key!
Try this:
colors = {1: ["blue", "5"], 2: ["red", "6"], 3: ["yellow", "8"]}
Now you can call the keys by number as if they are indexed like a list. You can also reference the color and number by their position within the list.
For example,
colors[1][0]
// returns 'blue'
colors[3][1]
// returns '8'
Of course, you will have to come up with another way of keeping track of what location each color is in. Maybe you can have another dictionary that stores each color's key as it's value.
colors_key = {'blue': 1, 'red': 6, 'yllow': 8}
Then, you will be able to also look up the colors key if you need to.
colors[colors_key['blue']][0] will return 'blue'
Something like that.
And then, while you're at it, you can make a dict with the number values as keys so that you can always use them to look up your colors, you know, if you need.
values = {5: [1, 'blue'], 6: [2, 'red'], 8: [3, 'yellow']}
Then, (colors[colors_key[values[5][1]]][0]) will return 'blue'.
Or you could use a list of lists.
Good luck!
My problem was that excel column was showing me "=concatenate(A1,B1)"
instead of
it 's value after concatenation.
I added a space after "," like this =concatenate(A1, B1)
and it worked.
This is just an example that solved my problem.
Try and let me know if it works for you as well.
Sometimes it works without space as well, but at other times it doesn't.
There is an command line application called "ShowVer" at CodeProject:
ShowVer.exe command-line VERSIONINFO display program
As usual the application comes with an exe and the source code (VisualC++ 6).
Out outputs all the meta data available:
On a German Win7 system the output for user32.dll is like this:
VERSIONINFO for file "C:\Windows\system32\user32.dll": (type:0)
Signature: feef04bd
StrucVersion: 1.0
FileVersion: 6.1.7601.17514
ProductVersion: 6.1.7601.17514
FileFlagsMask: 0x3f
FileFlags: 0
FileOS: VOS_NT_WINDOWS32
FileType: VFT_DLL
FileDate: 0.0
LangID: 040704B0
CompanyName : Microsoft Corporation
FileDescription : Multi-User Windows USER API Client DLL
FileVersion : 6.1.7601.17514 (win7sp1_rtm.101119-1850)
InternalName : user32
LegalCopyright : ® Microsoft Corporation. Alle Rechte vorbehalten.
OriginalFilename : user32
ProductName : Betriebssystem Microsoft« Windows«
ProductVersion : 6.1.7601.17514
Translation: 040704b0
String s = "1.210000";
while (s.endsWith("0")){
s = (s.substring(0, s.length() - 1));
}
This will make the string to drop the tailing 0-s.
Try using
for i in a :
print(i[0])
i represents individual row in a.So,i[0] represnts the 1st element of each row.
<script type="text/javascript">
function upperCaseF(a){
setTimeout(function(){
a.value = a.value.toUpperCase();
}, 1);
}
</script>
<input type="text" required="" name="partno" class="form-control" placeholder="Enter a Part No*" onkeydown="upperCaseF(this)">
Another solution would be to use the ManagedTask and ManagedTaskListener.
You need a Callable or Runnable which implements the interface ManagedTask.
The method getManagedTaskListener
returns the instance you want.
public ManagedTaskListener getManagedTaskListener() {
And you implement in ManagedTaskListener the taskDone
method:
@Override
public void taskDone(Future<?> future, ManagedExecutorService executor, Object task, Throwable exception) {
if (exception != null) {
LOGGER.log(Level.SEVERE, exception.getMessage());
}
}
More details about managed task lifecycle and listener.
You can create $i
outside the loop and do $i++
at the bottom of the loop.
When you use the input function it automatically turns it into a string. You need to go:
vote = int(input('Enter the name of the player you wish to vote for'))
which turns the input into a int type value
Try
import sys
print(sys.version)
This prints the full version information string. If you only want the python version number, then Bastien Léonard's solution is the best. You might want to examine the full string and see if you need it or portions of it.
No, that's more or less what they're meant to do.
In C (and many other languages), you can insert hard-to-see/type characters using \
notation:
\a
is alert/bell\b
is backspace/rubout\n
is newline\r
is carriage return (return to left margin)\t
is tabYou can also specify the octal value of any character using \0
nnn, or the hexadecimal value of any character with \x
nn.
_
is octal 137, hex 5f, so it can also be typed \0137
or \x5f
, if your keyboard didn't have a _
key or something. This is more useful for control characters like NUL (\0
) and ESC (\033
)As someone posted (then deleted their answer before I could +1 it), there are also some less-frequently-used ones:
\f
is a form feed/new page (eject page from printer)\v
is a vertical tab (move down one line, on the same column)On screens, \f
usually works the same as \v
, but on some printers/teletypes, it will
go all the way to the next form/sheet of paper.
You can use the Long
wrapper instead of long
primitive and call
Long.intValue()
It rounds/truncate the long
value accordingly to fit in an int
.
One more option is to add the path of the privatekey file like this in terminal:
ssh-add "path to the privatekeyfile"
and then execute the pull command
Just create an extension for the StringBuilder class:
Public Module Extensions
<Extension()>
Public Sub AppendFormatWithNewLine(ByRef sb As System.Text.StringBuilder, ByVal format As String, ParamArray values() As Object)
sb.AppendLine(String.Format(format, values))
End Sub
End Module
First off:
public class ProfileCollection implements Iterable<Profile> {
Second:
return m_Profiles.get(m_ActiveProfile);
Firefox 44 includes a built-in JSON viewer (no add-ons required). The feature is turned off by default, so turn on devtools.jsonview.enabled
:
How can you disable the new JSON Viewer/Reader in Firefox Developer Edition?
Try a case statement
WHERE
CASE WHEN @zipCode IS NULL THEN 1
ELSE @zipCode
END
I used this method to load a script file dynamically (inside a controller).
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "https://maps.googleapis.com/maps/api/js";
document.body.appendChild(script);
I like the approach from Fusion, but there's a small error in it. Like that it is correct:
function closest(array, number) {
var num = 0;
for (var i = array.length - 1; i >= 0; i--) {
if(Math.abs(number - array[i]) < Math.abs(number - array[num])){
num = i;
}
}
return array[num];
}
It it also a bit faster because it uses the improved for
loop.
At the end I wrote my function like this:
var getClosest = function(number, array) {
var current = array[0];
var difference = Math.abs(number - current);
var index = array.length;
while (index--) {
var newDifference = Math.abs(number - array[index]);
if (newDifference < difference) {
difference = newDifference;
current = array[index];
}
}
return current;
};
I tested it with console.time()
and it is slightly faster than the other function.
You can use urllib2
import urllib2
content = urllib2.urlopen(some_url).read()
print content
Also you can use httplib
import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK
or the requests library
import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200
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.
Browser caching strategies can be controlled by HTTP headers. Remember that they are just a hint, really. Since browsers are terribly inconsistent in this (and any other) field, you'll need several headers to get the desired effect on a range of browsers.
header ("Pragma-directive: no-cache");
header ("Cache-directive: no-cache");
header ("Cache-control: no-cache");
header ("Pragma: no-cache");
header ("Expires: 0");
For this is important to understand the difference between Merge and Rebase.
Rebases are how changes should pass from the top of hierarchy downwards and merges are how they flow back upwards.
For details refer - http://www.derekgourlay.com/archives/428
None of these answer were working for me on my macbook pro. So what i had to do was go to:
Preferences -> Source Code -> Code Formatting -> C# source code.
From here I could change my style and spacing tabs etc. This is the only project i have where the lead developer has different formatting than i do. It was a pain in the butt that my IDE would format my code different than theirs.
Eventual if you don't have a trusted connection as the –E switch declares
Use following command line
"[program dir]\[sql server version]\Tools\Binn\osql.exe" -Q "BACKUP DATABASE mydatabase TO DISK='C:\tmp\db.bak'" -S [server] –U [login id] -P [password]
Where
[program dir] is the directory where the osql.exe exists
On 32bit OS c:\Program Files\Microsoft SQL Server\
On 64bit OS c:\Program Files (x86)\Microsoft SQL Server\
[sql server version] your sql server version 110 or 100 or 90 or 80 begin with the largest number
[server] your servername or server ip
[login id] your ms-sql server user login name
[password] the required login password
While executing the job we need to pass Job parameters as follows:
JobParameters jobParameters= new JobParametersBuilder().addString("file.name", "filename.txt").toJobParameters();
JobExecution execution = jobLauncher.run(job, jobParameters);
by using the expression language we can import the value as follows:
#{jobParameters['file.name']}
The best way is to use IN
statement :
DELETE from tablename WHERE id IN (1,2,3,...,254);
You can also use BETWEEN
if you have consecutive IDs :
DELETE from tablename WHERE id BETWEEN 1 AND 254;
You can of course limit for some IDs using other WHERE clause :
DELETE from tablename WHERE id BETWEEN 1 AND 254 AND id<>10;
In classic sh, you have to do something like:
s=test1
s="${s}test2"
(there are lots of variations on that theme, like s="$s""test2"
)
In bash, you can use +=:
s=test1
s+=test2
As for adding a dependency, I'm afraid the java.util.Date & .Calendar really are so bad that the first thing I do to any new project is add the Joda-Time library. In Java 8 you can use the new java.time package, inspired by Joda-Time.
The core of Joda-Time is the DateTime
class. Unlike java.util.Date, it understands its assigned time zone (DateTimeZone
). When converting from j.u.Date, assign a zone.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTimeQuébec = new DateTime( date , zone );
LocalDate
One way to verify if two date-times land on the same date is to convert to LocalDate
objects.
That conversion depends on the assigned time zone. To compare LocalDate
objects, they must have been converted with the same zone.
Here is a little utility method.
static public Boolean sameDate ( DateTime dt1 , DateTime dt2 )
{
LocalDate ld1 = new LocalDate( dt1 );
// LocalDate determination depends on the time zone.
// So be sure the date-time values are adjusted to the same time zone.
LocalDate ld2 = new LocalDate( dt2.withZone( dt1.getZone() ) );
Boolean match = ld1.equals( ld2 );
return match;
}
Better would be another argument, specifying the time zone rather than assuming the first DateTime object’s time zone should be used.
static public Boolean sameDate ( DateTimeZone zone , DateTime dt1 , DateTime dt2 )
{
LocalDate ld1 = new LocalDate( dt1.withZone( zone ) );
// LocalDate determination depends on the time zone.
// So be sure the date-time values are adjusted to the same time zone.
LocalDate ld2 = new LocalDate( dt2.withZone( zone ) );
return ld1.equals( ld2 );
}
Another approach is to create a string representation of the date portion of each date-time, then compare strings.
Again, the assigned time zone is crucial.
DateTimeFormatter formatter = ISODateTimeFormat.date(); // Static method.
String s1 = formatter.print( dateTime1 );
String s2 = formatter.print( dateTime2.withZone( dt1.getZone() ) );
Boolean match = s1.equals( s2 );
return match;
The generalized solution is to define a span of time, then ask if the span contains your target. This example code is in Joda-Time 2.4. Note that the "midnight"-related classes are deprecated. Instead use the withTimeAtStartOfDay
method. Joda-Time offers three classes to represent a span of time in various ways: Interval, Period, and Duration.
Using the "Half-Open" approach where the beginning of the span is inclusive and the ending exclusive.
The time zone of the target can be different than the time zone of the interval.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime target = new DateTime( 2012, 3, 4, 5, 6, 7, timeZone );
DateTime start = DateTime.now( timeZone ).withTimeAtStartOfDay();
DateTime stop = start.plusDays( 1 ).withTimeAtStartOfDay();
Interval interval = new Interval( start, stop );
boolean containsTarget = interval.contains( target );
Java 8 and later comes with the java.time framework. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. See Tutorial.
The makers of Joda-Time have instructed us all to move to java.time as soon as is convenient. In the meantime Joda-Time continues as an actively maintained project. But expect future work to occur only in java.time and ThreeTen-Extra rather than Joda-Time.
To summarize java.time in a nutshell… An Instant
is a moment on the timeline in UTC. Apply a time zone (ZoneId
) to get a ZonedDateTime
object. To move off the timeline, to get the vague indefinite idea of a date-time, use the "local" classes: LocalDateTime
, LocalDate
, LocalTime
.
The logic discussed in the Joda-Time section of this Answer applies to java.time.
The old java.util.Date class has a new toInstant
method for conversion to java.time.
Instant instant = yourJavaUtilDate.toInstant(); // Convert into java.time type.
Determining a date requires a time zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
We apply that time zone object to the Instant
to obtain a ZonedDateTime
. From that we extract a date-only value (a LocalDate
) as our goal is to compare dates (not hours, minutes, etc.).
ZonedDateTime zdt1 = ZonedDateTime.ofInstant( instant , zoneId );
LocalDate localDate1 = LocalDate.from( zdt1 );
Do the same to the second java.util.Date
object we need for comparison. I’ll just use the current moment instead.
ZonedDateTime zdt2 = ZonedDateTime.now( zoneId );
LocalDate localDate2 = LocalDate.from( zdt2 );
Use the special isEqual
method to test for the same date value.
Boolean sameDate = localDate1.isEqual( localDate2 );
Depending on what browsers/devices you are looking to support, or what you are prepared to put up with for non-compliant browsers you may want to check out the <summary>
and <detail>
tags. They are for exactly this purpose. No css is required at all as the collapsing and showing are part of the tags definition/formatting.
I've made an example here:
<details>
<summary>This is what you want to show before expanding</summary>
<p>This is where you put the details that are shown once expanded</p>
</details>
Browser support varies. Try in webkit for best results. Other browsers may default to showing all the solutions. You can perhaps fallback to the hide/show method described above.
For ExpressJs router:
router.post('/login', async(req, res) => {
return res.send({redirect: '/yoururl'});
})
Client-side:
success: function (response) {
if (response.redirect) {
window.location = response.redirect
}
},
The BlackBerry browser and Safari for iOS (iPhone/iPod/iPad) automatically detect phone numbers and email addresses and convert them to links. If you don’t want this feature, you should use the following meta tags.
For Safari:
<meta name="format-detection" content="telephone=no">
For BlackBerry:
<meta http-equiv="x-rim-auto-match" content="none">
Source: mobilexweb.com
Serial Data Speed:
Data rate (bps) = 1/Tb Tb is the time duration of 1 bit If the bit duration is 2ms then data rate is 1/2x10-3 , which is about 500 bps.
Baud rate:
Baud rate is defined as no. of signalling elements(symbols) in a given unit of time (say 1 sec) or it means number of time signal changes its state.When the signal is binary then baud rate and bit rate are same.
Bit rate:- Bit rate is nothing but number of bits transmitted per second.For example if Bit rate is 1000 bps then 1000 bits are i.e. 0s or 1s transmitted per second.
There are few other terms similar to this (i.e serial speed, bit rate, baud rate, USB transfer rate),and i guess(?) the values that are printed on serial monitor relates to serial speed, baud rate and USB transfer rate. Bit rate isn't an another term, please correct me if i am wrong, because serial monitor prints some values at an interval of time and value is definitely a set of bits. so if one value is printed i can say no of bits present in the respective value which gets printed on serial monitor per unit time will be the bit rate.
You don't necessarily have to create a Spring project. Almost all Java web applications have he same project structure. In almost every project I create, I automatically add these source folder:
src/main/webapp isn't actually a source folder. The web.xml file under src/main/webapp/WEB-INF will allow you to run your java application on any Java enabled web server (Tomcat, Jetty, etc.). I typically add the Jetty Plugin to my POM (assuming you use Maven), and launch the web app in development using mvn clean jetty:run.
I fear you will have to do somthing like this, I mutated the regex from here.
var searchPattern = new Regex(
@"$(?<=\.(aspx|ascx))",
RegexOptions.IgnoreCase);
var files = Directory.EnumerateFiles(path)
.Where(f => searchPattern.IsMatch(f))
.ToList();
use this command for run every service just write name service for example :
for xrdp :
sudo /etc/init.d/xrdp start
for redis :
sudo /etc/init.d/redis start
(for any other service, check the init.d folder for filenames)
File f1 = new File("..\\..\\..\\config.properties");
this path trying to access file is in Project directory then just access file like this.
File f=new File("filename.txt");
if your file is in OtherSources/Resources
this.getClass().getClassLoader().getResource("relative path");//-> relative path from resources folder
I ran into an article that illustrates a method where the data from the same excel sheet can be imported in the selected table until there is no modifications in excel with data types.
If the data is inserted or overwritten with new ones, importing process will be successfully accomplished, and the data will be added to the table in SQL database.
The article may be found here: http://www.sqlshack.com/using-ssis-packages-import-ms-excel-data-database/
Hope it helps.
you have id="#message"
... should be id="message"
All callbacks and functions are documented here: http://fronteed.com/iCheck/#usage
$('input').iCheck('check'); — change input's state to checked
$('input').iCheck('uncheck'); — remove checked state
$('input').iCheck('toggle'); — toggle checked state
$('input').iCheck('disable'); — change input's state to disabled
$('input').iCheck('enable'); — remove disabled state
$('input').iCheck('indeterminate'); — change input's state to indeterminate
$('input').iCheck('determinate'); — remove indeterminate state
$('input').iCheck('update'); — apply input changes, which were done outside the plugin
$('input').iCheck('destroy'); — remove all traces of iCheck
$mail->SMTPDebug = 2; // to see exactly what's the issue
In my case this helped:
$mail->SMTPSecure = false;
$mail->SMTPAutoTLS = false;
Delete your bin and obj subfolders to remove a load of incorrect reference then use windows to search for old name.
Edit any code or xml files found and rebuild, should be ok now.
Okay. If you do not want to store the file in database and store in the application, like assets (custom folder), you can define non-db instance variable defined by attr_accessor: document and use form_for - f.file_field
to get the file,
In controller,
@person = Person.new(person_params)
Here person_params
return whitelisted params[:person]
(define yourself)
Save file as,
dir = "#{Rails.root}/app/assets/custom_path"
FileUtils.mkdir(dir) unless File.directory? dir
document = @person.document.document_file_name # check document uploaded params
File.copy_stream(@font.document, "#{dir}/#{document}")
Note, Add this path in .gitignore
& if you want to use this file again add this path asset_path
an of application by application.rb
Whenever form read file field, it get store in tmp folder, later you can store at your place, I gave example to store at assets
note: Storing files like this will increase the size of the application, better to store in the database using paperclip
.
Here is a simple php script for login and a page that can only be accessed by logged in users.
login.php
<?php
session_start();
echo isset($_SESSION['login']);
if(isset($_SESSION['login'])) {
header('LOCATION:index.php'); die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="text-center">Login</h3>
<?php
if(isset($_POST['submit'])){
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:admin.php'); die();
} {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
}
?>
<form action="" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password" required>
</div>
<button type="submit" name="submit" class="btn btn-default">Login</button>
</form>
</div>
</body>
</html>
admin.php ( only logged in users can access it )
<?php
session_start();
if(!isset($_SESSION['login'])) {
header('LOCATION:login.php'); die();
}
?>
<html>
<head>
<title>Admin Page</title>
</head>
<body>
This is admin page view able only by logged in users.
</body>
</html>
For Tomcat running on Ubuntu server, to find out which Java is being used, use "ps -ef | grep tomcat" command:
Sample:
/home/mcp01$ **ps -ef |grep tomcat**
tomcat7 28477 1 0 10:59 ? 00:00:18 **/usr/local/java/jdk1.7.0_15/bin/java** -Djava.util.logging.config.file=/var/lib/tomcat7/conf/logging.properties -Djava.awt.headless=true -Xmx512m -XX:+UseConcMarkSweepGC -Djava.net.preferIPv4Stack=true -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.endorsed.dirs=/usr/share/tomcat7/endorsed -classpath /usr/share/tomcat7/bin/bootstrap.jar:/usr/share/tomcat7/bin/tomcat-juli.jar -Dcatalina.base=/var/lib/tomcat7 -Dcatalina.home=/usr/share/tomcat7 -Djava.io.tmpdir=/tmp/tomcat7-tomcat7-tmp org.apache.catalina.startup.Bootstrap start
1005 28567 28131 0 11:34 pts/1 00:00:00 grep --color=auto tomcat
Then, we can go in to: cd /usr/local/java/jdk1.7.0_15/jre/lib/security
Default cacerts file is located in here. Insert the untrusted certificate into it.
Try this:
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
Logger root = (Logger)LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.INFO);
Note that you can also tell logback to periodically scan your config file like this:
<configuration scan="true" scanPeriod="30 seconds" >
...
</configuration>
I used the same method mentioned by @S-T after the pip uninstall command. And even after that the I got the message that Django was already installed. So i deleted the 'Django-1.7.6.egg-info' folder from '/usr/lib/python2.7/dist-packages' and then it worked for me.
I think there's no foolproof way to do it. For example, consider the following:
$t = "A+B";
Is that an URL encoded "A B" or does it need to be encoded to "A%2BB"?
You could use the INDIRECT function. This takes a string and converts it into a range
More info here
=INDIRECT("K"&A2)
But it's preferable to use INDEX as it is less volatile.
=INDEX(K:K,A2)
This returns a value or the reference to a value from within a table or range
More info here
Put either function into cell B2 and fill down.
I prefer the solution using replace
with a dict
because of its simplicity and elegance:
df.replace({'-': None})
You can also have more replacements:
df.replace({'-': None, 'None': None})
And even for larger replacements, it is always obvious and clear what is replaced by what - which is way harder for long lists, in my opinion.
This example shows how to convert from string to ip, and viceversa:
struct sockaddr_in sa;
char ip_saver[INET_ADDRSTRLEN];
// store this IP address in sa:
inet_pton(AF_INET, "192.0.1.10", &(sa.sin_addr));
// now get it back
sprintf(ip_saver, "%s", sa.sin_addr));
// prints "192.0.2.10"
printf("%s\n", ip_saver);
You can add a wrapper around promise functionality to return an Observable to observer.
import { of, Observable, defer } from 'rxjs';
import { map } from 'rxjs/operators';
function getTodos$(): Observable<any> {
return defer(()=>{
return fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => {
return json;
})
});
}
getTodos$().
subscribe(
(next)=>{
console.log('Data is:', next);
}
)
I think you should add style="background:white;" to make looks like it is writable
<input type="text" size="23" name="dateMonthly" id="dateMonthly" readonly="readonly" style="background:white;"/>
On Ubuntu:
sudo apt-get install python-virtualenv
The package python-pip
is a dependency, so it will be installed as well.
void printLL(){
NodeLL cur = head;
if(cur.getNext() == null){
System.out.println("LL is emplty");
}else{
//System.out.println("printing Node");
while(cur.getNext() != null){
cur = cur.getNext();
System.out.print(cur.getData()+ " ");
}
}
System.out.println();
}
void mergeSortedList(NodeLL node1, NodeLL node2){
NodeLL cur1 = node1.getNext();
NodeLL cur2 = node2.getNext();
NodeLL cur = head;
if(cur1 == null){
cur = node2;
}
if(cur2 == null){
cur = node1;
}
while(cur1 != null && cur2 != null){
if(cur1.getData() <= cur2.getData()){
cur.setNext(cur1);
cur1 = cur1.getNext();
}
else{
cur.setNext(cur2);
cur2 = cur2.getNext();
}
cur = cur.getNext();
}
while(cur1 != null){
cur.setNext(cur1);
cur1 = cur1.getNext();
cur = cur.getNext();
}
while(cur2 != null){
cur.setNext(cur2);
cur2 = cur2.getNext();
cur = cur.getNext();
}
printLL();
}
No, that's not how it is done. Normal way to initialize the base class is in the initialization list :
class A
{
public:
A(int val) {}
};
class B : public A
{
public:
B( int v) : A( v )
{
}
};
void main()
{
B b(10);
}
Try this
declare @v varchar(20)
set @v = 'Number'
select case when isnumeric(@v) = 1 then @v
else @v end
and
declare @v varchar(20)
set @v = '7082.7758172'
select case when isnumeric(@v) = 1 then @v
else convert(numeric(18,0),@v) end
Your solution is calling round without specifying the second argument (number of decimal places)
>>> round(0.44)
0
>>> round(0.64)
1
which is a much better result than
>>> int(round(0.44, 2))
0
>>> int(round(0.64, 2))
0
From the Python documentation at https://docs.python.org/3/library/functions.html#round
round(number[, ndigits])
Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.
Note
The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.
I have resolve the problem by using the command:
- Go to: C:\Users\ [PC NAME] \AppData\Local\Android\sdk\tools\bin\ (If the folder is not available then download the android SDK first, or you can install it from the android studio installation process.)
- Shift+Left click and Press W,then Enter to open CMD on the folder path
- Type in the cmd: sdkmanager --licenses
- Once press enter, you need to accept all the licenses by pressing y
CHECKING THE LICENSES
- Go to: C:\Users[PC NAME]\AppData\Local\Android\sdk\
- Check the folder named licenses
android-googletv-license
android-sdk-license
android-sdk-preview-license
google-gdk-license
intel-android-extra-license
mips-android-sysimage-license
WAS TESTED ON CORDOVA USING THE COMMAND:
cordova build android
-- UPDATE NEW FOLDER PATH --
Open Android Studio, Tools > Sdk Manager > Android SDK Command-Line Tools (Just Opt-in)
SDKManager will be store in :
- Go to C:\Users\ [PC NAME] \AppData\Local\Android\Sdk\cmdline-tools\latest\bin
- Type in the cmd: sdkmanager --licenses
Documentation to using the Android SDK: https://developer.android.com/studio/command-line/sdkmanager.html
For me this worked:
int imgCarMarginRightPx = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, definedValueInDp, res.getDisplayMetrics());
MarginLayoutParams lp = (MarginLayoutParams) imgCar.getLayoutParams();
lp.setMargins(0,0,imgCarMarginRightPx,0);
imgCar.setLayoutParams(lp);
Instead of storing images in database store them in a folder in your disk and store their location in your data base.