text:
Q: Caching Tweets on iOS What is the best way to cache tweets - text, image, etc. - so they can be displayed right away when a user launches an app while new ones are fetched for in the background? It sounds like NSCachesDirectory is the best way since this is not backed up and if it is cleared the data can just be re-downloaded. I'm just curious if the best way is to create a "Tweet" class and create instances of this class and store them in the cache each time new ones are downloaded or if there is another recommended way?

A: NSCachesDirectory is just /Library/Caches folder of your app sandbox. It appears to be a system managed folder. The last time I checked, it's used by several APIs to keep caches of downloaded files from the Internet (CFURL related APIs). You can use it though. But I wouldn't keep tweets and images directly as files in this folder.
Depending on the purpose of your app, the common approach to cache downloaded content is still to use a database. You can choose to use sqlite3 API directly, or CoreData which is built on top of sqlite3. I imagine most apps calls sqlite3 directly because CoreData is not that clear and bulletproof on the Mac OS X platform historically. It's designed so that you wouldn't need knowledge of SQL to start development. If you did know something about SQL, you'll find it lacking of certain features.


text:
Q: Regularization when you need predictor selection with high collinearity I have two questions about regularization:

*

*In the presence of high collinearity, ridge is better than Lasso, but if you need predictor selection, ridge is not what you want. In those cases, should you still use Lasso or is there any alternative (e.g., subset selection)?

*Can you use regularization on every predictive methods (regression, classification)?

A:
In the presence of high collinearity, ridge is better than Lasso, but if you need predictor selection, ridge is not what you want. In those cases, should you still use Lasso or is there any alternative (e.g., subset selection)?

Yes, there is an alternative that combines ridge and LASSO together called Elastic net.  This minimizes the loss function:
$$ L = \sum_i (y_i - \hat y_i)^2 + \lambda \left( \alpha \sum_j \| \beta_j \| + (1 - \alpha) \frac{1}{2} \sum_j \beta_j^2 \right) $$
Here, $\lambda$ controls the overall regularization strength, and $\alpha$ is a number between zero and one (inclusive) that adjusts the relative strengths of the ridge vs. LASSO penalization.
I do not know of a situation where best subset selection is appropriate which does not arise from software or computing environment constraints.

Can you use regularization on every predictive methods (regression, classification)?

Yes.  In the context of linear models, the elastic net is generalized by glmnet, which applies to any generalized linear model structure.  For example, in logistic regression, the loss function for glmnet would be:
$$ L = \sum_i y_i \log(p_i) + (1 - y_i) \log(1 - p_i) + \lambda \left( \alpha \sum_j \| \beta_j \| + (1 - \alpha) \frac{1}{2} \sum_j \beta_j^2 \right) $$
These models are available in the glmnet package in R.  You can learn to use the package here.  You can read about how it works here.
There are other options as well, multilevel models can be seen as another way to apply regularization.  That is well covered in the book by Gelman and Hill.
There are also a multitude of Bayesian approaches, here the choice of prior can be thought of as a regularization strategy.

redpajama_set_name: RedPajamaStackExchange


text:
Q: flutter The method 'File.create' has fewer named arguments than those of overridden method 'File.create' When I try to run my Flutter project, I get errors like:

../../../.pub-cache/hosted/pub.dev/file-6.1.2/lib/src/interface/file.dart:15:16: Error: The method 'File.create' has fewer named arguments than those of overridden method 'File.create'. Future create({bool recursive = false});

Running flutter clean and flutter upgrade didn't help.  What's wrong?  How do I fix this?

A: For me the packages in my pubspec.yaml were all up to date, but the following fixed it:

*

*Delete pubspec.lock.

*Run flutter pub get again.

A: I just ran in to this issue and I was on flutter's master channel. I switched back to stable (flutter channel stable) and everything works fine.

A: Solution 1:
I kept getting the same error, But I solved it adding by adding
file: ^6.1.4 in my dependencies
If you are having the same problem. Make sure you have the latest file dependency.
Solution 2:
If file wasn't one of your dependency. Just run the below command to upgrade transitive dependencies
flutter pub upgrade

This will update all packages to latest compatible versions. And file may be updated as well to latest version.

A: i solved it by adding file: ^6.1.4 to my pubspec i dont know why this is needed in dependenccies but when i added it worked
this error occured to me when i was trying to update my flutter and packages
but error thrown was of transitive dependencies i guess when u defin in dependencies it over rides the transitive one
but it worked for me
but after wards once project ran i removed the file dependencie from my punspec did a flutter clean and a pub get again and ran the project again it worked without any problem

A: I think the problem is caused by an outdated reference to file dependency. See this issue.
For fix this, on the project or library folder run:
dart pub upgrade

This command will upgrade your dependencies and the problem will be solved without adding the reference to latest version of file dependency.

A: I am also getting this issue after upgrading to the latest version v3.7.
I solved the issue by doing the following thing:
First, run this command:
flutter clean

after this, run the pub get to get the dependencies and run this command :
dart pub upgrade

it will fix the project or library version prob for file


text:
Q: How to Programatically Enable "Keep Running After Screen Off" In Android? I would like my application to always run while the screen is off just like Google Chrome in the following picture:

I'm not quite sure how I would enable this button in my application. Does this button require an extra permission in the manifest file?

A: I think it's not a component or a permission that you can use it directly.it will just change a boolean flag to use it in code.If you want your app keep running after screen off you should use android services and sync state when screen become on,because services can keep running in background.


text:
Q: Generating spatially-aware degree-preserving random graphs? In the study of biological neural networks, researchers sometimes compare hypotheses vs. a degree-preserving random null model.  One major criticism against this approach is that connections in neural networks are greatly affected by their location in 3D Euclidean space (whereas the null model isn't).

Question: Is there a random graph model that both

*

*preserves vertex degrees, and

*accounts for the 3D location of vertices in space (i.e., nearby vertices are more likely to be connected than distant vertices)?

I'd be interested in both directed or undirected graphs (usually they can be adapted to suit, anyway).

A: I can make you a directed model! Let's specify the out-degree of each vertex: $o_x$ is the out-degree of vertex $x$.
Choose yourself an increasing function $F(d)$ that encodes a distance penalty. For each pair of vertices $x$ and $y$, let $A_{xy}=F(\|x-y\|)U_{xy}$. The edges leaving vertex $x$ are then the $\vec{xy}$ corresponding to the $o_x$ smallest values of $A_{xy}$.
Doing the undirected case seems a bit more subtle...
EDIT: Let me expand/change this a bit. For a mathematically interesting model, where you might be able to prove something, you could look at a Gibbs probability distribution. You define an "energy" for each legal configuration (i.e. subgraph of $G$ satisfying the degree constraints). Then, based on the hypothesis that high energy states are unlikely, you assign them low probability.
More specifically, a reasonable approach would be to define the energy of a configuration $\xi$ to be $\Phi(\xi)=\sum_{e\in E(\xi)}F(\|e\|)$. If you let $\Lambda$ be the set of all legal configurations, then the Gibbs measure is defined by $\mathbb P(\xi)=e^{-\Phi(\xi)}/\sum_{\zeta\in\Lambda}e^{-\Phi(\zeta)}$.
(The normalization, which is sometimes called the partition function, $Z(\Lambda)$, there makes this a probability measure). The reason that Gibbs measures are nice is that the multiplicative properties of the exponential function ($e^{a+b}=e^ae^b$) lead to some independence properties of the measure you've constructed. For example it's easy to see that if $\xi$ and $\xi'$ are 2 configurations that agree except that $\xi$ contains edges $ab$ and $cd$, while $\xi'$ contains edges $ac$ and $bd$, there's an easily calculated relationship between $\mathbb P(\xi)$ and $\mathbb P(\xi')$.


text:
Q: vlc fonts too small My system:
AMD A8-7650K Radeon R7, 10 Compute Cores 4C+6G
memory: 15338MB
System  Ubuntu 18.04.1 LTS     3840x2160 pixels
AMD KAVERI (DRM 2.50.0 / 4.15.0-33-generic, LLVM 6.0.0)
I am using a 4k tv for my monitor
my resolution is 3840x2160
I am using vlc 4.0.0
I have tried to use gnome tweaks but none of those setting will deal with the vlc fonts. I have also messed with ubuntu settings but nothing there will change the fonts either.  I should also mention that this is not isolated to just vlc as I have the same problem with Stacer.
Thank you............
The fonts in vlc are very small

A: Vlc and stacer use QT as a graphical user interface. That's why you don't see other applications with the smaller fonts/icon issues.
To fix this solution install qt5ct and execute the following in the command line;
export QT_QPA_PLATFORMTHEME=qt5ct
export QT_SCALE_FACTOR=2

vlc

A: Probably not the perfect solution but open the terminal and type:
xrandr --dpi 288
vlc

A: Thank you for the reply.  I don't have the guts to try xrandr because I only have a problem with specific applications and this will deal with all the fonts in my system (I think).  Setting up this system to use a 4k tv as a monitor was a bit pesky from the getgo and don't really want to mess with it as its working. I think the font thing comes from what was used to create these programs from the beginning.  I have noted that there have been suggestions for that one too but I am hoping somebody a lot smarter than I can give me a specific solution.
I also know that this only happens when I am using the 4k monitor and not when I am using, say, 1920x1080 on a normal monitor so I know this has something to do with the running with a 4k monitor (3840x2160) which is simply not recognized by the program itself.  I suspect the font being used by vlc has a size that is kinda set in stone.  The problem is that I can't get to the font to figure out what it is and where it comes from.
Here is the same problem by somebody else who has exactly the same problem and tried on the vlc forum:
I just upgraded to Xubuntu 18.04 from 16.04, and I am running VLC 3.0.3. On my old installation, VLC obeyed the setting for the system fonts (which is a gtk setting because it is XFCE), which I have set very large so I can see them on my 50 inch screen from far away. Now, however, the fonts are extremely small.
I thought (I think) that VLC pulled the font settings from qt5, and so I installed qt5ct and changed the font preferences there. But there was no change.
I also tried starting vlc with the -style gtk as I thought most qt options allowed, but it seems this is not an option.
Can someone please tell me where VLC gets its font settings and maybe point me in the right direction to change them? I will try any workaround. I just need to be able to see the menu. :)
Thanks in advance.
Top
Kallaste
    New Cone
    New Cone
    Posts: 3
    Joined: 17 Oct 2015 06:35
Re: Menu font sizes and qt5ct
Quote

Postby Kallaste » 19 Aug 2018 05:08
Well, 8 days later and nothing. I had forgotten no one bothers to respond at this forum. I'm really not sure why you keep it up.
I will just use another player. I would have been willing to do the research and write a fix for this myself, if anyone on the project had simply had the courtesy to say, sorry, we don't know. But if you don't care, neither do I.
Top


text:
Q: Spring Castor Unmarshalling with Mapping I am trying to unmarshall an XML to Object using Castor OXM Unmarshalling in Spring.
XML:

<LevelA>
  <LevelB>
    <item name="itemA">value</item>
    <item name="itemB">value</item>
    <item name="itemC">value</item>
    <item name="itemD">value</item>
    <item name="itemE">value</item>
  </LevelB>
</LevelA>

Object:
 Class LevelA {
     LevelB objLevelB;
     //getter and setter
   }

 Class LevelB {
     List<Items> item = new ArrayList<Items>();
     //getter and setter
   }

 Class Items {
     String Name;
     String Value;
    //getter and setter
  }

 Castor Mapping:

  <mapping>
    <class name="LevelA">
      <map-to xml="LevelA" />
      <field name="objLevelB" type="LevelB">
        <bind-xml name="LevelB" />
          <class name="LevelB">
           <field name="item" type="Items" collection="arraylist">
             <bind-xml name="item" node="element" />
                <class name="Items">
                  <field name="Name" type="string">
                    <bind-xml name="name" node="attribute" />
                  </field>
                  <field name="Value" type="string">
                    <bind-xml node="text" />
                  </field>
                 </class>
            </field>
          </class>
      </field>
    </class>
  </mapping>

I am getting the following error:
org.xml.sax.SAXException: unable to find FieldDescriptor for 'item' in ClassDescriptor of LevelB

I have tried several ways and spent enough time that I need some help from you all now.
Any help would be useful.

A: Figured out the way myself, here is the mapping that worked for me. I am sharing the answer to help others, in the same situation.
<?xml version="1.0" encoding="UTF-8"?>
<mapping>
    <description> Provides Mapping to Convert Document to POJO</description>
    <class name="LevelAClass">
        <map-to xml="LevelA" />
        <field name="objLevelB" type="LevelBClass">
            <bind-xml name="LevelB" />
        </field>
    </class>

    <class name="LevelBClass">
        <field name="item" type="LevelCClass"
            collection="arraylist">
            <bind-xml name="item" />
        </field>
    </class>

    <class name="LevelCClass">
        <field name="Name">
            <bind-xml name="name" node="attribute" />
        </field>
        <field name="Value">
            <bind-xml name="item" node="text" />
        </field>
    </class>
</mapping>


text:
Q: Facebook SDK for Android 3.0: UnsupportedOperationException  01-29 21:06:00.601: ERROR/AndroidRuntime(582): FATAL EXCEPTION: main
     java.lang.IllegalStateException: Could not execute method of the activity
     at android.view.View$1.onClick(View.java:2144)
     at android.view.View.performClick(View.java:2485)
     at android.view.View$PerformClick.run(View.java:9080)
     at android.os.Handler.handleCallback(Handler.java:587)
     at android.os.Handler.dispatchMessage(Handler.java:92)
     at android.os.Looper.loop(Looper.java:130)
     at android.app.ActivityThread.main(ActivityThread.java:3687)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:507)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
     at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.reflect.InvocationTargetException
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:507)
     at android.view.View$1.onClick(View.java:2139)
     ... 11 more
     Caused by: java.lang.UnsupportedOperationException: Session: an attempt was made to request new permissions for a session that is not currently open.
     at com.facebook.Session.requestNewPermissions(Session.java:977)
     at com.facebook.Session.requestNewPublishPermissions(Session.java:501)
     at ***.MainActivity.postToFacebook(MainActivity.java:105)
     ... 14 more

The exception is thrown in line
 session.requestNewPublishPermissions(newPermissionsRequest);
 // Check for publish permissions
            List<String> permissions = session.getPermissions();
            if (!isSubsetOf(PERMISSIONS, permissions)) {
                pendingPublishReauthorization = true;
                Session.NewPermissionsRequest newPermissionsRequest = new Session
                        .NewPermissionsRequest(this, PERMISSIONS);

                session.requestNewPublishPermissions(newPermissionsRequest);

                Toast.makeText(getActivity().getApplicationContext(),
                        "Not enough permissions",
                        Toast.LENGTH_SHORT).show();
                return;
            }

What does this exception mean and how to fix it?

A: Dmytro, as per my comment, I've put together a couple of articles which fully explain opening a Facebook session and requesting additional permissions: here and here. Hope you and others find it beneficial and save time getting started with the SDK! :)

Edit: The reason you are getting this exception is because you can't
  request new permissions on a non-open session. You need to open your
  session before requesting new permissions or making other Facebook API
  requests. I've put together a guide in the articles linked to above
  which ensure a Facebook API request (such as posting to a user's feed
  and so forth) is not made until the the user's session is open and the
  user has the required permissions.

A: It means that the session you are requesting permissions for is inactive/expired. You need to re-establish the session before you can request permissions.

A: Did you call session.openForPublish(Session.OpenRequest openRequest) before calling requestNewPublishPermissions?


text:
Q: is this invalid C++? struct HybridExpression {
    RawExpressionElement *ree;
    ExpressionNode *en;
};

vector<HybridExpression> hexpression;

hexpression.insert(hexpression.begin() + starti,
        (HybridExpression) {NULL, en});

gcc builds without warning but visual studio 2010 wont even compile it.
It doesnt like this bit: (HybridExpression) {NULL, en}

A: According to http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/C_002b_002b-Extensions.html#C_002b_002b-Extensions, you can use C extensions (including C99 stuff) in C++ programs compiled with GCC.
Compound literals is the extension you're actually using.

A: This is using a part of the C programming language that is not included in C++, it's called "compound literal". g++ -ansi will diagnose this, saying

warning: ISO C++ forbids compound-literals

This is not a part of C++0x.
The C++0x compatible syntax would have been
hexpression.insert(hexpression.begin() + starti, HybridExpression{NULL, en});

To quote the C99 standard, paragraph 6.5.2.5:

A postfix expression that consists of  a  parenthesized
         type  name followed by a brace-enclosed list of initializers
         is a compound literal.  It provides an unnamed object  whose
         value is given by the initializer list.

A: This is not valid C++ in the current Standard.  I think GCC allows it because of a GCC-specific compiler extension.


text:
Q: Sequelize js how to get average (aggregate) of associated model I am trying to get average rating of an associated Model "Rating" of Model "User" using sequelize.
sequelize.sync({logging: false}).then(()=>{
  return Model.Rating.findAll({
    attributes: [[Sequelize.fn('avg', Sequelize.col('stars')),'rating']]
  })
}).then(res => {
  res = res.map(r => r.get())
  console.log(res);
})

I get correct response when trying directly from "Rating" Model:
[ { rating: '3.5000000000000000' } ]

However, when trying to do the same through the association of "User", I get separate values instead of getting average.
sequelize.sync({logging: false}).then(()=>{
  return Model.User.findOne({
    where: {id: 7},
    include : [{
      model: Model.Rating, as: 'seller_rating',
      attributes: [[Sequelize.fn('avg', Sequelize.col('stars')),'rating']]
    }],
    attributes: {
      exclude: ['password']
    },
    group: ['seller_rating.id', 'user.id'],
  })
}).then(res => {
  res = res.get()
  res.seller_rating = res.seller_rating.map(r => r.get())
  console.log(res)
})

I had to add "seller_rating.id" and "user.id" in group as sequelize was throwing error otherwise.
{
  id: 7,
  email: 'example@gmail.com',
  createdAt: 2020-01-20T09:07:47.101Z,
  updatedAt: 2020-01-21T08:58:52.036Z,
  seller_rating: [
    { rating: '4.0000000000000000' },
    { rating: '3.0000000000000000' }
  ]
}

Following are the models for User and Rating
User:
let User = sequelize.define('user', {
    email: {type: Sequelize.STRING, unique: true, allowNull: false},
    password : {type: Sequelize.STRING, },
})

Rating:
let Rating = sequelize.define('rating', {
    seller_id: {
        type: Sequelize.INTEGER,
        references: {model: User, key: 'id'},
        unique: 'rateObject'
    },
    buyer_id: {
        type: Sequelize.INTEGER,
        references: {model: User, key: 'id'},
        unique: 'rateObject'
    },
    stars: {
        type: Sequelize.INTEGER,
        validate: {
            min: 1,
            max: 5
        },
        allowNull: false
    }
})

Rating.belongsTo(User,{ onDelete: 'cascade', foreignKey: 'seller_id'})
Rating.belongsTo(User,{ onDelete: 'cascade', foreignKey: 'buyer_id'})
User.hasMany(Rating, { foreignKey: 'seller_id', as: 'seller_rating'})
User.hasMany(Rating, { foreignKey: 'buyer_id', as: 'buyer_rating'})

A: This solution should work for you:
Model.User.findOne({
  where: { id: 7 },
  attributes: [
    [Sequelize.fn('AVG', Sequelize.col('seller_rating.stars')), 'avgRating'],
  ],
  include: [
    {
      model: Model.Rating,
      as: 'seller_rating',
      attributes: [],
    },
  ],
  raw: true,
  group: ['User.id'],
}).then((res) => console.log(res));

A: Solution that worked for me:
const product = await Product.findOne({
  where: {id: 1},
  include: [
    {
      model: Rating, //including ratings array
      as: 'ratings',
      attributes: [], //but making it empty
    },
  ],
  attributes: {
    include: [ // this adds AVG attribute to others instead of rewriting
      [sequelize.fn('AVG', sequelize.col('ratings.rating')), 'avgRating'],
    ],
  },
  group: ['Product.id'],
});

result:
{
  "id": 1,
  "name": "product",
  "price": 50,
  "createdAt": "2022-04-21T11:32:56.666Z",
  "updatedAt": "2022-04-21T11:32:56.666Z",
  "categoryId": 1,
  "avgRating": "2.7500000000000000"
}


text:
Q: How to make Android app recover from pause and resume gracefully I am very familiar with the Android activity lifecycle, but I feel like I am missing something that should be pretty obvious here.
I have a multi-activity Android app; it uses static variables (in the application class) to keep a handle on the various objects that are used across the different views. The problem occurs when the app is paused (exited) and Android (presumably) cleans up memory to maintain foreground processes. When the user resumes the app, it occasionally (not always) seems to come back and resume in the Activity that the user left, but with the static variables nulled. Even worse, the activity sometimes seems to resume with the static variables still present, but with internal variables in objects nulled.
I eventually implemented a simple sanity check, which checks that the statics are not nulled (and also the most vital inner variables of relevant objects) and returns the app to start if it fails. This did cut down on a lot on the problems, but I still see the occasional issues with this, as it is simply not practical to check everything for every resume().
What I really need is for the app to restart from scratch if the Android OS decides it needs to clean anything non-GC from memory while the app is inactive. I feel there should be a graceful way to do this, but haven't noticed anything in the documentation.
Any thoughts? How do others avoid this problem?

A: Using the Application class for preserving state can result in unexpected behaviour if Android decides to kill your process completely. Check out this answer to a similar question
i.e. you should probably use some sort of persistence (SharedPreferences or some DB) in your Activity lifecycle callbacks.


text:
Q: How to do column editing in vim? Vim is pretty powerful when editing by line - the search/replace tools are modeled to work linewise.
But what if I want to change a particular column across all lines? For example, how can I change the 80th column in my file to a # easily?

A: ...I couldn't follow the steps of sa125 (facepalm) so I looked someplace else and found a simpler explanation at: https://blog.pivotal.io/labs/labs/column-edit-mode-in-vi

*

*Ctrl+v [ and select what ever you want]

*Shift+i [and write whatever...(check out ** below)]

*Esc
*c without Shift can be used instead of step 2, to delete selection before insert. And also r to replace.
**!! Attention Don't be discouraged by the fact that only the first row is changed when you 'write whatever...'!!
Hope it helps!

A: You can use a substitution where the pattern matches a specific column (\%c):
:%s/\%80c/#/<CR>

Or you can use block-wise visual mode:
gg80|CTRL+vGr#
The 'virtualedit' option can be used to allow positioning the cursor to
positions where there is no actual character:
:set virtualedit

A: To edit a column, follow these steps:

*

*Stand on the beginning of the column

*Press Ctrl+v, then mark across the column you want to edit.

*Press Shift+i to insert text at the beginning of the column, Shift+a to append text, r to replace highlighted text, d to delete, c to change... etc.

*Hit ESC when done.

I think people (me) sometimes map the column editing keys to Ctrl+Q so it won't collide with visual select line (V) or paste-text if you mapped it as such.

A: I may be totally off topic here, but if your idea is to avoid long lines, you could have a look at the colorcolumn option of vim 7.3.

A: For column-wise editing, vis.vim is really useful. You can block-select your column of interest, and manipulate it with normal commands, and even arbitrary Ex commands. From the example on that page, I have often used the pattern:
:'<,'>B s/abc/ABC/g

You can Vundle/Pathogen install vis.vim from github:
Plugin 'taku-o/vim-vis'


text:
Q: Combining two led strips with separate controllers Out of practice and have forgotten basic principles but would like to combine two led strips to one controller so they operate in sync. Have combined output from sensor into control box but outputs from control boxes not in sync when using RGB light shows. How can I split output from one controller to two light strips using driver and controller in image. Thanks

A: If the controller output parameters like brightness, speed of animation, color are not in sync between the two led strips then you need to reset both controllers to there initial states.
These kind of controllers store the previously set parameters in their memory and thus are able to start from the previously know state on each power cycle. You must have set different parameters for the two controllers before you combined the receiver sensor output.
i.e. If brightness in one was set to 50 and in the other to 25, then since they have common receiver sensor now, on increasing brightness by 10, one will increase to 60 and the other to 35.
To fix this sync problem you need to just keep lowering the brightness / speed of animation / the parameter not in sync, until the parameters become equal on both.


text:
Q: The result of the algorithm always return zero - C I'm trying make an algorithm to calculate a readjusted salary from employee, but always the algorithm returns zero and still gets an error message:
lucas@lucas-pc:~/VSCodeProjects/C$ cd "/home/lucas/VSCodeProjects/C/" && gcc logic.c -o logic && "/home/lucas/VSCodeProjects/C/"logic
logic.c: In function 'main':
logic.c:14:32: warning: format '%f' expects argument of type 'double', but argument 2 has type 'float *' [-Wformat=]
   14 |    printf("Readjusted salary: %f", &readjustedSalary);
      |                               ~^   ~~~~~~~~~~~~~~~~~
      |                                |   |
      |                                |   float *
      |                                double

Algorithm:
#include <stdio.h>

int main() {
   float salary, readjustedSalary;
   printf("Enter your salary: ");
   scanf("%f", &salary);

   if(salary >= 5000){
      readjustedSalary = salary + (salary * 0.2);
   } else {
      readjustedSalary = salary + (salary * 0.3);
   }

   printf("Readjusted salary: %f", &readjustedSalary);
   return 0;
}

What I doing wrong? I'm beginning on C...

*

*I'm using vscode..

A: Your problem is that you're using & in printf, when you use & you mean the memory position of a variable (summarizing). So to write a value to a variable (using scanf) you need to pass the memory position, but to print it, no.
#include <stdio.h>

int main() {
   float salary, readjustedSalary;
   printf("Enter your salary: ");
   scanf("%f", &salary);

   if(salary >= 5000){
      readjustedSalary = salary + (salary * 0.2);
   } else {
      readjustedSalary = salary + (salary * 0.3);
   }

   printf("Readjusted salary: %f", readjustedSalary);
   return 0;
}


text:
Q: Clicking URL Link on TTStyledTextLabel doesn't push a new page When I am clicking URL link on TTStyleTextLabel, it doesn't push a new page.
But when I looked at the TTCatalog, they don't have any method in the styledtexttestcontroller which seem to open up the webpage.
So how does TTCatalog do that?
How can I do that?

A: Make sure that you have the TTNavigator to map from url to TTWebController. In the sample TTCatalog app you have:
[map from:@"*" toViewController:[TTWebController class]];

This will let the http:// be mapped to TTWebController in case it does not have any other mapped view controller.


text:
Q: jinja + form + unicode control characters + xml/docx integration I am creating word documents based on a users input in a form. However, when the user inputs a unicode control character, and trying to make a word file out of this using the python-docx package, this error occurs:
File "src\lxml\apihelpers.pxi", line 1439, in lxml.etree._utf8
ValueError: All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters

I managed to tackle this issue by checking the form for invalid xml characters before each request (I have many forms where this problem might occur), and removing any invalid xml characters from the fields. I then make a new Immutable Multi Dictionary, and fill it with the cleaned text.
from docx import Document
from docx.shared import Inches
from flask import Flask, render_template_string, request
from werkzeug.datastructures import ImmutableMultiDict

def valid_xml_char_ordinal(c):
    codepoint = ord(c)
    return (0x20 <= codepoint <= 0xD7FF or codepoint in (0x9, 0xA, 0xD) or
            0xE000 <= codepoint <= 0xFFFD or 0x10000 <= codepoint <= 0x10FFFF)

app = Flask(__name__)

@app.before_request
def before_request():
    if 'check_form_xml_validity' in request.form:
        tuple_list = []
        for field_name in request.form:
            all_field_values = request.form.getlist(field_name)
            for field_value in all_field_values:
                cleaned_field_value = ''.join(c for c in field_value if valid_xml_char_ordinal(c))
                tuple_list.append((field_name, cleaned_field_value))
        request.form = ImmutableMultiDict(tuple_list)

@app.route('/', methods=['GET', 'POST'])
def form_test():
    if request.method == 'GET':
        x = '' # this seemingly empty string is not empty, but contains a bunch of control characters
        return render_template_string(
            """<form action="{{ url_for('form_test') }}" method="post">
                <input name="some_field" value="{{x}}">

                check the xml validity of this form?

                <input type="checkbox" checked name="check_form_xml_validity">

                <button>submit</button>
            </form>""",
            x=x)
    else:
        doc = Document()
        p = doc.add_paragraph(request.form['some_field'])
        return 'yay'

And this method works perfectly. However, it seems very unlikely that I'm the only one with this problem, but yet I couldn't find any clean solutions. So the question is, should I really be solving this problem in the current way? It's pretty tedious, and it feels like I'm overlooking some Flask or python-docx setting or argument somewhere which would solve this issue.
The example is fully functional, and if the checkbox is checked, the before_request function is executed. If the checkbox is not checked, it is not executed and the mentioned server error will show.

The control character is: U+000C : <control-000C> (FORM FEED [FF])

A: There are tons of the control characters in the unicode. So, basically, you need to remove control characters, which is the one of the category in unicode chars. To do that I recommend you to use unicodedata.category from unicodedata module.
See code below:
import unicodedata

def remove_control_chars(s):
    return "".join(ch for ch in s if unicodedata.category(ch)[0] != "C")


text:
Q: canot find mongodb error but VS shows it I am developing Node.JS app in Visual Studio (2015) with Node.JS tools and I installed NPM package mongodb. But when I want to require mongodb module, it fails with error

Cannot find module 'mongodb'

In solution explorer > project > npm is this package shown´. Why it throws error? TypeScript Code for loading module is
import mongo = require('mongodb');
// converted to JS
var mongo = require('mongodb');

package.json:
{
  "name": "XYZ",
  "version": "0.0.0",
  "description": "_XYZ",
  "main": "app.js",
  "author": {
    "name": "zurmi",
    "email": "fsdgsdfgsdf@sadfasdf.sd"
  },
  "dependencies": {
    "mongodb": "2.0.47"
  }
}


text:
Q: Get One Top Image for each category I have grouped photos into categories . ( 2 tables categories and photos with catID field)
I have  a query that returns a list of categories and the number of photos it has and imagename of its top photo ( each photo record has a field IsTop ) .
But it's not working properly . it just returns imagepath for first record . for rest it returns null
select
T3.ImagePath,T2.ID,T2.Title,T2.ItemsCount
from (
select C.Title,C.ID,Count(Ph.CatID) as ItemsCount from Categories C
    left Outer join (select CatID from photos) Ph
    on C.ID=Ph.CatID group by C.Title,C.ID) T2
left outer join
(select top 1 ImagePath,CatID from photos where IsTop=1 order by id desc) T3
on T2.ID=T3.CatID
group by T3.ImagePath,T2.ID,T2.Title,T2.ItemsCount;

A: Assuming that you're on SQL Server 2005 or later, you can use a windowing function:
select
T3.ImagePath,T2.ID,T2.Title,T2.ItemsCount
from (
select C.Title,C.ID,Count(Ph.CatID) as ItemsCount from Categories C
    left Outer join (select CatID from photos) Ph
    on C.ID=Ph.CatID group by C.Title,C.ID) T2
left outer join
(select ImagePath,CatID,ROW_NUMBER() OVER (PARTITION BY CatID ORDER BY ID desc) as rn from photos where IsTop=1) T3
on T2.ID=T3.CatID and rn = 1 /* <-- New join condition also */
group by T3.ImagePath,T2.ID,T2.Title,T2.ItemsCount;

In this case, it allows us to number the rows, with row numbers being assigned independently for each CatID (the PARTITION BY bit), and with a specific ordering. For each CatID, we start assigning row numbers again starting at 1.


text:
Q: how to add images dynamically to a button background in salesforce lightning? I am finding difficulty to set an image dynamically as a background for the button. I can able to get static image from resource but I could not load in dynamic

A: You can try using :
<img src="/[namespace]/sfc/servlet.shepherd/version/download/[id]"/>
where id is the content version id(prefix 068).


text:
Q: How to hide and show the view in ViewPager Am using ViewPager to show bunch of images by one by one.Am customize the ViewPager use PagerContainer by refer this example.In ViewPager have two image view in default the both image view are visible.But i want to invisible one image view onselectedpage in ViewPager.For example view pager current position in 2 means the blur image in 2nd position is going to invisible.in all other position the blur image is visible.I don't how to do.Can any one know help me to solve this issue.
View Pager Declaration
ema = new Executive_member_adapter(getActivity());

executive_cont = (PagerContainer)findViewById(R.id.executive_memeber_container);
executive_members = executive_cont.getViewPager();

executive_members.setAdapter(ema);
executive_members.setOffscreenPageLimit(ema.getCount());

executive_members.setPageMargin(15);
executive_members.setClipChildren(false);
executive_members.setOnPageChangeListener(ema);

PagerAdapter
public class Executive_member_adapter  extends PagerAdapter implements OnPageChangeListener{

LayoutInflater inflater;
Activity activity;

ImageView members_img,blur_img;

int photos[] = {R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,R.drawable.pic4,R.drawable.pic5,R.drawable.pick6};

public Executive_member_adapter(Activity activity) {
    // TODO Auto-generated constructor stub

    this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return photos.length;
}

@Override
public boolean isViewFromObject(View view, Object object) {
    // TODO Auto-generated method stub
    return view == ((RelativeLayout) object);
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {

   ((ViewPager) container).removeView((View)object);
}

@Override
public Object instantiateItem(final ViewGroup container, final int position) {

    View itemView;
    itemView = inflater.inflate(R.layout.executive_members_pic, container, false);

    members_img = (ImageView)itemView.findViewById(R.id.memebers_image);
    members_img.setBackgroundResource(photos[position]);

   blur_img = (ImageView)itemView.findViewById(R.id.blur_image);

    ((ViewPager) container).addView(itemView);

    return itemView;
}

@Override
public void onPageScrollStateChanged(int position) {
    // TODO Auto-generated method stub

}

@Override
public void onPageScrolled(int position, float arg1, int arg2) {
    // TODO Auto-generated method stub

}

@Override
public void onPageSelected(int position) {
    // TODO Auto-generated method stub

}
}

A: the array from which you are showing the images, you can dynamically add/remove the image that you want to hide or show.

A: Dit you mean something like this?
On the selected page a ImageView becomes invisible. In this case the ViewPager got 4 pages.
@Override
    public void onPageSelected(int position) {
        switch (position) {
        case 0:
            blur_img.setVisibility(ImageView.VISIBLE);
            break;
        case 1:
            blur_img.setVisibility(ImageView.GONE);
            break;
        case 2:
            blur_img.setVisibility(ImageView.VISIBLE);
            break;
        case 3:
            blur_img.setVisibility(ImageView.VISIBLE);
            break;

    }


text:
Q: Sinatra and Foursquare - undefined method `web_server' I'm trying to run a simple Foursquare auth in Ruby with Sinatra. I am using the example here.
When I try to run this code on my local server, I get this error
 NoMethodError at /
undefined method `web_server' for #<OAuth2::Client:0x16168bc>

I can't figure out how to fix this... Ideas?

A: the web_server method was removed in v0.5.0 of the OAuth2 ruby gem.
install a prior version of the gem to make use of the missing method:
gem install oauth2 -v 0.4.1
and modify your script by adding the following line before the require 'oauth2' so it will only accept that particular version of the gem:
gem 'oauth2', '=0.4.1'
edit: looks like the example hasn't been updated for a while -- I forked it and included the above suggested workaround (which has since been merged into the original repository).


text:
Q: Is there any difference between "next time" and "next time around"? Could you tell me if there is any difference between next time and next time around? For example:

If you pay for the dinner this time, next time/next time around it's on me.

A: Essentially no difference. I would say "around" is a colloquial way to add a bit of emphasis that something is repeating (or expected to repeat).


text:
Q: Word for "using other's thing without their permission" Could you give me a word which means using things of other people without their permission?
For example, in the sentence:

You shouldn't touch my phone without my permission

I want to find an adverb to replace without my permission.
Can I say: you shouldn't touch my phone freely?

A: I don't think it's used often (at least not when talking about phones), but you might use nonconsensually.
Nonconsensual means, according to Merriram Webster dictionary:

not agreed to by one or more of the people involved

A: It's challenging to find a good adverb here, since we need to start with an adjective that means permitted, negate it, and then turn it into an adverb. The concept of permission typically requires that the permitter be stronger than the permittee, even if this is simply by appealing to social norms, e.g. it would be impolite to use someone's phone without asking them for permission. So the adjective has to convey something about the social framework in which permission is granted, since the listener is expected (through the use of should) to respect its rules. That's asking a single word to do a lot.
That said, there are many possible adverbs, although IMHO they don't really improve on the OP's original construction, such as:

*

*unpermittedly, or just unpermitted,

*illegally,

*uninvited,

*discourteously,

*selfishly.

Finally, is an adverb even needed?  If the social framework for permission is the relationship between the speaker and the listener, what's wrong with Don't touch my phone.


text:
Q: Windows (steam) games So I recently got a new computer and switched from windows to manjaro, and I, of course, can't play some of my games I bought on steam (I can't even attempt to install them because the install button is gone). I was told to download wine + other add-ons for wine, didn't do anything. Is there anyway I can play these games? (Keep in mind I'm new to Linux)

A: To install and run Windows games using Steam and Wine, you need to install Steam in Wine. You need to download the Steam client for Windows, install it using Wine, and connect to your Steam account. (You won't be able to run both the Linux and Windows clients simultaneously.) Then you'll have access to your Windows games from the Steam client running in Wine, and you'll be able to install and run some of them.
Not all Windows games work well using Wine. You'll find compatibility information, bugs and workarounds in the Wine AppDB.


text:
Q: Why does Mozilla insert duplicate rows? php/sql So, i got this code:
<?php
    $servername = "localhost";
    $username = "**";
    $password = "**";
    $dbname = "TestDB";
    // Create connection
    $conn = new mysqli($servername, $username, $password,$dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    echo "Connected successfully
";

    $ip = $_SERVER['REMOTE_ADDR'];

    $sql = "INSERT INTO testdata (id,address,count) VALUES (DEFAULT,'$ip',1) ON DUPLICATE KEY UPDATE count=count+1";

    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully
";
    } else {
        echo "Error: " ;
    }

    $conn->close();
    ?>

With this code ip-addresses of customers are saved and it should increase count by 1 every time they return to the website. When i visit database.php directly it works like it should in every browser, but when i call the php-file via the index.html-page it counts up twice (most of the times, not always) in Mozilla, other browsers no problem, the code in html-file:

Anyone know why? Please help, i'm really stuck here


text:
Q: Effect of surrounding material on microstrip impedance? If you were to have a microstrip transmission line PCB trace, which then had a dielectric material run completely on top of the PCB track coverlayer. Would this surrounding material affect the impedance of the line, causing a need to change the width to accommodate? I see that by adding this dielectric material, it starts to look more like a strip line in that it is sandwiched by dielectric on either side.
This would be for a high frequency (GHz) signal.

A: Yes, any dielectric above will have an effect, although not a large one since most of the field is below the microstrip.  Lots of calculators can do embedded microstrips, so you can see for yourself.  For example, to pick one at random:

Edit: this calculator may not be accurate, check the one suggested below.
https://www.eeweb.com/tools/embedded-microstrip-impedance/
Adding 20 microns of dielectric (same as substrate) above the microstrip will change the impedance by about 3.5 ohms.  Usually not significant, but not unmeasurable either.


text:
Q: Write csv file from byte[] I am getting a file in byte[] which have comma separated values in quotes, I want to save it as CSV by using OpenCSV. I am using this to save it in CSV format.
Following is my code to convert byte[] to array and then store it in file
byte[] bytes = myByteStream.getFile();

String decoded = new String(bytes, "UTF-8");
//String lines[] = decoded.split("\\r?\\n");

FileOutputStream fos = new FileOutputStream("/home/myPC/Desktop/test.csv");
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
CSVWriter writer = new CSVWriter(osw);
String[] row = {decoded};

writer.writeNext(row);
writer.close();
osw.close();

But this above code puts extra quotes around and also merge all lines in one line.
Any help on how to do this properly ?

A: You can prevent adding quotes to the cell values within the constructor of CSVWriter, for example:
CSVWriter writer = new CSVWriter(osw, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);

Regarding the whole byte array persisted as a single row. Are you sure there are newlines within the original file.
If so you might get away by doing the following:
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "ASCII"));

String line;
while ((line = reader.readLine()) != null) {
    // Handle the line, ideally in a separate method
}

Got this from splitting a byte array on a particular byte

A: I think Apache Commons CSV is a better CSV library. From the pasted code it is not clear if you want to somehow change the contents of the file or just duplicate it: in the latter case you don't even need to parse the file as CSV records - just copy it byte-for-byte. In the former case, ie if you need to modify the content of the file, you need something like (Commons CSV used here)
CSVParser parser = CSVFormat.newFormat(',').parse(
    new InputStreamReader(new ByteArrayInputStream(bytes), "UTF8"));
CSVPrinter printer = CSVFormat.newFormat(',').print(out);
for (CSVRecord record : parser) {
  try {
    printer.printRecord(record);
  } catch (Exception e) {
    throw new RuntimeException("Error at line "
      + parser.getCurrentLineNumber(), e);
  }
}
parser.close();
printer.close();

Look at the Javadoc for CSVFormat


text:
Q: Trying to recieve a string through a broadcast in an activity from a service, not seeing anything Here's my code below.  The first bit of code is for my activity.  I put a click listener on a button in that activity that starts my service.  Right now, I just want to see that I can recieve strings from that service so here is my code trying to do that.  I put a "hello world" broadcast in the oncreate of the service to test.  Can anyone spot the issue?  The service code is below the activity code.
package homeBrewChatter.Calcs;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;

import java.util.List;

public class Hop_Timer extends Activity {
    private TextView timerOut;

     private BroadcastReceiver onBroadcast = new BroadcastReceiver() {
            @Override
            public void onReceive(Context ctxt, Intent i) {
                Hop_Timer.this.timerOut = (TextView)Hop_Timer.this.findViewById(R.id.display_time);
                Hop_Timer.this.timerOut.setText("RECIEVED");
            }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hoptimer);

        Button setVars = (Button) findViewById(R.id.add_alarm_button);
        setVars.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                //Hop_Timer.this.timerOut = (TextView)Hop_Timer.this.findViewById(R.id.display_time);
                //Hop_Timer.this.timerOut.setText("working so far");
                startService(new Intent(Hop_Timer.this, Hop_Timer_Service.class));
            }

        });
    }

    public void onResume() {
        super.onResume();
        registerReceiver(onBroadcast, new IntentFilter("mymessage"));
    }
    public void onPause() {
        super.onPause();
        unregisterReceiver(onBroadcast);
    }
}

package homeBrewChatter.Calcs;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;

public class Hop_Timer_Service extends Service {
    private Handler mHandler = new Handler();
    private int length_minutes;
    private boolean timer_running;
    private long startTime = 0L;
    public String currentTime = "";

    @Override
    public void onCreate() {
        length_minutes = 0;
        timer_running = false;
        getApplicationContext().sendBroadcast(new Intent("Hello World"));
    }

    public void setTime(int mins) {
        length_minutes = mins;
    }

    public void startTimer() {
        startTime = System.currentTimeMillis();
        mHandler.removeCallbacks(mUpdateTimerTask);
        mHandler.postDelayed(mUpdateTimerTask, 100);
    }

    private Runnable mUpdateTimerTask = new Runnable() {
        public void run() {
            final long start = startTime;
            long millis = SystemClock.uptimeMillis() - start;
            int seconds = (int) (millis/1000);
            int minutes = seconds /60;
            seconds = seconds %60;
            if(seconds < 10) {
                currentTime = "" + minutes + ":0" + seconds;
            } else {
                currentTime = "" + minutes + ":" + seconds;
            }
            getApplicationContext().sendBroadcast(new Intent(currentTime));
            mHandler.postAtTime(this, start + (((minutes * 60) + seconds + 1) * 1000));
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
}

A: With respect to your actual question, the Intent that you are broadcasting does not match the IntentFilter you are using in registerReceiver(). Since your IntentFilter says it is looking for "mymessage" Intents, your Intent that you broadcast needs to have the "mymessage" action. Right now, one of your Intents has an action that is based on the current time, which is unlikely to be received by anything. The other has an action of "Hello World".
Beyond that:

*

*By default, broadcasts are broadcast to the entire device. If you are intending to broadcast to the entire device, please use an action string that is namespaced to your app (e.g., homeBrewChatter.Calcs.mymessage). If you are not intending to broadcast to the entire device, please use setPackage() on the Intent that you broadcast to keep it within your application.

*Since Service is a Context, you do not need to use getApplicationContext() in your Service for your broadcasts.

*You do not appear to be calling startTimer().

*It is infrequently a good idea, in production code, to have a Service whose primary job is to sit and watch time tick by. AlarmManager is a more common solution here, so your Service can be in memory only when it is adding actual value to the user.

*You start the service, but never stop it.


text:
Q: R - "what is a function within a function" Context is that I am still learning R as a beginner. Can I explain the concept of "a function within a function" as below?

It works like "in" and "out"- you give a
  function in, another function comes out.

For example:
addsth<-function(xx){function(yy){xx+yy}}

*

*function of xx goes in, function of yy comes out (inside of function of yy, yy goes in, xx+yy comes out)

addsth(7)

*

*means it is a function of 7, 7 goes in, function(yy){xx+yy} needs to come out.
Now 7 "flow into" the body of what needs to come out the body says yy goes it take a value of 7, xx+yy comes out when all is ready to invoke, which also means I have to define xx for it to operate.

That definition cannot be assigned as a value, like xx=9, but it needs to be assigned within a function to satisfy the requirement to invoke.
Therefore: now since addsth(7) only defines a function, it needs to be given a value of xx
afteradd<-addsth(7)
afteradd(1000)
returns 1007

many thanks!

A: I am not completely sure what your question is. addsth() - to be exact - is a "closure". The function it self doesn't change, but "The parent environment of a closure is the execution environment of the function that created it" (Wickham)
The book 'Advanced R' by Hadley Wickham explains this pretty well, and is actually available online: http://adv-r.had.co.nz/Functional-programming.html
Hope this helps a little.


text:
Q: Windbg !name2ee mscorlib.dll Exception I use windbg to debug .Net 4.0 on window 10 64bit
.loadby sos clr
!name2ee mscorlib.dll

c0000005 Exception in C:\Windows\Microsoft.NET\Framework\v4.0.30319\sos.name2ee debugger extension.
        PC: 571ebff3  VA: 00000000  R/W: 0  Parameter: 00000000

How to fix this exception ?


text:
Q: How to install and setup graylog-server and graylog-web on Ubuntu from repository? I am trying to setup graylog on Ubuntu 14.04. I tried to find out installation steps on internet I found few links. but their method of installation is manual I mean installation from the source. and I don't want to follow installation from source because posts are old, some are talking about graylog2(I could not found difference between normal graylog and graylog2), their source package is old so there configuration files are not matching with latest configuration files.
so I decided to setup latest greylog from official documentation at http://docs.graylog.org/en/1.0/pages/installation.html#ubuntu-14-04
I have installed latest mongodb and elasticsearch.
after that I followed steps to install graylog-server and graylog-web from official documentation.
$ wget https://packages.graylog2.org/repo/packages/graylog-1.0-repository-ubuntu14.04_latest.deb
$ sudo dpkg -i graylog-1.0-repository-ubuntu14.04_latest.deb
$ sudo apt-get install apt-transport-https
$ sudo apt-get update
$ sudo apt-get install graylog-server graylog-web

I am able to see configuration files after installation
/etc/graylog/server/server.conf
/etc/graylog/web/web.conf

I am able to see other files at
/usr/share/graylog-server
/usr/share/graylog-server/bin
/usr/share/graylog-server/graylog.jar
/usr/share/graylog-web
/usr/share/graylog-web/bin/
/usr/share/graylog-web/conf

I configured /etc/graylog/server/server.conf and /etc/elasticsearch/elasticsearch.yml with help of https://www.digitalocean.com/community/tutorials/how-to-install-graylog2-and-centralize-logs-on-ubuntu-14-04 and able to run graylog-server by running
java -jar /usr/share/graylog-server/graylog.jar server

this shows me
Started REST API at <http://127.0.0.1:12900/
Graylog server up and running.

After that I am not understanding how to setup graylog-server and graylog-web properly because these steps are not complete. I will appreciate if someone could give clean steps for proper setup. thanks in advance

A: I am writing steps to setup graylog-server and graylog-web from repository. graylog-web is webbased frontend to graylog.

*

*mongodb and elasticsearch are the dependencies so we have to install these first.

*now configure elasticsearch e.g. edit /etc/elasticsearch/elasticsearch.yml
sample setting is
cluster.name: graylog-production
network.bind_host: 0.0.0.0
discovery.zen.ping.multicast.enabled: false
discovery.zen.ping.unicast.hosts: ["127.0.0.1:9300"]
script.disable_dynamic: true

*now restart elasticsearch by sudo service elasticsearch restart

*Now install graylog-server and graylog-web
first setup graylog repository
$ wget https://packages.graylog2.org/repo/packages/graylog-1.0-repository-ubuntu14.04_latest.deb
$ sudo dpkg -i graylog-1.0-repository-ubuntu14.04_latest.deb
$ sudo apt-get install apt-transport-https
$ sudo apt-get update
now we can install graylog-server and graylog-web by apt-get
$ sudo apt-get install graylog-server graylog-web

*Now graylog-server has installed, we need to configure setting e.g. edit file /etc/graylog/server/server.conf
follow https://www.digitalocean.com/community/tutorials/how-to-install-graylog2-and-centralize-logs-on-ubuntu-14-04 and http://docs.graylog.org/en/1.0/pages/installation.html#ubuntu-14-04 for settings.
see sample setting file at http://paste.ubuntu.com/12426568/

*check if graylog-server is running or not
java -jar /usr/share/graylog-server/graylog.jar server
if its running then you will see lines
Started REST API at <http://127.0.0.1:12900/
Graylog server up and running.

*Now if graylog-server is running fine then you re ready to setup graylog-web. we have already installed it so now copy /etc/graylog/web/web.conf to /usr/share/graylog-web/conf/web.conf and give values
graylog2-server.uris="http://127.0.0.1:12900/" and set application.secret

*we are done now, so lets start graylog-web
sudo /usr/share/graylog-web/bin/graylog-web-interface or by sudo start graylog-web

*check by opening http://localhost:9000

A: install Graylog2 Server v0.20.2 in /opt. First, download the Graylog2 archive to /opt with this command:
cd /opt; sudo wget https://github.com/Graylog2/graylog2server/releases/download/0.20.2/graylog2server-0.20.2.tgz
sudo tar xvf graylog2-server-0.20.2.tgz sudo ln -sgraylog2-server-0.20.2 graylog2-server
sudo cp /opt/graylog2-server/graylog2.conf.example /etc/graylog2.conf sudo apt-get install pwgen SECRET=$(pwgen -s 96 1)

sudo -E sed -i -e 's/password_secret =.*/password_secret = '$SECRET'/' /etc/graylog2.conf

Full tutorial at allubuntu.com


text:
Q: Difference in Days in DB2 I have to calculate the difference in days between two dates and I figured out that
there is no such thing as a DATEDIFF() function in DB2.
I tried doing it like that:
(DAYOFYEAR(date1)-DAYOFYEAR(date2)+(YEAR(date1)-YEAR(date2))*365)

This is obviously not working for leap years, but I do not have to deal with that.
I know that date1 is always later than date2.
Do I have any flaws in my logic? It is not working (it's an exercise and I have a function to test my results). Is there an easier way to do that?
Thank you.

A: It would possibly help if we knew what version of DB2 you were using and what platform it was running on. But it seems likely that you can do something like this:
select
      days(my1stdate) - days(my2nddate) as myDuration
from mySchema.myTable

The DAYS() function converts a DATE value into the number of days between Jan 1, 0001, and the supplied DATE value. Once both DATEs are converted, the subtraction (difference) is straightforward.


text:
Q: Should we start with multiple small-grained databases for an app that may scale massively We're developing a new eCommerce website and are using NHibernate for the first time.  At present we are splitting our data into multiple SQL Server databases, divided per area of functionality.  So we have one for UserInfo, one for Orders, one for ProductCatalogue and so on...
Our justification for this decision is twofold really:

*

*the website has the potential to be HUGE (it is a new website for one of the largest online brands in the UK) and we feel that by partitioning our data along functional lines we will be able to move the databases onto their own servers which would give us an easy scaling route should we need it;

*my team has always worked this way - partly as a consequence of following the MS Commerce Server pattern from previous projects.
However, reading up on this decision on the internet, we find that the normal response to this sort of model is extremely scathing.  "Creating more work for the devs now in order to create more work for the devs later" is one sample comment from Stack Overflow!
In addition, NHibernate is much easier to use with only one database (just one SessionFactory needed).  And knowing that Stack Overflow ran off just one box for a long time makes me think that maybe we should not try to be so clever.
So, my question is, "are we correct in thinking that using fine-grained databases might increase our ability to scale or should we sacrifice this for easier development"?

A: Why don't you just design your database properly and put the files on appropriate disk? Use a cluster if necessary. Creating multiple databases is not an inherently scaling solution. Also - cross database referential integrity? Good luck.
What's your definition of "HUGE"? SQL Server can handle massive databases, but one thing I've learnt is that people often have no idea what constitutes a lot of data.

A: I've never worked in a project like this. I'm used to databases with several hundred tables, which had never been a problem.
Therefore I can't say if your idea is a good idea, I never tried it. The "my team has always worked this way"-argument is a major driver for many decisions, and I can't even say that it is always wrong.
With NHibernate you organize your data in classes. They can be in different namespaces and assemblies. You usually don't work much with the database directly, you don't need this kind of structure there.
About the scalability argument: I'm not sure if it is really scaling well when you need to access several databases every time. I mean: you always need users and orders and probably more. Then you need to get all this data from several databases.

A: Agree fully with starskythehutch - keep your related tables together in the same DB. BUT, you may want to consider having separate databases for things that are not related or non-critical to your main product; but that are a part of the app.
For eg: if you decide to log every visit/hit to the site in a DB, you should probably keep that in a separate DB.
The reason you should consider:
1. huge number of transactions - say hundreds of thousands / sec. Having non-critical un-related stuff in a separate DB will ensure that tlog contentions because of this are avoided.

*

*Restore, DBCC CHECKDB, backup times. If you stuff your non-related non-critical stuff in your main DB, you are essentially increasing the size of your DB and it will affect these operations. Having it in separate DB will help you improve performance of these operations.


text:
Q: Getting an error when creating a new laravel project whenever i try to create a new project, i get this error. any ideas on what it might be?

  Problem 1
    - laravel/framework[v8.75.0, ..., 8.x-dev] require league/flysystem ^1.1 -> satisfiable by league/flysystem[1.1.0, ..., 1.x-dev].
    - league/flysystem[1.1.0, ..., 1.x-dev] require ext-fileinfo * -> it is missing from your system. Install or enable PHP's fileinfo extension.
    - Root composer.json requires laravel/framework ^8.75 -> satisfiable by laravel/framework[v8.75.0, ..., 8.x-dev].

To enable extensions, verify that they are enabled in your .ini files:
    - C:\PHP7\php.ini
You can also run `php --ini` in a terminal to see which files are used by PHP in CLI mode.
Alternatively, you can run Composer with `--ignore-platform-req=ext-fileinfo` to temporarily ignore these required extensions.

A: Error tells you exactly what's happening.
laravel/framework required flysystem. flysystem requires PHP's fileinfo extension.
That seems to be disabled.
As it states go to your php.ini file (C:\PHP7\php.ini), edit the php.ini file using notepad for example. CTRL+F and search for fileinfo (or extension=php_fileinfo.dll if you want to be thorough).
In front of it should be a semicolon (;) meaning it's commented out and therefore disabled.
Remove the semicolon and go through the steps again. Should work now.


text:
Q: Convert binary to hex in node.js I want to ask I want to convert my binary data to hex before I will insert this to my table.
var net  = require('net');

var server = net.createServer(function(socket){

    socket.on('data',function(data){
    var bindata= data.toString('binary');

    //filter(bindata);

    //if no error convert to hex.
    var hexdata = bindata.toString('hex');

    //insert hexdata here.
});

server.listen(3030,'127.0.0.1', function () {
    console.log("server is listenining");
});

but the problem is that the binary data will be inserted.

A: parseInt("10101001", 2).toString(16)
// => "a9"

EDIT: I think I misunderstood the question. Your data starts out as Buffer, then you convert it to a string, then you want it as hex? If so, just do data.toString('hex'). If you have already manipulated bindata, then reconstruct into a buffer:
var bindata = data.toString('binary');
// do something with bindata
var hexdata = new Buffer(bindata, 'ascii').toString('hex');

A: Try this:
parseInt("1111", 2).toString(16);

Second param in parseInt is radix its represent "111" value to binary and toString(16) convert it to hex.


text:
Q: HttpContext.Current and ConcurrentDictionary Currently we have a very strange issue on our production server. For a specific param in query string, we get the data for query string in other request. I'm trying to figure out if this behavior can be caused, by the way I use ConcurrentDictionary in IHttpHandler:
Below is pseudo code example:
public class MyHandler : IHttpHandler
{
        private static ConcurrentDictionary<string, DataObject> _dataCache = new ConcurrentDictionary<string, DataObject>();

        public virtual bool IsReusable
        {
            get { return true; }
        }

        public virtual void ProcessRequest(HttpContext context)
        {
            Func<DataObject> getDataMethod = () =>
            {
                 return DataFactory.GetData(context.Request.QueryString["dataid"].ToLower());
            }

            string cacheKey = HttpUtility.UrlDecode(context.Request.QueryString["dataid"].ToLower());

            DataObject infoItem = _dataCache .GetOrAdd(cacheKey, (key) => { return getDataMethod(); })

            //Other processing code
        }
}

So it happens that for "dataid=1" i get the data for "dataid=2"...
When getDataMethod is executed, can I be sure that it will access the relevant context?


text:
Q: Unable to remove x-values from android from Android MpandroidChart library graph I have implemented Mp android chart real-time line graph on my android application. I have set of records(both x and y values) saved. I want to navigate through each records using next button and want to corresponding graph.
My problem is when the next graph is loading everything working fine but I am unable to remove x-values. Hence for the next graph previous x-values are showing.
Can anyone help me???
  private void addEntryNew(String timevalue, String value){
    LineData data = mChart.getData();
    if (data != null) {
        set = data.getDataSetByIndex(0);

        if (set == null) {
            set = createSet();
            data.addDataSet(set);
        }
        data.addXValue(timevalue);
        data.addEntry(new Entry(Float.parseFloat(value), set.getEntryCount()), 0);

        mChart.notifyDataSetChanged();
        mChart.setVisibleXRange(12);
        mChart.moveViewToX(data.getXValCount() - 7);
    }
    /** Code for ToggleFilled */
     ArrayList<LineDataSet> sets = (ArrayList<LineDataSet>) mChart.getData()
             .getDataSets();

     for (LineDataSet set : sets) {
             set.setDrawFilled(true);
     }
     mChart.invalidate();
     xpos_list.add(data.getXValCount()-1);
}

    private void clearGraphMethod() {
    try {
        mChart.clearValues();
        for(int i=0; i<xpos_list.size(); i++){
            data.removeXValue(xpos_list.get(i));
        }
        xpos_list.clear();
    } catch (Exception e) {
    }

}

A: I had similiar problem, when I've tryied to restart graph.
So you declarate your xVals like this. Set the xVals arraylist as your local variable inside activity or fragment.
ArrayList<String> xVals = new ArrayList<String>();
 mLineData = new LineData(xVals,dataSets);

and than somewhere use clear() to start indexing you Xvalues from scratch
xVals.clear();

I hope it is answer for ur question.

A: private void addEntryNew(String timevalue, String value){
LineData data = mChart.getData();
if (data != null) {
    set = data.getDataSetByIndex(0);

    if (set == null) {
        set = createSet();
        data.addDataSet(set);
    }
    data.addXValue(timevalue);
    data.addEntry(new Entry(Float.parseFloat(value), set.getEntryCount()), 0);

    mChart.notifyDataSetChanged();
    mChart.setVisibleXRange(12);
    mChart.moveViewToX(data.getXValCount() - 7);
}
/** Code for ToggleFilled */
 ArrayList<LineDataSet> sets = (ArrayList<LineDataSet>) mChart.getData()
         .getDataSets();

 for (LineDataSet set : sets) {
         set.setDrawFilled(true);
 }
 mChart.invalidate();
 xpos_list.add(data.getXValCount()-1);

}
where should i properly used these @murt
ArrayList xVals = new ArrayList();
mLineData = new LineData(xVals,dataSets);


text:
Q: SQL - "merge" 3 tables with JOIN I want to select users from a table depending from two relation tables
The Structure:
[user]

uid | firstname | lastname | ...
---------------------------------
482 | USERa     | USERa    | ...
885 | USERb     | USERb    | ...
405 | USERc     | USERc    | ...
385 | USERd     | USERd    | ...

[news_info]

uid_local   | uid_foreign
--------------------------------
125         | 482
100         | 405

[news_add]

uid_local   | uid_foreign
--------------------------------
125         | 885
105         | 385

Now i want to select only USERa and USERb via uid_local -> 125, from [news_info] and [news_add]
SELECT
  nnfo.uid_local,
  user.*
FROM user
  JOIN news_info nnfo
    ON nnfo.uid_foreign = user.uid
WHERE nnfo.uid_local = 125

result = USERa // works
SELECT
  nadd.uid_local,
  user.*
FROM user
  JOIN news_add nadd
    ON nadd.uid_foreign = user.uid
WHERE nadd.uid_local = 125

result = USERb // works
now "merge" the sql statement into one...to get USERa and USERb
SELECT
  nnfo.uid_local,
  nadd.uid_local,
  user.*
FROM user
  JOIN news_info nnfo
    ON nnfo.uid_foreign = user.uid
  JOIN news_add nadd
    ON nadd.uid_foreign = user.uid
WHERE nnfo.uid_local = 125 AND nadd.uid_local = 125

result = empty // no errors.....
what is wrong...i tryed some other statements but with no result :(

A: Your uid_local IDs exist on different rows: so when you want to AND the results, you get nothing (as nothing intersects). You could do it with a union:
SELECT * from
(
SELECT
  nnfo.uid_local,
  user.firstname, user.lastname
FROM user
  JOIN news_info nnfo
    ON nnfo.uid_foreign = user.uid
WHERE nnfo.uid_local = 125

UNION ALL

SELECT
  nadd.uid_local,
  user.firstname, user.lastname
FROM user
  JOIN news_add nadd
    ON nadd.uid_foreign = user.uid
WHERE nadd.uid_local = 125
) x

A: When merging results of queries, there are 2 different approaches:

*

*UNION

*JOINs

To know which one to choose you have to know whether there's a technical link between tables in the 2 queries you wish to merge. In your case, there's a functional link (nnfo.uid_local = 125 AND nadd.uid_local = 125) but it's not enough to join these 2 universes. You still could get the result with only one SELECT, but I think the final result would be unclear and somehow not really in the spirit of what SQL provides.
I'd go towards the UNION solution:
SELECT
  nnfo.uid_local,
  user.*
FROM user
  JOIN news_info nnfo
    ON nnfo.uid_foreign = user.uid
WHERE nnfo.uid_local = 125
UNION
SELECT
  nadd.uid_local,
  user.*
FROM user
  JOIN news_add nadd
    ON nadd.uid_foreign = user.uid
WHERE nadd.uid_local = 125

Edit: I see davek's result implements UNION ALL instead of UNION. I assumed you wished to return USERa only once if it happened to appear in both independant queries, that's why I used the simple UNION operator vs the UNION ALL that would return duplicate results as well.


text:
Q: How to solve system freezing or crashing due to NVIDIA on Ubuntu 20.04 and 18.04? I have a DELL G3 3590, with NVIDIA GeForce GTX 1650, and I experienced system crash or freeze on Ubuntu 18.04 and 20.04. How to solve it?

A: The solution I found for preventing system freezing for DELL G3 3590, with NVIDIA GeForce GTX 1650 (it may apply to other NVIDEA computers), on both Ubuntu 18.04 and 20.04 is:
Add to .profile:
nvidia-settings -a [gpu:0]/GpuPowerMizerMode=1

Open /etc/default/grub and edit the line
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

by adding "acpi_rev_override=1" to the list, so it becomes
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi_rev_override=1"

Then run
sudo update-grub


text:
Q: When installing JRE using INNO setup Installer, The existing JRE is getting uninstalled. I don't want to uninstall Description:
i want to install JRE using innosetup, suppose in windows system have already installed JRE 1.8 version skip JRE installion from innosetup.
Questions

*

*when Already installed JRE in a system, then from innosetup uninstalling JRE. Here i don't want to uninstall JRE from innosetup. skip the installtion of JRE.

*i have below code i don't no where exactly error is there, Please help me.

[File]
Source: "C:\Users\hyva\Desktop\HIaccounts\Dependies\jre-8u131-windows-i586.exe"; DestDir: "{tmp}"; DestName: "JREInstaller.exe";Flags: deleteafterinstall; AfterInstall: RunJavaInstaller(); Check: (NOT IsWin64) AND InstallJava();
 Source: "C:\Users\hyva\Desktop\HIaccounts\Dependies\jre-8u131-windows-x64.exe"; DestDir: "{tmp}"; DestName: "JREInstaller.exe"; Flags: deleteafterinstall; AfterInstall: RunJavaInstaller(); Check: IsWin64 AND InstallJava();

 [Code]

        procedure DecodeVersion(verstr: String; var verint: array of Integer);
        var
          i,p: Integer; s: string;
        begin
          { initialize array }
          verint := [0,0,0,0];
          i := 0;
          while ((Length(verstr) > 0) and (i < 4)) do
          begin
            p := pos ('.', verstr);
            if p > 0 then
            begin
              if p = 1 then s:= '0' else s:= Copy (verstr, 1, p - 1);
              verint[i] := StrToInt(s);
              i := i + 1;
              verstr := Copy (verstr, p+1, Length(verstr));
            end
            else
            begin
              verint[i] := StrToInt (verstr);
              verstr := '';
            end;
          end;
        end;

        function CompareVersion (ver1, ver2: String) : Integer;
        var
          verint1, verint2: array of Integer;
          i: integer;
        begin
          SetArrayLength (verint1, 4);
          DecodeVersion (ver1, verint1);

          SetArrayLength (verint2, 4);
          DecodeVersion (ver2, verint2);

          Result := 0; i := 0;
          while ((Result = 0) and ( i < 4 )) do
          begin
            if verint1[i] > verint2[i] then
              Result := 1
            else
              if verint1[i] < verint2[i] then
                Result := -1
              else
                Result := 0;
            i := i + 1;
          end;
        end;

        function InstallJava() : Boolean;
        var
          ErrCode: Integer;
          JVer: String;
          InstallJ: Boolean;
        begin
          RegQueryStringValue(
            HKLM, 'SOFTWARE\JavaSoft\Java Runtime Environment', 'CurrentVersion', JVer);
          InstallJ := true;
          if Length( JVer ) > 0 then
          begin
            if CompareVersion(JVer, '1.8') >= 0 then
            begin
              InstallJ := false;
            end;
          end;
          Result := InstallJ;
        end;

        procedure RunJavaInstaller();
        var
          StatusText: string;
          ResultCode: Integer;
          Path, Parameters: string;
        begin
          Path := '{tmp}\JREInstaller.exe';
          { http://docs.oracle.com/javase/8/docs/technotes/guides/install/config.html#table_config_file_options }
          Parameters := '/s INSTALL_SILENT=Enable REBOOT=Disable SPONSORS=Disable REMOVEOUTOFDATEJRES=0';
          StatusText:= WizardForm.StatusLabel.Caption;
          WizardForm.StatusLabel.Caption:='Installing the java runtime environment. Wait a moment ...';
          WizardForm.ProgressGauge.Style := npbstMarquee;
          try
            if not Exec(ExpandConstant(Path), Parameters, '', SW_SHOW, ewWaitUntilTerminated, ResultCode) then
            begin
              { we inform the user we couldn't install the JRE }
              MsgBox('Java runtime environment install failed with error ' + IntToStr(ResultCode) +
                '. Try installing it manually and try again to install MyProg.', mbError, MB_OK);
            end;
          finally
            WizardForm.StatusLabel.Caption := StatusText;
            WizardForm.ProgressGauge.Style := npbstNormal;
          end;
        end;

A: You probably need two different versions of the InstallJava function -- one that checks HKLM32 and is used for not IsWin64 and one that checks HKLM64 and is used for IsWin64.
(This assumes that the Java installer only updates either the 32-bit or 64-bit registry depending on which installer you run, and does not update both.  I have not verified this.)

A: This is the working code based on @Miral's answer.
[Files]
Source: "C:\Users\user\Desktop\Dependies\jre-8u131-windows-i586.exe"; \
    DestDir: "{tmp}"; DestName: "JREInstaller.exe"; Flags: deleteafterinstall; \
    AfterInstall: RunJavaInstaller(); Check: (NOT IsWin64) AND InstallJava();
Source: "C:\Users\user\Desktop\Dependies\jre-8u131-windows-x64.exe"; \
    DestDir: "{tmp}"; DestName: "JREInstaller.exe"; Flags: deleteafterinstall; \
    AfterInstall: RunJavaInstaller(); Check: IsWin64 AND InstallJava64();

[Code]

procedure DecodeVersion(verstr: String; var verint: array of Integer);
var
  i,p: Integer; s: string;
begin
  { initialize array }
  verint := [0,0,0,0];
  i := 0;
  while ((Length(verstr) > 0) and (i < 4)) do
  begin
    p := pos ('.', verstr);
    if p > 0 then
    begin
      if p = 1 then s:= '0' else s:= Copy (verstr, 1, p - 1);
      verint[i] := StrToInt(s);
      i := i + 1;
      verstr := Copy (verstr, p+1, Length(verstr));
    end
    else
    begin
      verint[i] := StrToInt (verstr);
      verstr := '';
    end;
  end;
end;

function CompareVersion (ver1, ver2: String) : Integer;
var
  verint1, verint2: array of Integer;
  i: integer;
begin
  SetArrayLength (verint1, 4);
  DecodeVersion (ver1, verint1);

  SetArrayLength (verint2, 4);
  DecodeVersion (ver2, verint2);

  Result := 0; i := 0;
  while ((Result = 0) and ( i < 4 )) do
  begin
    if verint1[i] > verint2[i] then
      Result := 1
    else
      if verint1[i] < verint2[i] then
        Result := -1
      else
        Result := 0;
    i := i + 1;
  end;
end;

function DoInstallJava(RootKey: Integer) : Boolean;
var
  JVer: String;
begin
  RegQueryStringValue(
    RootKey, 'SOFTWARE\JavaSoft\Java Runtime Environment', 'CurrentVersion', JVer);
  Result := (Length( JVer ) = 0) or (CompareVersion(JVer, '1.8') < 0);
end;

function InstallJava() : Boolean;
begin
  Result := DoInstallJava(HKLM);
end;

function InstallJava64() : Boolean;
begin
  Result := DoInstallJava(HKLM64);
end;

procedure RunJavaInstaller();
var
  StatusText: string;
  ResultCode: Integer;
  Path, Parameters: string;
begin
  Path := '{tmp}\JREInstaller.exe';
  { http://docs.oracle.com/javase/8/docs/technotes/guides/install/config.html#table_config_file_options }
  Parameters := '/s INSTALL_SILENT=Enable REBOOT=Disable SPONSORS=Disable REMOVEOUTOFDATEJRES=1';
  StatusText:= WizardForm.StatusLabel.Caption;
  WizardForm.StatusLabel.Caption:='Installing the java runtime environment. Wait a moment ...';
  WizardForm.ProgressGauge.Style := npbstMarquee;
  try
    if not Exec(ExpandConstant(Path), Parameters, '', SW_SHOW, ewWaitUntilTerminated, ResultCode) then
    begin
      { we inform the user we couldn't install the JRE }
      MsgBox('Java runtime environment install failed with error ' + IntToStr(ResultCode) +
        '. Try installing it manually and try again to install MyProg.', mbError, MB_OK);
    end;
  finally
    WizardForm.StatusLabel.Caption := StatusText;
    WizardForm.ProgressGauge.Style := npbstNormal;
  end;
end;


text:
Q: how to install lxde in centos 7 I installed a 64bit  Centos7 in my virtualbox running in windows7. The default desktop of the centos is genome3. I don't like it. So I am trying to install lxde desktop in my CentOS7. I searched the internet and tried lots of methods and I am still not having any luck. The command from lxde wiki doesn't work at all
# yum install lxde

I got "No package lxde available."
I found on the web some said to use rosalab.repo
http://lists.centos.org/pipermail/centos/2013-April/134465.html , it's still not working. It seemed the repo was broken.
Can anyone give me some instructions on how to install lxde on Centos7? Thank you in advance.


text:
Q: Can't get simple app with two ListView in one Column work I am trying to write app with two ListViews. The idea is simple. At start we have n-element in first ListView, and by clicking elements we move elements to second.
Something like this:

To get:

To simplified code I created two global variable lists (green and blue). But I faced with problem that I do not understanding how to call setState() from Stateless widgets. And I am not sure that I should change color boxes to something else.
Should I do all widgets statefull? How to trigger update in ListView?
I created copy-paste example:
import 'dart:convert';

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

List blueList = [1,2,3,4,5,6,7,8];
List greenList = [];

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomeView(),
      themeMode: ThemeMode.system,
    );
  }
}

class HomeView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
          appBar: AppBar(title: Text("Demo App"),),
          body: SafeArea(

            child: Column(children: [
              WidgetOne(),
              WidgetTwo(),
            ],)

            ),

  );

  }
}

class _WidgetOneState extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Expanded(child: ListView.builder(
            // shrinkWrap: true,
          itemBuilder: (ctx, idx) =>
              WidgetBlue(blueList[idx]),
          itemCount: blueList.length));
  }
}

class WidgetOne extends _WidgetOneState {
  @override
  _WidgetOneState createState() => _WidgetOneState();
}

class _WidgetTwoState extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Expanded(child: ListView.builder(
            // shrinkWrap: true,
          itemBuilder: (ctx, idx) =>
              WidgetGreen(greenList[idx]),
          itemCount: greenList.length));

  }
}

class WidgetTwo extends _WidgetOneState {
  @override
  _WidgetTwoState createState() => _WidgetTwoState();
}

class WidgetBlue extends StatelessWidget {
  int index;
  WidgetBlue(this.index);
  @override
  Widget build(BuildContext context) {
    return InkWell(
      child: Center(
        child: Container(
          color: Colors.blue,
          height: 50,
          width: 90,
          child: Text("$index"),
        ),

      ),
      onTap: () {
        blueList.removeLast();
      },
    );
  }

 }

class WidgetGreen extends StatelessWidget {
  int index;
  WidgetGreen(this.index);
  @override
  Widget build(BuildContext context) {
    return InkWell(
      child: Center(
        child: Container(
          color: Colors.green,
          height: 50,
          width: 90,
          child: Text("$index"),
        ),

      ),
      onTap: () {
        // do not do nothing
      },
    );
  }

 }

A: Here is your your full code:
import 'package:flutter/material.dart';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
List blueList = [
  1,
  2,
  3,
  4,
  5,
  6,
  7,
  8
];
List greenList = [];

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        theme: ThemeData.dark().copyWith(
          scaffoldBackgroundColor: darkBlue,
        ),
        debugShowCheckedModeBanner: false,
        home: HomeView());
  }
}

class HomeView extends StatefulWidget {
  @override
  _HomeView createState() => _HomeView();
}

class _HomeView extends State<HomeView> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Demo App"),
      ),
      body: SafeArea(
          child: Column(
        children: [
          blueList.isNotEmpty ? Expanded(
              child: ListView.builder(
                  //  shrinkWrap: true,
                  itemBuilder: (ctx, idx) => InkWell(
                        child: Center(
                          child: Container(
                            color: Colors.blue,
                            height: 50,
                            width: 90,
                            child: Text("${blueList[idx]}"),
                          ),
                        ),
                        onTap: () {
                          setState(() {
                            int r = blueList.removeLast();
                            greenList.add(r);
                            print("remove $r");
                            print("size ${blueList.length}");
                          });
                        },
                      ),
                  itemCount: blueList.length) ) : Container(),
          Expanded(
        child: ListView.builder(
            // shrinkWrap: true,

            itemBuilder: (ctx, idx) => InkWell(
      child: Center(
        child: Container(
          color: Colors.green,
          height: 50,
          width: 90,
          child: Text("${greenList[idx]}"),
        ),
      ),
      onTap: () {
        setState(() {
          //TODO
        });
        // do not do nothing
      },
    ) ,
            itemCount: greenList.length))
        ],
      )),
    );
  }
}

Run Code here

A: change StatelessWidget to StatefulWidget. for simplicity, right click on StatelessWidget and choose create StatefulWidget and call setState like
onTap: () {
        setState(() => blueList.removeLast());
      },


text:
Q: Reset Mac Function Keys A friend owns a MacBook (13-inch Late 2007), somehow he's managed to screw up all the function keys.
I've managed to reset the ones for dashboard, expose, etc but the play/pause/fast forward/rewind/increase volume/decrease volume  don't work.
Any ideas as to what's happened here and how to fix it?

A: There's a couple of things:

*

*Apple Menu -> System Preferences -> Keyboard

*Untick "Use All F1, F2, etc keys as standard keys"

*Click "Keyboard Shortcuts"

*Click "Restore Defaults"

That should fix the problem.
Edit:
Some people suggest powering off the MBP, or resetting the SMC completely. Here's a forum thread which describes a similar situation.
Here's how to reset the SMC on most recent Apple Portables.
The SMC is responsible for some system IO functions, such as the trackpad, as well as power management functions. It's entirely possible that your keyboard isn't behaving because of this SMC.
Also, does this behavior occur under a new user account? If it does not, I would be inclined to trash any files from the first user's library related to keyboard - or simply migrate to the new user account, whichever is easier.

A: Go to System Preferences and click Keyboard. There is an option to switch the behavior.

A: You can use the utility FunctionFlip to change the keys from Fn keys to special features. Maybe that can help fix the problem.


text:
Q: Text Cursor out of view when typing I have multiple PDFKit annotations added into my PDF Document. When the user selects the text annotations to add text, the keyboard appears and the document scrolls upward and the cursor is no long on the screen. I have tried treating the PDF Document as a textfield but that does not work. How can I keep the cursor on screen or centered above the keyboard when the user adds text on the PDF Annotation?
Here is my code:
import UIKit
import PDFKit

class PDFfun: UIViewController {

    var pdfView = PDFView()
    var textFieldMultiline3 = PDFAnnotation()
    let document = PDFDocument(url: Bundle.main.url(forResource: "DOCUMENT", withExtension: "pdf")!)

override func viewDidLoad() {
    super.viewDidLoad()

    pdfView = PDFView(frame: self.view.frame)

        pdfView.document = document
        pdfView.autoScales = true
        pdfView.backgroundColor = UIColor.lightGray
        self.insertMultilineTextBoxIntoOneOneNine(document!.page(at: 119)!)
        pdfView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(pdfView)
    view.addConstraints([
        NSLayoutConstraint(item: pdfView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0),
        NSLayoutConstraint(item: pdfView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0),
        NSLayoutConstraint(item: pdfView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0),
        NSLayoutConstraint(item: pdfView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0)
        ])
}
func insertMultilineTextBoxIntoOneOneNine(_ page: PDFPage) {

    _ = page.bounds(for: .cropBox)

    let textFieldMultilineBounds3 = CGRect(x: 27, y: 50, width: 339, height: 510)
    textFieldMultiline3 = PDFAnnotation(bounds: textFieldMultilineBounds3, forType: PDFAnnotationSubtype(rawValue: PDFAnnotationSubtype.widget.rawValue), withProperties: nil)
    textFieldMultiline3.widgetFieldType = PDFAnnotationWidgetSubtype(rawValue: PDFAnnotationWidgetSubtype.text.rawValue)
    textFieldMultiline3.backgroundColor = UIColor.white.withAlphaComponent(1)
    textFieldMultiline3.font = UIFont(name: "Arial", size: 15)
    textFieldMultiline3.isMultiline = true
    page.addAnnotation(textFieldMultiline3)
}
 override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    if UIDevice.current.orientation.isLandscape {
        print("landscape")
        pdfView = PDFView(frame: view.frame)
        pdfView.autoScales = true
    } else {
        print("portait")
        pdfView = PDFView(frame: view.frame)
        pdfView.autoScales = true
    }
}
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    pdfView.frame = view.frame
}
override var prefersStatusBarHidden: Bool {
    return false
}
override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}

}


text:
Q: detecting lines in tambola ticket My input image is available at https://ibb.co/c1CVTjLor

Here is my code
[code]
import cv2
import numpy as np
import sys
# Read input
if(len(sys.argv)!=2):
    print("give only input image file as argument")
    sys.exit(0)
img = cv2.imread(sys.argv[1], cv2.IMREAD_GRAYSCALE)

# Initialize output
out = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
# Median blurring to get rid of the noise; invert image
img = 255 - cv2.medianBlur(img, 3)
kernel_size = 3
img = cv2.GaussianBlur(img,(kernel_size, kernel_size),0)
low_threshold = 50
high_threshold = 150
img = cv2.Canny(img, low_threshold, high_threshold)
cv2.imshow("given-image after blurring",img)
cv2.waitKey(0)
cv2.imwrite("after-blurring-canny.jpg",img)
# Detect and draw lines
lines = cv2.HoughLinesP(img, 1, np.pi/180, 90, minLineLength=2, maxLineGap=1)
for line in lines:
    for x1, y1, x2, y2 in line:
        cv2.line(out, (x1, y1), (x2, y2), (0, 0, 255), 2)
print("number of lines found ",len(lines))br
cv2.imwrite("lines-found.jpg",out)
cv2.imshow('out', out)
cv2.waitKey(0)

[/code]
Here is the intermediate image after-blurring-canny.jpg at https://ibb.co/xg3txrY
or

My aim is to get all grid lines as red .Here is final output lines-found.jpg at https://ibb.co/NCD0wXLor

As you can see that very few lines are detected and that too partial . How can I improve line detection ?
Thanks.
PS : Here threshold votes in my code is 90 . On decreasing it to 70 , i start to get lines in numbers which I do not want .


text:
Q: Where should I add the where clause in a codeigniter model? I just want to create a sorting query. When I put the where clause nothing happened.
What should happen is when $search_param['type'] has value it should only output the one who has the $search_param['type'] in sp_archive.SP_Type
Below is the query:
function search_data($search_param){
    if(empty($search_param)){
        return array();
    }else{
    $this->db->select("sp_archive.SP_ID, SP_TITLE, SP_RATIONALE, SP_File, GROUP_CONCAT(Tag.Tag_Name) As Tag");
    $this->db->select("ad.Account_LastName AS ADLastName");
    $this->db->select("ad.Account_FirstName AS ADFirstName");
    $this->db->select("ad.Account_MiddleInitial AS ADMiddleInitial");

    $this->db->select("a.Account_FirstName AS AFirstName");
    $this->db->select("a.Account_MiddleInitial AS AMiddleInitial");
    $this->db->select("a.Account_LastName AS ALastName");

    $this->db->select("b.Account_FirstName AS BFirstName");
    $this->db->select("b.Account_MiddleInitial AS BMiddleInitial");
    $this->db->select("b.Account_LastName AS BLastName");

    $this->db->select("c.Account_FirstName AS CFirstName");
    $this->db->select("c.Account_MiddleInitial AS CMiddleInitial");
    $this->db->select("c.Account_LastName AS CLastName");

    $this->db->from("sp_archive");

    $this->db->join('account ad', 'sp_archive.Adviser = ad.Account_ID','left');
    $this->db->join('account a', 'sp_archive.Proponent_A = a.Account_ID','left');
    $this->db->join('account b', 'sp_archive.Proponent_B = b.Account_ID','left');
    $this->db->join('account c', 'sp_archive.Proponent_C = c.Account_ID','left');
    $this->db->join('tag', 'sp_archive.SP_ID = tag.SP_ID', 'inner');

    $this->db->where('sp_archive.SP_Type', array($search_param['type1'], $search_param['type2'],$search_param['type3'],$search_param['type4']));

    $this->db->like("SP_TITLE", $search_param['search']);

    $this->db->or_like("ad.Account_LastName", $search_param['search']);
    $this->db->or_like("ad.Account_FirstName", $search_param['search']);
    $this->db->or_like("a.Account_LastName", $search_param['search']);
    $this->db->or_like("a.Account_FirstName", $search_param['search']);
    $this->db->or_like("c.Account_LastName", $search_param['search']);
    $this->db->or_like("c.Account_FirstName", $search_param['search']);
    $this->db->or_like("c.Account_LastName", $search_param['search']);
    $this->db->or_like("c.Account_FirstName", $search_param['search']);

    $this->db->group_by("sp_archive.SP_ID");
    $query = $this->db->get();
    return $query;
    }

A: As per my comment Your code should be like
 $this->db->where('sp_archive.SP_Type', array($search_param['type1'], $search_param['type2'],$search_param['type3'],$search_param['type4']));

 $this->db->group_start();
 $this->db->like("SP_TITLE", $search_param['search']);

 $this->db->or_like("ad.Account_LastName", $search_param['search']);
 $this->db->or_like("ad.Account_FirstName", $search_param['search']);
 $this->db->or_like("a.Account_LastName", $search_param['search']);
 $this->db->or_like("a.Account_FirstName", $search_param['search']);
 $this->db->or_like("c.Account_LastName", $search_param['search']);
 $this->db->or_like("c.Account_FirstName", $search_param['search']);
 $this->db->or_like("c.Account_LastName", $search_param['search']);
 $this->db->or_like("c.Account_FirstName", $search_param['search']);
 $this->db->group_end();

A:

public function select_where($table,$where)
    {
          $r = $this->db->get_where($table,$where);
        // $sql  = $this->db->last_query();
        //echo $sql;
        $res = $r->result();
        //print_r($res);
        //die;
        return $res;
    }


text:
Q: Forcing Wix to go do a download page for a required component When I build an MSI in Visual Studio, I have the option of specifying required components (in this case, MSXML6), and if the component isn't installed then the installer would say that it was needed, and would open a browser to the download site for the component.
How can I implement this using Wix?
(Note that I don't necessarily want it to install the component, just exit the installation and go to the download page.  I'm not trying to execute MSI from within MSI.)

A: Are you sure you want to exit the installation?  We warn about missing required external components at install, then check at application startup & disable functions requiring them.  Our unattended batch services do the same startup check and log an error if not found, then exit gracefully.